@voxevolv/client 0.3.12 → 0.3.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
- function Nl(i,e){return e.forEach(function(t){t&&typeof t!="string"&&!Array.isArray(t)&&Object.keys(t).forEach(function(n){if(n!=="default"&&!(n in i)){var r=Object.getOwnPropertyDescriptor(t,n);Object.defineProperty(i,n,r.get?r:{enumerable:!0,get:function(){return t[n]}})}})}),Object.freeze(i)}var Ul=Object.defineProperty,Fl=(i,e,t)=>e in i?Ul(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Qa=(i,e,t)=>Fl(i,typeof e!="symbol"?e+"":e,t),de=class{constructor(){Qa(this,"_locking"),Qa(this,"_locks"),this._locking=Promise.resolve(),this._locks=0}isLocked(){return this._locks>0}lock(){this._locks+=1;let e,t=new Promise(r=>e=()=>{this._locks-=1,r()}),n=this._locking.then(()=>e);return this._locking=this._locking.then(()=>t),n}};function ne(i,e){if(!i)throw new Error(e)}var Bl=34028234663852886e22,ql=-34028234663852886e22,jl=4294967295,Vl=2147483647,Hl=-2147483648;function ni(i){if(typeof i!="number")throw new Error("invalid int 32: "+typeof i);if(!Number.isInteger(i)||i>Vl||i<Hl)throw new Error("invalid int 32: "+i)}function Br(i){if(typeof i!="number")throw new Error("invalid uint 32: "+typeof i);if(!Number.isInteger(i)||i>jl||i<0)throw new Error("invalid uint 32: "+i)}function hc(i){if(typeof i!="number")throw new Error("invalid float 32: "+typeof i);if(Number.isFinite(i)&&(i>Bl||i<ql))throw new Error("invalid float 32: "+i)}var mc=Symbol("@bufbuild/protobuf/enum-type");function Gl(i){let e=i[mc];return ne(e,"missing enum type on enum object"),e}function pc(i,e,t,n){i[mc]=fc(e,t.map(r=>({no:r.no,name:r.name,localName:i[r.no]})))}function fc(i,e,t){let n=Object.create(null),r=Object.create(null),s=[];for(let a of e){let o=gc(a);s.push(o),n[a.name]=o,r[a.no]=o}return{typeName:i,values:s,findName(a){return n[a]},findNumber(a){return r[a]}}}function Kl(i,e,t){let n={};for(let r of e){let s=gc(r);n[s.localName]=s.no,n[s.no]=s.localName}return pc(n,i,e),n}function gc(i){return"localName"in i?i:Object.assign(Object.assign({},i),{localName:i.name})}var In=class{equals(e){return this.getType().runtime.util.equals(this.getType(),this,e)}clone(){return this.getType().runtime.util.clone(this)}fromBinary(e,t){let n=this.getType(),r=n.runtime.bin,s=r.makeReadOptions(t);return r.readMessage(this,s.readerFactory(e),e.byteLength,s),this}fromJson(e,t){let n=this.getType(),r=n.runtime.json,s=r.makeReadOptions(t);return r.readMessage(n,e,s,this),this}fromJsonString(e,t){let n;try{n=JSON.parse(e)}catch(r){throw new Error("cannot decode ".concat(this.getType().typeName," from JSON: ").concat(r instanceof Error?r.message:String(r)))}return this.fromJson(n,t)}toBinary(e){let t=this.getType(),n=t.runtime.bin,r=n.makeWriteOptions(e),s=r.writerFactory();return n.writeMessage(this,s,r),s.finish()}toJson(e){let t=this.getType(),n=t.runtime.json,r=n.makeWriteOptions(e);return n.writeMessage(this,r)}toJsonString(e){var t;let n=this.toJson(e);return JSON.stringify(n,null,(t=e?.prettySpaces)!==null&&t!==void 0?t:0)}toJSON(){return this.toJson({emitDefaultValues:!0})}getType(){return Object.getPrototypeOf(this).constructor}};function Wl(i,e,t,n){var r;let s=(r=n?.localName)!==null&&r!==void 0?r:e.substring(e.lastIndexOf(".")+1),a={[s]:function(o){i.util.initFields(this),i.util.initPartial(o,this)}}[s];return Object.setPrototypeOf(a.prototype,new In),Object.assign(a,{runtime:i,typeName:e,fields:i.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 i.util.equals(a,o,d)}}),a}function zl(){let i=0,e=0;for(let n=0;n<28;n+=7){let r=this.buf[this.pos++];if(i|=(r&127)<<n,(r&128)==0)return this.assertBounds(),[i,e]}let t=this.buf[this.pos++];if(i|=(t&15)<<28,e=(t&112)>>4,(t&128)==0)return this.assertBounds(),[i,e];for(let n=3;n<=31;n+=7){let r=this.buf[this.pos++];if(e|=(r&127)<<n,(r&128)==0)return this.assertBounds(),[i,e]}throw new Error("invalid varint")}function yr(i,e,t){for(let s=0;s<28;s=s+7){let a=i>>>s,o=!(!(a>>>7)&&e==0),d=(o?a|128:a)&255;if(t.push(d),!o)return}let n=i>>>28&15|(e&7)<<4,r=e>>3!=0;if(t.push((r?n|128:n)&255),!!r){for(let s=3;s<31;s=s+7){let a=e>>>s,o=!!(a>>>7),d=(o?a|128:a)&255;if(t.push(d),!o)return}t.push(e>>>31&1)}}var ii=4294967296;function Ya(i){let e=i[0]==="-";e&&(i=i.slice(1));let t=1e6,n=0,r=0;function s(a,o){let d=Number(i.slice(a,o));r*=t,n=n*t+d,n>=ii&&(r=r+(n/ii|0),n=n%ii)}return s(-24,-18),s(-18,-12),s(-12,-6),s(-6),e?yc(n,r):pa(n,r)}function Jl(i,e){let t=pa(i,e),n=t.hi&2147483648;n&&(t=yc(t.lo,t.hi));let r=vc(t.lo,t.hi);return n?"-"+r:r}function vc(i,e){var t=$l(i,e);if(i=t.lo,e=t.hi,e<=2097151)return String(ii*e+i);let n=i&16777215,r=(i>>>24|e<<8)&16777215,s=e>>16&65535,a=n+r*6777216+s*6710656,o=r+s*8147497,d=s*2,c=1e7;return a>=c&&(o+=Math.floor(a/c),a%=c),o>=c&&(d+=Math.floor(o/c),o%=c),d.toString()+Xa(o)+Xa(a)}function $l(i,e){return{lo:i>>>0,hi:e>>>0}}function pa(i,e){return{lo:i|0,hi:e|0}}function yc(i,e){return e=~e,i?i=~i+1:e+=1,pa(i,e)}var Xa=i=>{let e=String(i);return"0000000".slice(e.length)+e};function Za(i,e){if(i>=0){for(;i>127;)e.push(i&127|128),i=i>>>7;e.push(i)}else{for(let t=0;t<9;t++)e.push(i&127|128),i=i>>7;e.push(1)}}function Ql(){let i=this.buf[this.pos++],e=i&127;if((i&128)==0)return this.assertBounds(),e;if(i=this.buf[this.pos++],e|=(i&127)<<7,(i&128)==0)return this.assertBounds(),e;if(i=this.buf[this.pos++],e|=(i&127)<<14,(i&128)==0)return this.assertBounds(),e;if(i=this.buf[this.pos++],e|=(i&127)<<21,(i&128)==0)return this.assertBounds(),e;i=this.buf[this.pos++],e|=(i&15)<<28;for(let t=5;(i&128)!==0&&t<10;t++)i=this.buf[this.pos++];if((i&128)!=0)throw new Error("invalid varint");return this.assertBounds(),e>>>0}function Yl(){let i=new DataView(new ArrayBuffer(8));if(typeof BigInt=="function"&&typeof i.getBigInt64=="function"&&typeof i.getBigUint64=="function"&&typeof i.setBigInt64=="function"&&typeof i.setBigUint64=="function"&&(typeof process!="object"||typeof process.env!="object"||process.env.BUF_BIGINT_DISABLE!=="1")){let r=BigInt("-9223372036854775808"),s=BigInt("9223372036854775807"),a=BigInt("0"),o=BigInt("18446744073709551615");return{zero:BigInt(0),supported:!0,parse(d){let c=typeof d=="bigint"?d:BigInt(d);if(c>s||c<r)throw new Error("int64 invalid: ".concat(d));return c},uParse(d){let c=typeof d=="bigint"?d:BigInt(d);if(c>o||c<a)throw new Error("uint64 invalid: ".concat(d));return c},enc(d){return i.setBigInt64(0,this.parse(d),!0),{lo:i.getInt32(0,!0),hi:i.getInt32(4,!0)}},uEnc(d){return i.setBigInt64(0,this.uParse(d),!0),{lo:i.getInt32(0,!0),hi:i.getInt32(4,!0)}},dec(d,c){return i.setInt32(0,d,!0),i.setInt32(4,c,!0),i.getBigInt64(0,!0)},uDec(d,c){return i.setInt32(0,d,!0),i.setInt32(4,c,!0),i.getBigUint64(0,!0)}}}let t=r=>ne(/^-?[0-9]+$/.test(r),"int64 invalid: ".concat(r)),n=r=>ne(/^[0-9]+$/.test(r),"uint64 invalid: ".concat(r));return{zero:"0",supported:!1,parse(r){return typeof r!="string"&&(r=r.toString()),t(r),r},uParse(r){return typeof r!="string"&&(r=r.toString()),n(r),r},enc(r){return typeof r!="string"&&(r=r.toString()),t(r),Ya(r)},uEnc(r){return typeof r!="string"&&(r=r.toString()),n(r),Ya(r)},dec(r,s){return Jl(r,s)},uDec(r,s){return vc(r,s)}}}var Y=Yl(),w;(function(i){i[i.DOUBLE=1]="DOUBLE",i[i.FLOAT=2]="FLOAT",i[i.INT64=3]="INT64",i[i.UINT64=4]="UINT64",i[i.INT32=5]="INT32",i[i.FIXED64=6]="FIXED64",i[i.FIXED32=7]="FIXED32",i[i.BOOL=8]="BOOL",i[i.STRING=9]="STRING",i[i.BYTES=12]="BYTES",i[i.UINT32=13]="UINT32",i[i.SFIXED32=15]="SFIXED32",i[i.SFIXED64=16]="SFIXED64",i[i.SINT32=17]="SINT32",i[i.SINT64=18]="SINT64"})(w||(w={}));var _t;(function(i){i[i.BIGINT=0]="BIGINT",i[i.STRING=1]="STRING"})(_t||(_t={}));function gt(i,e,t){if(e===t)return!0;if(i==w.BYTES){if(!(e instanceof Uint8Array)||!(t instanceof Uint8Array)||e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}switch(i){case w.UINT64:case w.FIXED64:case w.INT64:case w.SFIXED64:case w.SINT64:return e==t}return!1}function tn(i,e){switch(i){case w.BOOL:return!1;case w.UINT64:case w.FIXED64:case w.INT64:case w.SFIXED64:case w.SINT64:return e==0?Y.zero:"0";case w.DOUBLE:case w.FLOAT:return 0;case w.BYTES:return new Uint8Array(0);case w.STRING:return"";default:return 0}}function bc(i,e){switch(i){case w.BOOL:return e===!1;case w.STRING:return e==="";case w.BYTES:return e instanceof Uint8Array&&!e.byteLength;default:return e==0}}function eo(i,e){(e==null||e>i.length)&&(e=i.length);for(var t=0,n=Array(e);t<e;t++)n[t]=i[t];return n}function Xl(i){if(Array.isArray(i))return i}function H(i,e,t){return(e=nu(e))in i?Object.defineProperty(i,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):i[e]=t,i}function Zl(i,e){var t=i==null?null:typeof Symbol<"u"&&i[Symbol.iterator]||i["@@iterator"];if(t!=null){var n,r,s,a,o=[],d=!0,c=!1;try{if(s=(t=t.call(i)).next,e===0){if(Object(t)!==t)return;d=!1}else for(;!(d=(n=s.call(t)).done)&&(o.push(n.value),o.length!==e);d=!0);}catch(l){c=!0,r=l}finally{try{if(!d&&t.return!=null&&(a=t.return(),Object(a)!==a))return}finally{if(c)throw r}}return o}}function eu(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
2
- In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function O(i,e){return Xl(i)||Zl(i,e)||iu(i,e)||eu()}function tu(i,e){if(typeof i!="object"||!i)return i;var t=i[Symbol.toPrimitive];if(t!==void 0){var n=t.call(i,e);if(typeof n!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(i)}function nu(i){var e=tu(i,"string");return typeof e=="symbol"?e:e+""}function iu(i,e){if(i){if(typeof i=="string")return eo(i,e);var t={}.toString.call(i).slice(8,-1);return t==="Object"&&i.constructor&&(t=i.constructor.name),t==="Map"||t==="Set"?Array.from(i):t==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t)?eo(i,e):void 0}}var se;(function(i){i[i.Varint=0]="Varint",i[i.Bit64=1]="Bit64",i[i.LengthDelimited=2]="LengthDelimited",i[i.StartGroup=3]="StartGroup",i[i.EndGroup=4]="EndGroup",i[i.Bit32=5]="Bit32"})(se||(se={}));var qr=class{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),n=0;for(let r=0;r<this.chunks.length;r++)t.set(this.chunks[r],n),n+=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(Br(e);e>127;)this.buf.push(e&127|128),e=e>>>7;return this.buf.push(e),this}int32(e){return ni(e),Za(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){hc(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){Br(e);let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!0),this.raw(t)}sfixed32(e){ni(e);let t=new Uint8Array(4);return new DataView(t.buffer).setInt32(0,e,!0),this.raw(t)}sint32(e){return ni(e),e=(e<<1^e>>31)>>>0,Za(e,this.buf),this}sfixed64(e){let t=new Uint8Array(8),n=new DataView(t.buffer),r=Y.enc(e);return n.setInt32(0,r.lo,!0),n.setInt32(4,r.hi,!0),this.raw(t)}fixed64(e){let t=new Uint8Array(8),n=new DataView(t.buffer),r=Y.uEnc(e);return n.setInt32(0,r.lo,!0),n.setInt32(4,r.hi,!0),this.raw(t)}int64(e){let t=Y.enc(e);return yr(t.lo,t.hi,this.buf),this}sint64(e){let t=Y.enc(e),n=t.hi>>31,r=t.lo<<1^n,s=(t.hi<<1|t.lo>>>31)^n;return yr(r,s,this.buf),this}uint64(e){let t=Y.uEnc(e);return yr(t.lo,t.hi,this.buf),this}},jr=class{constructor(e,t){this.varint64=zl,this.uint32=Ql,this.buf=e,this.len=e.length,this.pos=0,this.view=new DataView(e.buffer,e.byteOffset,e.byteLength),this.textDecoder=t??new TextDecoder}tag(){let e=this.uint32(),t=e>>>3,n=e&7;if(t<=0||n<0||n>5)throw new Error("illegal tag: field no "+t+" wire type "+n);return[t,n]}skip(e,t){let n=this.pos;switch(e){case se.Varint:for(;this.buf[this.pos++]&128;);break;case se.Bit64:this.pos+=4;case se.Bit32:this.pos+=4;break;case se.LengthDelimited:let r=this.uint32();this.pos+=r;break;case se.StartGroup:for(;;){let s=this.tag(),a=O(s,2),o=a[0],d=a[1];if(d===se.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(n,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 Y.dec(...this.varint64())}uint64(){return Y.uDec(...this.varint64())}sint64(){let e=this.varint64(),t=O(e,2),n=t[0],r=t[1],s=-(n&1);return n=(n>>>1|(r&1)<<31)^s,r=r>>>1^s,Y.dec(n,r)}bool(){let e=this.varint64(),t=O(e,2),n=t[0],r=t[1];return n!==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 Y.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return Y.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 ru(i,e,t,n){let r;return{typeName:e,extendee:t,get field(){if(!r){let s=typeof n=="function"?n():n;s.name=e.split(".").pop(),s.jsonName="[".concat(e,"]"),r=i.util.newFieldList([s]).list()[0]}return r},runtime:i}}function kc(i){let e=i.field.localName,t=Object.create(null);return t[e]=su(i),[t,()=>t[e]]}function su(i){let e=i.field;if(e.repeated)return[];if(e.default!==void 0)return e.default;switch(e.kind){case"enum":return e.T.values[0].no;case"scalar":return tn(e.T,e.L);case"message":let t=e.T,n=new t;return t.fieldWrapper?t.fieldWrapper.unwrapField(n):n;case"map":throw"map fields are not allowed to be extensions"}}function au(i,e){if(!e.repeated&&(e.kind=="enum"||e.kind=="scalar")){for(let t=i.length-1;t>=0;--t)if(i[t].no==e.no)return[i[t]];return[]}return i.filter(t=>t.no===e.no)}var ct="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),Yi=[];for(let i=0;i<ct.length;i++)Yi[ct[i].charCodeAt(0)]=i;Yi[45]=ct.indexOf("+");Yi[95]=ct.indexOf("/");var Tc={dec(i){let e=i.length*3/4;i[i.length-2]=="="?e-=2:i[i.length-1]=="="&&(e-=1);let t=new Uint8Array(e),n=0,r=0,s,a=0;for(let o=0;o<i.length;o++){if(s=Yi[i.charCodeAt(o)],s===void 0)switch(i[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[n++]=a<<2|(s&48)>>4,a=s,r=2;break;case 2:t[n++]=(a&15)<<4|(s&60)>>2,a=s,r=3;break;case 3:t[n++]=(a&3)<<6|s,r=0;break}}if(r==1)throw Error("invalid base64 string.");return t.subarray(0,n)},enc(i){let e="",t=0,n,r=0;for(let s=0;s<i.length;s++)switch(n=i[s],t){case 0:e+=ct[n>>2],r=(n&3)<<4,t=1;break;case 1:e+=ct[r|n>>4],r=(n&15)<<2,t=2;break;case 2:e+=ct[r|n>>6],e+=ct[n&63],t=0;break}return t&&(e+=ct[r],e+="=",t==1&&(e+="=")),e}};function ou(i,e,t){Cc(e,i);let n=e.runtime.bin.makeReadOptions(t),r=au(i.getType().runtime.bin.listUnknownFields(i),e.field),s=kc(e),a=O(s,2),o=a[0],d=a[1];for(let c of r)e.runtime.bin.readField(o,n.readerFactory(c.data),e.field,c.wireType,n);return d()}function cu(i,e,t,n){Cc(e,i);let r=e.runtime.bin.makeReadOptions(n),s=e.runtime.bin.makeWriteOptions(n);if(Sc(i,e)){let c=i.getType().runtime.bin.listUnknownFields(i).filter(l=>l.no!=e.field.no);i.getType().runtime.bin.discardUnknownFields(i);for(let l of c)i.getType().runtime.bin.onUnknownField(i,l.no,l.wireType,l.data)}let a=s.writerFactory(),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);let d=r.readerFactory(a.finish());for(;d.pos<d.len;){let c=d.tag(),l=O(c,2),u=l[0],h=l[1],m=d.skip(h,u);i.getType().runtime.bin.onUnknownField(i,u,h,m)}}function Sc(i,e){let t=i.getType();return e.extendee.typeName===t.typeName&&!!t.runtime.bin.listUnknownFields(i).find(n=>n.no==e.field.no)}function Cc(i,e){ne(i.extendee.typeName==e.getType().typeName,"extension ".concat(i.typeName," can only be applied to message ").concat(i.extendee.typeName))}function _c(i,e){let t=i.localName;if(i.repeated)return e[t].length>0;if(i.oneof)return e[i.oneof.localName].case===t;switch(i.kind){case"enum":case"scalar":return i.opt||i.req?e[t]!==void 0:i.kind=="enum"?e[t]!==i.T.values[0].no:!bc(i.T,e[t]);case"message":return e[t]!==void 0;case"map":return Object.keys(e[t]).length>0}}function to(i,e){let t=i.localName,n=!i.opt&&!i.req;if(i.repeated)e[t]=[];else if(i.oneof)e[i.oneof.localName]={case:void 0};else switch(i.kind){case"map":e[t]={};break;case"enum":e[t]=n?i.T.values[0].no:void 0;break;case"scalar":e[t]=n?tn(i.T,i.L):void 0;break;case"message":e[t]=void 0;break}}function dt(i,e){if(i===null||typeof i!="object"||!Object.getOwnPropertyNames(In.prototype).every(n=>n in i&&typeof i[n]=="function"))return!1;let t=i.getType();return t===null||typeof t!="function"||!("typeName"in t)||typeof t.typeName!="string"?!1:e===void 0?!0:t.typeName==e.typeName}function wc(i,e){return dt(e)||!i.fieldWrapper?e:i.fieldWrapper.wrapField(e)}w.DOUBLE,w.FLOAT,w.INT64,w.UINT64,w.INT32,w.UINT32,w.BOOL,w.STRING,w.BYTES;var no={ignoreUnknownFields:!1},io={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0};function du(i){return i?Object.assign(Object.assign({},no),i):no}function lu(i){return i?Object.assign(Object.assign({},io),i):io}var fi=Symbol(),ri=Symbol();function uu(){return{makeReadOptions:du,makeWriteOptions:lu,readMessage(i,e,t,n){if(e==null||Array.isArray(e)||typeof e!="object")throw new Error("cannot decode message ".concat(i.typeName," from JSON: ").concat(Ye(e)));n=n??new i;let r=new Map,s=t.typeRegistry;for(let o of Object.entries(e)){var a=O(o,2);let d=a[0],c=a[1],l=i.fields.findJsonName(d);if(l){if(l.oneof){if(c===null&&l.kind=="scalar")continue;let u=r.get(l.oneof);if(u!==void 0)throw new Error("cannot decode message ".concat(i.typeName,' from JSON: multiple keys for oneof "').concat(l.oneof.name,'" present: "').concat(u,'", "').concat(d,'"'));r.set(l.oneof,d)}ro(n,c,l,t,i)}else{let u=!1;if(s?.findExtension&&d.startsWith("[")&&d.endsWith("]")){let h=s.findExtension(d.substring(1,d.length-1));if(h&&h.extendee.typeName==i.typeName){u=!0;let m=kc(h),g=O(m,2),f=g[0],T=g[1];ro(f,c,h.field,t,h),cu(n,h,T(),t)}}if(!u&&!t.ignoreUnknownFields)throw new Error("cannot decode message ".concat(i.typeName,' from JSON: key "').concat(d,'" is unknown'))}}return n},writeMessage(i,e){let t=i.getType(),n={},r;try{for(r of t.fields.byNumber()){if(!_c(r,i)){if(r.req)throw"required field not set";if(!e.emitDefaultValues||!mu(r))continue}let a=r.oneof?i[r.oneof.localName].value:i[r.localName],o=so(r,a,e);o!==void 0&&(n[e.useProtoFieldName?r.name:r.jsonName]=o)}let s=e.typeRegistry;if(s?.findExtensionFor)for(let a of t.runtime.bin.listUnknownFields(i)){let o=s.findExtensionFor(t.typeName,a.no);if(o&&Sc(i,o)){let d=ou(i,o,e),c=so(o.field,d,e);c!==void 0&&(n[o.field.jsonName]=c)}}}catch(s){let 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 n},readScalar(i,e,t){return Sn(i,e,t??_t.BIGINT,!0)},writeScalar(i,e,t){if(e!==void 0&&(t||bc(i,e)))return si(i,e)},debug:Ye}}function Ye(i){if(i===null)return"null";switch(typeof i){case"object":return Array.isArray(i)?"array":"object";case"string":return i.length>100?"string":'"'.concat(i.split('"').join('\\"'),'"');default:return String(i)}}function ro(i,e,t,n,r){let s=t.localName;if(t.repeated){if(ne(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(Ye(e)));let o=i[s];for(let d of e){if(d===null)throw new Error("cannot decode field ".concat(r.typeName,".").concat(t.name," from JSON: ").concat(Ye(d)));switch(t.kind){case"message":o.push(t.T.fromJson(d,n));break;case"enum":let c=br(t.T,d,n.ignoreUnknownFields,!0);c!==ri&&o.push(c);break;case"scalar":try{o.push(Sn(t.T,d,t.L,!0))}catch(l){let u="cannot decode field ".concat(r.typeName,".").concat(t.name," from JSON: ").concat(Ye(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(Ye(e)));let o=i[s];for(let d of Object.entries(e)){var a=O(d,2);let 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=hu(t.K,c)}catch(h){let m="cannot decode map key for field ".concat(r.typeName,".").concat(t.name," from JSON: ").concat(Ye(e));throw h instanceof Error&&h.message.length>0&&(m+=": ".concat(h.message)),new Error(m)}switch(t.V.kind){case"message":o[u]=t.V.T.fromJson(l,n);break;case"enum":let h=br(t.V.T,l,n.ignoreUnknownFields,!0);h!==ri&&(o[u]=h);break;case"scalar":try{o[u]=Sn(t.V.T,l,_t.BIGINT,!0)}catch(m){let g="cannot decode map value for field ".concat(r.typeName,".").concat(t.name," from JSON: ").concat(Ye(e));throw m instanceof Error&&m.message.length>0&&(g+=": ".concat(m.message)),new Error(g)}break}}}else switch(t.oneof&&(i=i[t.oneof.localName]={case:s},s="value"),t.kind){case"message":let o=t.T;if(e===null&&o.typeName!="google.protobuf.Value")return;let d=i[s];dt(d)?d.fromJson(e,n):(i[s]=d=o.fromJson(e,n),o.fieldWrapper&&!t.oneof&&(i[s]=o.fieldWrapper.unwrapField(d)));break;case"enum":let c=br(t.T,e,n.ignoreUnknownFields,!1);switch(c){case fi:to(t,i);break;case ri:break;default:i[s]=c;break}break;case"scalar":try{let l=Sn(t.T,e,t.L,!1);switch(l){case fi:to(t,i);break;default:i[s]=l;break}}catch(l){let u="cannot decode field ".concat(r.typeName,".").concat(t.name," from JSON: ").concat(Ye(e));throw l instanceof Error&&l.message.length>0&&(u+=": ".concat(l.message)),new Error(u)}break}}function hu(i,e){if(i===w.BOOL)switch(e){case"true":e=!0;break;case"false":e=!1;break}return Sn(i,e,_t.BIGINT,!0).toString()}function Sn(i,e,t,n){if(e===null)return n?tn(i,t):fi;switch(i){case w.DOUBLE:case w.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;let r=Number(e);if(Number.isNaN(r)||!Number.isFinite(r))break;return i==w.FLOAT&&hc(r),r;case w.INT32:case w.FIXED32:case w.SFIXED32:case w.SINT32:case w.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 i==w.UINT32||i==w.FIXED32?Br(s):ni(s),s;case w.INT64:case w.SFIXED64:case w.SINT64:if(typeof e!="number"&&typeof e!="string")break;let a=Y.parse(e);return t?a.toString():a;case w.FIXED64:case w.UINT64:if(typeof e!="number"&&typeof e!="string")break;let o=Y.uParse(e);return t?o.toString():o;case w.BOOL:if(typeof e!="boolean")break;return e;case w.STRING:if(typeof e!="string")break;try{encodeURIComponent(e)}catch{throw new Error("invalid UTF8")}return e;case w.BYTES:if(e==="")return new Uint8Array(0);if(typeof e!="string")break;return Tc.dec(e)}throw new Error}function br(i,e,t,n){if(e===null)return i.typeName=="google.protobuf.NullValue"?0:n?i.values[0].no:fi;switch(typeof e){case"number":if(Number.isInteger(e))return e;break;case"string":let r=i.findName(e);if(r!==void 0)return r.no;if(t)return ri;break}throw new Error("cannot decode enum ".concat(i.typeName," from JSON: ").concat(Ye(e)))}function mu(i){return i.repeated||i.kind=="map"?!0:!(i.oneof||i.kind=="message"||i.opt||i.req)}function so(i,e,t){if(i.kind=="map"){ne(typeof e=="object"&&e!=null);let a={},o=Object.entries(e);switch(i.V.kind){case"scalar":for(let c of o){var n=O(c,2);let l=n[0],u=n[1];a[l.toString()]=si(i.V.T,u)}break;case"message":for(let c of o){var r=O(c,2);let l=r[0],u=r[1];a[l.toString()]=u.toJson(t)}break;case"enum":let d=i.V.T;for(let c of o){var s=O(c,2);let l=s[0],u=s[1];a[l.toString()]=kr(d,u,t.enumAsInteger)}break}return t.emitDefaultValues||o.length>0?a:void 0}if(i.repeated){ne(Array.isArray(e));let a=[];switch(i.kind){case"scalar":for(let o=0;o<e.length;o++)a.push(si(i.T,e[o]));break;case"enum":for(let o=0;o<e.length;o++)a.push(kr(i.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(i.kind){case"scalar":return si(i.T,e);case"enum":return kr(i.T,e,t.enumAsInteger);case"message":return wc(i.T,e).toJson(t)}}function kr(i,e,t){var n;if(ne(typeof e=="number"),i.typeName=="google.protobuf.NullValue")return null;if(t)return e;let r=i.findNumber(e);return(n=r?.name)!==null&&n!==void 0?n:e}function si(i,e){switch(i){case w.INT32:case w.SFIXED32:case w.SINT32:case w.FIXED32:case w.UINT32:return ne(typeof e=="number"),e;case w.FLOAT:case w.DOUBLE:return ne(typeof e=="number"),Number.isNaN(e)?"NaN":e===Number.POSITIVE_INFINITY?"Infinity":e===Number.NEGATIVE_INFINITY?"-Infinity":e;case w.STRING:return ne(typeof e=="string"),e;case w.BOOL:return ne(typeof e=="boolean"),e;case w.UINT64:case w.FIXED64:case w.INT64:case w.SFIXED64:case w.SINT64:return ne(typeof e=="bigint"||typeof e=="string"||typeof e=="number"),e.toString();case w.BYTES:return ne(e instanceof Uint8Array),Tc.enc(e)}}var Kt=Symbol("@bufbuild/protobuf/unknown-fields"),ao={readUnknownFields:!0,readerFactory:i=>new jr(i)},oo={writeUnknownFields:!0,writerFactory:()=>new qr};function pu(i){return i?Object.assign(Object.assign({},ao),i):ao}function fu(i){return i?Object.assign(Object.assign({},oo),i):oo}function gu(){return{makeReadOptions:pu,makeWriteOptions:fu,listUnknownFields(i){var e;return(e=i[Kt])!==null&&e!==void 0?e:[]},discardUnknownFields(i){delete i[Kt]},writeUnknownFields(i,e){let n=i[Kt];if(n)for(let r of n)e.tag(r.no,r.wireType).raw(r.data)},onUnknownField(i,e,t,n){let r=i;Array.isArray(r[Kt])||(r[Kt]=[]),r[Kt].push({no:e,wireType:t,data:n})},readMessage(i,e,t,n,r){let s=i.getType(),a=r?e.len:e.pos+t,o,d;for(;e.pos<a;){var c=e.tag(),l=O(c,2);if(o=l[0],d=l[1],r===!0&&d==se.EndGroup)break;let u=s.fields.find(o);if(!u){let h=e.skip(d,o);n.readUnknownFields&&this.onUnknownField(i,o,d,h);continue}co(i,e,u,d,n)}if(r&&(d!=se.EndGroup||o!==t))throw new Error("invalid end group tag")},readField:co,writeMessage(i,e,t){let n=i.getType();for(let r of n.fields.byNumber()){if(!_c(r,i)){if(r.req)throw new Error("cannot encode field ".concat(n.typeName,".").concat(r.name," to binary: required field not set"));continue}let s=r.oneof?i[r.oneof.localName].value:i[r.localName];lo(r,s,e,t)}return t.writeUnknownFields&&this.writeUnknownFields(i,e),e},writeField(i,e,t,n){e!==void 0&&lo(i,e,t,n)}}}function co(i,e,t,n,r){let s=t.repeated,a=t.localName;switch(t.oneof&&(i=i[t.oneof.localName],i.case!=a&&delete i.value,i.case=a,a="value"),t.kind){case"scalar":case"enum":let o=t.kind=="enum"?w.INT32:t.T,d=gi;if(t.kind=="scalar"&&t.L>0&&(d=yu),s){let g=i[a];if(n==se.LengthDelimited&&o!=w.STRING&&o!=w.BYTES){let T=e.uint32()+e.pos;for(;e.pos<T;)g.push(d(e,o))}else g.push(d(e,o))}else i[a]=d(e,o);break;case"message":let c=t.T;s?i[a].push(ai(e,new c,r,t)):dt(i[a])?ai(e,i[a],r,t):(i[a]=ai(e,new c,r,t),c.fieldWrapper&&!t.oneof&&!t.repeated&&(i[a]=c.fieldWrapper.unwrapField(i[a])));break;case"map":let l=vu(t,e,r),u=O(l,2),h=u[0],m=u[1];i[a][h]=m;break}}function ai(i,e,t,n){let r=e.getType().runtime.bin,s=n?.delimited;return r.readMessage(e,i,s?n.no:i.uint32(),t,s),e}function vu(i,e,t){let n=e.uint32(),r=e.pos+n,s,a;for(;e.pos<r;){let o=e.tag();switch(O(o,1)[0]){case 1:s=gi(e,i.K);break;case 2:switch(i.V.kind){case"scalar":a=gi(e,i.V.T);break;case"enum":a=e.int32();break;case"message":a=ai(e,new i.V.T,t,void 0);break}break}}if(s===void 0&&(s=tn(i.K,_t.BIGINT)),typeof s!="string"&&typeof s!="number"&&(s=s.toString()),a===void 0)switch(i.V.kind){case"scalar":a=tn(i.V.T,_t.BIGINT);break;case"enum":a=i.V.T.values[0].no;break;case"message":a=new i.V.T;break}return[s,a]}function yu(i,e){let t=gi(i,e);return typeof t=="bigint"?t.toString():t}function gi(i,e){switch(e){case w.STRING:return i.string();case w.BOOL:return i.bool();case w.DOUBLE:return i.double();case w.FLOAT:return i.float();case w.INT32:return i.int32();case w.INT64:return i.int64();case w.UINT64:return i.uint64();case w.FIXED64:return i.fixed64();case w.BYTES:return i.bytes();case w.FIXED32:return i.fixed32();case w.SFIXED32:return i.sfixed32();case w.SFIXED64:return i.sfixed64();case w.SINT64:return i.sint64();case w.UINT32:return i.uint32();case w.SINT32:return i.sint32()}}function lo(i,e,t,n){ne(e!==void 0);let r=i.repeated;switch(i.kind){case"scalar":case"enum":let a=i.kind=="enum"?w.INT32:i.T;if(r)if(ne(Array.isArray(e)),i.packed)ku(t,a,i.no,e);else for(let o of e)Cn(t,a,i.no,o);else Cn(t,a,i.no,e);break;case"message":if(r){ne(Array.isArray(e));for(let o of e)uo(t,n,i,o)}else uo(t,n,i,e);break;case"map":ne(typeof e=="object"&&e!=null);for(let o of Object.entries(e)){var s=O(o,2);let d=s[0],c=s[1];bu(t,n,i,d,c)}break}}function bu(i,e,t,n,r){i.tag(t.no,se.LengthDelimited),i.fork();let s=n;switch(t.K){case w.INT32:case w.FIXED32:case w.UINT32:case w.SFIXED32:case w.SINT32:s=Number.parseInt(n);break;case w.BOOL:ne(n=="true"||n=="false"),s=n=="true";break}switch(Cn(i,t.K,1,s),t.V.kind){case"scalar":Cn(i,t.V.T,2,r);break;case"enum":Cn(i,w.INT32,2,r);break;case"message":ne(r!==void 0),i.tag(2,se.LengthDelimited).bytes(r.toBinary(e));break}i.join()}function uo(i,e,t,n){let r=wc(t.T,n);t.delimited?i.tag(t.no,se.StartGroup).raw(r.toBinary(e)).tag(t.no,se.EndGroup):i.tag(t.no,se.LengthDelimited).bytes(r.toBinary(e))}function Cn(i,e,t,n){ne(n!==void 0);let r=Ec(e),s=O(r,2),a=s[0],o=s[1];i.tag(t,a)[o](n)}function ku(i,e,t,n){if(!n.length)return;i.tag(t,se.LengthDelimited).fork();let r=Ec(e),s=O(r,2),a=s[1];for(let o=0;o<n.length;o++)i[a](n[o]);i.join()}function Ec(i){let e=se.Varint;switch(i){case w.BYTES:case w.STRING:e=se.LengthDelimited;break;case w.DOUBLE:case w.FIXED64:case w.SFIXED64:e=se.Bit64;break;case w.FIXED32:case w.SFIXED32:case w.FLOAT:e=se.Bit32;break}let t=w[i].toLowerCase();return[e,t]}function Tu(){return{setEnumType:pc,initPartial(i,e){if(i===void 0)return;let t=e.getType();for(let r of t.fields.byMember()){let s=r.localName,a=e,o=i;if(o[s]!=null)switch(r.kind){case"oneof":let d=o[s].case;if(d===void 0)continue;let c=r.findField(d),l=o[s].value;c&&c.kind=="message"&&!dt(l,c.T)?l=new c.T(l):c&&c.kind==="scalar"&&c.T===w.BYTES&&(l=pn(l)),a[s]={case:d,value:l};break;case"scalar":case"enum":let u=o[s];r.T===w.BYTES&&(u=r.repeated?u.map(pn):pn(u)),a[s]=u;break;case"map":switch(r.V.kind){case"scalar":case"enum":if(r.V.T===w.BYTES)for(let g of Object.entries(o[s])){var n=O(g,2);let f=n[0],T=n[1];a[s][f]=pn(T)}else Object.assign(a[s],o[s]);break;case"message":let m=r.V.T;for(let g of Object.keys(o[s])){let f=o[s][g];m.fieldWrapper||(f=new m(f)),a[s][g]=f}break}break;case"message":let h=r.T;if(r.repeated)a[s]=o[s].map(m=>dt(m,h)?m:new h(m));else{let m=o[s];h.fieldWrapper?h.typeName==="google.protobuf.BytesValue"?a[s]=pn(m):a[s]=m:a[s]=dt(m,h)?m:new h(m)}break}}},equals(i,e,t){return e===t?!0:!e||!t?!1:i.fields.byMember().every(n=>{let r=e[n.localName],s=t[n.localName];if(n.repeated){if(r.length!==s.length)return!1;switch(n.kind){case"message":return r.every((a,o)=>n.T.equals(a,s[o]));case"scalar":return r.every((a,o)=>gt(n.T,a,s[o]));case"enum":return r.every((a,o)=>gt(w.INT32,a,s[o]))}throw new Error("repeated cannot contain ".concat(n.kind))}switch(n.kind){case"message":let a=r,o=s;return n.T.fieldWrapper&&(a!==void 0&&!dt(a)&&(a=n.T.fieldWrapper.wrapField(a)),o!==void 0&&!dt(o)&&(o=n.T.fieldWrapper.wrapField(o))),n.T.equals(a,o);case"enum":return gt(w.INT32,r,s);case"scalar":return gt(n.T,r,s);case"oneof":if(r.case!==s.case)return!1;let d=n.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 gt(w.INT32,r.value,s.value);case"scalar":return gt(d.T,r.value,s.value)}throw new Error("oneof cannot contain ".concat(d.kind));case"map":let c=Object.keys(r).concat(Object.keys(s));switch(n.V.kind){case"message":let l=n.V.T;return c.every(h=>l.equals(r[h],s[h]));case"enum":return c.every(h=>gt(w.INT32,r[h],s[h]));case"scalar":let u=n.V.T;return c.every(h=>gt(u,r[h],s[h]))}break}})},clone(i){let e=i.getType(),t=new e,n=t;for(let s of e.fields.byMember()){let a=i[s.localName],o;if(s.repeated)o=a.map(Xn);else if(s.kind=="map"){o=n[s.localName];for(let d of Object.entries(a)){var r=O(d,2);let c=r[0],l=r[1];o[c]=Xn(l)}}else s.kind=="oneof"?o=s.findField(a.case)?{case:a.case,value:Xn(a.value)}:{case:void 0}:o=Xn(a);n[s.localName]=o}for(let s of e.runtime.bin.listUnknownFields(i))e.runtime.bin.onUnknownField(n,s.no,s.wireType,s.data);return t}}}function Xn(i){if(i===void 0)return i;if(dt(i))return i.clone();if(i instanceof Uint8Array){let e=new Uint8Array(i.byteLength);return e.set(i),e}return i}function pn(i){return i instanceof Uint8Array?i:new Uint8Array(i)}function Su(i,e,t){return{syntax:i,json:uu(),bin:gu(),util:Object.assign(Object.assign({},Tu()),{newFieldList:e,initFields:t}),makeMessageType(n,r,s){return Wl(this,n,r,s)},makeEnum:Kl,makeEnumType:fc,getEnumType:Gl,makeExtension(n,r,s){return ru(this,n,r,s)}}}var Vr=class{constructor(e,t){this._fields=e,this._normalizer=t}findJsonName(e){if(!this.jsonNames){let t={};for(let n of this.list())t[n.jsonName]=t[n.name]=n;this.jsonNames=t}return this.jsonNames[e]}find(e){if(!this.numbers){let t={};for(let n of this.list())t[n.no]=n;this.numbers=t}return this.numbers[e]}list(){return this.all||(this.all=this._normalizer(this._fields)),this.all}byNumber(){return this.numbersAsc||(this.numbersAsc=this.list().concat().sort((e,t)=>e.no-t.no)),this.numbersAsc}byMember(){if(!this.members){this.members=[];let e=this.members,t;for(let n of this.list())n.oneof?n.oneof!==t&&(t=n.oneof,e.push(t)):e.push(n)}return this.members}};function Rc(i,e){let t=Pc(i);return e?t:Pu(Ru(t))}function Cu(i){return Rc(i,!1)}var _u=Pc;function Pc(i){let e=!1,t=[];for(let n=0;n<i.length;n++){let r=i.charAt(n);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("")}var wu=new Set(["constructor","toString","toJSON","valueOf"]),Eu=new Set(["getType","clone","equals","fromBinary","fromJson","fromJsonString","toBinary","toJson","toJsonString","toObject"]),Ic=i=>"".concat(i,"$"),Ru=i=>Eu.has(i)?Ic(i):i,Pu=i=>wu.has(i)?Ic(i):i,Hr=class{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=Cu(e)}addField(e){ne(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 Iu(i,e){var t,n,r,s,a,o;let d=[],c;for(let l of typeof i=="function"?i():i){let u=l;if(u.localName=Rc(l.name,l.oneof!==void 0),u.jsonName=(t=l.jsonName)!==null&&t!==void 0?t:_u(l.name),u.repeated=(n=l.repeated)!==null&&n!==void 0?n:!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!=w.BYTES&&l.T!=w.STRING),l.oneof!==void 0){let h=typeof l.oneof=="string"?l.oneof:l.oneof.name;(!c||c.name!=h)&&(c=new Hr(h)),u.oneof=c,c.addField(u)}d.push(u)}return d}var v=Su("proto3",i=>new Vr(i,e=>Iu(e)),i=>{for(let e of i.getType().fields.byMember()){if(e.opt)continue;let t=e.localName,n=i;if(e.repeated){n[t]=[];continue}switch(e.kind){case"oneof":n[t]={case:void 0};break;case"enum":n[t]=0;break;case"map":n[t]={};break;case"scalar":n[t]=tn(e.T,e.L);break}}}),ut=class i extends In{constructor(e){super(),this.seconds=Y.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)));let n=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(!n)throw new Error("cannot decode google.protobuf.Timestamp from JSON: invalid RFC 3339 string");let r=Date.parse(n[1]+"-"+n[2]+"-"+n[3]+"T"+n[4]+":"+n[5]+":"+n[6]+(n[8]?n[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=Y.parse(r/1e3),this.nanos=0,n[7]&&(this.nanos=parseInt("1"+n[7]+"0".repeat(9-n[7].length))-1e9),this}toJson(e){let 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 n="Z";if(this.nanos>0){let r=(this.nanos+1e9).toString().substring(1);r.substring(3)==="000000"?n="."+r.substring(0,3)+"Z":r.substring(6)==="000"?n="."+r.substring(0,6)+"Z":n="."+r+"Z"}return new Date(t).toISOString().replace(".000Z",n)}toDate(){return new Date(Number(this.seconds)*1e3+Math.ceil(this.nanos/1e6))}static now(){return i.fromDate(new Date)}static fromDate(e){let t=e.getTime();return new i({seconds:Y.parse(Math.floor(t/1e3)),nanos:t%1e3*1e6})}static fromBinary(e,t){return new i().fromBinary(e,t)}static fromJson(e,t){return new i().fromJson(e,t)}static fromJsonString(e,t){return new i().fromJsonString(e,t)}static equals(e,t){return v.util.equals(i,e,t)}};ut.runtime=v;ut.typeName="google.protobuf.Timestamp";ut.fields=v.util.newFieldList(()=>[{no:1,name:"seconds",kind:"scalar",T:3},{no:2,name:"nanos",kind:"scalar",T:5}]);var Mu=v.makeMessageType("livekit.MetricsBatch",()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:ut},{no:3,name:"str_data",kind:"scalar",T:9,repeated:!0},{no:4,name:"time_series",kind:"message",T:Au,repeated:!0},{no:5,name:"events",kind:"message",T:Du,repeated:!0}]),Au=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:xu,repeated:!0},{no:5,name:"rid",kind:"scalar",T:13}]),xu=v.makeMessageType("livekit.MetricSample",()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:ut},{no:3,name:"value",kind:"scalar",T:2}]),Du=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:ut},{no:7,name:"normalized_end_timestamp",kind:"message",T:ut,opt:!0},{no:8,name:"metadata",kind:"scalar",T:9},{no:9,name:"rid",kind:"scalar",T:13}]);var Mc=v.makeEnum("livekit.BackupCodecPolicy",[{no:0,name:"PREFER_REGRESSION"},{no:1,name:"SIMULCAST"},{no:2,name:"REGRESSION"}]),Ue=v.makeEnum("livekit.TrackType",[{no:0,name:"AUDIO"},{no:1,name:"VIDEO"},{no:2,name:"DATA"}]),ae=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"}]),fa=v.makeEnum("livekit.VideoQuality",[{no:0,name:"LOW"},{no:1,name:"MEDIUM"},{no:2,name:"HIGH"},{no:3,name:"OFF"}]),kn=v.makeEnum("livekit.ConnectionQuality",[{no:0,name:"POOR"},{no:1,name:"GOOD"},{no:2,name:"EXCELLENT"},{no:3,name:"LOST"}]),Mn=v.makeEnum("livekit.ClientConfigSetting",[{no:0,name:"UNSET"},{no:1,name:"DISABLED"},{no:2,name:"ENABLED"}]),oe=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"}]),Rt=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"}]),Ou=v.makeEnum("livekit.SubscriptionError",[{no:0,name:"SE_UNKNOWN"},{no:1,name:"SE_CODEC_UNSUPPORTED"},{no:2,name:"SE_TRACK_NOTFOUND"}]),le=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"}]),nn=v.makeEnum("livekit.PacketTrailerFeature",[{no:0,name:"PTF_USER_TIMESTAMP"},{no:1,name:"PTF_FRAME_ID"}]),Xi=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:vi,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:Gc}]),vi=v.makeMessageType("livekit.Codec",()=>[{no:1,name:"mime",kind:"scalar",T:9},{no:2,name:"fmtp_line",kind:"scalar",T:9}]),Lu=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(ae),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}]),Ut=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(Jt)},{no:4,name:"tracks",kind:"message",T:Wt,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:Lu},{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(An)},{no:15,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:16,name:"disconnect_reason",kind:"enum",T:v.getEnumType(oe)},{no:18,name:"kind_details",kind:"enum",T:v.getEnumType(Nu),repeated:!0},{no:19,name:"data_tracks",kind:"message",T:Zi,repeated:!0},{no:20,name:"client_protocol",kind:"scalar",T:5}]),Jt=v.makeEnum("livekit.ParticipantInfo.State",[{no:0,name:"JOINING"},{no:1,name:"JOINED"},{no:2,name:"ACTIVE"},{no:3,name:"DISCONNECTED"}]),An=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"}]),Nu=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"}]),J=v.makeEnum("livekit.Encryption.Type",[{no:0,name:"NONE"},{no:1,name:"GCM"},{no:2,name:"CUSTOM"}]),Uu=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:Tt,repeated:!0},{no:5,name:"video_layer_mode",kind:"enum",T:v.getEnumType(Ac)},{no:6,name:"sdp_cid",kind:"scalar",T:9}]),Wt=v.makeMessageType("livekit.TrackInfo",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"type",kind:"enum",T:v.getEnumType(Ue)},{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(ae)},{no:10,name:"layers",kind:"message",T:Tt,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:Uu,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(J)},{no:17,name:"stream",kind:"scalar",T:9},{no:18,name:"version",kind:"message",T:Gc},{no:19,name:"audio_features",kind:"enum",T:v.getEnumType(le),repeated:!0},{no:20,name:"backup_codec_policy",kind:"enum",T:v.getEnumType(Mc)},{no:21,name:"packet_trailer_features",kind:"enum",T:v.getEnumType(nn),repeated:!0}]),Zi=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(J)}]),Fu=v.makeMessageType("livekit.DataTrackSubscriptionOptions",()=>[{no:1,name:"target_fps",kind:"scalar",T:13,opt:!0}]),Tt=v.makeMessageType("livekit.VideoLayer",()=>[{no:1,name:"quality",kind:"enum",T:v.getEnumType(fa)},{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}]),Ac=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"}]),ge=v.makeMessageType("livekit.DataPacket",()=>[{no:1,name:"kind",kind:"enum",T:v.getEnumType(Ze)},{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:ga,oneof:"value"},{no:3,name:"speaker",kind:"message",T:Bu,oneof:"value"},{no:6,name:"sip_dtmf",kind:"message",T:Lc,oneof:"value"},{no:7,name:"transcription",kind:"message",T:qu,oneof:"value"},{no:8,name:"metrics",kind:"message",T:Mu,oneof:"value"},{no:9,name:"chat_message",kind:"message",T:yi,oneof:"value"},{no:10,name:"rpc_request",kind:"message",T:va,oneof:"value"},{no:11,name:"rpc_ack",kind:"message",T:er,oneof:"value"},{no:12,name:"rpc_response",kind:"message",T:ya,oneof:"value"},{no:13,name:"stream_header",kind:"message",T:bi,oneof:"value"},{no:14,name:"stream_chunk",kind:"message",T:ki,oneof:"value"},{no:15,name:"stream_trailer",kind:"message",T:Ti,oneof:"value"},{no:18,name:"encrypted_packet",kind:"message",T:xc,oneof:"value"},{no:16,name:"sequence",kind:"scalar",T:13},{no:17,name:"participant_sid",kind:"scalar",T:9}]),Ze=v.makeEnum("livekit.DataPacket.Kind",[{no:0,name:"RELIABLE"},{no:1,name:"LOSSY"}]),xc=v.makeMessageType("livekit.EncryptedPacket",()=>[{no:1,name:"encryption_type",kind:"enum",T:v.getEnumType(J)},{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}]),Dc=v.makeMessageType("livekit.EncryptedPacketPayload",()=>[{no:1,name:"user",kind:"message",T:ga,oneof:"value"},{no:3,name:"chat_message",kind:"message",T:yi,oneof:"value"},{no:4,name:"rpc_request",kind:"message",T:va,oneof:"value"},{no:5,name:"rpc_ack",kind:"message",T:er,oneof:"value"},{no:6,name:"rpc_response",kind:"message",T:ya,oneof:"value"},{no:7,name:"stream_header",kind:"message",T:bi,oneof:"value"},{no:8,name:"stream_chunk",kind:"message",T:ki,oneof:"value"},{no:9,name:"stream_trailer",kind:"message",T:Ti,oneof:"value"}]),Bu=v.makeMessageType("livekit.ActiveSpeakerUpdate",()=>[{no:1,name:"speakers",kind:"message",T:Oc,repeated:!0}]),Oc=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}]),ga=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}]),Lc=v.makeMessageType("livekit.SipDTMF",()=>[{no:3,name:"code",kind:"scalar",T:13},{no:4,name:"digit",kind:"scalar",T:9}]),qu=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:ju,repeated:!0}]),ju=v.makeMessageType("livekit.TranscriptionSegment",()=>[{no:1,name:"id",kind:"scalar",T:9},{no:2,name:"text",kind:"scalar",T:9},{no:3,name:"start_time",kind:"scalar",T:4},{no:4,name:"end_time",kind:"scalar",T:4},{no:5,name:"final",kind:"scalar",T:8},{no:6,name:"language",kind:"scalar",T:9}]),yi=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}]),va=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}]),er=v.makeMessageType("livekit.RpcAck",()=>[{no:1,name:"request_id",kind:"scalar",T:9}]),ya=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:Nc,oneof:"value"},{no:4,name:"compressed_payload",kind:"scalar",T:12,oneof:"value"}]),Nc=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}]),Uc=v.makeMessageType("livekit.ParticipantTracks",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"track_sids",kind:"scalar",T:9,repeated:!0}]),Fc=v.makeMessageType("livekit.ServerInfo",()=>[{no:1,name:"edition",kind:"enum",T:v.getEnumType(Bc)},{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}]),Bc=v.makeEnum("livekit.ServerInfo.Edition",[{no:0,name:"Standard"},{no:1,name:"Cloud"}]),qc=v.makeMessageType("livekit.ClientInfo",()=>[{no:1,name:"sdk",kind:"enum",T:v.getEnumType(jc)},{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(Vc),repeated:!0}]),jc=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"}]),Vc=v.makeEnum("livekit.ClientInfo.Capability",[{no:0,name:"CAP_UNUSED"},{no:1,name:"CAP_PACKET_TRAILER"}]),Hc=v.makeMessageType("livekit.ClientConfiguration",()=>[{no:1,name:"video",kind:"message",T:ho},{no:2,name:"screen",kind:"message",T:ho},{no:3,name:"resume_connection",kind:"enum",T:v.getEnumType(Mn)},{no:4,name:"disabled_codecs",kind:"message",T:Vu},{no:5,name:"force_relay",kind:"enum",T:v.getEnumType(Mn)}]),ho=v.makeMessageType("livekit.VideoConfiguration",()=>[{no:1,name:"hardware_encoder",kind:"enum",T:v.getEnumType(Mn)}]),Vu=v.makeMessageType("livekit.DisabledCodecs",()=>[{no:1,name:"codecs",kind:"message",T:vi,repeated:!0},{no:2,name:"publish",kind:"message",T:vi,repeated:!0}]),Gc=v.makeMessageType("livekit.TimedVersion",()=>[{no:1,name:"unix_micro",kind:"scalar",T:3},{no:2,name:"ticks",kind:"scalar",T:5}]),Gr=v.makeEnum("livekit.DataStream.OperationType",[{no:0,name:"CREATE"},{no:1,name:"UPDATE"},{no:2,name:"DELETE"},{no:3,name:"REACTION"}]),Kc=v.makeMessageType("livekit.DataStream.TextHeader",()=>[{no:1,name:"operation_type",kind:"enum",T:v.getEnumType(Gr)},{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"}),Wc=v.makeMessageType("livekit.DataStream.ByteHeader",()=>[{no:1,name:"name",kind:"scalar",T:9}],{localName:"DataStream_ByteHeader"}),bi=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(J)},{no:8,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:9,name:"text_header",kind:"message",T:Kc,oneof:"content_header"},{no:10,name:"byte_header",kind:"message",T:Wc,oneof:"content_header"}],{localName:"DataStream_Header"}),ki=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"}),Ti=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"});var Hu=v.makeMessageType("livekit.SubscribedAudioCodec",()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"enabled",kind:"scalar",T:8}]);var Fe=v.makeEnum("livekit.SignalTarget",[{no:0,name:"PUBLISHER"},{no:1,name:"SUBSCRIBER"}]),Kr=v.makeEnum("livekit.StreamState",[{no:0,name:"ACTIVE"},{no:1,name:"PAUSED"}]),Gu=v.makeEnum("livekit.CandidateProtocol",[{no:0,name:"UDP"},{no:1,name:"TCP"},{no:2,name:"TLS"}]),Ku=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:tr,oneof:"message"},{no:4,name:"add_track",kind:"message",T:xn,oneof:"message"},{no:5,name:"mute",kind:"message",T:nr,oneof:"message"},{no:6,name:"subscription",kind:"message",T:ir,oneof:"message"},{no:7,name:"track_setting",kind:"message",T:$c,oneof:"message"},{no:8,name:"leave",kind:"message",T:rr,oneof:"message"},{no:10,name:"update_layers",kind:"message",T:Yc,oneof:"message"},{no:11,name:"subscription_permission",kind:"message",T:ed,oneof:"message"},{no:12,name:"sync_state",kind:"message",T:Ea,oneof:"message"},{no:13,name:"simulate",kind:"message",T:Qe,oneof:"message"},{no:14,name:"ping",kind:"scalar",T:3,oneof:"message"},{no:15,name:"update_metadata",kind:"message",T:_a,oneof:"message"},{no:16,name:"ping_req",kind:"message",T:id,oneof:"message"},{no:17,name:"update_audio_track",kind:"message",T:Ca,oneof:"message"},{no:18,name:"update_video_track",kind:"message",T:Qc,oneof:"message"},{no:19,name:"publish_data_track_request",kind:"message",T:ba,oneof:"message"},{no:20,name:"unpublish_data_track_request",kind:"message",T:Ta,oneof:"message"},{no:21,name:"update_data_subscription",kind:"message",T:zc,oneof:"message"}]),mo=v.makeMessageType("livekit.SignalResponse",()=>[{no:1,name:"join",kind:"message",T:$u,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:tr,oneof:"message"},{no:5,name:"update",kind:"message",T:Xu,oneof:"message"},{no:6,name:"track_published",kind:"message",T:Sa,oneof:"message"},{no:8,name:"leave",kind:"message",T:rr,oneof:"message"},{no:9,name:"mute",kind:"message",T:nr,oneof:"message"},{no:10,name:"speakers_changed",kind:"message",T:Zu,oneof:"message"},{no:11,name:"room_update",kind:"message",T:eh,oneof:"message"},{no:12,name:"connection_quality",kind:"message",T:nh,oneof:"message"},{no:13,name:"stream_state_update",kind:"message",T:rh,oneof:"message"},{no:14,name:"subscribed_quality_update",kind:"message",T:ah,oneof:"message"},{no:15,name:"subscription_permission_update",kind:"message",T:ch,oneof:"message"},{no:16,name:"refresh_token",kind:"scalar",T:9,oneof:"message"},{no:17,name:"track_unpublished",kind:"message",T:Yu,oneof:"message"},{no:18,name:"pong",kind:"scalar",T:3,oneof:"message"},{no:19,name:"reconnect",kind:"message",T:Qu,oneof:"message"},{no:20,name:"pong_resp",kind:"message",T:lh,oneof:"message"},{no:21,name:"subscription_response",kind:"message",T:mh,oneof:"message"},{no:22,name:"request_response",kind:"message",T:ph,oneof:"message"},{no:23,name:"track_subscribed",kind:"message",T:fh,oneof:"message"},{no:24,name:"room_moved",kind:"message",T:dh,oneof:"message"},{no:25,name:"media_sections_requirement",kind:"message",T:yh,oneof:"message"},{no:26,name:"subscribed_audio_codec_update",kind:"message",T:oh,oneof:"message"},{no:27,name:"publish_data_track_response",kind:"message",T:ka,oneof:"message"},{no:28,name:"unpublish_data_track_response",kind:"message",T:Wu,oneof:"message"},{no:29,name:"data_track_subscriber_handles",kind:"message",T:zu,oneof:"message"}]),Wr=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:Tt,repeated:!0},{no:5,name:"video_layer_mode",kind:"enum",T:v.getEnumType(Ac)}]),xn=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(Ue)},{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(ae)},{no:9,name:"layers",kind:"message",T:Tt,repeated:!0},{no:10,name:"simulcast_codecs",kind:"message",T:Wr,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(J)},{no:15,name:"stream",kind:"scalar",T:9},{no:16,name:"backup_codec_policy",kind:"enum",T:v.getEnumType(Mc)},{no:17,name:"audio_features",kind:"enum",T:v.getEnumType(le),repeated:!0},{no:18,name:"packet_trailer_features",kind:"enum",T:v.getEnumType(nn),repeated:!0}]),ba=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(J)}]),ka=v.makeMessageType("livekit.PublishDataTrackResponse",()=>[{no:1,name:"info",kind:"message",T:Zi}]),Ta=v.makeMessageType("livekit.UnpublishDataTrackRequest",()=>[{no:1,name:"pub_handle",kind:"scalar",T:13}]),Wu=v.makeMessageType("livekit.UnpublishDataTrackResponse",()=>[{no:1,name:"info",kind:"message",T:Zi}]),zu=v.makeMessageType("livekit.DataTrackSubscriberHandles",()=>[{no:1,name:"sub_handles",kind:"map",K:13,V:{kind:"message",T:Ju}}]),Ju=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"}),tr=v.makeMessageType("livekit.TrickleRequest",()=>[{no:1,name:"candidateInit",kind:"scalar",T:9},{no:2,name:"target",kind:"enum",T:v.getEnumType(Fe)},{no:3,name:"final",kind:"scalar",T:8}]),nr=v.makeMessageType("livekit.MuteTrackRequest",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"muted",kind:"scalar",T:8}]),$u=v.makeMessageType("livekit.JoinResponse",()=>[{no:1,name:"room",kind:"message",T:Xi},{no:2,name:"participant",kind:"message",T:Ut},{no:3,name:"other_participants",kind:"message",T:Ut,repeated:!0},{no:4,name:"server_version",kind:"scalar",T:9},{no:5,name:"ice_servers",kind:"message",T:Xc,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:Hc},{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:Fc},{no:13,name:"sif_trailer",kind:"scalar",T:12},{no:14,name:"enabled_publish_codecs",kind:"message",T:vi,repeated:!0},{no:15,name:"fast_publish",kind:"scalar",T:8}]),Qu=v.makeMessageType("livekit.ReconnectResponse",()=>[{no:1,name:"ice_servers",kind:"message",T:Xc,repeated:!0},{no:2,name:"client_configuration",kind:"message",T:Hc},{no:3,name:"server_info",kind:"message",T:Fc},{no:4,name:"last_message_seq",kind:"scalar",T:13}]),Sa=v.makeMessageType("livekit.TrackPublishedResponse",()=>[{no:1,name:"cid",kind:"scalar",T:9},{no:2,name:"track",kind:"message",T:Wt}]),Yu=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}}]),Xu=v.makeMessageType("livekit.ParticipantUpdate",()=>[{no:1,name:"participants",kind:"message",T:Ut,repeated:!0}]),ir=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:Uc,repeated:!0}]),zc=v.makeMessageType("livekit.UpdateDataSubscription",()=>[{no:1,name:"updates",kind:"message",T:Jc,repeated:!0}]),Jc=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:Fu}],{localName:"UpdateDataSubscription_Update"}),$c=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(fa)},{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}]),Ca=v.makeMessageType("livekit.UpdateLocalAudioTrack",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"features",kind:"enum",T:v.getEnumType(le),repeated:!0}]),Qc=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}]),rr=v.makeMessageType("livekit.LeaveRequest",()=>[{no:1,name:"can_reconnect",kind:"scalar",T:8},{no:2,name:"reason",kind:"enum",T:v.getEnumType(oe)},{no:3,name:"action",kind:"enum",T:v.getEnumType($t)},{no:4,name:"regions",kind:"message",T:uh}]),$t=v.makeEnum("livekit.LeaveRequest.Action",[{no:0,name:"DISCONNECT"},{no:1,name:"RESUME"},{no:2,name:"RECONNECT"}]),Yc=v.makeMessageType("livekit.UpdateVideoLayers",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"layers",kind:"message",T:Tt,repeated:!0}]),_a=v.makeMessageType("livekit.UpdateParticipantMetadata",()=>[{no:1,name:"metadata",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",T:9},{no:3,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:4,name:"request_id",kind:"scalar",T:13}]),Xc=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}]),Zu=v.makeMessageType("livekit.SpeakersChanged",()=>[{no:1,name:"speakers",kind:"message",T:Oc,repeated:!0}]),eh=v.makeMessageType("livekit.RoomUpdate",()=>[{no:1,name:"room",kind:"message",T:Xi}]),th=v.makeMessageType("livekit.ConnectionQualityInfo",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"quality",kind:"enum",T:v.getEnumType(kn)},{no:3,name:"score",kind:"scalar",T:2}]),nh=v.makeMessageType("livekit.ConnectionQualityUpdate",()=>[{no:1,name:"updates",kind:"message",T:th,repeated:!0}]),ih=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(Kr)}]),rh=v.makeMessageType("livekit.StreamStateUpdate",()=>[{no:1,name:"stream_states",kind:"message",T:ih,repeated:!0}]),wa=v.makeMessageType("livekit.SubscribedQuality",()=>[{no:1,name:"quality",kind:"enum",T:v.getEnumType(fa)},{no:2,name:"enabled",kind:"scalar",T:8}]),sh=v.makeMessageType("livekit.SubscribedCodec",()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"qualities",kind:"message",T:wa,repeated:!0}]),ah=v.makeMessageType("livekit.SubscribedQualityUpdate",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribed_qualities",kind:"message",T:wa,repeated:!0},{no:3,name:"subscribed_codecs",kind:"message",T:sh,repeated:!0}]),oh=v.makeMessageType("livekit.SubscribedAudioCodecUpdate",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribed_audio_codecs",kind:"message",T:Hu,repeated:!0}]),Zc=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}]),ed=v.makeMessageType("livekit.SubscriptionPermission",()=>[{no:1,name:"all_participants",kind:"scalar",T:8},{no:2,name:"track_permissions",kind:"message",T:Zc,repeated:!0}]),ch=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}]),dh=v.makeMessageType("livekit.RoomMovedResponse",()=>[{no:1,name:"room",kind:"message",T:Xi},{no:2,name:"token",kind:"scalar",T:9},{no:3,name:"participant",kind:"message",T:Ut},{no:4,name:"other_participants",kind:"message",T:Ut,repeated:!0}]),Ea=v.makeMessageType("livekit.SyncState",()=>[{no:1,name:"answer",kind:"message",T:wt},{no:2,name:"subscription",kind:"message",T:ir},{no:3,name:"publish_tracks",kind:"message",T:Sa,repeated:!0},{no:4,name:"data_channels",kind:"message",T:nd,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:td,repeated:!0},{no:8,name:"publish_data_tracks",kind:"message",T:ka,repeated:!0}]),td=v.makeMessageType("livekit.DataChannelReceiveState",()=>[{no:1,name:"publisher_sid",kind:"scalar",T:9},{no:2,name:"last_seq",kind:"scalar",T:13}]),nd=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(Fe)}]),Qe=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(Gu),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"}]),id=v.makeMessageType("livekit.Ping",()=>[{no:1,name:"timestamp",kind:"scalar",T:3},{no:2,name:"rtt",kind:"scalar",T:3}]),lh=v.makeMessageType("livekit.Pong",()=>[{no:1,name:"last_ping_timestamp",kind:"scalar",T:3},{no:2,name:"timestamp",kind:"scalar",T:3}]),uh=v.makeMessageType("livekit.RegionSettings",()=>[{no:1,name:"regions",kind:"message",T:hh,repeated:!0}]),hh=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}]),mh=v.makeMessageType("livekit.SubscriptionResponse",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"err",kind:"enum",T:v.getEnumType(Ou)}]),ph=v.makeMessageType("livekit.RequestResponse",()=>[{no:1,name:"request_id",kind:"scalar",T:13},{no:2,name:"reason",kind:"enum",T:v.getEnumType(It)},{no:3,name:"message",kind:"scalar",T:9},{no:4,name:"trickle",kind:"message",T:tr,oneof:"request"},{no:5,name:"add_track",kind:"message",T:xn,oneof:"request"},{no:6,name:"mute",kind:"message",T:nr,oneof:"request"},{no:7,name:"update_metadata",kind:"message",T:_a,oneof:"request"},{no:8,name:"update_audio_track",kind:"message",T:Ca,oneof:"request"},{no:9,name:"update_video_track",kind:"message",T:Qc,oneof:"request"},{no:10,name:"publish_data_track",kind:"message",T:ba,oneof:"request"},{no:11,name:"unpublish_data_track",kind:"message",T:Ta,oneof:"request"}]),It=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"},{no:8,name:"INVALID_NAME"},{no:9,name:"DUPLICATE_HANDLE"},{no:10,name:"DUPLICATE_NAME"}]),fh=v.makeMessageType("livekit.TrackSubscribed",()=>[{no:1,name:"track_sid",kind:"scalar",T:9}]),rd=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}]),gh=v.makeMessageType("livekit.JoinRequest",()=>[{no:1,name:"client_info",kind:"message",T:qc},{no:2,name:"connection_settings",kind:"message",T:rd},{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:xn,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(Rt)},{no:9,name:"participant_sid",kind:"scalar",T:9},{no:10,name:"sync_state",kind:"message",T:Ea}]),vh=v.makeMessageType("livekit.WrappedJoinRequest",()=>[{no:1,name:"compression",kind:"enum",T:v.getEnumType(zr)},{no:2,name:"join_request",kind:"scalar",T:12}]),zr=v.makeEnum("livekit.WrappedJoinRequest.Compression",[{no:0,name:"NONE"},{no:1,name:"GZIP"}]),yh=v.makeMessageType("livekit.MediaSectionsRequirement",()=>[{no:1,name:"num_audios",kind:"scalar",T:13},{no:2,name:"num_videos",kind:"scalar",T:13}]);function bh(i){return i&&i.__esModule&&Object.prototype.hasOwnProperty.call(i,"default")?i.default:i}var oi={exports:{}},kh=oi.exports,po;function Th(){return po||(po=1,(function(i){(function(e,t){i.exports?i.exports=t():e.log=t()})(kh,function(){var e=function(){},t="undefined",n=typeof window!==t&&typeof window.navigator!==t&&/Trident\/|MSIE /.test(window.navigator.userAgent),r=["trace","debug","info","warn","error"],s={},a=null;function o(f,T){var k=f[T];if(typeof k.bind=="function")return k.bind(f);try{return Function.prototype.bind.call(k,f)}catch{return function(){return Function.prototype.apply.apply(k,[f,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(f){return f==="debug"&&(f="log"),typeof console===t?!1:f==="trace"&&n?d:console[f]!==void 0?o(console,f):console.log!==void 0?o(console,"log"):e}function l(){for(var f=this.getLevel(),T=0;T<r.length;T++){var k=r[T];this[k]=T<f?e:this.methodFactory(k,f,this.name)}if(this.log=this.debug,typeof console===t&&f<this.levels.SILENT)return"No console available for logging"}function u(f){return function(){typeof console!==t&&(l.call(this),this[f].apply(this,arguments))}}function h(f,T,k){return c(f)||u.apply(this,arguments)}function m(f,T){var k=this,S,L,y,b="loglevel";typeof f=="string"?b+=":"+f:typeof f=="symbol"&&(b=void 0);function E(x){var B=(r[x]||"silent").toUpperCase();if(!(typeof window===t||!b)){try{window.localStorage[b]=B;return}catch{}try{window.document.cookie=encodeURIComponent(b)+"="+B+";"}catch{}}}function M(){var x;if(!(typeof window===t||!b)){try{x=window.localStorage[b]}catch{}if(typeof x===t)try{var B=window.document.cookie,Z=encodeURIComponent(b),ee=B.indexOf(Z+"=");ee!==-1&&(x=/^([^;]+)/.exec(B.slice(ee+Z.length+1))[1])}catch{}return k.levels[x]===void 0&&(x=void 0),x}}function D(){if(!(typeof window===t||!b)){try{window.localStorage.removeItem(b)}catch{}try{window.document.cookie=encodeURIComponent(b)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}function q(x){var B=x;if(typeof B=="string"&&k.levels[B.toUpperCase()]!==void 0&&(B=k.levels[B.toUpperCase()]),typeof B=="number"&&B>=0&&B<=k.levels.SILENT)return B;throw new TypeError("log.setLevel() called with invalid level: "+x)}k.name=f,k.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},k.methodFactory=T||h,k.getLevel=function(){return y??L??S},k.setLevel=function(x,B){return y=q(x),B!==!1&&E(y),l.call(k)},k.setDefaultLevel=function(x){L=q(x),M()||k.setLevel(x,!1)},k.resetLevel=function(){y=null,D(),l.call(k)},k.enableAll=function(x){k.setLevel(k.levels.TRACE,x)},k.disableAll=function(x){k.setLevel(k.levels.SILENT,x)},k.rebuild=function(){if(a!==k&&(S=q(a.getLevel())),l.call(k),a===k)for(var x in s)s[x].rebuild()},S=q(a?a.getLevel():"WARN");var A=M();A!=null&&(y=q(A)),l.call(k)}a=new m,a.getLogger=function(T){if(typeof T!="symbol"&&typeof T!="string"||T==="")throw new TypeError("You must supply a name when creating a logger.");var k=s[T];return k||(k=s[T]=new m(T,a.methodFactory)),k};var g=typeof window!==t?window.log:void 0;return a.noConflict=function(){return typeof window!==t&&window.log===a&&(window.log=g),a},a.getLoggers=function(){return s},a.default=a,a})})(oi)),oi.exports}var sr=Th(),Jr;(function(i){i[i.trace=0]="trace",i[i.debug=1]="debug",i[i.info=2]="info",i[i.warn=3]="warn",i[i.error=4]="error",i[i.silent=5]="silent"})(Jr||(Jr={}));var ue;(function(i){i.Default="livekit",i.Room="livekit-room",i.TokenSource="livekit-token-source",i.Participant="livekit-participant",i.Track="livekit-track",i.Publication="livekit-track-publication",i.Engine="livekit-engine",i.Signal="livekit-signal",i.PCManager="livekit-pc-manager",i.PCTransport="livekit-pc-transport",i.E2EE="lk-e2ee",i.DataTracks="livekit-data-tracks"})(ue||(ue={}));var F=sr.getLogger(ue.Default),lf=Object.values(ue).map(i=>sr.getLogger(i));F.setDefaultLevel(Jr.info);function _e(i,e){let t=sr.getLogger(i);return t.setDefaultLevel(F.getLevel()),e?Sh(t,e):t}function Sh(i,e){let t=r=>(s,a)=>{let o=e(),d=o||a?Object.assign(Object.assign({},o),a):void 0;i[r](s,d)},n=Object.create(i);return n.trace=t("trace"),n.debug=t("debug"),n.info=t("info"),n.warn=t("warn"),n.error=t("error"),n}var Ch=sr.getLogger(ue.E2EE),fn=7e3,_h=[0,300,4*300,9*300,16*300,fn,fn,fn,fn,fn],$r=class{constructor(e){this._retryDelays=e!==void 0?[...e]:_h}nextRetryDelayInMs(e){if(e.retryCount>=this._retryDelays.length)return null;let t=this._retryDelays[e.retryCount];return e.retryCount<=1?t:t+Math.random()*1e3}};function wh(i,e){var t={};for(var n in i)Object.prototype.hasOwnProperty.call(i,n)&&e.indexOf(n)<0&&(t[n]=i[n]);if(i!=null&&typeof Object.getOwnPropertySymbols=="function")for(var r=0,n=Object.getOwnPropertySymbols(i);r<n.length;r++)e.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(i,n[r])&&(t[n[r]]=i[n[r]]);return t}function p(i,e,t,n){function r(s){return s instanceof t?s:new t(function(a){a(s)})}return new(t||(t=Promise))(function(s,a){function o(l){try{c(n.next(l))}catch(u){a(u)}}function d(l){try{c(n.throw(l))}catch(u){a(u)}}function c(l){l.done?s(l.value):r(l.value).then(o,d)}c((n=n.apply(i,e||[])).next())})}function fo(i){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&i[e],n=0;if(t)return t.call(i);if(i&&typeof i.length=="number")return{next:function(){return i&&n>=i.length&&(i=void 0),{value:i&&i[n++],done:!i}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function rn(i){return this instanceof rn?(this.v=i,this):new rn(i)}function Eh(i,e,t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n=t.apply(i,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(m){return function(g){return Promise.resolve(g).then(m,u)}}function o(m,g){n[m]&&(r[m]=function(f){return new Promise(function(T,k){s.push([m,f,T,k])>1||d(m,f)})},g&&(r[m]=g(r[m])))}function d(m,g){try{c(n[m](g))}catch(f){h(s[0][3],f)}}function c(m){m.value instanceof rn?Promise.resolve(m.value.v).then(l,u):h(s[0][2],m)}function l(m){d("next",m)}function u(m){d("throw",m)}function h(m,g){m(g),s.shift(),s.length&&d(s[0][0],s[0][1])}}function Rh(i){var e,t;return e={},n("next"),n("throw",function(r){throw r}),n("return"),e[Symbol.iterator]=function(){return this},e;function n(r,s){e[r]=i[r]?function(a){return(t=!t)?{value:rn(i[r](a)),done:!1}:s?s(a):a}:s}}function Be(i){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=i[Symbol.asyncIterator],t;return e?e.call(i):(i=typeof fo=="function"?fo(i):i[Symbol.iterator](),t={},n("next"),n("throw"),n("return"),t[Symbol.asyncIterator]=function(){return this},t);function n(s){t[s]=i[s]&&function(a){return new Promise(function(o,d){a=i[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 Zn={exports:{}},go;function Ph(){if(go)return Zn.exports;go=1;var i=typeof Reflect=="object"?Reflect:null,e=i&&typeof i.apply=="function"?i.apply:function(b,E,M){return Function.prototype.apply.call(b,E,M)},t;i&&typeof i.ownKeys=="function"?t=i.ownKeys:Object.getOwnPropertySymbols?t=function(b){return Object.getOwnPropertyNames(b).concat(Object.getOwnPropertySymbols(b))}:t=function(b){return Object.getOwnPropertyNames(b)};function n(y){console&&console.warn&&console.warn(y)}var r=Number.isNaN||function(b){return b!==b};function s(){s.init.call(this)}Zn.exports=s,Zn.exports.once=k,s.EventEmitter=s,s.prototype._events=void 0,s.prototype._eventsCount=0,s.prototype._maxListeners=void 0;var a=10;function o(y){if(typeof y!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof y)}Object.defineProperty(s,"defaultMaxListeners",{enumerable:!0,get:function(){return a},set:function(y){if(typeof y!="number"||y<0||r(y))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+y+".");a=y}}),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(b){if(typeof b!="number"||b<0||r(b))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+b+".");return this._maxListeners=b,this};function d(y){return y._maxListeners===void 0?s.defaultMaxListeners:y._maxListeners}s.prototype.getMaxListeners=function(){return d(this)},s.prototype.emit=function(b){for(var E=[],M=1;M<arguments.length;M++)E.push(arguments[M]);var D=b==="error",q=this._events;if(q!==void 0)D=D&&q.error===void 0;else if(!D)return!1;if(D){var A;if(E.length>0&&(A=E[0]),A instanceof Error)throw A;var x=new Error("Unhandled error."+(A?" ("+A.message+")":""));throw x.context=A,x}var B=q[b];if(B===void 0)return!1;if(typeof B=="function")e(B,this,E);else for(var Z=B.length,ee=g(B,Z),M=0;M<Z;++M)e(ee[M],this,E);return!0};function c(y,b,E,M){var D,q,A;if(o(E),q=y._events,q===void 0?(q=y._events=Object.create(null),y._eventsCount=0):(q.newListener!==void 0&&(y.emit("newListener",b,E.listener?E.listener:E),q=y._events),A=q[b]),A===void 0)A=q[b]=E,++y._eventsCount;else if(typeof A=="function"?A=q[b]=M?[E,A]:[A,E]:M?A.unshift(E):A.push(E),D=d(y),D>0&&A.length>D&&!A.warned){A.warned=!0;var x=new Error("Possible EventEmitter memory leak detected. "+A.length+" "+String(b)+" listeners added. Use emitter.setMaxListeners() to increase limit");x.name="MaxListenersExceededWarning",x.emitter=y,x.type=b,x.count=A.length,n(x)}return y}s.prototype.addListener=function(b,E){return c(this,b,E,!1)},s.prototype.on=s.prototype.addListener,s.prototype.prependListener=function(b,E){return c(this,b,E,!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(y,b,E){var M={fired:!1,wrapFn:void 0,target:y,type:b,listener:E},D=l.bind(M);return D.listener=E,M.wrapFn=D,D}s.prototype.once=function(b,E){return o(E),this.on(b,u(this,b,E)),this},s.prototype.prependOnceListener=function(b,E){return o(E),this.prependListener(b,u(this,b,E)),this},s.prototype.removeListener=function(b,E){var M,D,q,A,x;if(o(E),D=this._events,D===void 0)return this;if(M=D[b],M===void 0)return this;if(M===E||M.listener===E)--this._eventsCount===0?this._events=Object.create(null):(delete D[b],D.removeListener&&this.emit("removeListener",b,M.listener||E));else if(typeof M!="function"){for(q=-1,A=M.length-1;A>=0;A--)if(M[A]===E||M[A].listener===E){x=M[A].listener,q=A;break}if(q<0)return this;q===0?M.shift():f(M,q),M.length===1&&(D[b]=M[0]),D.removeListener!==void 0&&this.emit("removeListener",b,x||E)}return this},s.prototype.off=s.prototype.removeListener,s.prototype.removeAllListeners=function(b){var E,M,D;if(M=this._events,M===void 0)return this;if(M.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):M[b]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete M[b]),this;if(arguments.length===0){var q=Object.keys(M),A;for(D=0;D<q.length;++D)A=q[D],A!=="removeListener"&&this.removeAllListeners(A);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(E=M[b],typeof E=="function")this.removeListener(b,E);else if(E!==void 0)for(D=E.length-1;D>=0;D--)this.removeListener(b,E[D]);return this};function h(y,b,E){var M=y._events;if(M===void 0)return[];var D=M[b];return D===void 0?[]:typeof D=="function"?E?[D.listener||D]:[D]:E?T(D):g(D,D.length)}s.prototype.listeners=function(b){return h(this,b,!0)},s.prototype.rawListeners=function(b){return h(this,b,!1)},s.listenerCount=function(y,b){return typeof y.listenerCount=="function"?y.listenerCount(b):m.call(y,b)},s.prototype.listenerCount=m;function m(y){var b=this._events;if(b!==void 0){var E=b[y];if(typeof E=="function")return 1;if(E!==void 0)return E.length}return 0}s.prototype.eventNames=function(){return this._eventsCount>0?t(this._events):[]};function g(y,b){for(var E=new Array(b),M=0;M<b;++M)E[M]=y[M];return E}function f(y,b){for(;b+1<y.length;b++)y[b]=y[b+1];y.pop()}function T(y){for(var b=new Array(y.length),E=0;E<b.length;++E)b[E]=y[E].listener||y[E];return b}function k(y,b){return new Promise(function(E,M){function D(A){y.removeListener(b,q),M(A)}function q(){typeof y.removeListener=="function"&&y.removeListener("error",D),E([].slice.call(arguments))}L(y,b,q,{once:!0}),b!=="error"&&S(y,D,{once:!0})})}function S(y,b,E){typeof y.on=="function"&&L(y,"error",b,E)}function L(y,b,E,M){if(typeof y.on=="function")M.once?y.once(b,E):y.on(b,E);else if(typeof y.addEventListener=="function")y.addEventListener(b,function D(q){M.once&&y.removeEventListener(b,D),E(q)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof y)}return Zn.exports}var Ee=Ph(),sd=!0,ad=!0;function Tn(i,e,t){let n=i.match(e);return n&&n.length>=t&&parseFloat(n[t],10)}function Vt(i,e,t){if(!i.RTCPeerConnection)return;if(!Object.getOwnPropertyDescriptor(EventTarget.prototype,"addEventListener").writable){Ra("Unable to polyfill events");return}let r=i.RTCPeerConnection.prototype,s=r.addEventListener;r.addEventListener=function(o,d){if(o!==e)return s.apply(this,arguments);let c=l=>{let 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])};let 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);let 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 Ih(i){return typeof i!="boolean"?new Error("Argument type: "+typeof i+". Please use a boolean."):(sd=i,i?"adapter.js logging disabled":"adapter.js logging enabled")}function Mh(i){return typeof i!="boolean"?new Error("Argument type: "+typeof i+". Please use a boolean."):(ad=!i,"adapter.js deprecation warnings "+(i?"disabled":"enabled"))}function Ra(){if(typeof window=="object"){if(sd)return;typeof console<"u"&&typeof console.log=="function"&&console.log.apply(console,arguments)}}function Pa(i,e){ad&&console.warn(i+" is deprecated, please use "+e+" instead.")}function Ah(i){let e={browser:null,version:null};if(typeof i>"u"||!i.navigator||!i.navigator.userAgent)return e.browser="Not a browser.",e;let t=i.navigator;if(t.userAgentData&&t.userAgentData.brands){let n=t.userAgentData.brands.find(r=>r.brand==="Chromium");if(n)return{browser:"chrome",version:parseInt(n.version,10)}}if(t.mozGetUserMedia)e.browser="firefox",e.version=parseInt(Tn(t.userAgent,/Firefox\/(\d+)\./,1));else if(t.webkitGetUserMedia||i.isSecureContext===!1&&i.webkitRTCPeerConnection)e.browser="chrome",e.version=parseInt(Tn(t.userAgent,/Chrom(e|ium)\/(\d+)\./,2))||null;else if(i.RTCPeerConnection&&t.userAgent.match(/AppleWebKit\/(\d+)\./))e.browser="safari",e.version=parseInt(Tn(t.userAgent,/AppleWebKit\/(\d+)\./,1)),e.supportsUnifiedPlan=i.RTCRtpTransceiver&&"currentDirection"in i.RTCRtpTransceiver.prototype,e._safariVersion=Tn(t.userAgent,/Version\/(\d+(\.?\d+))/,1);else return e.browser="Not a supported browser.",e;return e}function vo(i){return Object.prototype.toString.call(i)==="[object Object]"}function od(i){return vo(i)?Object.keys(i).reduce(function(e,t){let n=vo(i[t]),r=n?od(i[t]):i[t],s=n&&!Object.keys(r).length;return r===void 0||s?e:Object.assign(e,{[t]:r})},{}):i}function Qr(i,e,t){!e||t.has(e.id)||(t.set(e.id,e),Object.keys(e).forEach(n=>{n.endsWith("Id")?Qr(i,i.get(e[n]),t):n.endsWith("Ids")&&e[n].forEach(r=>{Qr(i,i.get(r),t)})}))}function yo(i,e,t){let n=t?"outbound-rtp":"inbound-rtp",r=new Map;if(e===null)return r;let s=[];return i.forEach(a=>{a.type==="track"&&a.trackIdentifier===e.id&&s.push(a)}),s.forEach(a=>{i.forEach(o=>{o.type===n&&o.trackId===a.id&&Qr(i,o,r)})}),r}var bo=Ra;function cd(i,e){let t=i&&i.navigator;if(!t.mediaDevices)return;let n=function(o){if(typeof o!="object"||o.mandatory||o.optional)return o;let d={};return Object.keys(o).forEach(c=>{if(c==="require"||c==="advanced"||c==="mediaSource")return;let l=typeof o[c]=="object"?o[c]:{ideal:o[c]};l.exact!==void 0&&typeof l.exact=="number"&&(l.min=l.max=l.exact);let u=function(h,m){return h?h+m.charAt(0).toUpperCase()+m.slice(1):m==="deviceId"?"sourceId":m};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"){let 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=n(o.audio)}if(o&&typeof o.video=="object"){let c=o.video.facingMode;c=c&&(typeof c=="object"?c:{ideal:c});let 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(g=>g.kind==="videoinput");let m=h.find(g=>u.some(f=>g.label.toLowerCase().includes(f)));return!m&&h.length&&u.includes("back")&&(m=h[h.length-1]),m&&(o.video.deviceId=c.exact?{exact:m.deviceId}:{ideal:m.deviceId}),o.video=n(o.video),bo("chrome: "+JSON.stringify(o)),d(o)})}o.video=n(o.video)}return bo("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){let 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 dd(i){i.MediaStream=i.MediaStream||i.webkitMediaStream}function ld(i,e){if(!(e.version>102))if(typeof i=="object"&&i.RTCPeerConnection&&!("ontrack"in i.RTCPeerConnection.prototype)){Object.defineProperty(i.RTCPeerConnection.prototype,"ontrack",{get(){return this._ontrack},set(n){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=n)},enumerable:!0,configurable:!0});let t=i.RTCPeerConnection.prototype.setRemoteDescription;i.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=r=>{r.stream.addEventListener("addtrack",s=>{let a;i.RTCPeerConnection.prototype.getReceivers?a=this.getReceivers().find(d=>d.track&&d.track.id===s.track.id):a={track:s.track};let 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;i.RTCPeerConnection.prototype.getReceivers?a=this.getReceivers().find(d=>d.track&&d.track.id===s.id):a={track:s};let 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(i,"track",t=>(t.transceiver||Object.defineProperty(t,"transceiver",{value:{receiver:t.receiver}}),t))}function ud(i){if(typeof i=="object"&&i.RTCPeerConnection&&!("getSenders"in i.RTCPeerConnection.prototype)&&"createDTMFSender"in i.RTCPeerConnection.prototype){let e=function(r,s){return{track:s,get dtmf(){return this._dtmf===void 0&&(s.kind==="audio"?this._dtmf=r.createDTMFSender(s):this._dtmf=null),this._dtmf},_pc:r}};if(!i.RTCPeerConnection.prototype.getSenders){i.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};let r=i.RTCPeerConnection.prototype.addTrack;i.RTCPeerConnection.prototype.addTrack=function(o,d){let c=r.apply(this,arguments);return c||(c=e(this,o),this._senders.push(c)),c};let s=i.RTCPeerConnection.prototype.removeTrack;i.RTCPeerConnection.prototype.removeTrack=function(o){s.apply(this,arguments);let d=this._senders.indexOf(o);d!==-1&&this._senders.splice(d,1)}}let t=i.RTCPeerConnection.prototype.addStream;i.RTCPeerConnection.prototype.addStream=function(s){this._senders=this._senders||[],t.apply(this,[s]),s.getTracks().forEach(a=>{this._senders.push(e(this,a))})};let n=i.RTCPeerConnection.prototype.removeStream;i.RTCPeerConnection.prototype.removeStream=function(s){this._senders=this._senders||[],n.apply(this,[s]),s.getTracks().forEach(a=>{let o=this._senders.find(d=>d.track===a);o&&this._senders.splice(this._senders.indexOf(o),1)})}}else if(typeof i=="object"&&i.RTCPeerConnection&&"getSenders"in i.RTCPeerConnection.prototype&&"createDTMFSender"in i.RTCPeerConnection.prototype&&i.RTCRtpSender&&!("dtmf"in i.RTCRtpSender.prototype)){let e=i.RTCPeerConnection.prototype.getSenders;i.RTCPeerConnection.prototype.getSenders=function(){let n=e.apply(this,[]);return n.forEach(r=>r._pc=this),n},Object.defineProperty(i.RTCRtpSender.prototype,"dtmf",{get(){return this._dtmf===void 0&&(this.track.kind==="audio"?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}})}}function hd(i,e){if(e.version>=67||!(typeof i=="object"&&i.RTCPeerConnection&&i.RTCRtpSender&&i.RTCRtpReceiver))return;if(!("getStats"in i.RTCRtpSender.prototype)){let n=i.RTCPeerConnection.prototype.getSenders;n&&(i.RTCPeerConnection.prototype.getSenders=function(){let a=n.apply(this,[]);return a.forEach(o=>o._pc=this),a});let r=i.RTCPeerConnection.prototype.addTrack;r&&(i.RTCPeerConnection.prototype.addTrack=function(){let a=r.apply(this,arguments);return a._pc=this,a}),i.RTCRtpSender.prototype.getStats=function(){let a=this;return this._pc.getStats().then(o=>yo(o,a.track,!0))}}if(!("getStats"in i.RTCRtpReceiver.prototype)){let n=i.RTCPeerConnection.prototype.getReceivers;n&&(i.RTCPeerConnection.prototype.getReceivers=function(){let s=n.apply(this,[]);return s.forEach(a=>a._pc=this),s}),Vt(i,"track",r=>(r.receiver._pc=r.srcElement,r)),i.RTCRtpReceiver.prototype.getStats=function(){let s=this;return this._pc.getStats().then(a=>yo(a,s.track,!1))}}if(!("getStats"in i.RTCRtpSender.prototype&&"getStats"in i.RTCRtpReceiver.prototype))return;let t=i.RTCPeerConnection.prototype.getStats;i.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof i.MediaStreamTrack){let r=arguments[0],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 md(i){i.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map(a=>this._shimmedLocalStreams[a][0])};let e=i.RTCPeerConnection.prototype.addTrack;i.RTCPeerConnection.prototype.addTrack=function(a,o){if(!o)return e.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};let 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};let t=i.RTCPeerConnection.prototype.addStream;i.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")});let o=this.getSenders();t.apply(this,arguments);let d=this.getSenders().filter(c=>o.indexOf(c)===-1);this._shimmedLocalStreams[a.id]=[a].concat(d)};let n=i.RTCPeerConnection.prototype.removeStream;i.RTCPeerConnection.prototype.removeStream=function(a){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[a.id],n.apply(this,arguments)};let r=i.RTCPeerConnection.prototype.removeTrack;i.RTCPeerConnection.prototype.removeTrack=function(a){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},a&&Object.keys(this._shimmedLocalStreams).forEach(o=>{let 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 pd(i,e){if(!i.RTCPeerConnection)return;if(i.RTCPeerConnection.prototype.addTrack&&e.version>=65)return md(i);let t=i.RTCPeerConnection.prototype.getLocalStreams;i.RTCPeerConnection.prototype.getLocalStreams=function(){let l=t.apply(this);return this._reverseStreams=this._reverseStreams||{},l.map(u=>this._reverseStreams[u.id])};let n=i.RTCPeerConnection.prototype.addStream;i.RTCPeerConnection.prototype.addStream=function(l){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},l.getTracks().forEach(u=>{if(this.getSenders().find(m=>m.track===u))throw new DOMException("Track already exists.","InvalidAccessError")}),!this._reverseStreams[l.id]){let u=new i.MediaStream(l.getTracks());this._streams[l.id]=u,this._reverseStreams[u.id]=l,l=u}n.apply(this,[l])};let r=i.RTCPeerConnection.prototype.removeStream;i.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]},i.RTCPeerConnection.prototype.addTrack=function(l,u){if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");let h=[].slice.call(arguments,1);if(h.length!==1||!h[0].getTracks().find(f=>f===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(f=>f.track===l))throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};let g=this._streams[u.id];if(g)g.addTrack(l),Promise.resolve().then(()=>{this.dispatchEvent(new Event("negotiationneeded"))});else{let f=new i.MediaStream([l]);this._streams[u.id]=f,this._reverseStreams[f.id]=u,this.addStream(f)}return this.getSenders().find(f=>f.track===l)};function s(c,l){let u=l.sdp;return Object.keys(c._reverseStreams||[]).forEach(h=>{let m=c._reverseStreams[h],g=c._streams[m.id];u=u.replace(new RegExp(g.id,"g"),m.id)}),new RTCSessionDescription({type:l.type,sdp:u})}function a(c,l){let u=l.sdp;return Object.keys(c._reverseStreams||[]).forEach(h=>{let m=c._reverseStreams[h],g=c._streams[m.id];u=u.replace(new RegExp(m.id,"g"),g.id)}),new RTCSessionDescription({type:l.type,sdp:u})}["createOffer","createAnswer"].forEach(function(c){let l=i.RTCPeerConnection.prototype[c],u={[c](){let h=arguments;return arguments.length&&typeof arguments[0]=="function"?l.apply(this,[g=>{let f=s(this,g);h[0].apply(null,[f])},g=>{h[1]&&h[1].apply(null,g)},arguments[2]]):l.apply(this,arguments).then(g=>s(this,g))}};i.RTCPeerConnection.prototype[c]=u[c]});let o=i.RTCPeerConnection.prototype.setLocalDescription;i.RTCPeerConnection.prototype.setLocalDescription=function(){return!arguments.length||!arguments[0].type?o.apply(this,arguments):(arguments[0]=a(this,arguments[0]),o.apply(this,arguments))};let d=Object.getOwnPropertyDescriptor(i.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(i.RTCPeerConnection.prototype,"localDescription",{get(){let c=d.get.apply(this);return c.type===""?c:s(this,c)}}),i.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(m=>{this._streams[m].getTracks().find(f=>l.track===f)&&(h=this._streams[m])}),h&&(h.getTracks().length===1?this.removeStream(this._reverseStreams[h.id]):h.removeTrack(l.track),this.dispatchEvent(new Event("negotiationneeded")))}}function Yr(i,e){!i.RTCPeerConnection&&i.webkitRTCPeerConnection&&(i.RTCPeerConnection=i.webkitRTCPeerConnection),i.RTCPeerConnection&&e.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(t){let n=i.RTCPeerConnection.prototype[t],r={[t](){return arguments[0]=new(t==="addIceCandidate"?i.RTCIceCandidate:i.RTCSessionDescription)(arguments[0]),n.apply(this,arguments)}};i.RTCPeerConnection.prototype[t]=r[t]})}function fd(i,e){e.version>102||Vt(i,"negotiationneeded",t=>{let n=t.target;if(!((e.version<72||n.getConfiguration&&n.getConfiguration().sdpSemantics==="plan-b")&&n.signalingState!=="stable"))return t})}var ko=Object.freeze({__proto__:null,fixNegotiationNeeded:fd,shimAddTrackRemoveTrack:pd,shimAddTrackRemoveTrackWithNative:md,shimGetSendersWithDtmf:ud,shimGetUserMedia:cd,shimMediaStream:dd,shimOnTrack:ld,shimPeerConnection:Yr,shimSenderReceiverGetStats:hd});function gd(i,e){let t=i&&i.navigator,n=i&&i.MediaStreamTrack;if(t.getUserMedia=function(r,s,a){Pa("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),t.mediaDevices.getUserMedia(r).then(s,a)},!(e.version>55&&"autoGainControl"in t.mediaDevices.getSupportedConstraints())){let 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)},n&&n.prototype.getSettings){let a=n.prototype.getSettings;n.prototype.getSettings=function(){let o=a.apply(this,arguments);return r(o,"mozAutoGainControl","autoGainControl"),r(o,"mozNoiseSuppression","noiseSuppression"),o}}if(n&&n.prototype.applyConstraints){let a=n.prototype.applyConstraints;n.prototype.applyConstraints=function(o){return this.kind==="audio"&&typeof o=="object"&&(o=JSON.parse(JSON.stringify(o)),r(o,"autoGainControl","mozAutoGainControl"),r(o,"noiseSuppression","mozNoiseSuppression")),a.apply(this,[o])}}}}function xh(i,e){i.navigator.mediaDevices&&"getDisplayMedia"in i.navigator.mediaDevices||i.navigator.mediaDevices&&(i.navigator.mediaDevices.getDisplayMedia=function(n){if(!(n&&n.video)){let r=new DOMException("getDisplayMedia without video constraints is undefined");return r.name="NotFoundError",r.code=8,Promise.reject(r)}return n.video===!0?n.video={mediaSource:e}:n.video.mediaSource=e,i.navigator.mediaDevices.getUserMedia(n)})}function vd(i){typeof i=="object"&&i.RTCTrackEvent&&"receiver"in i.RTCTrackEvent.prototype&&!("transceiver"in i.RTCTrackEvent.prototype)&&Object.defineProperty(i.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function Xr(i,e){typeof i!="object"||!(i.RTCPeerConnection||i.mozRTCPeerConnection)||(!i.RTCPeerConnection&&i.mozRTCPeerConnection&&(i.RTCPeerConnection=i.mozRTCPeerConnection),e.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(t){let n=i.RTCPeerConnection.prototype[t],r={[t](){return arguments[0]=new(t==="addIceCandidate"?i.RTCIceCandidate:i.RTCSessionDescription)(arguments[0]),n.apply(this,arguments)}};i.RTCPeerConnection.prototype[t]=r[t]}))}function yd(i,e){if(typeof i!="object"||!(i.RTCPeerConnection||i.mozRTCPeerConnection)||e.version>=151)return;let t={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},n=i.RTCPeerConnection.prototype.getStats;i.RTCPeerConnection.prototype.getStats=function(){let s=Array.prototype.slice.call(arguments),a=s[0],o=s[1],d=s[2];return this.signalingState==="closed"?Promise.resolve(new Map):n.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 bd(i){if(!(typeof i=="object"&&i.RTCPeerConnection&&i.RTCRtpSender)||i.RTCRtpSender&&"getStats"in i.RTCRtpSender.prototype)return;let e=i.RTCPeerConnection.prototype.getSenders;e&&(i.RTCPeerConnection.prototype.getSenders=function(){let r=e.apply(this,[]);return r.forEach(s=>s._pc=this),r});let t=i.RTCPeerConnection.prototype.addTrack;t&&(i.RTCPeerConnection.prototype.addTrack=function(){let r=t.apply(this,arguments);return r._pc=this,r}),i.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}function kd(i){if(!(typeof i=="object"&&i.RTCPeerConnection&&i.RTCRtpSender)||i.RTCRtpSender&&"getStats"in i.RTCRtpReceiver.prototype)return;let e=i.RTCPeerConnection.prototype.getReceivers;e&&(i.RTCPeerConnection.prototype.getReceivers=function(){let n=e.apply(this,[]);return n.forEach(r=>r._pc=this),n}),Vt(i,"track",t=>(t.receiver._pc=t.srcElement,t)),i.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function Td(i){!i.RTCPeerConnection||"removeStream"in i.RTCPeerConnection.prototype||(i.RTCPeerConnection.prototype.removeStream=function(t){Pa("removeStream","removeTrack"),this.getSenders().forEach(n=>{n.track&&t.getTracks().includes(n.track)&&this.removeTrack(n)})})}function Sd(i){i.DataChannel&&!i.RTCDataChannel&&(i.RTCDataChannel=i.DataChannel)}function Cd(i){if(!(typeof i=="object"&&i.RTCPeerConnection))return;let e=i.RTCPeerConnection.prototype.addTransceiver;e&&(i.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let n=arguments[1]&&arguments[1].sendEncodings;n===void 0&&(n=[]),n=[...n];let r=n.length>0;r&&n.forEach(a=>{if("rid"in a&&!/^[a-z0-9]{0,16}$/i.test(a.rid))throw new TypeError("Invalid RID value provided.");if("scaleResolutionDownBy"in a&&!(parseFloat(a.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in a&&!(parseFloat(a.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")});let s=e.apply(this,arguments);if(r){let a=s.sender,o=a.getParameters();(!("encodings"in o)||o.encodings.length===1&&Object.keys(o.encodings[0]).length===0)&&(o.encodings=n,a.sendEncodings=n,this.setParametersPromises.push(a.setParameters(o).then(()=>{delete a.sendEncodings}).catch(()=>{delete a.sendEncodings})))}return s})}function _d(i){if(!(typeof i=="object"&&i.RTCRtpSender))return;let e=i.RTCRtpSender.prototype.getParameters;e&&(i.RTCRtpSender.prototype.getParameters=function(){let n=e.apply(this,arguments);return"encodings"in n||(n.encodings=[].concat(this.sendEncodings||[{}])),n})}function wd(i){if(!(typeof i=="object"&&i.RTCPeerConnection))return;let e=i.RTCPeerConnection.prototype.createOffer;i.RTCPeerConnection.prototype.createOffer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>e.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):e.apply(this,arguments)}}function Ed(i){if(!(typeof i=="object"&&i.RTCPeerConnection))return;let e=i.RTCPeerConnection.prototype.createAnswer;i.RTCPeerConnection.prototype.createAnswer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>e.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):e.apply(this,arguments)}}var To=Object.freeze({__proto__:null,shimAddTransceiver:Cd,shimCreateAnswer:Ed,shimCreateOffer:wd,shimGetDisplayMedia:xh,shimGetParameters:_d,shimGetStats:yd,shimGetUserMedia:gd,shimOnTrack:vd,shimPeerConnection:Xr,shimRTCDataChannel:Sd,shimReceiverGetStats:kd,shimRemoveStream:Td,shimSenderGetStats:bd});function Rd(i){if(!(typeof i!="object"||!i.RTCPeerConnection)){if("getLocalStreams"in i.RTCPeerConnection.prototype||(i.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in i.RTCPeerConnection.prototype)){let e=i.RTCPeerConnection.prototype.addTrack;i.RTCPeerConnection.prototype.addStream=function(n){this._localStreams||(this._localStreams=[]),this._localStreams.includes(n)||this._localStreams.push(n),n.getAudioTracks().forEach(r=>e.call(this,r,n)),n.getVideoTracks().forEach(r=>e.call(this,r,n))},i.RTCPeerConnection.prototype.addTrack=function(n){for(var r=arguments.length,s=new Array(r>1?r-1:0),a=1;a<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 i.RTCPeerConnection.prototype||(i.RTCPeerConnection.prototype.removeStream=function(t){this._localStreams||(this._localStreams=[]);let n=this._localStreams.indexOf(t);if(n===-1)return;this._localStreams.splice(n,1);let r=t.getTracks();this.getSenders().forEach(s=>{r.includes(s.track)&&this.removeTrack(s)})})}}function Pd(i){if(!(typeof i!="object"||!i.RTCPeerConnection)&&("getRemoteStreams"in i.RTCPeerConnection.prototype||(i.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]}),!("onaddstream"in i.RTCPeerConnection.prototype))){Object.defineProperty(i.RTCPeerConnection.prototype,"onaddstream",{get(){return this._onaddstream},set(t){this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=t),this.addEventListener("track",this._onaddstreampoly=n=>{n.streams.forEach(r=>{if(this._remoteStreams||(this._remoteStreams=[]),this._remoteStreams.includes(r))return;this._remoteStreams.push(r);let s=new Event("addstream");s.stream=r,this.dispatchEvent(s)})})}});let e=i.RTCPeerConnection.prototype.setRemoteDescription;i.RTCPeerConnection.prototype.setRemoteDescription=function(){let n=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(r){r.streams.forEach(s=>{if(n._remoteStreams||(n._remoteStreams=[]),n._remoteStreams.indexOf(s)>=0)return;n._remoteStreams.push(s);let a=new Event("addstream");a.stream=s,n.dispatchEvent(a)})}),e.apply(n,arguments)}}}function Id(i){if(typeof i!="object"||!i.RTCPeerConnection)return;let e=i.RTCPeerConnection.prototype,t=e.createOffer,n=e.createAnswer,r=e.setLocalDescription,s=e.setRemoteDescription,a=e.addIceCandidate;e.createOffer=function(c,l){let 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){let u=arguments.length>=2?arguments[2]:arguments[0],h=n.apply(this,[u]);return l?(h.then(c,l),Promise.resolve()):h};let o=function(d,c,l){let u=r.apply(this,[d]);return l?(u.then(c,l),Promise.resolve()):u};e.setLocalDescription=o,o=function(d,c,l){let u=s.apply(this,[d]);return l?(u.then(c,l),Promise.resolve()):u},e.setRemoteDescription=o,o=function(d,c,l){let u=a.apply(this,[d]);return l?(u.then(c,l),Promise.resolve()):u},e.addIceCandidate=o}function Md(i){let e=i&&i.navigator;if(e.mediaDevices&&e.mediaDevices.getUserMedia){let t=e.mediaDevices,n=t.getUserMedia.bind(t);e.mediaDevices.getUserMedia=r=>n(Ad(r))}!e.getUserMedia&&e.mediaDevices&&e.mediaDevices.getUserMedia&&(e.getUserMedia=function(n,r,s){e.mediaDevices.getUserMedia(n).then(r,s)}.bind(e))}function Ad(i){return i&&i.video!==void 0?Object.assign({},i,{video:od(i.video)}):i}function xd(i){if(!i.RTCPeerConnection)return;let e=i.RTCPeerConnection;i.RTCPeerConnection=function(n,r){if(n&&n.iceServers){let s=[];for(let a=0;a<n.iceServers.length;a++){let o=n.iceServers[a];o.urls===void 0&&o.url?(Pa("RTCIceServer.url","RTCIceServer.urls"),o=JSON.parse(JSON.stringify(o)),o.urls=o.url,delete o.url,s.push(o)):s.push(n.iceServers[a])}n.iceServers=s}return new e(n,r)},i.RTCPeerConnection.prototype=e.prototype,"generateCertificate"in e&&Object.defineProperty(i.RTCPeerConnection,"generateCertificate",{get(){return e.generateCertificate}})}function Dd(i){typeof i=="object"&&i.RTCTrackEvent&&"receiver"in i.RTCTrackEvent.prototype&&!("transceiver"in i.RTCTrackEvent.prototype)&&Object.defineProperty(i.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function Od(i){let e=i.RTCPeerConnection.prototype.createOffer;i.RTCPeerConnection.prototype.createOffer=function(n){if(n){typeof n.offerToReceiveAudio<"u"&&(n.offerToReceiveAudio=!!n.offerToReceiveAudio);let r=this.getTransceivers().find(a=>a.receiver.track.kind==="audio");n.offerToReceiveAudio===!1&&r?r.direction==="sendrecv"?r.setDirection?r.setDirection("sendonly"):r.direction="sendonly":r.direction==="recvonly"&&(r.setDirection?r.setDirection("inactive"):r.direction="inactive"):n.offerToReceiveAudio===!0&&!r&&this.addTransceiver("audio",{direction:"recvonly"}),typeof n.offerToReceiveVideo<"u"&&(n.offerToReceiveVideo=!!n.offerToReceiveVideo);let s=this.getTransceivers().find(a=>a.receiver.track.kind==="video");n.offerToReceiveVideo===!1&&s?s.direction==="sendrecv"?s.setDirection?s.setDirection("sendonly"):s.direction="sendonly":s.direction==="recvonly"&&(s.setDirection?s.setDirection("inactive"):s.direction="inactive"):n.offerToReceiveVideo===!0&&!s&&this.addTransceiver("video",{direction:"recvonly"})}return e.apply(this,arguments)}}function Ld(i){typeof i!="object"||i.AudioContext||(i.AudioContext=i.webkitAudioContext)}var So=Object.freeze({__proto__:null,shimAudioContext:Ld,shimCallbacksAPI:Id,shimConstraints:Ad,shimCreateOfferLegacy:Od,shimGetUserMedia:Md,shimLocalStreamsAPI:Rd,shimRTCIceServerUrls:xd,shimRemoteStreamsAPI:Pd,shimTrackEventTransceiver:Dd}),Tr={exports:{}},Co;function Dh(){return Co||(Co=1,(function(i){let e={};e.generateIdentifier=function(){return Math.random().toString(36).substring(2,12)},e.localCName=e.generateIdentifier(),e.splitLines=function(t){return t.trim().split(`
1
+ function Bl(i,e){return e.forEach(function(t){t&&typeof t!="string"&&!Array.isArray(t)&&Object.keys(t).forEach(function(n){if(n!=="default"&&!(n in i)){var r=Object.getOwnPropertyDescriptor(t,n);Object.defineProperty(i,n,r.get?r:{enumerable:!0,get:function(){return t[n]}})}})}),Object.freeze(i)}var ql=Object.defineProperty,jl=(i,e,t)=>e in i?ql(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Xa=(i,e,t)=>jl(i,typeof e!="symbol"?e+"":e,t),de=class{constructor(){Xa(this,"_locking"),Xa(this,"_locks"),this._locking=Promise.resolve(),this._locks=0}isLocked(){return this._locks>0}lock(){this._locks+=1;let e,t=new Promise(r=>e=()=>{this._locks-=1,r()}),n=this._locking.then(()=>e);return this._locking=this._locking.then(()=>t),n}};function ne(i,e){if(!i)throw new Error(e)}var Vl=34028234663852886e22,Hl=-34028234663852886e22,Gl=4294967295,Kl=2147483647,Wl=-2147483648;function ni(i){if(typeof i!="number")throw new Error("invalid int 32: "+typeof i);if(!Number.isInteger(i)||i>Kl||i<Wl)throw new Error("invalid int 32: "+i)}function Br(i){if(typeof i!="number")throw new Error("invalid uint 32: "+typeof i);if(!Number.isInteger(i)||i>Gl||i<0)throw new Error("invalid uint 32: "+i)}function pc(i){if(typeof i!="number")throw new Error("invalid float 32: "+typeof i);if(Number.isFinite(i)&&(i>Vl||i<Hl))throw new Error("invalid float 32: "+i)}var fc=Symbol("@bufbuild/protobuf/enum-type");function zl(i){let e=i[fc];return ne(e,"missing enum type on enum object"),e}function gc(i,e,t,n){i[fc]=vc(e,t.map(r=>({no:r.no,name:r.name,localName:i[r.no]})))}function vc(i,e,t){let n=Object.create(null),r=Object.create(null),s=[];for(let a of e){let o=yc(a);s.push(o),n[a.name]=o,r[a.no]=o}return{typeName:i,values:s,findName(a){return n[a]},findNumber(a){return r[a]}}}function Jl(i,e,t){let n={};for(let r of e){let s=yc(r);n[s.localName]=s.no,n[s.no]=s.localName}return gc(n,i,e),n}function yc(i){return"localName"in i?i:Object.assign(Object.assign({},i),{localName:i.name})}var In=class{equals(e){return this.getType().runtime.util.equals(this.getType(),this,e)}clone(){return this.getType().runtime.util.clone(this)}fromBinary(e,t){let n=this.getType(),r=n.runtime.bin,s=r.makeReadOptions(t);return r.readMessage(this,s.readerFactory(e),e.byteLength,s),this}fromJson(e,t){let n=this.getType(),r=n.runtime.json,s=r.makeReadOptions(t);return r.readMessage(n,e,s,this),this}fromJsonString(e,t){let n;try{n=JSON.parse(e)}catch(r){throw new Error("cannot decode ".concat(this.getType().typeName," from JSON: ").concat(r instanceof Error?r.message:String(r)))}return this.fromJson(n,t)}toBinary(e){let t=this.getType(),n=t.runtime.bin,r=n.makeWriteOptions(e),s=r.writerFactory();return n.writeMessage(this,s,r),s.finish()}toJson(e){let t=this.getType(),n=t.runtime.json,r=n.makeWriteOptions(e);return n.writeMessage(this,r)}toJsonString(e){var t;let n=this.toJson(e);return JSON.stringify(n,null,(t=e?.prettySpaces)!==null&&t!==void 0?t:0)}toJSON(){return this.toJson({emitDefaultValues:!0})}getType(){return Object.getPrototypeOf(this).constructor}};function $l(i,e,t,n){var r;let s=(r=n?.localName)!==null&&r!==void 0?r:e.substring(e.lastIndexOf(".")+1),a={[s]:function(o){i.util.initFields(this),i.util.initPartial(o,this)}}[s];return Object.setPrototypeOf(a.prototype,new In),Object.assign(a,{runtime:i,typeName:e,fields:i.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 i.util.equals(a,o,d)}}),a}function Ql(){let i=0,e=0;for(let n=0;n<28;n+=7){let r=this.buf[this.pos++];if(i|=(r&127)<<n,(r&128)==0)return this.assertBounds(),[i,e]}let t=this.buf[this.pos++];if(i|=(t&15)<<28,e=(t&112)>>4,(t&128)==0)return this.assertBounds(),[i,e];for(let n=3;n<=31;n+=7){let r=this.buf[this.pos++];if(e|=(r&127)<<n,(r&128)==0)return this.assertBounds(),[i,e]}throw new Error("invalid varint")}function yr(i,e,t){for(let s=0;s<28;s=s+7){let a=i>>>s,o=!(!(a>>>7)&&e==0),d=(o?a|128:a)&255;if(t.push(d),!o)return}let n=i>>>28&15|(e&7)<<4,r=e>>3!=0;if(t.push((r?n|128:n)&255),!!r){for(let s=3;s<31;s=s+7){let a=e>>>s,o=!!(a>>>7),d=(o?a|128:a)&255;if(t.push(d),!o)return}t.push(e>>>31&1)}}var ii=4294967296;function Za(i){let e=i[0]==="-";e&&(i=i.slice(1));let t=1e6,n=0,r=0;function s(a,o){let d=Number(i.slice(a,o));r*=t,n=n*t+d,n>=ii&&(r=r+(n/ii|0),n=n%ii)}return s(-24,-18),s(-18,-12),s(-12,-6),s(-6),e?kc(n,r):pa(n,r)}function Yl(i,e){let t=pa(i,e),n=t.hi&2147483648;n&&(t=kc(t.lo,t.hi));let r=bc(t.lo,t.hi);return n?"-"+r:r}function bc(i,e){var t=Xl(i,e);if(i=t.lo,e=t.hi,e<=2097151)return String(ii*e+i);let n=i&16777215,r=(i>>>24|e<<8)&16777215,s=e>>16&65535,a=n+r*6777216+s*6710656,o=r+s*8147497,d=s*2,c=1e7;return a>=c&&(o+=Math.floor(a/c),a%=c),o>=c&&(d+=Math.floor(o/c),o%=c),d.toString()+eo(o)+eo(a)}function Xl(i,e){return{lo:i>>>0,hi:e>>>0}}function pa(i,e){return{lo:i|0,hi:e|0}}function kc(i,e){return e=~e,i?i=~i+1:e+=1,pa(i,e)}var eo=i=>{let e=String(i);return"0000000".slice(e.length)+e};function to(i,e){if(i>=0){for(;i>127;)e.push(i&127|128),i=i>>>7;e.push(i)}else{for(let t=0;t<9;t++)e.push(i&127|128),i=i>>7;e.push(1)}}function Zl(){let i=this.buf[this.pos++],e=i&127;if((i&128)==0)return this.assertBounds(),e;if(i=this.buf[this.pos++],e|=(i&127)<<7,(i&128)==0)return this.assertBounds(),e;if(i=this.buf[this.pos++],e|=(i&127)<<14,(i&128)==0)return this.assertBounds(),e;if(i=this.buf[this.pos++],e|=(i&127)<<21,(i&128)==0)return this.assertBounds(),e;i=this.buf[this.pos++],e|=(i&15)<<28;for(let t=5;(i&128)!==0&&t<10;t++)i=this.buf[this.pos++];if((i&128)!=0)throw new Error("invalid varint");return this.assertBounds(),e>>>0}function eu(){let i=new DataView(new ArrayBuffer(8));if(typeof BigInt=="function"&&typeof i.getBigInt64=="function"&&typeof i.getBigUint64=="function"&&typeof i.setBigInt64=="function"&&typeof i.setBigUint64=="function"&&(typeof process!="object"||typeof process.env!="object"||process.env.BUF_BIGINT_DISABLE!=="1")){let r=BigInt("-9223372036854775808"),s=BigInt("9223372036854775807"),a=BigInt("0"),o=BigInt("18446744073709551615");return{zero:BigInt(0),supported:!0,parse(d){let c=typeof d=="bigint"?d:BigInt(d);if(c>s||c<r)throw new Error("int64 invalid: ".concat(d));return c},uParse(d){let c=typeof d=="bigint"?d:BigInt(d);if(c>o||c<a)throw new Error("uint64 invalid: ".concat(d));return c},enc(d){return i.setBigInt64(0,this.parse(d),!0),{lo:i.getInt32(0,!0),hi:i.getInt32(4,!0)}},uEnc(d){return i.setBigInt64(0,this.uParse(d),!0),{lo:i.getInt32(0,!0),hi:i.getInt32(4,!0)}},dec(d,c){return i.setInt32(0,d,!0),i.setInt32(4,c,!0),i.getBigInt64(0,!0)},uDec(d,c){return i.setInt32(0,d,!0),i.setInt32(4,c,!0),i.getBigUint64(0,!0)}}}let t=r=>ne(/^-?[0-9]+$/.test(r),"int64 invalid: ".concat(r)),n=r=>ne(/^[0-9]+$/.test(r),"uint64 invalid: ".concat(r));return{zero:"0",supported:!1,parse(r){return typeof r!="string"&&(r=r.toString()),t(r),r},uParse(r){return typeof r!="string"&&(r=r.toString()),n(r),r},enc(r){return typeof r!="string"&&(r=r.toString()),t(r),Za(r)},uEnc(r){return typeof r!="string"&&(r=r.toString()),n(r),Za(r)},dec(r,s){return Yl(r,s)},uDec(r,s){return bc(r,s)}}}var Y=eu(),w;(function(i){i[i.DOUBLE=1]="DOUBLE",i[i.FLOAT=2]="FLOAT",i[i.INT64=3]="INT64",i[i.UINT64=4]="UINT64",i[i.INT32=5]="INT32",i[i.FIXED64=6]="FIXED64",i[i.FIXED32=7]="FIXED32",i[i.BOOL=8]="BOOL",i[i.STRING=9]="STRING",i[i.BYTES=12]="BYTES",i[i.UINT32=13]="UINT32",i[i.SFIXED32=15]="SFIXED32",i[i.SFIXED64=16]="SFIXED64",i[i.SINT32=17]="SINT32",i[i.SINT64=18]="SINT64"})(w||(w={}));var _t;(function(i){i[i.BIGINT=0]="BIGINT",i[i.STRING=1]="STRING"})(_t||(_t={}));function gt(i,e,t){if(e===t)return!0;if(i==w.BYTES){if(!(e instanceof Uint8Array)||!(t instanceof Uint8Array)||e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}switch(i){case w.UINT64:case w.FIXED64:case w.INT64:case w.SFIXED64:case w.SINT64:return e==t}return!1}function tn(i,e){switch(i){case w.BOOL:return!1;case w.UINT64:case w.FIXED64:case w.INT64:case w.SFIXED64:case w.SINT64:return e==0?Y.zero:"0";case w.DOUBLE:case w.FLOAT:return 0;case w.BYTES:return new Uint8Array(0);case w.STRING:return"";default:return 0}}function Tc(i,e){switch(i){case w.BOOL:return e===!1;case w.STRING:return e==="";case w.BYTES:return e instanceof Uint8Array&&!e.byteLength;default:return e==0}}function no(i,e){(e==null||e>i.length)&&(e=i.length);for(var t=0,n=Array(e);t<e;t++)n[t]=i[t];return n}function tu(i){if(Array.isArray(i))return i}function H(i,e,t){return(e=su(e))in i?Object.defineProperty(i,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):i[e]=t,i}function nu(i,e){var t=i==null?null:typeof Symbol<"u"&&i[Symbol.iterator]||i["@@iterator"];if(t!=null){var n,r,s,a,o=[],d=!0,c=!1;try{if(s=(t=t.call(i)).next,e===0){if(Object(t)!==t)return;d=!1}else for(;!(d=(n=s.call(t)).done)&&(o.push(n.value),o.length!==e);d=!0);}catch(l){c=!0,r=l}finally{try{if(!d&&t.return!=null&&(a=t.return(),Object(a)!==a))return}finally{if(c)throw r}}return o}}function iu(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
2
+ In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function O(i,e){return tu(i)||nu(i,e)||au(i,e)||iu()}function ru(i,e){if(typeof i!="object"||!i)return i;var t=i[Symbol.toPrimitive];if(t!==void 0){var n=t.call(i,e);if(typeof n!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(i)}function su(i){var e=ru(i,"string");return typeof e=="symbol"?e:e+""}function au(i,e){if(i){if(typeof i=="string")return no(i,e);var t={}.toString.call(i).slice(8,-1);return t==="Object"&&i.constructor&&(t=i.constructor.name),t==="Map"||t==="Set"?Array.from(i):t==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t)?no(i,e):void 0}}var ae;(function(i){i[i.Varint=0]="Varint",i[i.Bit64=1]="Bit64",i[i.LengthDelimited=2]="LengthDelimited",i[i.StartGroup=3]="StartGroup",i[i.EndGroup=4]="EndGroup",i[i.Bit32=5]="Bit32"})(ae||(ae={}));var qr=class{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),n=0;for(let r=0;r<this.chunks.length;r++)t.set(this.chunks[r],n),n+=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(Br(e);e>127;)this.buf.push(e&127|128),e=e>>>7;return this.buf.push(e),this}int32(e){return ni(e),to(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){pc(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){Br(e);let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!0),this.raw(t)}sfixed32(e){ni(e);let t=new Uint8Array(4);return new DataView(t.buffer).setInt32(0,e,!0),this.raw(t)}sint32(e){return ni(e),e=(e<<1^e>>31)>>>0,to(e,this.buf),this}sfixed64(e){let t=new Uint8Array(8),n=new DataView(t.buffer),r=Y.enc(e);return n.setInt32(0,r.lo,!0),n.setInt32(4,r.hi,!0),this.raw(t)}fixed64(e){let t=new Uint8Array(8),n=new DataView(t.buffer),r=Y.uEnc(e);return n.setInt32(0,r.lo,!0),n.setInt32(4,r.hi,!0),this.raw(t)}int64(e){let t=Y.enc(e);return yr(t.lo,t.hi,this.buf),this}sint64(e){let t=Y.enc(e),n=t.hi>>31,r=t.lo<<1^n,s=(t.hi<<1|t.lo>>>31)^n;return yr(r,s,this.buf),this}uint64(e){let t=Y.uEnc(e);return yr(t.lo,t.hi,this.buf),this}},jr=class{constructor(e,t){this.varint64=Ql,this.uint32=Zl,this.buf=e,this.len=e.length,this.pos=0,this.view=new DataView(e.buffer,e.byteOffset,e.byteLength),this.textDecoder=t??new TextDecoder}tag(){let e=this.uint32(),t=e>>>3,n=e&7;if(t<=0||n<0||n>5)throw new Error("illegal tag: field no "+t+" wire type "+n);return[t,n]}skip(e,t){let n=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(;;){let s=this.tag(),a=O(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(n,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 Y.dec(...this.varint64())}uint64(){return Y.uDec(...this.varint64())}sint64(){let e=this.varint64(),t=O(e,2),n=t[0],r=t[1],s=-(n&1);return n=(n>>>1|(r&1)<<31)^s,r=r>>>1^s,Y.dec(n,r)}bool(){let e=this.varint64(),t=O(e,2),n=t[0],r=t[1];return n!==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 Y.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return Y.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 ou(i,e,t,n){let r;return{typeName:e,extendee:t,get field(){if(!r){let s=typeof n=="function"?n():n;s.name=e.split(".").pop(),s.jsonName="[".concat(e,"]"),r=i.util.newFieldList([s]).list()[0]}return r},runtime:i}}function Sc(i){let e=i.field.localName,t=Object.create(null);return t[e]=cu(i),[t,()=>t[e]]}function cu(i){let e=i.field;if(e.repeated)return[];if(e.default!==void 0)return e.default;switch(e.kind){case"enum":return e.T.values[0].no;case"scalar":return tn(e.T,e.L);case"message":let t=e.T,n=new t;return t.fieldWrapper?t.fieldWrapper.unwrapField(n):n;case"map":throw"map fields are not allowed to be extensions"}}function du(i,e){if(!e.repeated&&(e.kind=="enum"||e.kind=="scalar")){for(let t=i.length-1;t>=0;--t)if(i[t].no==e.no)return[i[t]];return[]}return i.filter(t=>t.no===e.no)}var ct="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),Yi=[];for(let i=0;i<ct.length;i++)Yi[ct[i].charCodeAt(0)]=i;Yi[45]=ct.indexOf("+");Yi[95]=ct.indexOf("/");var Cc={dec(i){let e=i.length*3/4;i[i.length-2]=="="?e-=2:i[i.length-1]=="="&&(e-=1);let t=new Uint8Array(e),n=0,r=0,s,a=0;for(let o=0;o<i.length;o++){if(s=Yi[i.charCodeAt(o)],s===void 0)switch(i[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[n++]=a<<2|(s&48)>>4,a=s,r=2;break;case 2:t[n++]=(a&15)<<4|(s&60)>>2,a=s,r=3;break;case 3:t[n++]=(a&3)<<6|s,r=0;break}}if(r==1)throw Error("invalid base64 string.");return t.subarray(0,n)},enc(i){let e="",t=0,n,r=0;for(let s=0;s<i.length;s++)switch(n=i[s],t){case 0:e+=ct[n>>2],r=(n&3)<<4,t=1;break;case 1:e+=ct[r|n>>4],r=(n&15)<<2,t=2;break;case 2:e+=ct[r|n>>6],e+=ct[n&63],t=0;break}return t&&(e+=ct[r],e+="=",t==1&&(e+="=")),e}};function lu(i,e,t){wc(e,i);let n=e.runtime.bin.makeReadOptions(t),r=du(i.getType().runtime.bin.listUnknownFields(i),e.field),s=Sc(e),a=O(s,2),o=a[0],d=a[1];for(let c of r)e.runtime.bin.readField(o,n.readerFactory(c.data),e.field,c.wireType,n);return d()}function uu(i,e,t,n){wc(e,i);let r=e.runtime.bin.makeReadOptions(n),s=e.runtime.bin.makeWriteOptions(n);if(_c(i,e)){let c=i.getType().runtime.bin.listUnknownFields(i).filter(l=>l.no!=e.field.no);i.getType().runtime.bin.discardUnknownFields(i);for(let l of c)i.getType().runtime.bin.onUnknownField(i,l.no,l.wireType,l.data)}let a=s.writerFactory(),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);let d=r.readerFactory(a.finish());for(;d.pos<d.len;){let c=d.tag(),l=O(c,2),u=l[0],h=l[1],m=d.skip(h,u);i.getType().runtime.bin.onUnknownField(i,u,h,m)}}function _c(i,e){let t=i.getType();return e.extendee.typeName===t.typeName&&!!t.runtime.bin.listUnknownFields(i).find(n=>n.no==e.field.no)}function wc(i,e){ne(i.extendee.typeName==e.getType().typeName,"extension ".concat(i.typeName," can only be applied to message ").concat(i.extendee.typeName))}function Ec(i,e){let t=i.localName;if(i.repeated)return e[t].length>0;if(i.oneof)return e[i.oneof.localName].case===t;switch(i.kind){case"enum":case"scalar":return i.opt||i.req?e[t]!==void 0:i.kind=="enum"?e[t]!==i.T.values[0].no:!Tc(i.T,e[t]);case"message":return e[t]!==void 0;case"map":return Object.keys(e[t]).length>0}}function io(i,e){let t=i.localName,n=!i.opt&&!i.req;if(i.repeated)e[t]=[];else if(i.oneof)e[i.oneof.localName]={case:void 0};else switch(i.kind){case"map":e[t]={};break;case"enum":e[t]=n?i.T.values[0].no:void 0;break;case"scalar":e[t]=n?tn(i.T,i.L):void 0;break;case"message":e[t]=void 0;break}}function dt(i,e){if(i===null||typeof i!="object"||!Object.getOwnPropertyNames(In.prototype).every(n=>n in i&&typeof i[n]=="function"))return!1;let t=i.getType();return t===null||typeof t!="function"||!("typeName"in t)||typeof t.typeName!="string"?!1:e===void 0?!0:t.typeName==e.typeName}function Rc(i,e){return dt(e)||!i.fieldWrapper?e:i.fieldWrapper.wrapField(e)}w.DOUBLE,w.FLOAT,w.INT64,w.UINT64,w.INT32,w.UINT32,w.BOOL,w.STRING,w.BYTES;var ro={ignoreUnknownFields:!1},so={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0};function hu(i){return i?Object.assign(Object.assign({},ro),i):ro}function mu(i){return i?Object.assign(Object.assign({},so),i):so}var fi=Symbol(),ri=Symbol();function pu(){return{makeReadOptions:hu,makeWriteOptions:mu,readMessage(i,e,t,n){if(e==null||Array.isArray(e)||typeof e!="object")throw new Error("cannot decode message ".concat(i.typeName," from JSON: ").concat(Ye(e)));n=n??new i;let r=new Map,s=t.typeRegistry;for(let o of Object.entries(e)){var a=O(o,2);let d=a[0],c=a[1],l=i.fields.findJsonName(d);if(l){if(l.oneof){if(c===null&&l.kind=="scalar")continue;let u=r.get(l.oneof);if(u!==void 0)throw new Error("cannot decode message ".concat(i.typeName,' from JSON: multiple keys for oneof "').concat(l.oneof.name,'" present: "').concat(u,'", "').concat(d,'"'));r.set(l.oneof,d)}ao(n,c,l,t,i)}else{let u=!1;if(s?.findExtension&&d.startsWith("[")&&d.endsWith("]")){let h=s.findExtension(d.substring(1,d.length-1));if(h&&h.extendee.typeName==i.typeName){u=!0;let m=Sc(h),f=O(m,2),g=f[0],k=f[1];ao(g,c,h.field,t,h),uu(n,h,k(),t)}}if(!u&&!t.ignoreUnknownFields)throw new Error("cannot decode message ".concat(i.typeName,' from JSON: key "').concat(d,'" is unknown'))}}return n},writeMessage(i,e){let t=i.getType(),n={},r;try{for(r of t.fields.byNumber()){if(!Ec(r,i)){if(r.req)throw"required field not set";if(!e.emitDefaultValues||!gu(r))continue}let a=r.oneof?i[r.oneof.localName].value:i[r.localName],o=oo(r,a,e);o!==void 0&&(n[e.useProtoFieldName?r.name:r.jsonName]=o)}let s=e.typeRegistry;if(s?.findExtensionFor)for(let a of t.runtime.bin.listUnknownFields(i)){let o=s.findExtensionFor(t.typeName,a.no);if(o&&_c(i,o)){let d=lu(i,o,e),c=oo(o.field,d,e);c!==void 0&&(n[o.field.jsonName]=c)}}}catch(s){let 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 n},readScalar(i,e,t){return Sn(i,e,t??_t.BIGINT,!0)},writeScalar(i,e,t){if(e!==void 0&&(t||Tc(i,e)))return si(i,e)},debug:Ye}}function Ye(i){if(i===null)return"null";switch(typeof i){case"object":return Array.isArray(i)?"array":"object";case"string":return i.length>100?"string":'"'.concat(i.split('"').join('\\"'),'"');default:return String(i)}}function ao(i,e,t,n,r){let s=t.localName;if(t.repeated){if(ne(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(Ye(e)));let o=i[s];for(let d of e){if(d===null)throw new Error("cannot decode field ".concat(r.typeName,".").concat(t.name," from JSON: ").concat(Ye(d)));switch(t.kind){case"message":o.push(t.T.fromJson(d,n));break;case"enum":let c=br(t.T,d,n.ignoreUnknownFields,!0);c!==ri&&o.push(c);break;case"scalar":try{o.push(Sn(t.T,d,t.L,!0))}catch(l){let u="cannot decode field ".concat(r.typeName,".").concat(t.name," from JSON: ").concat(Ye(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(Ye(e)));let o=i[s];for(let d of Object.entries(e)){var a=O(d,2);let 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=fu(t.K,c)}catch(h){let m="cannot decode map key for field ".concat(r.typeName,".").concat(t.name," from JSON: ").concat(Ye(e));throw h instanceof Error&&h.message.length>0&&(m+=": ".concat(h.message)),new Error(m)}switch(t.V.kind){case"message":o[u]=t.V.T.fromJson(l,n);break;case"enum":let h=br(t.V.T,l,n.ignoreUnknownFields,!0);h!==ri&&(o[u]=h);break;case"scalar":try{o[u]=Sn(t.V.T,l,_t.BIGINT,!0)}catch(m){let f="cannot decode map value for field ".concat(r.typeName,".").concat(t.name," from JSON: ").concat(Ye(e));throw m instanceof Error&&m.message.length>0&&(f+=": ".concat(m.message)),new Error(f)}break}}}else switch(t.oneof&&(i=i[t.oneof.localName]={case:s},s="value"),t.kind){case"message":let o=t.T;if(e===null&&o.typeName!="google.protobuf.Value")return;let d=i[s];dt(d)?d.fromJson(e,n):(i[s]=d=o.fromJson(e,n),o.fieldWrapper&&!t.oneof&&(i[s]=o.fieldWrapper.unwrapField(d)));break;case"enum":let c=br(t.T,e,n.ignoreUnknownFields,!1);switch(c){case fi:io(t,i);break;case ri:break;default:i[s]=c;break}break;case"scalar":try{let l=Sn(t.T,e,t.L,!1);switch(l){case fi:io(t,i);break;default:i[s]=l;break}}catch(l){let u="cannot decode field ".concat(r.typeName,".").concat(t.name," from JSON: ").concat(Ye(e));throw l instanceof Error&&l.message.length>0&&(u+=": ".concat(l.message)),new Error(u)}break}}function fu(i,e){if(i===w.BOOL)switch(e){case"true":e=!0;break;case"false":e=!1;break}return Sn(i,e,_t.BIGINT,!0).toString()}function Sn(i,e,t,n){if(e===null)return n?tn(i,t):fi;switch(i){case w.DOUBLE:case w.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;let r=Number(e);if(Number.isNaN(r)||!Number.isFinite(r))break;return i==w.FLOAT&&pc(r),r;case w.INT32:case w.FIXED32:case w.SFIXED32:case w.SINT32:case w.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 i==w.UINT32||i==w.FIXED32?Br(s):ni(s),s;case w.INT64:case w.SFIXED64:case w.SINT64:if(typeof e!="number"&&typeof e!="string")break;let a=Y.parse(e);return t?a.toString():a;case w.FIXED64:case w.UINT64:if(typeof e!="number"&&typeof e!="string")break;let o=Y.uParse(e);return t?o.toString():o;case w.BOOL:if(typeof e!="boolean")break;return e;case w.STRING:if(typeof e!="string")break;try{encodeURIComponent(e)}catch{throw new Error("invalid UTF8")}return e;case w.BYTES:if(e==="")return new Uint8Array(0);if(typeof e!="string")break;return Cc.dec(e)}throw new Error}function br(i,e,t,n){if(e===null)return i.typeName=="google.protobuf.NullValue"?0:n?i.values[0].no:fi;switch(typeof e){case"number":if(Number.isInteger(e))return e;break;case"string":let r=i.findName(e);if(r!==void 0)return r.no;if(t)return ri;break}throw new Error("cannot decode enum ".concat(i.typeName," from JSON: ").concat(Ye(e)))}function gu(i){return i.repeated||i.kind=="map"?!0:!(i.oneof||i.kind=="message"||i.opt||i.req)}function oo(i,e,t){if(i.kind=="map"){ne(typeof e=="object"&&e!=null);let a={},o=Object.entries(e);switch(i.V.kind){case"scalar":for(let c of o){var n=O(c,2);let l=n[0],u=n[1];a[l.toString()]=si(i.V.T,u)}break;case"message":for(let c of o){var r=O(c,2);let l=r[0],u=r[1];a[l.toString()]=u.toJson(t)}break;case"enum":let d=i.V.T;for(let c of o){var s=O(c,2);let l=s[0],u=s[1];a[l.toString()]=kr(d,u,t.enumAsInteger)}break}return t.emitDefaultValues||o.length>0?a:void 0}if(i.repeated){ne(Array.isArray(e));let a=[];switch(i.kind){case"scalar":for(let o=0;o<e.length;o++)a.push(si(i.T,e[o]));break;case"enum":for(let o=0;o<e.length;o++)a.push(kr(i.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(i.kind){case"scalar":return si(i.T,e);case"enum":return kr(i.T,e,t.enumAsInteger);case"message":return Rc(i.T,e).toJson(t)}}function kr(i,e,t){var n;if(ne(typeof e=="number"),i.typeName=="google.protobuf.NullValue")return null;if(t)return e;let r=i.findNumber(e);return(n=r?.name)!==null&&n!==void 0?n:e}function si(i,e){switch(i){case w.INT32:case w.SFIXED32:case w.SINT32:case w.FIXED32:case w.UINT32:return ne(typeof e=="number"),e;case w.FLOAT:case w.DOUBLE:return ne(typeof e=="number"),Number.isNaN(e)?"NaN":e===Number.POSITIVE_INFINITY?"Infinity":e===Number.NEGATIVE_INFINITY?"-Infinity":e;case w.STRING:return ne(typeof e=="string"),e;case w.BOOL:return ne(typeof e=="boolean"),e;case w.UINT64:case w.FIXED64:case w.INT64:case w.SFIXED64:case w.SINT64:return ne(typeof e=="bigint"||typeof e=="string"||typeof e=="number"),e.toString();case w.BYTES:return ne(e instanceof Uint8Array),Cc.enc(e)}}var Kt=Symbol("@bufbuild/protobuf/unknown-fields"),co={readUnknownFields:!0,readerFactory:i=>new jr(i)},lo={writeUnknownFields:!0,writerFactory:()=>new qr};function vu(i){return i?Object.assign(Object.assign({},co),i):co}function yu(i){return i?Object.assign(Object.assign({},lo),i):lo}function bu(){return{makeReadOptions:vu,makeWriteOptions:yu,listUnknownFields(i){var e;return(e=i[Kt])!==null&&e!==void 0?e:[]},discardUnknownFields(i){delete i[Kt]},writeUnknownFields(i,e){let n=i[Kt];if(n)for(let r of n)e.tag(r.no,r.wireType).raw(r.data)},onUnknownField(i,e,t,n){let r=i;Array.isArray(r[Kt])||(r[Kt]=[]),r[Kt].push({no:e,wireType:t,data:n})},readMessage(i,e,t,n,r){let s=i.getType(),a=r?e.len:e.pos+t,o,d;for(;e.pos<a;){var c=e.tag(),l=O(c,2);if(o=l[0],d=l[1],r===!0&&d==ae.EndGroup)break;let u=s.fields.find(o);if(!u){let h=e.skip(d,o);n.readUnknownFields&&this.onUnknownField(i,o,d,h);continue}uo(i,e,u,d,n)}if(r&&(d!=ae.EndGroup||o!==t))throw new Error("invalid end group tag")},readField:uo,writeMessage(i,e,t){let n=i.getType();for(let r of n.fields.byNumber()){if(!Ec(r,i)){if(r.req)throw new Error("cannot encode field ".concat(n.typeName,".").concat(r.name," to binary: required field not set"));continue}let s=r.oneof?i[r.oneof.localName].value:i[r.localName];ho(r,s,e,t)}return t.writeUnknownFields&&this.writeUnknownFields(i,e),e},writeField(i,e,t,n){e!==void 0&&ho(i,e,t,n)}}}function uo(i,e,t,n,r){let s=t.repeated,a=t.localName;switch(t.oneof&&(i=i[t.oneof.localName],i.case!=a&&delete i.value,i.case=a,a="value"),t.kind){case"scalar":case"enum":let o=t.kind=="enum"?w.INT32:t.T,d=gi;if(t.kind=="scalar"&&t.L>0&&(d=Tu),s){let f=i[a];if(n==ae.LengthDelimited&&o!=w.STRING&&o!=w.BYTES){let k=e.uint32()+e.pos;for(;e.pos<k;)f.push(d(e,o))}else f.push(d(e,o))}else i[a]=d(e,o);break;case"message":let c=t.T;s?i[a].push(ai(e,new c,r,t)):dt(i[a])?ai(e,i[a],r,t):(i[a]=ai(e,new c,r,t),c.fieldWrapper&&!t.oneof&&!t.repeated&&(i[a]=c.fieldWrapper.unwrapField(i[a])));break;case"map":let l=ku(t,e,r),u=O(l,2),h=u[0],m=u[1];i[a][h]=m;break}}function ai(i,e,t,n){let r=e.getType().runtime.bin,s=n?.delimited;return r.readMessage(e,i,s?n.no:i.uint32(),t,s),e}function ku(i,e,t){let n=e.uint32(),r=e.pos+n,s,a;for(;e.pos<r;){let o=e.tag();switch(O(o,1)[0]){case 1:s=gi(e,i.K);break;case 2:switch(i.V.kind){case"scalar":a=gi(e,i.V.T);break;case"enum":a=e.int32();break;case"message":a=ai(e,new i.V.T,t,void 0);break}break}}if(s===void 0&&(s=tn(i.K,_t.BIGINT)),typeof s!="string"&&typeof s!="number"&&(s=s.toString()),a===void 0)switch(i.V.kind){case"scalar":a=tn(i.V.T,_t.BIGINT);break;case"enum":a=i.V.T.values[0].no;break;case"message":a=new i.V.T;break}return[s,a]}function Tu(i,e){let t=gi(i,e);return typeof t=="bigint"?t.toString():t}function gi(i,e){switch(e){case w.STRING:return i.string();case w.BOOL:return i.bool();case w.DOUBLE:return i.double();case w.FLOAT:return i.float();case w.INT32:return i.int32();case w.INT64:return i.int64();case w.UINT64:return i.uint64();case w.FIXED64:return i.fixed64();case w.BYTES:return i.bytes();case w.FIXED32:return i.fixed32();case w.SFIXED32:return i.sfixed32();case w.SFIXED64:return i.sfixed64();case w.SINT64:return i.sint64();case w.UINT32:return i.uint32();case w.SINT32:return i.sint32()}}function ho(i,e,t,n){ne(e!==void 0);let r=i.repeated;switch(i.kind){case"scalar":case"enum":let a=i.kind=="enum"?w.INT32:i.T;if(r)if(ne(Array.isArray(e)),i.packed)Cu(t,a,i.no,e);else for(let o of e)Cn(t,a,i.no,o);else Cn(t,a,i.no,e);break;case"message":if(r){ne(Array.isArray(e));for(let o of e)mo(t,n,i,o)}else mo(t,n,i,e);break;case"map":ne(typeof e=="object"&&e!=null);for(let o of Object.entries(e)){var s=O(o,2);let d=s[0],c=s[1];Su(t,n,i,d,c)}break}}function Su(i,e,t,n,r){i.tag(t.no,ae.LengthDelimited),i.fork();let s=n;switch(t.K){case w.INT32:case w.FIXED32:case w.UINT32:case w.SFIXED32:case w.SINT32:s=Number.parseInt(n);break;case w.BOOL:ne(n=="true"||n=="false"),s=n=="true";break}switch(Cn(i,t.K,1,s),t.V.kind){case"scalar":Cn(i,t.V.T,2,r);break;case"enum":Cn(i,w.INT32,2,r);break;case"message":ne(r!==void 0),i.tag(2,ae.LengthDelimited).bytes(r.toBinary(e));break}i.join()}function mo(i,e,t,n){let r=Rc(t.T,n);t.delimited?i.tag(t.no,ae.StartGroup).raw(r.toBinary(e)).tag(t.no,ae.EndGroup):i.tag(t.no,ae.LengthDelimited).bytes(r.toBinary(e))}function Cn(i,e,t,n){ne(n!==void 0);let r=Pc(e),s=O(r,2),a=s[0],o=s[1];i.tag(t,a)[o](n)}function Cu(i,e,t,n){if(!n.length)return;i.tag(t,ae.LengthDelimited).fork();let r=Pc(e),s=O(r,2),a=s[1];for(let o=0;o<n.length;o++)i[a](n[o]);i.join()}function Pc(i){let e=ae.Varint;switch(i){case w.BYTES:case w.STRING:e=ae.LengthDelimited;break;case w.DOUBLE:case w.FIXED64:case w.SFIXED64:e=ae.Bit64;break;case w.FIXED32:case w.SFIXED32:case w.FLOAT:e=ae.Bit32;break}let t=w[i].toLowerCase();return[e,t]}function _u(){return{setEnumType:gc,initPartial(i,e){if(i===void 0)return;let t=e.getType();for(let r of t.fields.byMember()){let s=r.localName,a=e,o=i;if(o[s]!=null)switch(r.kind){case"oneof":let d=o[s].case;if(d===void 0)continue;let c=r.findField(d),l=o[s].value;c&&c.kind=="message"&&!dt(l,c.T)?l=new c.T(l):c&&c.kind==="scalar"&&c.T===w.BYTES&&(l=pn(l)),a[s]={case:d,value:l};break;case"scalar":case"enum":let u=o[s];r.T===w.BYTES&&(u=r.repeated?u.map(pn):pn(u)),a[s]=u;break;case"map":switch(r.V.kind){case"scalar":case"enum":if(r.V.T===w.BYTES)for(let f of Object.entries(o[s])){var n=O(f,2);let g=n[0],k=n[1];a[s][g]=pn(k)}else Object.assign(a[s],o[s]);break;case"message":let m=r.V.T;for(let f of Object.keys(o[s])){let g=o[s][f];m.fieldWrapper||(g=new m(g)),a[s][f]=g}break}break;case"message":let h=r.T;if(r.repeated)a[s]=o[s].map(m=>dt(m,h)?m:new h(m));else{let m=o[s];h.fieldWrapper?h.typeName==="google.protobuf.BytesValue"?a[s]=pn(m):a[s]=m:a[s]=dt(m,h)?m:new h(m)}break}}},equals(i,e,t){return e===t?!0:!e||!t?!1:i.fields.byMember().every(n=>{let r=e[n.localName],s=t[n.localName];if(n.repeated){if(r.length!==s.length)return!1;switch(n.kind){case"message":return r.every((a,o)=>n.T.equals(a,s[o]));case"scalar":return r.every((a,o)=>gt(n.T,a,s[o]));case"enum":return r.every((a,o)=>gt(w.INT32,a,s[o]))}throw new Error("repeated cannot contain ".concat(n.kind))}switch(n.kind){case"message":let a=r,o=s;return n.T.fieldWrapper&&(a!==void 0&&!dt(a)&&(a=n.T.fieldWrapper.wrapField(a)),o!==void 0&&!dt(o)&&(o=n.T.fieldWrapper.wrapField(o))),n.T.equals(a,o);case"enum":return gt(w.INT32,r,s);case"scalar":return gt(n.T,r,s);case"oneof":if(r.case!==s.case)return!1;let d=n.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 gt(w.INT32,r.value,s.value);case"scalar":return gt(d.T,r.value,s.value)}throw new Error("oneof cannot contain ".concat(d.kind));case"map":let c=Object.keys(r).concat(Object.keys(s));switch(n.V.kind){case"message":let l=n.V.T;return c.every(h=>l.equals(r[h],s[h]));case"enum":return c.every(h=>gt(w.INT32,r[h],s[h]));case"scalar":let u=n.V.T;return c.every(h=>gt(u,r[h],s[h]))}break}})},clone(i){let e=i.getType(),t=new e,n=t;for(let s of e.fields.byMember()){let a=i[s.localName],o;if(s.repeated)o=a.map(Xn);else if(s.kind=="map"){o=n[s.localName];for(let d of Object.entries(a)){var r=O(d,2);let c=r[0],l=r[1];o[c]=Xn(l)}}else s.kind=="oneof"?o=s.findField(a.case)?{case:a.case,value:Xn(a.value)}:{case:void 0}:o=Xn(a);n[s.localName]=o}for(let s of e.runtime.bin.listUnknownFields(i))e.runtime.bin.onUnknownField(n,s.no,s.wireType,s.data);return t}}}function Xn(i){if(i===void 0)return i;if(dt(i))return i.clone();if(i instanceof Uint8Array){let e=new Uint8Array(i.byteLength);return e.set(i),e}return i}function pn(i){return i instanceof Uint8Array?i:new Uint8Array(i)}function wu(i,e,t){return{syntax:i,json:pu(),bin:bu(),util:Object.assign(Object.assign({},_u()),{newFieldList:e,initFields:t}),makeMessageType(n,r,s){return $l(this,n,r,s)},makeEnum:Jl,makeEnumType:vc,getEnumType:zl,makeExtension(n,r,s){return ou(this,n,r,s)}}}var Vr=class{constructor(e,t){this._fields=e,this._normalizer=t}findJsonName(e){if(!this.jsonNames){let t={};for(let n of this.list())t[n.jsonName]=t[n.name]=n;this.jsonNames=t}return this.jsonNames[e]}find(e){if(!this.numbers){let t={};for(let n of this.list())t[n.no]=n;this.numbers=t}return this.numbers[e]}list(){return this.all||(this.all=this._normalizer(this._fields)),this.all}byNumber(){return this.numbersAsc||(this.numbersAsc=this.list().concat().sort((e,t)=>e.no-t.no)),this.numbersAsc}byMember(){if(!this.members){this.members=[];let e=this.members,t;for(let n of this.list())n.oneof?n.oneof!==t&&(t=n.oneof,e.push(t)):e.push(n)}return this.members}};function Ic(i,e){let t=Mc(i);return e?t:Au(Mu(t))}function Eu(i){return Ic(i,!1)}var Ru=Mc;function Mc(i){let e=!1,t=[];for(let n=0;n<i.length;n++){let r=i.charAt(n);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("")}var Pu=new Set(["constructor","toString","toJSON","valueOf"]),Iu=new Set(["getType","clone","equals","fromBinary","fromJson","fromJsonString","toBinary","toJson","toJsonString","toObject"]),Ac=i=>"".concat(i,"$"),Mu=i=>Iu.has(i)?Ac(i):i,Au=i=>Pu.has(i)?Ac(i):i,Hr=class{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=Eu(e)}addField(e){ne(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 xu(i,e){var t,n,r,s,a,o;let d=[],c;for(let l of typeof i=="function"?i():i){let u=l;if(u.localName=Ic(l.name,l.oneof!==void 0),u.jsonName=(t=l.jsonName)!==null&&t!==void 0?t:Ru(l.name),u.repeated=(n=l.repeated)!==null&&n!==void 0?n:!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!=w.BYTES&&l.T!=w.STRING),l.oneof!==void 0){let h=typeof l.oneof=="string"?l.oneof:l.oneof.name;(!c||c.name!=h)&&(c=new Hr(h)),u.oneof=c,c.addField(u)}d.push(u)}return d}var v=wu("proto3",i=>new Vr(i,e=>xu(e)),i=>{for(let e of i.getType().fields.byMember()){if(e.opt)continue;let t=e.localName,n=i;if(e.repeated){n[t]=[];continue}switch(e.kind){case"oneof":n[t]={case:void 0};break;case"enum":n[t]=0;break;case"map":n[t]={};break;case"scalar":n[t]=tn(e.T,e.L);break}}}),ut=class i extends In{constructor(e){super(),this.seconds=Y.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)));let n=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(!n)throw new Error("cannot decode google.protobuf.Timestamp from JSON: invalid RFC 3339 string");let r=Date.parse(n[1]+"-"+n[2]+"-"+n[3]+"T"+n[4]+":"+n[5]+":"+n[6]+(n[8]?n[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=Y.parse(r/1e3),this.nanos=0,n[7]&&(this.nanos=parseInt("1"+n[7]+"0".repeat(9-n[7].length))-1e9),this}toJson(e){let 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 n="Z";if(this.nanos>0){let r=(this.nanos+1e9).toString().substring(1);r.substring(3)==="000000"?n="."+r.substring(0,3)+"Z":r.substring(6)==="000"?n="."+r.substring(0,6)+"Z":n="."+r+"Z"}return new Date(t).toISOString().replace(".000Z",n)}toDate(){return new Date(Number(this.seconds)*1e3+Math.ceil(this.nanos/1e6))}static now(){return i.fromDate(new Date)}static fromDate(e){let t=e.getTime();return new i({seconds:Y.parse(Math.floor(t/1e3)),nanos:t%1e3*1e6})}static fromBinary(e,t){return new i().fromBinary(e,t)}static fromJson(e,t){return new i().fromJson(e,t)}static fromJsonString(e,t){return new i().fromJsonString(e,t)}static equals(e,t){return v.util.equals(i,e,t)}};ut.runtime=v;ut.typeName="google.protobuf.Timestamp";ut.fields=v.util.newFieldList(()=>[{no:1,name:"seconds",kind:"scalar",T:3},{no:2,name:"nanos",kind:"scalar",T:5}]);var Du=v.makeMessageType("livekit.MetricsBatch",()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:ut},{no:3,name:"str_data",kind:"scalar",T:9,repeated:!0},{no:4,name:"time_series",kind:"message",T:Ou,repeated:!0},{no:5,name:"events",kind:"message",T:Nu,repeated:!0}]),Ou=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:Lu,repeated:!0},{no:5,name:"rid",kind:"scalar",T:13}]),Lu=v.makeMessageType("livekit.MetricSample",()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:ut},{no:3,name:"value",kind:"scalar",T:2}]),Nu=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:ut},{no:7,name:"normalized_end_timestamp",kind:"message",T:ut,opt:!0},{no:8,name:"metadata",kind:"scalar",T:9},{no:9,name:"rid",kind:"scalar",T:13}]);var xc=v.makeEnum("livekit.BackupCodecPolicy",[{no:0,name:"PREFER_REGRESSION"},{no:1,name:"SIMULCAST"},{no:2,name:"REGRESSION"}]),Ue=v.makeEnum("livekit.TrackType",[{no:0,name:"AUDIO"},{no:1,name:"VIDEO"},{no:2,name:"DATA"}]),oe=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"}]),fa=v.makeEnum("livekit.VideoQuality",[{no:0,name:"LOW"},{no:1,name:"MEDIUM"},{no:2,name:"HIGH"},{no:3,name:"OFF"}]),kn=v.makeEnum("livekit.ConnectionQuality",[{no:0,name:"POOR"},{no:1,name:"GOOD"},{no:2,name:"EXCELLENT"},{no:3,name:"LOST"}]),Mn=v.makeEnum("livekit.ClientConfigSetting",[{no:0,name:"UNSET"},{no:1,name:"DISABLED"},{no:2,name:"ENABLED"}]),re=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"}]),Rt=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"}]),Uu=v.makeEnum("livekit.SubscriptionError",[{no:0,name:"SE_UNKNOWN"},{no:1,name:"SE_CODEC_UNSUPPORTED"},{no:2,name:"SE_TRACK_NOTFOUND"}]),le=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"}]),nn=v.makeEnum("livekit.PacketTrailerFeature",[{no:0,name:"PTF_USER_TIMESTAMP"},{no:1,name:"PTF_FRAME_ID"}]),Xi=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:vi,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:Wc}]),vi=v.makeMessageType("livekit.Codec",()=>[{no:1,name:"mime",kind:"scalar",T:9},{no:2,name:"fmtp_line",kind:"scalar",T:9}]),Fu=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(oe),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}]),Ut=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(Jt)},{no:4,name:"tracks",kind:"message",T:Wt,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:Fu},{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(An)},{no:15,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:16,name:"disconnect_reason",kind:"enum",T:v.getEnumType(re)},{no:18,name:"kind_details",kind:"enum",T:v.getEnumType(Bu),repeated:!0},{no:19,name:"data_tracks",kind:"message",T:Zi,repeated:!0},{no:20,name:"client_protocol",kind:"scalar",T:5}]),Jt=v.makeEnum("livekit.ParticipantInfo.State",[{no:0,name:"JOINING"},{no:1,name:"JOINED"},{no:2,name:"ACTIVE"},{no:3,name:"DISCONNECTED"}]),An=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"}]),Bu=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"}]),$=v.makeEnum("livekit.Encryption.Type",[{no:0,name:"NONE"},{no:1,name:"GCM"},{no:2,name:"CUSTOM"}]),qu=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:Tt,repeated:!0},{no:5,name:"video_layer_mode",kind:"enum",T:v.getEnumType(Dc)},{no:6,name:"sdp_cid",kind:"scalar",T:9}]),Wt=v.makeMessageType("livekit.TrackInfo",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"type",kind:"enum",T:v.getEnumType(Ue)},{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(oe)},{no:10,name:"layers",kind:"message",T:Tt,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:qu,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($)},{no:17,name:"stream",kind:"scalar",T:9},{no:18,name:"version",kind:"message",T:Wc},{no:19,name:"audio_features",kind:"enum",T:v.getEnumType(le),repeated:!0},{no:20,name:"backup_codec_policy",kind:"enum",T:v.getEnumType(xc)},{no:21,name:"packet_trailer_features",kind:"enum",T:v.getEnumType(nn),repeated:!0}]),Zi=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($)}]),ju=v.makeMessageType("livekit.DataTrackSubscriptionOptions",()=>[{no:1,name:"target_fps",kind:"scalar",T:13,opt:!0}]),Tt=v.makeMessageType("livekit.VideoLayer",()=>[{no:1,name:"quality",kind:"enum",T:v.getEnumType(fa)},{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}]),Dc=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"}]),ge=v.makeMessageType("livekit.DataPacket",()=>[{no:1,name:"kind",kind:"enum",T:v.getEnumType(Ze)},{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:ga,oneof:"value"},{no:3,name:"speaker",kind:"message",T:Vu,oneof:"value"},{no:6,name:"sip_dtmf",kind:"message",T:Uc,oneof:"value"},{no:7,name:"transcription",kind:"message",T:Hu,oneof:"value"},{no:8,name:"metrics",kind:"message",T:Du,oneof:"value"},{no:9,name:"chat_message",kind:"message",T:yi,oneof:"value"},{no:10,name:"rpc_request",kind:"message",T:va,oneof:"value"},{no:11,name:"rpc_ack",kind:"message",T:er,oneof:"value"},{no:12,name:"rpc_response",kind:"message",T:ya,oneof:"value"},{no:13,name:"stream_header",kind:"message",T:bi,oneof:"value"},{no:14,name:"stream_chunk",kind:"message",T:ki,oneof:"value"},{no:15,name:"stream_trailer",kind:"message",T:Ti,oneof:"value"},{no:18,name:"encrypted_packet",kind:"message",T:Oc,oneof:"value"},{no:16,name:"sequence",kind:"scalar",T:13},{no:17,name:"participant_sid",kind:"scalar",T:9}]),Ze=v.makeEnum("livekit.DataPacket.Kind",[{no:0,name:"RELIABLE"},{no:1,name:"LOSSY"}]),Oc=v.makeMessageType("livekit.EncryptedPacket",()=>[{no:1,name:"encryption_type",kind:"enum",T:v.getEnumType($)},{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}]),Lc=v.makeMessageType("livekit.EncryptedPacketPayload",()=>[{no:1,name:"user",kind:"message",T:ga,oneof:"value"},{no:3,name:"chat_message",kind:"message",T:yi,oneof:"value"},{no:4,name:"rpc_request",kind:"message",T:va,oneof:"value"},{no:5,name:"rpc_ack",kind:"message",T:er,oneof:"value"},{no:6,name:"rpc_response",kind:"message",T:ya,oneof:"value"},{no:7,name:"stream_header",kind:"message",T:bi,oneof:"value"},{no:8,name:"stream_chunk",kind:"message",T:ki,oneof:"value"},{no:9,name:"stream_trailer",kind:"message",T:Ti,oneof:"value"}]),Vu=v.makeMessageType("livekit.ActiveSpeakerUpdate",()=>[{no:1,name:"speakers",kind:"message",T:Nc,repeated:!0}]),Nc=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}]),ga=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}]),Uc=v.makeMessageType("livekit.SipDTMF",()=>[{no:3,name:"code",kind:"scalar",T:13},{no:4,name:"digit",kind:"scalar",T:9}]),Hu=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:Gu,repeated:!0}]),Gu=v.makeMessageType("livekit.TranscriptionSegment",()=>[{no:1,name:"id",kind:"scalar",T:9},{no:2,name:"text",kind:"scalar",T:9},{no:3,name:"start_time",kind:"scalar",T:4},{no:4,name:"end_time",kind:"scalar",T:4},{no:5,name:"final",kind:"scalar",T:8},{no:6,name:"language",kind:"scalar",T:9}]),yi=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}]),va=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}]),er=v.makeMessageType("livekit.RpcAck",()=>[{no:1,name:"request_id",kind:"scalar",T:9}]),ya=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:Fc,oneof:"value"},{no:4,name:"compressed_payload",kind:"scalar",T:12,oneof:"value"}]),Fc=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}]),Bc=v.makeMessageType("livekit.ParticipantTracks",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"track_sids",kind:"scalar",T:9,repeated:!0}]),qc=v.makeMessageType("livekit.ServerInfo",()=>[{no:1,name:"edition",kind:"enum",T:v.getEnumType(jc)},{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}]),jc=v.makeEnum("livekit.ServerInfo.Edition",[{no:0,name:"Standard"},{no:1,name:"Cloud"}]),Vc=v.makeMessageType("livekit.ClientInfo",()=>[{no:1,name:"sdk",kind:"enum",T:v.getEnumType(Hc)},{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(Gc),repeated:!0}]),Hc=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"}]),Gc=v.makeEnum("livekit.ClientInfo.Capability",[{no:0,name:"CAP_UNUSED"},{no:1,name:"CAP_PACKET_TRAILER"}]),Kc=v.makeMessageType("livekit.ClientConfiguration",()=>[{no:1,name:"video",kind:"message",T:po},{no:2,name:"screen",kind:"message",T:po},{no:3,name:"resume_connection",kind:"enum",T:v.getEnumType(Mn)},{no:4,name:"disabled_codecs",kind:"message",T:Ku},{no:5,name:"force_relay",kind:"enum",T:v.getEnumType(Mn)}]),po=v.makeMessageType("livekit.VideoConfiguration",()=>[{no:1,name:"hardware_encoder",kind:"enum",T:v.getEnumType(Mn)}]),Ku=v.makeMessageType("livekit.DisabledCodecs",()=>[{no:1,name:"codecs",kind:"message",T:vi,repeated:!0},{no:2,name:"publish",kind:"message",T:vi,repeated:!0}]),Wc=v.makeMessageType("livekit.TimedVersion",()=>[{no:1,name:"unix_micro",kind:"scalar",T:3},{no:2,name:"ticks",kind:"scalar",T:5}]),Gr=v.makeEnum("livekit.DataStream.OperationType",[{no:0,name:"CREATE"},{no:1,name:"UPDATE"},{no:2,name:"DELETE"},{no:3,name:"REACTION"}]),zc=v.makeMessageType("livekit.DataStream.TextHeader",()=>[{no:1,name:"operation_type",kind:"enum",T:v.getEnumType(Gr)},{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"}),Jc=v.makeMessageType("livekit.DataStream.ByteHeader",()=>[{no:1,name:"name",kind:"scalar",T:9}],{localName:"DataStream_ByteHeader"}),bi=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($)},{no:8,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:9,name:"text_header",kind:"message",T:zc,oneof:"content_header"},{no:10,name:"byte_header",kind:"message",T:Jc,oneof:"content_header"}],{localName:"DataStream_Header"}),ki=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"}),Ti=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"});var Wu=v.makeMessageType("livekit.SubscribedAudioCodec",()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"enabled",kind:"scalar",T:8}]);var Fe=v.makeEnum("livekit.SignalTarget",[{no:0,name:"PUBLISHER"},{no:1,name:"SUBSCRIBER"}]),Kr=v.makeEnum("livekit.StreamState",[{no:0,name:"ACTIVE"},{no:1,name:"PAUSED"}]),zu=v.makeEnum("livekit.CandidateProtocol",[{no:0,name:"UDP"},{no:1,name:"TCP"},{no:2,name:"TLS"}]),Ju=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:tr,oneof:"message"},{no:4,name:"add_track",kind:"message",T:xn,oneof:"message"},{no:5,name:"mute",kind:"message",T:nr,oneof:"message"},{no:6,name:"subscription",kind:"message",T:ir,oneof:"message"},{no:7,name:"track_setting",kind:"message",T:Yc,oneof:"message"},{no:8,name:"leave",kind:"message",T:rr,oneof:"message"},{no:10,name:"update_layers",kind:"message",T:Zc,oneof:"message"},{no:11,name:"subscription_permission",kind:"message",T:nd,oneof:"message"},{no:12,name:"sync_state",kind:"message",T:Ea,oneof:"message"},{no:13,name:"simulate",kind:"message",T:Qe,oneof:"message"},{no:14,name:"ping",kind:"scalar",T:3,oneof:"message"},{no:15,name:"update_metadata",kind:"message",T:_a,oneof:"message"},{no:16,name:"ping_req",kind:"message",T:sd,oneof:"message"},{no:17,name:"update_audio_track",kind:"message",T:Ca,oneof:"message"},{no:18,name:"update_video_track",kind:"message",T:Xc,oneof:"message"},{no:19,name:"publish_data_track_request",kind:"message",T:ba,oneof:"message"},{no:20,name:"unpublish_data_track_request",kind:"message",T:Ta,oneof:"message"},{no:21,name:"update_data_subscription",kind:"message",T:$c,oneof:"message"}]),fo=v.makeMessageType("livekit.SignalResponse",()=>[{no:1,name:"join",kind:"message",T:Xu,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:tr,oneof:"message"},{no:5,name:"update",kind:"message",T:th,oneof:"message"},{no:6,name:"track_published",kind:"message",T:Sa,oneof:"message"},{no:8,name:"leave",kind:"message",T:rr,oneof:"message"},{no:9,name:"mute",kind:"message",T:nr,oneof:"message"},{no:10,name:"speakers_changed",kind:"message",T:nh,oneof:"message"},{no:11,name:"room_update",kind:"message",T:ih,oneof:"message"},{no:12,name:"connection_quality",kind:"message",T:sh,oneof:"message"},{no:13,name:"stream_state_update",kind:"message",T:oh,oneof:"message"},{no:14,name:"subscribed_quality_update",kind:"message",T:dh,oneof:"message"},{no:15,name:"subscription_permission_update",kind:"message",T:uh,oneof:"message"},{no:16,name:"refresh_token",kind:"scalar",T:9,oneof:"message"},{no:17,name:"track_unpublished",kind:"message",T:eh,oneof:"message"},{no:18,name:"pong",kind:"scalar",T:3,oneof:"message"},{no:19,name:"reconnect",kind:"message",T:Zu,oneof:"message"},{no:20,name:"pong_resp",kind:"message",T:mh,oneof:"message"},{no:21,name:"subscription_response",kind:"message",T:gh,oneof:"message"},{no:22,name:"request_response",kind:"message",T:vh,oneof:"message"},{no:23,name:"track_subscribed",kind:"message",T:yh,oneof:"message"},{no:24,name:"room_moved",kind:"message",T:hh,oneof:"message"},{no:25,name:"media_sections_requirement",kind:"message",T:Th,oneof:"message"},{no:26,name:"subscribed_audio_codec_update",kind:"message",T:lh,oneof:"message"},{no:27,name:"publish_data_track_response",kind:"message",T:ka,oneof:"message"},{no:28,name:"unpublish_data_track_response",kind:"message",T:$u,oneof:"message"},{no:29,name:"data_track_subscriber_handles",kind:"message",T:Qu,oneof:"message"}]),Wr=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:Tt,repeated:!0},{no:5,name:"video_layer_mode",kind:"enum",T:v.getEnumType(Dc)}]),xn=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(Ue)},{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(oe)},{no:9,name:"layers",kind:"message",T:Tt,repeated:!0},{no:10,name:"simulcast_codecs",kind:"message",T:Wr,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($)},{no:15,name:"stream",kind:"scalar",T:9},{no:16,name:"backup_codec_policy",kind:"enum",T:v.getEnumType(xc)},{no:17,name:"audio_features",kind:"enum",T:v.getEnumType(le),repeated:!0},{no:18,name:"packet_trailer_features",kind:"enum",T:v.getEnumType(nn),repeated:!0}]),ba=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($)}]),ka=v.makeMessageType("livekit.PublishDataTrackResponse",()=>[{no:1,name:"info",kind:"message",T:Zi}]),Ta=v.makeMessageType("livekit.UnpublishDataTrackRequest",()=>[{no:1,name:"pub_handle",kind:"scalar",T:13}]),$u=v.makeMessageType("livekit.UnpublishDataTrackResponse",()=>[{no:1,name:"info",kind:"message",T:Zi}]),Qu=v.makeMessageType("livekit.DataTrackSubscriberHandles",()=>[{no:1,name:"sub_handles",kind:"map",K:13,V:{kind:"message",T:Yu}}]),Yu=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"}),tr=v.makeMessageType("livekit.TrickleRequest",()=>[{no:1,name:"candidateInit",kind:"scalar",T:9},{no:2,name:"target",kind:"enum",T:v.getEnumType(Fe)},{no:3,name:"final",kind:"scalar",T:8}]),nr=v.makeMessageType("livekit.MuteTrackRequest",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"muted",kind:"scalar",T:8}]),Xu=v.makeMessageType("livekit.JoinResponse",()=>[{no:1,name:"room",kind:"message",T:Xi},{no:2,name:"participant",kind:"message",T:Ut},{no:3,name:"other_participants",kind:"message",T:Ut,repeated:!0},{no:4,name:"server_version",kind:"scalar",T:9},{no:5,name:"ice_servers",kind:"message",T:ed,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:Kc},{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:qc},{no:13,name:"sif_trailer",kind:"scalar",T:12},{no:14,name:"enabled_publish_codecs",kind:"message",T:vi,repeated:!0},{no:15,name:"fast_publish",kind:"scalar",T:8}]),Zu=v.makeMessageType("livekit.ReconnectResponse",()=>[{no:1,name:"ice_servers",kind:"message",T:ed,repeated:!0},{no:2,name:"client_configuration",kind:"message",T:Kc},{no:3,name:"server_info",kind:"message",T:qc},{no:4,name:"last_message_seq",kind:"scalar",T:13}]),Sa=v.makeMessageType("livekit.TrackPublishedResponse",()=>[{no:1,name:"cid",kind:"scalar",T:9},{no:2,name:"track",kind:"message",T:Wt}]),eh=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}}]),th=v.makeMessageType("livekit.ParticipantUpdate",()=>[{no:1,name:"participants",kind:"message",T:Ut,repeated:!0}]),ir=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:Bc,repeated:!0}]),$c=v.makeMessageType("livekit.UpdateDataSubscription",()=>[{no:1,name:"updates",kind:"message",T:Qc,repeated:!0}]),Qc=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:ju}],{localName:"UpdateDataSubscription_Update"}),Yc=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(fa)},{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}]),Ca=v.makeMessageType("livekit.UpdateLocalAudioTrack",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"features",kind:"enum",T:v.getEnumType(le),repeated:!0}]),Xc=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}]),rr=v.makeMessageType("livekit.LeaveRequest",()=>[{no:1,name:"can_reconnect",kind:"scalar",T:8},{no:2,name:"reason",kind:"enum",T:v.getEnumType(re)},{no:3,name:"action",kind:"enum",T:v.getEnumType($t)},{no:4,name:"regions",kind:"message",T:ph}]),$t=v.makeEnum("livekit.LeaveRequest.Action",[{no:0,name:"DISCONNECT"},{no:1,name:"RESUME"},{no:2,name:"RECONNECT"}]),Zc=v.makeMessageType("livekit.UpdateVideoLayers",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"layers",kind:"message",T:Tt,repeated:!0}]),_a=v.makeMessageType("livekit.UpdateParticipantMetadata",()=>[{no:1,name:"metadata",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",T:9},{no:3,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:4,name:"request_id",kind:"scalar",T:13}]),ed=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}]),nh=v.makeMessageType("livekit.SpeakersChanged",()=>[{no:1,name:"speakers",kind:"message",T:Nc,repeated:!0}]),ih=v.makeMessageType("livekit.RoomUpdate",()=>[{no:1,name:"room",kind:"message",T:Xi}]),rh=v.makeMessageType("livekit.ConnectionQualityInfo",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"quality",kind:"enum",T:v.getEnumType(kn)},{no:3,name:"score",kind:"scalar",T:2}]),sh=v.makeMessageType("livekit.ConnectionQualityUpdate",()=>[{no:1,name:"updates",kind:"message",T:rh,repeated:!0}]),ah=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(Kr)}]),oh=v.makeMessageType("livekit.StreamStateUpdate",()=>[{no:1,name:"stream_states",kind:"message",T:ah,repeated:!0}]),wa=v.makeMessageType("livekit.SubscribedQuality",()=>[{no:1,name:"quality",kind:"enum",T:v.getEnumType(fa)},{no:2,name:"enabled",kind:"scalar",T:8}]),ch=v.makeMessageType("livekit.SubscribedCodec",()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"qualities",kind:"message",T:wa,repeated:!0}]),dh=v.makeMessageType("livekit.SubscribedQualityUpdate",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribed_qualities",kind:"message",T:wa,repeated:!0},{no:3,name:"subscribed_codecs",kind:"message",T:ch,repeated:!0}]),lh=v.makeMessageType("livekit.SubscribedAudioCodecUpdate",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribed_audio_codecs",kind:"message",T:Wu,repeated:!0}]),td=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}]),nd=v.makeMessageType("livekit.SubscriptionPermission",()=>[{no:1,name:"all_participants",kind:"scalar",T:8},{no:2,name:"track_permissions",kind:"message",T:td,repeated:!0}]),uh=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}]),hh=v.makeMessageType("livekit.RoomMovedResponse",()=>[{no:1,name:"room",kind:"message",T:Xi},{no:2,name:"token",kind:"scalar",T:9},{no:3,name:"participant",kind:"message",T:Ut},{no:4,name:"other_participants",kind:"message",T:Ut,repeated:!0}]),Ea=v.makeMessageType("livekit.SyncState",()=>[{no:1,name:"answer",kind:"message",T:wt},{no:2,name:"subscription",kind:"message",T:ir},{no:3,name:"publish_tracks",kind:"message",T:Sa,repeated:!0},{no:4,name:"data_channels",kind:"message",T:rd,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:id,repeated:!0},{no:8,name:"publish_data_tracks",kind:"message",T:ka,repeated:!0}]),id=v.makeMessageType("livekit.DataChannelReceiveState",()=>[{no:1,name:"publisher_sid",kind:"scalar",T:9},{no:2,name:"last_seq",kind:"scalar",T:13}]),rd=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(Fe)}]),Qe=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(zu),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"}]),sd=v.makeMessageType("livekit.Ping",()=>[{no:1,name:"timestamp",kind:"scalar",T:3},{no:2,name:"rtt",kind:"scalar",T:3}]),mh=v.makeMessageType("livekit.Pong",()=>[{no:1,name:"last_ping_timestamp",kind:"scalar",T:3},{no:2,name:"timestamp",kind:"scalar",T:3}]),ph=v.makeMessageType("livekit.RegionSettings",()=>[{no:1,name:"regions",kind:"message",T:fh,repeated:!0}]),fh=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}]),gh=v.makeMessageType("livekit.SubscriptionResponse",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"err",kind:"enum",T:v.getEnumType(Uu)}]),vh=v.makeMessageType("livekit.RequestResponse",()=>[{no:1,name:"request_id",kind:"scalar",T:13},{no:2,name:"reason",kind:"enum",T:v.getEnumType(It)},{no:3,name:"message",kind:"scalar",T:9},{no:4,name:"trickle",kind:"message",T:tr,oneof:"request"},{no:5,name:"add_track",kind:"message",T:xn,oneof:"request"},{no:6,name:"mute",kind:"message",T:nr,oneof:"request"},{no:7,name:"update_metadata",kind:"message",T:_a,oneof:"request"},{no:8,name:"update_audio_track",kind:"message",T:Ca,oneof:"request"},{no:9,name:"update_video_track",kind:"message",T:Xc,oneof:"request"},{no:10,name:"publish_data_track",kind:"message",T:ba,oneof:"request"},{no:11,name:"unpublish_data_track",kind:"message",T:Ta,oneof:"request"}]),It=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"},{no:8,name:"INVALID_NAME"},{no:9,name:"DUPLICATE_HANDLE"},{no:10,name:"DUPLICATE_NAME"}]),yh=v.makeMessageType("livekit.TrackSubscribed",()=>[{no:1,name:"track_sid",kind:"scalar",T:9}]),ad=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}]),bh=v.makeMessageType("livekit.JoinRequest",()=>[{no:1,name:"client_info",kind:"message",T:Vc},{no:2,name:"connection_settings",kind:"message",T:ad},{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:xn,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(Rt)},{no:9,name:"participant_sid",kind:"scalar",T:9},{no:10,name:"sync_state",kind:"message",T:Ea}]),kh=v.makeMessageType("livekit.WrappedJoinRequest",()=>[{no:1,name:"compression",kind:"enum",T:v.getEnumType(zr)},{no:2,name:"join_request",kind:"scalar",T:12}]),zr=v.makeEnum("livekit.WrappedJoinRequest.Compression",[{no:0,name:"NONE"},{no:1,name:"GZIP"}]),Th=v.makeMessageType("livekit.MediaSectionsRequirement",()=>[{no:1,name:"num_audios",kind:"scalar",T:13},{no:2,name:"num_videos",kind:"scalar",T:13}]);function Sh(i){return i&&i.__esModule&&Object.prototype.hasOwnProperty.call(i,"default")?i.default:i}var oi={exports:{}},Ch=oi.exports,go;function _h(){return go||(go=1,(function(i){(function(e,t){i.exports?i.exports=t():e.log=t()})(Ch,function(){var e=function(){},t="undefined",n=typeof window!==t&&typeof window.navigator!==t&&/Trident\/|MSIE /.test(window.navigator.userAgent),r=["trace","debug","info","warn","error"],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"&&n?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 m(g,k){var T=this,S,L,y,b="loglevel";typeof g=="string"?b+=":"+g:typeof g=="symbol"&&(b=void 0);function E(x){var B=(r[x]||"silent").toUpperCase();if(!(typeof window===t||!b)){try{window.localStorage[b]=B;return}catch{}try{window.document.cookie=encodeURIComponent(b)+"="+B+";"}catch{}}}function M(){var x;if(!(typeof window===t||!b)){try{x=window.localStorage[b]}catch{}if(typeof x===t)try{var B=window.document.cookie,Z=encodeURIComponent(b),ee=B.indexOf(Z+"=");ee!==-1&&(x=/^([^;]+)/.exec(B.slice(ee+Z.length+1))[1])}catch{}return T.levels[x]===void 0&&(x=void 0),x}}function D(){if(!(typeof window===t||!b)){try{window.localStorage.removeItem(b)}catch{}try{window.document.cookie=encodeURIComponent(b)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}function q(x){var B=x;if(typeof B=="string"&&T.levels[B.toUpperCase()]!==void 0&&(B=T.levels[B.toUpperCase()]),typeof B=="number"&&B>=0&&B<=T.levels.SILENT)return B;throw new TypeError("log.setLevel() called with invalid level: "+x)}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 y??L??S},T.setLevel=function(x,B){return y=q(x),B!==!1&&E(y),l.call(T)},T.setDefaultLevel=function(x){L=q(x),M()||T.setLevel(x,!1)},T.resetLevel=function(){y=null,D(),l.call(T)},T.enableAll=function(x){T.setLevel(T.levels.TRACE,x)},T.disableAll=function(x){T.setLevel(T.levels.SILENT,x)},T.rebuild=function(){if(a!==T&&(S=q(a.getLevel())),l.call(T),a===T)for(var x in s)s[x].rebuild()},S=q(a?a.getLevel():"WARN");var A=M();A!=null&&(y=q(A)),l.call(T)}a=new m,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 m(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})})(oi)),oi.exports}var sr=_h(),Jr;(function(i){i[i.trace=0]="trace",i[i.debug=1]="debug",i[i.info=2]="info",i[i.warn=3]="warn",i[i.error=4]="error",i[i.silent=5]="silent"})(Jr||(Jr={}));var ue;(function(i){i.Default="livekit",i.Room="livekit-room",i.TokenSource="livekit-token-source",i.Participant="livekit-participant",i.Track="livekit-track",i.Publication="livekit-track-publication",i.Engine="livekit-engine",i.Signal="livekit-signal",i.PCManager="livekit-pc-manager",i.PCTransport="livekit-pc-transport",i.E2EE="lk-e2ee",i.DataTracks="livekit-data-tracks"})(ue||(ue={}));var F=sr.getLogger(ue.Default),lf=Object.values(ue).map(i=>sr.getLogger(i));F.setDefaultLevel(Jr.info);function _e(i,e){let t=sr.getLogger(i);return t.setDefaultLevel(F.getLevel()),e?wh(t,e):t}function wh(i,e){let t=r=>(s,a)=>{let o=e(),d=o||a?Object.assign(Object.assign({},o),a):void 0;i[r](s,d)},n=Object.create(i);return n.trace=t("trace"),n.debug=t("debug"),n.info=t("info"),n.warn=t("warn"),n.error=t("error"),n}var Eh=sr.getLogger(ue.E2EE),fn=7e3,Rh=[0,300,4*300,9*300,16*300,fn,fn,fn,fn,fn],$r=class{constructor(e){this._retryDelays=e!==void 0?[...e]:Rh}nextRetryDelayInMs(e){if(e.retryCount>=this._retryDelays.length)return null;let t=this._retryDelays[e.retryCount];return e.retryCount<=1?t:t+Math.random()*1e3}};function Ph(i,e){var t={};for(var n in i)Object.prototype.hasOwnProperty.call(i,n)&&e.indexOf(n)<0&&(t[n]=i[n]);if(i!=null&&typeof Object.getOwnPropertySymbols=="function")for(var r=0,n=Object.getOwnPropertySymbols(i);r<n.length;r++)e.indexOf(n[r])<0&&Object.prototype.propertyIsEnumerable.call(i,n[r])&&(t[n[r]]=i[n[r]]);return t}function p(i,e,t,n){function r(s){return s instanceof t?s:new t(function(a){a(s)})}return new(t||(t=Promise))(function(s,a){function o(l){try{c(n.next(l))}catch(u){a(u)}}function d(l){try{c(n.throw(l))}catch(u){a(u)}}function c(l){l.done?s(l.value):r(l.value).then(o,d)}c((n=n.apply(i,e||[])).next())})}function vo(i){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&i[e],n=0;if(t)return t.call(i);if(i&&typeof i.length=="number")return{next:function(){return i&&n>=i.length&&(i=void 0),{value:i&&i[n++],done:!i}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function rn(i){return this instanceof rn?(this.v=i,this):new rn(i)}function Ih(i,e,t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n=t.apply(i,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(m){return function(f){return Promise.resolve(f).then(m,u)}}function o(m,f){n[m]&&(r[m]=function(g){return new Promise(function(k,T){s.push([m,g,k,T])>1||d(m,g)})},f&&(r[m]=f(r[m])))}function d(m,f){try{c(n[m](f))}catch(g){h(s[0][3],g)}}function c(m){m.value instanceof rn?Promise.resolve(m.value.v).then(l,u):h(s[0][2],m)}function l(m){d("next",m)}function u(m){d("throw",m)}function h(m,f){m(f),s.shift(),s.length&&d(s[0][0],s[0][1])}}function Mh(i){var e,t;return e={},n("next"),n("throw",function(r){throw r}),n("return"),e[Symbol.iterator]=function(){return this},e;function n(r,s){e[r]=i[r]?function(a){return(t=!t)?{value:rn(i[r](a)),done:!1}:s?s(a):a}:s}}function Be(i){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=i[Symbol.asyncIterator],t;return e?e.call(i):(i=typeof vo=="function"?vo(i):i[Symbol.iterator](),t={},n("next"),n("throw"),n("return"),t[Symbol.asyncIterator]=function(){return this},t);function n(s){t[s]=i[s]&&function(a){return new Promise(function(o,d){a=i[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 Zn={exports:{}},yo;function Ah(){if(yo)return Zn.exports;yo=1;var i=typeof Reflect=="object"?Reflect:null,e=i&&typeof i.apply=="function"?i.apply:function(b,E,M){return Function.prototype.apply.call(b,E,M)},t;i&&typeof i.ownKeys=="function"?t=i.ownKeys:Object.getOwnPropertySymbols?t=function(b){return Object.getOwnPropertyNames(b).concat(Object.getOwnPropertySymbols(b))}:t=function(b){return Object.getOwnPropertyNames(b)};function n(y){console&&console.warn&&console.warn(y)}var r=Number.isNaN||function(b){return b!==b};function s(){s.init.call(this)}Zn.exports=s,Zn.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(y){if(typeof y!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof y)}Object.defineProperty(s,"defaultMaxListeners",{enumerable:!0,get:function(){return a},set:function(y){if(typeof y!="number"||y<0||r(y))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+y+".");a=y}}),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(b){if(typeof b!="number"||b<0||r(b))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+b+".");return this._maxListeners=b,this};function d(y){return y._maxListeners===void 0?s.defaultMaxListeners:y._maxListeners}s.prototype.getMaxListeners=function(){return d(this)},s.prototype.emit=function(b){for(var E=[],M=1;M<arguments.length;M++)E.push(arguments[M]);var D=b==="error",q=this._events;if(q!==void 0)D=D&&q.error===void 0;else if(!D)return!1;if(D){var A;if(E.length>0&&(A=E[0]),A instanceof Error)throw A;var x=new Error("Unhandled error."+(A?" ("+A.message+")":""));throw x.context=A,x}var B=q[b];if(B===void 0)return!1;if(typeof B=="function")e(B,this,E);else for(var Z=B.length,ee=f(B,Z),M=0;M<Z;++M)e(ee[M],this,E);return!0};function c(y,b,E,M){var D,q,A;if(o(E),q=y._events,q===void 0?(q=y._events=Object.create(null),y._eventsCount=0):(q.newListener!==void 0&&(y.emit("newListener",b,E.listener?E.listener:E),q=y._events),A=q[b]),A===void 0)A=q[b]=E,++y._eventsCount;else if(typeof A=="function"?A=q[b]=M?[E,A]:[A,E]:M?A.unshift(E):A.push(E),D=d(y),D>0&&A.length>D&&!A.warned){A.warned=!0;var x=new Error("Possible EventEmitter memory leak detected. "+A.length+" "+String(b)+" listeners added. Use emitter.setMaxListeners() to increase limit");x.name="MaxListenersExceededWarning",x.emitter=y,x.type=b,x.count=A.length,n(x)}return y}s.prototype.addListener=function(b,E){return c(this,b,E,!1)},s.prototype.on=s.prototype.addListener,s.prototype.prependListener=function(b,E){return c(this,b,E,!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(y,b,E){var M={fired:!1,wrapFn:void 0,target:y,type:b,listener:E},D=l.bind(M);return D.listener=E,M.wrapFn=D,D}s.prototype.once=function(b,E){return o(E),this.on(b,u(this,b,E)),this},s.prototype.prependOnceListener=function(b,E){return o(E),this.prependListener(b,u(this,b,E)),this},s.prototype.removeListener=function(b,E){var M,D,q,A,x;if(o(E),D=this._events,D===void 0)return this;if(M=D[b],M===void 0)return this;if(M===E||M.listener===E)--this._eventsCount===0?this._events=Object.create(null):(delete D[b],D.removeListener&&this.emit("removeListener",b,M.listener||E));else if(typeof M!="function"){for(q=-1,A=M.length-1;A>=0;A--)if(M[A]===E||M[A].listener===E){x=M[A].listener,q=A;break}if(q<0)return this;q===0?M.shift():g(M,q),M.length===1&&(D[b]=M[0]),D.removeListener!==void 0&&this.emit("removeListener",b,x||E)}return this},s.prototype.off=s.prototype.removeListener,s.prototype.removeAllListeners=function(b){var E,M,D;if(M=this._events,M===void 0)return this;if(M.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):M[b]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete M[b]),this;if(arguments.length===0){var q=Object.keys(M),A;for(D=0;D<q.length;++D)A=q[D],A!=="removeListener"&&this.removeAllListeners(A);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(E=M[b],typeof E=="function")this.removeListener(b,E);else if(E!==void 0)for(D=E.length-1;D>=0;D--)this.removeListener(b,E[D]);return this};function h(y,b,E){var M=y._events;if(M===void 0)return[];var D=M[b];return D===void 0?[]:typeof D=="function"?E?[D.listener||D]:[D]:E?k(D):f(D,D.length)}s.prototype.listeners=function(b){return h(this,b,!0)},s.prototype.rawListeners=function(b){return h(this,b,!1)},s.listenerCount=function(y,b){return typeof y.listenerCount=="function"?y.listenerCount(b):m.call(y,b)},s.prototype.listenerCount=m;function m(y){var b=this._events;if(b!==void 0){var E=b[y];if(typeof E=="function")return 1;if(E!==void 0)return E.length}return 0}s.prototype.eventNames=function(){return this._eventsCount>0?t(this._events):[]};function f(y,b){for(var E=new Array(b),M=0;M<b;++M)E[M]=y[M];return E}function g(y,b){for(;b+1<y.length;b++)y[b]=y[b+1];y.pop()}function k(y){for(var b=new Array(y.length),E=0;E<b.length;++E)b[E]=y[E].listener||y[E];return b}function T(y,b){return new Promise(function(E,M){function D(A){y.removeListener(b,q),M(A)}function q(){typeof y.removeListener=="function"&&y.removeListener("error",D),E([].slice.call(arguments))}L(y,b,q,{once:!0}),b!=="error"&&S(y,D,{once:!0})})}function S(y,b,E){typeof y.on=="function"&&L(y,"error",b,E)}function L(y,b,E,M){if(typeof y.on=="function")M.once?y.once(b,E):y.on(b,E);else if(typeof y.addEventListener=="function")y.addEventListener(b,function D(q){M.once&&y.removeEventListener(b,D),E(q)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof y)}return Zn.exports}var Ee=Ah(),od=!0,cd=!0;function Tn(i,e,t){let n=i.match(e);return n&&n.length>=t&&parseFloat(n[t],10)}function Vt(i,e,t){if(!i.RTCPeerConnection)return;if(!Object.getOwnPropertyDescriptor(EventTarget.prototype,"addEventListener").writable){Ra("Unable to polyfill events");return}let r=i.RTCPeerConnection.prototype,s=r.addEventListener;r.addEventListener=function(o,d){if(o!==e)return s.apply(this,arguments);let c=l=>{let 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])};let 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);let 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 xh(i){return typeof i!="boolean"?new Error("Argument type: "+typeof i+". Please use a boolean."):(od=i,i?"adapter.js logging disabled":"adapter.js logging enabled")}function Dh(i){return typeof i!="boolean"?new Error("Argument type: "+typeof i+". Please use a boolean."):(cd=!i,"adapter.js deprecation warnings "+(i?"disabled":"enabled"))}function Ra(){if(typeof window=="object"){if(od)return;typeof console<"u"&&typeof console.log=="function"&&console.log.apply(console,arguments)}}function Pa(i,e){cd&&console.warn(i+" is deprecated, please use "+e+" instead.")}function Oh(i){let e={browser:null,version:null};if(typeof i>"u"||!i.navigator||!i.navigator.userAgent)return e.browser="Not a browser.",e;let t=i.navigator;if(t.userAgentData&&t.userAgentData.brands){let n=t.userAgentData.brands.find(r=>r.brand==="Chromium");if(n)return{browser:"chrome",version:parseInt(n.version,10)}}if(t.mozGetUserMedia)e.browser="firefox",e.version=parseInt(Tn(t.userAgent,/Firefox\/(\d+)\./,1));else if(t.webkitGetUserMedia||i.isSecureContext===!1&&i.webkitRTCPeerConnection)e.browser="chrome",e.version=parseInt(Tn(t.userAgent,/Chrom(e|ium)\/(\d+)\./,2))||null;else if(i.RTCPeerConnection&&t.userAgent.match(/AppleWebKit\/(\d+)\./))e.browser="safari",e.version=parseInt(Tn(t.userAgent,/AppleWebKit\/(\d+)\./,1)),e.supportsUnifiedPlan=i.RTCRtpTransceiver&&"currentDirection"in i.RTCRtpTransceiver.prototype,e._safariVersion=Tn(t.userAgent,/Version\/(\d+(\.?\d+))/,1);else return e.browser="Not a supported browser.",e;return e}function bo(i){return Object.prototype.toString.call(i)==="[object Object]"}function dd(i){return bo(i)?Object.keys(i).reduce(function(e,t){let n=bo(i[t]),r=n?dd(i[t]):i[t],s=n&&!Object.keys(r).length;return r===void 0||s?e:Object.assign(e,{[t]:r})},{}):i}function Qr(i,e,t){!e||t.has(e.id)||(t.set(e.id,e),Object.keys(e).forEach(n=>{n.endsWith("Id")?Qr(i,i.get(e[n]),t):n.endsWith("Ids")&&e[n].forEach(r=>{Qr(i,i.get(r),t)})}))}function ko(i,e,t){let n=t?"outbound-rtp":"inbound-rtp",r=new Map;if(e===null)return r;let s=[];return i.forEach(a=>{a.type==="track"&&a.trackIdentifier===e.id&&s.push(a)}),s.forEach(a=>{i.forEach(o=>{o.type===n&&o.trackId===a.id&&Qr(i,o,r)})}),r}var To=Ra;function ld(i,e){let t=i&&i.navigator;if(!t.mediaDevices)return;let n=function(o){if(typeof o!="object"||o.mandatory||o.optional)return o;let d={};return Object.keys(o).forEach(c=>{if(c==="require"||c==="advanced"||c==="mediaSource")return;let l=typeof o[c]=="object"?o[c]:{ideal:o[c]};l.exact!==void 0&&typeof l.exact=="number"&&(l.min=l.max=l.exact);let u=function(h,m){return h?h+m.charAt(0).toUpperCase()+m.slice(1):m==="deviceId"?"sourceId":m};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"){let 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=n(o.audio)}if(o&&typeof o.video=="object"){let c=o.video.facingMode;c=c&&(typeof c=="object"?c:{ideal:c});let 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 m=h.find(f=>u.some(g=>f.label.toLowerCase().includes(g)));return!m&&h.length&&u.includes("back")&&(m=h[h.length-1]),m&&(o.video.deviceId=c.exact?{exact:m.deviceId}:{ideal:m.deviceId}),o.video=n(o.video),To("chrome: "+JSON.stringify(o)),d(o)})}o.video=n(o.video)}return To("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){let 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 ud(i){i.MediaStream=i.MediaStream||i.webkitMediaStream}function hd(i,e){if(!(e.version>102))if(typeof i=="object"&&i.RTCPeerConnection&&!("ontrack"in i.RTCPeerConnection.prototype)){Object.defineProperty(i.RTCPeerConnection.prototype,"ontrack",{get(){return this._ontrack},set(n){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=n)},enumerable:!0,configurable:!0});let t=i.RTCPeerConnection.prototype.setRemoteDescription;i.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=r=>{r.stream.addEventListener("addtrack",s=>{let a;i.RTCPeerConnection.prototype.getReceivers?a=this.getReceivers().find(d=>d.track&&d.track.id===s.track.id):a={track:s.track};let 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;i.RTCPeerConnection.prototype.getReceivers?a=this.getReceivers().find(d=>d.track&&d.track.id===s.id):a={track:s};let 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(i,"track",t=>(t.transceiver||Object.defineProperty(t,"transceiver",{value:{receiver:t.receiver}}),t))}function md(i){if(typeof i=="object"&&i.RTCPeerConnection&&!("getSenders"in i.RTCPeerConnection.prototype)&&"createDTMFSender"in i.RTCPeerConnection.prototype){let e=function(r,s){return{track:s,get dtmf(){return this._dtmf===void 0&&(s.kind==="audio"?this._dtmf=r.createDTMFSender(s):this._dtmf=null),this._dtmf},_pc:r}};if(!i.RTCPeerConnection.prototype.getSenders){i.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};let r=i.RTCPeerConnection.prototype.addTrack;i.RTCPeerConnection.prototype.addTrack=function(o,d){let c=r.apply(this,arguments);return c||(c=e(this,o),this._senders.push(c)),c};let s=i.RTCPeerConnection.prototype.removeTrack;i.RTCPeerConnection.prototype.removeTrack=function(o){s.apply(this,arguments);let d=this._senders.indexOf(o);d!==-1&&this._senders.splice(d,1)}}let t=i.RTCPeerConnection.prototype.addStream;i.RTCPeerConnection.prototype.addStream=function(s){this._senders=this._senders||[],t.apply(this,[s]),s.getTracks().forEach(a=>{this._senders.push(e(this,a))})};let n=i.RTCPeerConnection.prototype.removeStream;i.RTCPeerConnection.prototype.removeStream=function(s){this._senders=this._senders||[],n.apply(this,[s]),s.getTracks().forEach(a=>{let o=this._senders.find(d=>d.track===a);o&&this._senders.splice(this._senders.indexOf(o),1)})}}else if(typeof i=="object"&&i.RTCPeerConnection&&"getSenders"in i.RTCPeerConnection.prototype&&"createDTMFSender"in i.RTCPeerConnection.prototype&&i.RTCRtpSender&&!("dtmf"in i.RTCRtpSender.prototype)){let e=i.RTCPeerConnection.prototype.getSenders;i.RTCPeerConnection.prototype.getSenders=function(){let n=e.apply(this,[]);return n.forEach(r=>r._pc=this),n},Object.defineProperty(i.RTCRtpSender.prototype,"dtmf",{get(){return this._dtmf===void 0&&(this.track.kind==="audio"?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}})}}function pd(i,e){if(e.version>=67||!(typeof i=="object"&&i.RTCPeerConnection&&i.RTCRtpSender&&i.RTCRtpReceiver))return;if(!("getStats"in i.RTCRtpSender.prototype)){let n=i.RTCPeerConnection.prototype.getSenders;n&&(i.RTCPeerConnection.prototype.getSenders=function(){let a=n.apply(this,[]);return a.forEach(o=>o._pc=this),a});let r=i.RTCPeerConnection.prototype.addTrack;r&&(i.RTCPeerConnection.prototype.addTrack=function(){let a=r.apply(this,arguments);return a._pc=this,a}),i.RTCRtpSender.prototype.getStats=function(){let a=this;return this._pc.getStats().then(o=>ko(o,a.track,!0))}}if(!("getStats"in i.RTCRtpReceiver.prototype)){let n=i.RTCPeerConnection.prototype.getReceivers;n&&(i.RTCPeerConnection.prototype.getReceivers=function(){let s=n.apply(this,[]);return s.forEach(a=>a._pc=this),s}),Vt(i,"track",r=>(r.receiver._pc=r.srcElement,r)),i.RTCRtpReceiver.prototype.getStats=function(){let s=this;return this._pc.getStats().then(a=>ko(a,s.track,!1))}}if(!("getStats"in i.RTCRtpSender.prototype&&"getStats"in i.RTCRtpReceiver.prototype))return;let t=i.RTCPeerConnection.prototype.getStats;i.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof i.MediaStreamTrack){let r=arguments[0],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 fd(i){i.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map(a=>this._shimmedLocalStreams[a][0])};let e=i.RTCPeerConnection.prototype.addTrack;i.RTCPeerConnection.prototype.addTrack=function(a,o){if(!o)return e.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};let 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};let t=i.RTCPeerConnection.prototype.addStream;i.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")});let o=this.getSenders();t.apply(this,arguments);let d=this.getSenders().filter(c=>o.indexOf(c)===-1);this._shimmedLocalStreams[a.id]=[a].concat(d)};let n=i.RTCPeerConnection.prototype.removeStream;i.RTCPeerConnection.prototype.removeStream=function(a){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[a.id],n.apply(this,arguments)};let r=i.RTCPeerConnection.prototype.removeTrack;i.RTCPeerConnection.prototype.removeTrack=function(a){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},a&&Object.keys(this._shimmedLocalStreams).forEach(o=>{let 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 gd(i,e){if(!i.RTCPeerConnection)return;if(i.RTCPeerConnection.prototype.addTrack&&e.version>=65)return fd(i);let t=i.RTCPeerConnection.prototype.getLocalStreams;i.RTCPeerConnection.prototype.getLocalStreams=function(){let l=t.apply(this);return this._reverseStreams=this._reverseStreams||{},l.map(u=>this._reverseStreams[u.id])};let n=i.RTCPeerConnection.prototype.addStream;i.RTCPeerConnection.prototype.addStream=function(l){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},l.getTracks().forEach(u=>{if(this.getSenders().find(m=>m.track===u))throw new DOMException("Track already exists.","InvalidAccessError")}),!this._reverseStreams[l.id]){let u=new i.MediaStream(l.getTracks());this._streams[l.id]=u,this._reverseStreams[u.id]=l,l=u}n.apply(this,[l])};let r=i.RTCPeerConnection.prototype.removeStream;i.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]},i.RTCPeerConnection.prototype.addTrack=function(l,u){if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");let 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||{};let f=this._streams[u.id];if(f)f.addTrack(l),Promise.resolve().then(()=>{this.dispatchEvent(new Event("negotiationneeded"))});else{let g=new i.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=>{let m=c._reverseStreams[h],f=c._streams[m.id];u=u.replace(new RegExp(f.id,"g"),m.id)}),new RTCSessionDescription({type:l.type,sdp:u})}function a(c,l){let u=l.sdp;return Object.keys(c._reverseStreams||[]).forEach(h=>{let m=c._reverseStreams[h],f=c._streams[m.id];u=u.replace(new RegExp(m.id,"g"),f.id)}),new RTCSessionDescription({type:l.type,sdp:u})}["createOffer","createAnswer"].forEach(function(c){let l=i.RTCPeerConnection.prototype[c],u={[c](){let h=arguments;return arguments.length&&typeof arguments[0]=="function"?l.apply(this,[f=>{let 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))}};i.RTCPeerConnection.prototype[c]=u[c]});let o=i.RTCPeerConnection.prototype.setLocalDescription;i.RTCPeerConnection.prototype.setLocalDescription=function(){return!arguments.length||!arguments[0].type?o.apply(this,arguments):(arguments[0]=a(this,arguments[0]),o.apply(this,arguments))};let d=Object.getOwnPropertyDescriptor(i.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(i.RTCPeerConnection.prototype,"localDescription",{get(){let c=d.get.apply(this);return c.type===""?c:s(this,c)}}),i.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(m=>{this._streams[m].getTracks().find(g=>l.track===g)&&(h=this._streams[m])}),h&&(h.getTracks().length===1?this.removeStream(this._reverseStreams[h.id]):h.removeTrack(l.track),this.dispatchEvent(new Event("negotiationneeded")))}}function Yr(i,e){!i.RTCPeerConnection&&i.webkitRTCPeerConnection&&(i.RTCPeerConnection=i.webkitRTCPeerConnection),i.RTCPeerConnection&&e.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(t){let n=i.RTCPeerConnection.prototype[t],r={[t](){return arguments[0]=new(t==="addIceCandidate"?i.RTCIceCandidate:i.RTCSessionDescription)(arguments[0]),n.apply(this,arguments)}};i.RTCPeerConnection.prototype[t]=r[t]})}function vd(i,e){e.version>102||Vt(i,"negotiationneeded",t=>{let n=t.target;if(!((e.version<72||n.getConfiguration&&n.getConfiguration().sdpSemantics==="plan-b")&&n.signalingState!=="stable"))return t})}var So=Object.freeze({__proto__:null,fixNegotiationNeeded:vd,shimAddTrackRemoveTrack:gd,shimAddTrackRemoveTrackWithNative:fd,shimGetSendersWithDtmf:md,shimGetUserMedia:ld,shimMediaStream:ud,shimOnTrack:hd,shimPeerConnection:Yr,shimSenderReceiverGetStats:pd});function yd(i,e){let t=i&&i.navigator,n=i&&i.MediaStreamTrack;if(t.getUserMedia=function(r,s,a){Pa("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),t.mediaDevices.getUserMedia(r).then(s,a)},!(e.version>55&&"autoGainControl"in t.mediaDevices.getSupportedConstraints())){let 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)},n&&n.prototype.getSettings){let a=n.prototype.getSettings;n.prototype.getSettings=function(){let o=a.apply(this,arguments);return r(o,"mozAutoGainControl","autoGainControl"),r(o,"mozNoiseSuppression","noiseSuppression"),o}}if(n&&n.prototype.applyConstraints){let a=n.prototype.applyConstraints;n.prototype.applyConstraints=function(o){return this.kind==="audio"&&typeof o=="object"&&(o=JSON.parse(JSON.stringify(o)),r(o,"autoGainControl","mozAutoGainControl"),r(o,"noiseSuppression","mozNoiseSuppression")),a.apply(this,[o])}}}}function Lh(i,e){i.navigator.mediaDevices&&"getDisplayMedia"in i.navigator.mediaDevices||i.navigator.mediaDevices&&(i.navigator.mediaDevices.getDisplayMedia=function(n){if(!(n&&n.video)){let r=new DOMException("getDisplayMedia without video constraints is undefined");return r.name="NotFoundError",r.code=8,Promise.reject(r)}return n.video===!0?n.video={mediaSource:e}:n.video.mediaSource=e,i.navigator.mediaDevices.getUserMedia(n)})}function bd(i){typeof i=="object"&&i.RTCTrackEvent&&"receiver"in i.RTCTrackEvent.prototype&&!("transceiver"in i.RTCTrackEvent.prototype)&&Object.defineProperty(i.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function Xr(i,e){typeof i!="object"||!(i.RTCPeerConnection||i.mozRTCPeerConnection)||(!i.RTCPeerConnection&&i.mozRTCPeerConnection&&(i.RTCPeerConnection=i.mozRTCPeerConnection),e.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(t){let n=i.RTCPeerConnection.prototype[t],r={[t](){return arguments[0]=new(t==="addIceCandidate"?i.RTCIceCandidate:i.RTCSessionDescription)(arguments[0]),n.apply(this,arguments)}};i.RTCPeerConnection.prototype[t]=r[t]}))}function kd(i,e){if(typeof i!="object"||!(i.RTCPeerConnection||i.mozRTCPeerConnection)||e.version>=151)return;let t={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},n=i.RTCPeerConnection.prototype.getStats;i.RTCPeerConnection.prototype.getStats=function(){let s=Array.prototype.slice.call(arguments),a=s[0],o=s[1],d=s[2];return this.signalingState==="closed"?Promise.resolve(new Map):n.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 Td(i){if(!(typeof i=="object"&&i.RTCPeerConnection&&i.RTCRtpSender)||i.RTCRtpSender&&"getStats"in i.RTCRtpSender.prototype)return;let e=i.RTCPeerConnection.prototype.getSenders;e&&(i.RTCPeerConnection.prototype.getSenders=function(){let r=e.apply(this,[]);return r.forEach(s=>s._pc=this),r});let t=i.RTCPeerConnection.prototype.addTrack;t&&(i.RTCPeerConnection.prototype.addTrack=function(){let r=t.apply(this,arguments);return r._pc=this,r}),i.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}function Sd(i){if(!(typeof i=="object"&&i.RTCPeerConnection&&i.RTCRtpSender)||i.RTCRtpSender&&"getStats"in i.RTCRtpReceiver.prototype)return;let e=i.RTCPeerConnection.prototype.getReceivers;e&&(i.RTCPeerConnection.prototype.getReceivers=function(){let n=e.apply(this,[]);return n.forEach(r=>r._pc=this),n}),Vt(i,"track",t=>(t.receiver._pc=t.srcElement,t)),i.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function Cd(i){!i.RTCPeerConnection||"removeStream"in i.RTCPeerConnection.prototype||(i.RTCPeerConnection.prototype.removeStream=function(t){Pa("removeStream","removeTrack"),this.getSenders().forEach(n=>{n.track&&t.getTracks().includes(n.track)&&this.removeTrack(n)})})}function _d(i){i.DataChannel&&!i.RTCDataChannel&&(i.RTCDataChannel=i.DataChannel)}function wd(i){if(!(typeof i=="object"&&i.RTCPeerConnection))return;let e=i.RTCPeerConnection.prototype.addTransceiver;e&&(i.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let n=arguments[1]&&arguments[1].sendEncodings;n===void 0&&(n=[]),n=[...n];let r=n.length>0;r&&n.forEach(a=>{if("rid"in a&&!/^[a-z0-9]{0,16}$/i.test(a.rid))throw new TypeError("Invalid RID value provided.");if("scaleResolutionDownBy"in a&&!(parseFloat(a.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in a&&!(parseFloat(a.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")});let s=e.apply(this,arguments);if(r){let a=s.sender,o=a.getParameters();(!("encodings"in o)||o.encodings.length===1&&Object.keys(o.encodings[0]).length===0)&&(o.encodings=n,a.sendEncodings=n,this.setParametersPromises.push(a.setParameters(o).then(()=>{delete a.sendEncodings}).catch(()=>{delete a.sendEncodings})))}return s})}function Ed(i){if(!(typeof i=="object"&&i.RTCRtpSender))return;let e=i.RTCRtpSender.prototype.getParameters;e&&(i.RTCRtpSender.prototype.getParameters=function(){let n=e.apply(this,arguments);return"encodings"in n||(n.encodings=[].concat(this.sendEncodings||[{}])),n})}function Rd(i){if(!(typeof i=="object"&&i.RTCPeerConnection))return;let e=i.RTCPeerConnection.prototype.createOffer;i.RTCPeerConnection.prototype.createOffer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>e.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):e.apply(this,arguments)}}function Pd(i){if(!(typeof i=="object"&&i.RTCPeerConnection))return;let e=i.RTCPeerConnection.prototype.createAnswer;i.RTCPeerConnection.prototype.createAnswer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>e.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):e.apply(this,arguments)}}var Co=Object.freeze({__proto__:null,shimAddTransceiver:wd,shimCreateAnswer:Pd,shimCreateOffer:Rd,shimGetDisplayMedia:Lh,shimGetParameters:Ed,shimGetStats:kd,shimGetUserMedia:yd,shimOnTrack:bd,shimPeerConnection:Xr,shimRTCDataChannel:_d,shimReceiverGetStats:Sd,shimRemoveStream:Cd,shimSenderGetStats:Td});function Id(i){if(!(typeof i!="object"||!i.RTCPeerConnection)){if("getLocalStreams"in i.RTCPeerConnection.prototype||(i.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in i.RTCPeerConnection.prototype)){let e=i.RTCPeerConnection.prototype.addTrack;i.RTCPeerConnection.prototype.addStream=function(n){this._localStreams||(this._localStreams=[]),this._localStreams.includes(n)||this._localStreams.push(n),n.getAudioTracks().forEach(r=>e.call(this,r,n)),n.getVideoTracks().forEach(r=>e.call(this,r,n))},i.RTCPeerConnection.prototype.addTrack=function(n){for(var r=arguments.length,s=new Array(r>1?r-1:0),a=1;a<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 i.RTCPeerConnection.prototype||(i.RTCPeerConnection.prototype.removeStream=function(t){this._localStreams||(this._localStreams=[]);let n=this._localStreams.indexOf(t);if(n===-1)return;this._localStreams.splice(n,1);let r=t.getTracks();this.getSenders().forEach(s=>{r.includes(s.track)&&this.removeTrack(s)})})}}function Md(i){if(!(typeof i!="object"||!i.RTCPeerConnection)&&("getRemoteStreams"in i.RTCPeerConnection.prototype||(i.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]}),!("onaddstream"in i.RTCPeerConnection.prototype))){Object.defineProperty(i.RTCPeerConnection.prototype,"onaddstream",{get(){return this._onaddstream},set(t){this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=t),this.addEventListener("track",this._onaddstreampoly=n=>{n.streams.forEach(r=>{if(this._remoteStreams||(this._remoteStreams=[]),this._remoteStreams.includes(r))return;this._remoteStreams.push(r);let s=new Event("addstream");s.stream=r,this.dispatchEvent(s)})})}});let e=i.RTCPeerConnection.prototype.setRemoteDescription;i.RTCPeerConnection.prototype.setRemoteDescription=function(){let n=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(r){r.streams.forEach(s=>{if(n._remoteStreams||(n._remoteStreams=[]),n._remoteStreams.indexOf(s)>=0)return;n._remoteStreams.push(s);let a=new Event("addstream");a.stream=s,n.dispatchEvent(a)})}),e.apply(n,arguments)}}}function Ad(i){if(typeof i!="object"||!i.RTCPeerConnection)return;let e=i.RTCPeerConnection.prototype,t=e.createOffer,n=e.createAnswer,r=e.setLocalDescription,s=e.setRemoteDescription,a=e.addIceCandidate;e.createOffer=function(c,l){let 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){let u=arguments.length>=2?arguments[2]:arguments[0],h=n.apply(this,[u]);return l?(h.then(c,l),Promise.resolve()):h};let o=function(d,c,l){let u=r.apply(this,[d]);return l?(u.then(c,l),Promise.resolve()):u};e.setLocalDescription=o,o=function(d,c,l){let u=s.apply(this,[d]);return l?(u.then(c,l),Promise.resolve()):u},e.setRemoteDescription=o,o=function(d,c,l){let u=a.apply(this,[d]);return l?(u.then(c,l),Promise.resolve()):u},e.addIceCandidate=o}function xd(i){let e=i&&i.navigator;if(e.mediaDevices&&e.mediaDevices.getUserMedia){let t=e.mediaDevices,n=t.getUserMedia.bind(t);e.mediaDevices.getUserMedia=r=>n(Dd(r))}!e.getUserMedia&&e.mediaDevices&&e.mediaDevices.getUserMedia&&(e.getUserMedia=function(n,r,s){e.mediaDevices.getUserMedia(n).then(r,s)}.bind(e))}function Dd(i){return i&&i.video!==void 0?Object.assign({},i,{video:dd(i.video)}):i}function Od(i){if(!i.RTCPeerConnection)return;let e=i.RTCPeerConnection;i.RTCPeerConnection=function(n,r){if(n&&n.iceServers){let s=[];for(let a=0;a<n.iceServers.length;a++){let o=n.iceServers[a];o.urls===void 0&&o.url?(Pa("RTCIceServer.url","RTCIceServer.urls"),o=JSON.parse(JSON.stringify(o)),o.urls=o.url,delete o.url,s.push(o)):s.push(n.iceServers[a])}n.iceServers=s}return new e(n,r)},i.RTCPeerConnection.prototype=e.prototype,"generateCertificate"in e&&Object.defineProperty(i.RTCPeerConnection,"generateCertificate",{get(){return e.generateCertificate}})}function Ld(i){typeof i=="object"&&i.RTCTrackEvent&&"receiver"in i.RTCTrackEvent.prototype&&!("transceiver"in i.RTCTrackEvent.prototype)&&Object.defineProperty(i.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function Nd(i){let e=i.RTCPeerConnection.prototype.createOffer;i.RTCPeerConnection.prototype.createOffer=function(n){if(n){typeof n.offerToReceiveAudio<"u"&&(n.offerToReceiveAudio=!!n.offerToReceiveAudio);let r=this.getTransceivers().find(a=>a.receiver.track.kind==="audio");n.offerToReceiveAudio===!1&&r?r.direction==="sendrecv"?r.setDirection?r.setDirection("sendonly"):r.direction="sendonly":r.direction==="recvonly"&&(r.setDirection?r.setDirection("inactive"):r.direction="inactive"):n.offerToReceiveAudio===!0&&!r&&this.addTransceiver("audio",{direction:"recvonly"}),typeof n.offerToReceiveVideo<"u"&&(n.offerToReceiveVideo=!!n.offerToReceiveVideo);let s=this.getTransceivers().find(a=>a.receiver.track.kind==="video");n.offerToReceiveVideo===!1&&s?s.direction==="sendrecv"?s.setDirection?s.setDirection("sendonly"):s.direction="sendonly":s.direction==="recvonly"&&(s.setDirection?s.setDirection("inactive"):s.direction="inactive"):n.offerToReceiveVideo===!0&&!s&&this.addTransceiver("video",{direction:"recvonly"})}return e.apply(this,arguments)}}function Ud(i){typeof i!="object"||i.AudioContext||(i.AudioContext=i.webkitAudioContext)}var _o=Object.freeze({__proto__:null,shimAudioContext:Ud,shimCallbacksAPI:Ad,shimConstraints:Dd,shimCreateOfferLegacy:Nd,shimGetUserMedia:xd,shimLocalStreamsAPI:Id,shimRTCIceServerUrls:Od,shimRemoteStreamsAPI:Md,shimTrackEventTransceiver:Ld}),Tr={exports:{}},wo;function Nh(){return wo||(wo=1,(function(i){let 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
4
  `).map(n=>n.trim())},e.splitSections=function(t){return t.split(`
5
5
  m=`).map((r,s)=>(s>0?"m="+r:r).trim()+`\r
6
6
  `)},e.getDescription=function(t){let n=e.splitSections(t);return n&&n[0]},e.getMediaSections=function(t){let n=e.splitSections(t);return n.shift(),n},e.matchPrefix=function(t,n){return e.splitLines(t).filter(r=>r.indexOf(n)===0)},e.parseCandidate=function(t){let n;t.indexOf("a=candidate:")===0?n=t.substring(12).split(" "):n=t.substring(10).split(" ");let r={foundation:n[0],component:{1:"rtp",2:"rtcp"}[n[1]]||n[1],protocol:n[2].toLowerCase(),priority:parseInt(n[3],10),ip:n[4],address:n[4],port:parseInt(n[5],10),type:n[7]};for(let s=8;s<n.length;s+=2)switch(n[s]){case"raddr":r.relatedAddress=n[s+1];break;case"rport":r.relatedPort=parseInt(n[s+1],10);break;case"tcptype":r.tcpType=n[s+1];break;case"ufrag":r.ufrag=n[s+1],r.usernameFragment=n[s+1];break;default:r[n[s]]===void 0&&(r[n[s]]=n[s+1]);break}return r},e.writeCandidate=function(t){let n=[];n.push(t.foundation);let r=t.component;r==="rtp"?n.push(1):r==="rtcp"?n.push(2):n.push(r),n.push(t.protocol.toUpperCase()),n.push(t.priority),n.push(t.address||t.ip),n.push(t.port);let s=t.type;return n.push("typ"),n.push(s),s!=="host"&&t.relatedAddress&&t.relatedPort!==void 0&&(n.push("raddr"),n.push(t.relatedAddress),n.push("rport"),n.push(t.relatedPort)),t.tcpType&&t.protocol.toLowerCase()==="tcp"&&(n.push("tcptype"),n.push(t.tcpType)),(t.usernameFragment||t.ufrag)&&(n.push("ufrag"),n.push(t.usernameFragment||t.ufrag)),"candidate:"+n.join(" ")},e.parseIceOptions=function(t){return t.substring(14).split(" ")},e.parseRtpMap=function(t){let n=t.substring(9).split(" "),r={payloadType:parseInt(n.shift(),10)};return n=n[0].split("/"),r.name=n[0],r.clockRate=parseInt(n[1],10),r.channels=n.length===3?parseInt(n[2],10):1,r.numChannels=r.channels,r},e.writeRtpMap=function(t){let n=t.payloadType;t.preferredPayloadType!==void 0&&(n=t.preferredPayloadType);let r=t.channels||t.numChannels||1;return"a=rtpmap:"+n+" "+t.name+"/"+t.clockRate+(r!==1?"/"+r:"")+`\r
@@ -17,7 +17,7 @@ a=ice-pwd:`+t.password+`\r
17
17
  `,r+=`c=IN IP4 0.0.0.0\r
18
18
  `,r+=`a=rtcp:9 IN IP4 0.0.0.0\r
19
19
  `,n.codecs.forEach(a=>{r+=e.writeRtpMap(a),r+=e.writeFmtp(a),r+=e.writeRtcpFb(a)});let s=0;return n.codecs.forEach(a=>{a.maxptime>s&&(s=a.maxptime)}),s>0&&(r+="a=maxptime:"+s+`\r
20
- `),n.headerExtensions&&n.headerExtensions.forEach(a=>{r+=e.writeExtmap(a)}),r},e.parseRtpEncodingParameters=function(t){let n=[],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,c,l=e.matchPrefix(t,"a=ssrc-group:FID").map(h=>h.substring(17).split(" ").map(g=>parseInt(g,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 m={ssrc:d,codecPayloadType:parseInt(h.parameters.apt,10)};d&&c&&(m.rtx={ssrc:c}),n.push(m),s&&(m=JSON.parse(JSON.stringify(m)),m.fec={ssrc:d,mechanism:a?"red+ulpfec":"red"},n.push(m))}}),n.length===0&&d&&n.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,n.forEach(h=>{h.maxBitrate=u})),n},e.parseRtcpParameters=function(t){let n={},r=e.matchPrefix(t,"a=ssrc:").map(o=>e.parseSsrcMedia(o)).filter(o=>o.attribute==="cname")[0];r&&(n.cname=r.value,n.ssrc=r.ssrc);let s=e.matchPrefix(t,"a=rtcp-rsize");n.reducedSize=s.length>0,n.compound=s.length===0;let a=e.matchPrefix(t,"a=rtcp-mux");return n.mux=a.length>0,n},e.writeRtcpParameters=function(t){let n="";return t.reducedSize&&(n+=`a=rtcp-rsize\r
20
+ `),n.headerExtensions&&n.headerExtensions.forEach(a=>{r+=e.writeExtmap(a)}),r},e.parseRtpEncodingParameters=function(t){let n=[],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,c,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 m={ssrc:d,codecPayloadType:parseInt(h.parameters.apt,10)};d&&c&&(m.rtx={ssrc:c}),n.push(m),s&&(m=JSON.parse(JSON.stringify(m)),m.fec={ssrc:d,mechanism:a?"red+ulpfec":"red"},n.push(m))}}),n.length===0&&d&&n.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,n.forEach(h=>{h.maxBitrate=u})),n},e.parseRtcpParameters=function(t){let n={},r=e.matchPrefix(t,"a=ssrc:").map(o=>e.parseSsrcMedia(o)).filter(o=>o.attribute==="cname")[0];r&&(n.cname=r.value,n.ssrc=r.ssrc);let s=e.matchPrefix(t,"a=rtcp-rsize");n.reducedSize=s.length>0,n.compound=s.length===0;let a=e.matchPrefix(t,"a=rtcp-mux");return n.mux=a.length>0,n},e.writeRtcpParameters=function(t){let n="";return t.reducedSize&&(n+=`a=rtcp-rsize\r
21
21
  `),t.mux&&(n+=`a=rtcp-mux\r
22
22
  `),t.ssrc!==void 0&&t.cname&&(n+="a=ssrc:"+t.ssrc+" cname:"+t.cname+`\r
23
23
  `),n},e.parseMsid=function(t){let n,r=e.matchPrefix(t,"a=msid:");if(r.length===1)return n=r[0].substring(7).split(" "),{stream:n[0],track:n[1]};let s=e.matchPrefix(t,"a=ssrc:").map(a=>e.parseSsrcMedia(a)).filter(a=>a.attribute==="msid");if(s.length>0)return n=s[0].value.split(" "),{stream:n[0],track:n[1]}},e.parseSctpDescription=function(t){let n=e.parseMLine(t),r=e.matchPrefix(t,"a=max-message-size:"),s;r.length>0&&(s=parseInt(r[0].substring(19),10)),isNaN(s)&&(s=65536);let a=e.matchPrefix(t,"a=sctp-port:");if(a.length>0)return{port:parseInt(a[0].substring(12),10),protocol:n.fmt,maxMessageSize:s};let o=e.matchPrefix(t,"a=sctpmap:");if(o.length>0){let d=o[0].substring(10).split(" ");return{port:parseInt(d[0],10),protocol:d[1],maxMessageSize:s}}},e.writeSctpDescription=function(t,n){let r=[];return t.protocol!=="DTLS/SCTP"?r=["m="+t.kind+" 9 "+t.protocol+" "+n.protocol+`\r
@@ -31,10 +31,10 @@ a=ice-pwd:`+t.password+`\r
31
31
  o=`+(r||"thisisadapterortc")+" "+s+" "+a+` IN IP4 127.0.0.1\r
32
32
  s=-\r
33
33
  t=0 0\r
34
- `},e.getDirection=function(t,n){let 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 n?e.getDirection(n):"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){let 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){let 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;let n=e.splitLines(t);for(let r=0;r<n.length;r++)if(n[r].length<2||n[r].charAt(1)!=="=")return!1;return!0},i.exports=e})(Tr)),Tr.exports}var Nd=Dh(),Qt=bh(Nd),Oh=Nl({__proto__:null,default:Qt},[Nd]);function ci(i){if(!i.RTCIceCandidate||i.RTCIceCandidate&&"foundation"in i.RTCIceCandidate.prototype)return;let e=i.RTCIceCandidate;i.RTCIceCandidate=function(n){if(typeof n=="object"&&n.candidate&&n.candidate.indexOf("a=")===0&&(n=JSON.parse(JSON.stringify(n)),n.candidate=n.candidate.substring(2)),n.candidate&&n.candidate.length){let r=new e(n),s=Qt.parseCandidate(n.candidate);for(let 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(n)},i.RTCIceCandidate.prototype=e.prototype,Vt(i,"icecandidate",t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new i.RTCIceCandidate(t.candidate),writable:"false"}),t))}function Zr(i){!i.RTCIceCandidate||i.RTCIceCandidate&&"relayProtocol"in i.RTCIceCandidate.prototype||Vt(i,"icecandidate",e=>{if(e.candidate){let t=Qt.parseCandidate(e.candidate.candidate);t.type==="relay"&&(e.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[t.priority>>24])}return e})}function di(i,e){if(!i.RTCPeerConnection)return;"sctp"in i.RTCPeerConnection.prototype||Object.defineProperty(i.RTCPeerConnection.prototype,"sctp",{get(){return typeof this._sctp>"u"?null:this._sctp}});let t=function(o){if(!o||!o.sdp)return!1;let d=Qt.splitSections(o.sdp);return d.shift(),d.some(c=>{let l=Qt.parseMLine(c);return l&&l.kind==="application"&&l.protocol.indexOf("SCTP")!==-1})},n=function(o){let d=o.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(d===null||d.length<2)return-1;let 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);let 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=i.RTCPeerConnection.prototype.setRemoteDescription;i.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])){let d=n(arguments[0]),c=r(d),l=s(arguments[0],d),u;c===0&&l===0?u=Number.POSITIVE_INFINITY:c===0||l===0?u=Math.max(c,l):u=Math.min(c,l);let h={};Object.defineProperty(h,"maxMessageSize",{get(){return u}}),this._sctp=h}return a.apply(this,arguments)}}function li(i,e){if(!(i.RTCPeerConnection&&"createDataChannel"in i.RTCPeerConnection.prototype)||e.browser==="chrome"&&e.version>149||e.browser==="firefox"&&e.version>60)return;function t(r,s){let a=r.send;r.send=function(){let 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)}}let n=i.RTCPeerConnection.prototype.createDataChannel;i.RTCPeerConnection.prototype.createDataChannel=function(){let s=n.apply(this,arguments);return t(s,this),s},Vt(i,"datachannel",r=>(t(r.channel,r.target),r))}function es(i){if(!i.RTCPeerConnection||"connectionState"in i.RTCPeerConnection.prototype)return;let e=i.RTCPeerConnection.prototype;Object.defineProperty(e,"connectionState",{get(){return{completed:"connected",checking:"connecting"}[this.iceConnectionState]||this.iceConnectionState},enumerable:!0,configurable:!0}),Object.defineProperty(e,"onconnectionstatechange",{get(){return this._onconnectionstatechange||null},set(t){this._onconnectionstatechange&&(this.removeEventListener("connectionstatechange",this._onconnectionstatechange),delete this._onconnectionstatechange),t&&this.addEventListener("connectionstatechange",this._onconnectionstatechange=t)},enumerable:!0,configurable:!0}),["setLocalDescription","setRemoteDescription"].forEach(t=>{let n=e[t];e[t]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=r=>{let s=r.target;if(s._lastConnectionState!==s.connectionState){s._lastConnectionState=s.connectionState;let a=new Event("connectionstatechange",r);s.dispatchEvent(a)}return r},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),n.apply(this,arguments)}})}function ts(i,e){if(!i.RTCPeerConnection||e.browser==="chrome"&&e.version>=71||e.browser==="safari"&&e._safariVersion>=13.1)return;let t=i.RTCPeerConnection.prototype.setRemoteDescription;i.RTCPeerConnection.prototype.setRemoteDescription=function(r){if(r&&r.sdp&&r.sdp.indexOf(`
34
+ `},e.getDirection=function(t,n){let 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 n?e.getDirection(n):"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){let 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){let 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;let n=e.splitLines(t);for(let r=0;r<n.length;r++)if(n[r].length<2||n[r].charAt(1)!=="=")return!1;return!0},i.exports=e})(Tr)),Tr.exports}var Fd=Nh(),Qt=Sh(Fd),Uh=Bl({__proto__:null,default:Qt},[Fd]);function ci(i){if(!i.RTCIceCandidate||i.RTCIceCandidate&&"foundation"in i.RTCIceCandidate.prototype)return;let e=i.RTCIceCandidate;i.RTCIceCandidate=function(n){if(typeof n=="object"&&n.candidate&&n.candidate.indexOf("a=")===0&&(n=JSON.parse(JSON.stringify(n)),n.candidate=n.candidate.substring(2)),n.candidate&&n.candidate.length){let r=new e(n),s=Qt.parseCandidate(n.candidate);for(let 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(n)},i.RTCIceCandidate.prototype=e.prototype,Vt(i,"icecandidate",t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new i.RTCIceCandidate(t.candidate),writable:"false"}),t))}function Zr(i){!i.RTCIceCandidate||i.RTCIceCandidate&&"relayProtocol"in i.RTCIceCandidate.prototype||Vt(i,"icecandidate",e=>{if(e.candidate){let t=Qt.parseCandidate(e.candidate.candidate);t.type==="relay"&&(e.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[t.priority>>24])}return e})}function di(i,e){if(!i.RTCPeerConnection)return;"sctp"in i.RTCPeerConnection.prototype||Object.defineProperty(i.RTCPeerConnection.prototype,"sctp",{get(){return typeof this._sctp>"u"?null:this._sctp}});let t=function(o){if(!o||!o.sdp)return!1;let d=Qt.splitSections(o.sdp);return d.shift(),d.some(c=>{let l=Qt.parseMLine(c);return l&&l.kind==="application"&&l.protocol.indexOf("SCTP")!==-1})},n=function(o){let d=o.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(d===null||d.length<2)return-1;let 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);let 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=i.RTCPeerConnection.prototype.setRemoteDescription;i.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])){let d=n(arguments[0]),c=r(d),l=s(arguments[0],d),u;c===0&&l===0?u=Number.POSITIVE_INFINITY:c===0||l===0?u=Math.max(c,l):u=Math.min(c,l);let h={};Object.defineProperty(h,"maxMessageSize",{get(){return u}}),this._sctp=h}return a.apply(this,arguments)}}function li(i,e){if(!(i.RTCPeerConnection&&"createDataChannel"in i.RTCPeerConnection.prototype)||e.browser==="chrome"&&e.version>149||e.browser==="firefox"&&e.version>60)return;function t(r,s){let a=r.send;r.send=function(){let 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)}}let n=i.RTCPeerConnection.prototype.createDataChannel;i.RTCPeerConnection.prototype.createDataChannel=function(){let s=n.apply(this,arguments);return t(s,this),s},Vt(i,"datachannel",r=>(t(r.channel,r.target),r))}function es(i){if(!i.RTCPeerConnection||"connectionState"in i.RTCPeerConnection.prototype)return;let e=i.RTCPeerConnection.prototype;Object.defineProperty(e,"connectionState",{get(){return{completed:"connected",checking:"connecting"}[this.iceConnectionState]||this.iceConnectionState},enumerable:!0,configurable:!0}),Object.defineProperty(e,"onconnectionstatechange",{get(){return this._onconnectionstatechange||null},set(t){this._onconnectionstatechange&&(this.removeEventListener("connectionstatechange",this._onconnectionstatechange),delete this._onconnectionstatechange),t&&this.addEventListener("connectionstatechange",this._onconnectionstatechange=t)},enumerable:!0,configurable:!0}),["setLocalDescription","setRemoteDescription"].forEach(t=>{let n=e[t];e[t]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=r=>{let s=r.target;if(s._lastConnectionState!==s.connectionState){s._lastConnectionState=s.connectionState;let a=new Event("connectionstatechange",r);s.dispatchEvent(a)}return r},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),n.apply(this,arguments)}})}function ts(i,e){if(!i.RTCPeerConnection||e.browser==="chrome"&&e.version>=71||e.browser==="safari"&&e._safariVersion>=13.1)return;let t=i.RTCPeerConnection.prototype.setRemoteDescription;i.RTCPeerConnection.prototype.setRemoteDescription=function(r){if(r&&r.sdp&&r.sdp.indexOf(`
35
35
  a=extmap-allow-mixed`)!==-1){let s=r.sdp.split(`
36
36
  `).filter(a=>a.trim()!=="a=extmap-allow-mixed").join(`
37
- `);i.RTCSessionDescription&&r instanceof i.RTCSessionDescription?arguments[0]=new i.RTCSessionDescription({type:r.type,sdp:s}):r.sdp=s}return t.apply(this,arguments)}}function ui(i,e){if(!(i.RTCPeerConnection&&i.RTCPeerConnection.prototype))return;let t=i.RTCPeerConnection.prototype.addIceCandidate;!t||t.length===0||(i.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?(e.browser==="chrome"&&e.version<78||e.browser==="firefox"&&e.version<68||e.browser==="safari")&&arguments[0]&&arguments[0].candidate===""?Promise.resolve():t.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}function hi(i,e){if(!(i.RTCPeerConnection&&i.RTCPeerConnection.prototype))return;let t=i.RTCPeerConnection.prototype.setLocalDescription;!t||t.length===0||(i.RTCPeerConnection.prototype.setLocalDescription=function(){let r=arguments[0]||{};if(typeof r!="object"||r.type&&r.sdp)return t.apply(this,arguments);if(r={type:r.type,sdp:r.sdp},!r.type)switch(this.signalingState){case"stable":case"have-local-offer":case"have-remote-pranswer":r.type="offer";break;default:r.type="answer";break}return r.sdp||r.type!=="offer"&&r.type!=="answer"?t.apply(this,[r]):(r.type==="offer"?this.createOffer:this.createAnswer).apply(this).then(a=>t.apply(this,[a]))})}var Lh=Object.freeze({__proto__:null,removeExtmapAllowMixed:ts,shimAddIceCandidateNullOrEmpty:ui,shimConnectionState:es,shimMaxMessageSize:di,shimParameterlessSetLocalDescription:hi,shimRTCIceCandidate:ci,shimRTCIceCandidateRelayProtocol:Zr,shimSendThrowTypeError:li});function Nh(){let i=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},e=i.window,t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{shimChrome:!0,shimFirefox:!0,shimSafari:!0},n=Ra,r=Ah(e),s={browserDetails:r,commonShim:Lh,extractVersion:Tn,disableLog:Ih,disableWarnings:Mh,sdp:Oh};switch(r.browser){case"chrome":if(!ko||!Yr||!t.shimChrome)return n("Chrome shim is not included in this adapter release."),s;if(r.version===null)return n("Chrome shim can not determine version, not shimming."),s;n("adapter.js shimming chrome."),s.browserShim=ko,ui(e,r),hi(e),cd(e,r),dd(e),Yr(e,r),ld(e,r),pd(e,r),ud(e),hd(e,r),fd(e,r),ci(e),Zr(e),es(e),di(e,r),li(e,r),ts(e,r);break;case"firefox":if(!To||!Xr||!t.shimFirefox)return n("Firefox shim is not included in this adapter release."),s;n("adapter.js shimming firefox."),s.browserShim=To,ui(e,r),hi(e),gd(e,r),Xr(e,r),yd(e,r),vd(e),Td(e),bd(e),kd(e),Sd(e),Cd(e),_d(e),wd(e),Ed(e),ci(e),es(e),di(e,r),li(e,r);break;case"safari":if(!So||!t.shimSafari)return n("Safari shim is not included in this adapter release."),s;n("adapter.js shimming safari."),s.browserShim=So,ui(e,r),hi(e),xd(e),Od(e),Id(e),Rd(e),Pd(e),Dd(e),Md(e),Ld(e),ci(e),Zr(e),di(e,r),li(e,r),ts(e,r);break;default:n("Unsupported browser!");break}return s}Nh({window:typeof window>"u"?void 0:window});var ns,Ud,pe=class extends(Ud=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)}};ns=pe;pe.resolve=i=>Reflect.get(Ud,"resolve",ns).call(ns,i);var Uh=/version\/(\d+(\.?_?\d+)+)/i,Sr;function ke(i){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;if(typeof i>"u"&&typeof navigator>"u")return;let t=(i??navigator.userAgent).toLowerCase();if(Sr===void 0||e){let n=Fh.find(r=>r.test.test(t));Sr=n?.describe(t)}return Sr}var Fh=[{test:/firefox|iceweasel|fxios/i,describe(i){return{name:"Firefox",version:mi(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,i),os:i.toLowerCase().includes("fxios")?"iOS":void 0,osVersion:Cr(i)}}},{test:/chrom|crios|crmo/i,describe(i){return{name:"Chrome",version:mi(/(?:chrome|chromium|crios|crmo)\/(\d+(\.?_?\d+)+)/i,i),os:i.toLowerCase().includes("crios")?"iOS":void 0,osVersion:Cr(i)}}},{test:/safari|applewebkit/i,describe(i){return{name:"Safari",version:mi(Uh,i),os:i.includes("mobile/")?"iOS":"macOS",osVersion:Cr(i)}}}];function mi(i,e){let t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:1,n=e.match(i);return n&&n.length>=t&&n[t]||""}function Cr(i){return i.includes("mac os")?mi(/\(.+?(\d+_\d+(:?_\d+)?)/,i,1).replace(/_/g,"."):void 0}var Bh="2.20.0",qh=Bh,jh=17,Fd=0,Si=1,Vh=Si,Ve=class extends Error{constructor(e,t,n){super(t||"an error has occurred"),this.name="LiveKitError",this.code=e,typeof n?.cause<"u"&&(this.cause=n?.cause)}},we=class extends Ve{};var z;(function(i){i[i.NotAllowed=0]="NotAllowed",i[i.ServerUnreachable=1]="ServerUnreachable",i[i.InternalError=2]="InternalError",i[i.Cancelled=3]="Cancelled",i[i.LeaveRequest=4]="LeaveRequest",i[i.Timeout=5]="Timeout",i[i.WebSocket=6]="WebSocket",i[i.ServiceNotFound=7]="ServiceNotFound"})(z||(z={}));var N=class i extends we{constructor(e,t,n,r){super(1,e),this.name="ConnectionError",this.status=n,this.reason=t,this.context=r,this.reasonName=z[t]}static notAllowed(e,t,n){return new i(e,z.NotAllowed,t,n)}static timeout(e){return new i(e,z.Timeout)}static leaveRequest(e,t){return new i(e,z.LeaveRequest,void 0,t)}static internal(e,t){return new i(e,z.InternalError,void 0,t)}static cancelled(e){return new i(e,z.Cancelled)}static serverUnreachable(e,t){return new i(e,z.ServerUnreachable,t)}static websocket(e,t,n){return new i(e,z.WebSocket,t,n)}static serviceNotFound(e,t){return new i(e,z.ServiceNotFound,void 0,t)}},Dn=class extends Ve{constructor(e){super(21,e??"device is unsupported"),this.name="DeviceUnsupportedError"}},qe=class extends Ve{constructor(e){super(20,e??"track is invalid"),this.name="TrackInvalidError"}},is=class extends Ve{constructor(e){super(10,e??"unsupported server"),this.name="UnsupportedServer"}},$=class extends Ve{constructor(e){super(12,e??"unexpected connection state"),this.name="UnexpectedConnectionState"}},lt=class extends Ve{constructor(e){super(13,e??"unable to negotiate"),this.name="NegotiationError"}},rs=class extends Ve{constructor(e){super(14,e??"unable to publish data"),this.name="PublishDataError"}},Ci=class extends Ve{constructor(e,t){super(15,e),this.name="PublishTrackError",this.status=t}},_i=class extends we{constructor(e,t){super(15,e),this.name="SignalRequestError",this.reason=t,this.reasonName=typeof t=="string"?t:It[t]}},be;(function(i){i[i.AlreadyOpened=0]="AlreadyOpened",i[i.AbnormalEnd=1]="AbnormalEnd",i[i.DecodeFailed=2]="DecodeFailed",i[i.LengthExceeded=3]="LengthExceeded",i[i.Incomplete=4]="Incomplete",i[i.HandlerAlreadyRegistered=7]="HandlerAlreadyRegistered",i[i.EncryptionTypeMismatch=8]="EncryptionTypeMismatch"})(be||(be={}));var Se=class extends we{constructor(e,t){super(16,e),this.name="DataStreamError",this.reason=t,this.reasonName=be[t]}},vt=class extends Ve{constructor(e){super(18,e),this.name="SignalReconnectError"}},wi;(function(i){i.PermissionDenied="PermissionDenied",i.NotFound="NotFound",i.DeviceInUse="DeviceInUse",i.Other="Other"})(wi||(wi={}));(function(i){function e(t){if(t&&"name"in t)return t.name==="NotFoundError"||t.name==="DevicesNotFoundError"?i.NotFound:t.name==="NotAllowedError"||t.name==="PermissionDeniedError"?i.PermissionDenied:t.name==="NotReadableError"||t.name==="TrackStartError"?i.DeviceInUse:i.Other}i.getFailure=e})(wi||(wi={}));var re=class{};re.setTimeout=function(){return setTimeout(...arguments)};re.setInterval=function(){return setInterval(...arguments)};re.clearTimeout=function(){return clearTimeout(...arguments)};re.clearInterval=function(){return clearInterval(...arguments)};var C;(function(i){i.Connected="connected",i.Reconnecting="reconnecting",i.SignalReconnecting="signalReconnecting",i.Reconnected="reconnected",i.Disconnected="disconnected",i.ConnectionStateChanged="connectionStateChanged",i.Moved="moved",i.MediaDevicesChanged="mediaDevicesChanged",i.ParticipantConnected="participantConnected",i.ParticipantDisconnected="participantDisconnected",i.TrackPublished="trackPublished",i.TrackSubscribed="trackSubscribed",i.TrackSubscriptionFailed="trackSubscriptionFailed",i.TrackUnpublished="trackUnpublished",i.TrackUnsubscribed="trackUnsubscribed",i.TrackMuted="trackMuted",i.TrackUnmuted="trackUnmuted",i.LocalTrackPublished="localTrackPublished",i.LocalTrackUnpublished="localTrackUnpublished",i.LocalAudioSilenceDetected="localAudioSilenceDetected",i.ActiveSpeakersChanged="activeSpeakersChanged",i.ParticipantMetadataChanged="participantMetadataChanged",i.ParticipantNameChanged="participantNameChanged",i.ParticipantAttributesChanged="participantAttributesChanged",i.ParticipantActive="participantActive",i.RoomMetadataChanged="roomMetadataChanged",i.DataReceived="dataReceived",i.SipDTMFReceived="sipDTMFReceived",i.TranscriptionReceived="transcriptionReceived",i.ConnectionQualityChanged="connectionQualityChanged",i.TrackStreamStateChanged="trackStreamStateChanged",i.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",i.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",i.AudioPlaybackStatusChanged="audioPlaybackChanged",i.VideoPlaybackStatusChanged="videoPlaybackChanged",i.MediaDevicesError="mediaDevicesError",i.ParticipantPermissionsChanged="participantPermissionsChanged",i.SignalConnected="signalConnected",i.RecordingStatusChanged="recordingStatusChanged",i.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",i.EncryptionError="encryptionError",i.DCBufferStatusChanged="dcBufferStatusChanged",i.ActiveDeviceChanged="activeDeviceChanged",i.ChatMessage="chatMessage",i.LocalTrackSubscribed="localTrackSubscribed",i.MetricsReceived="metricsReceived",i.DataTrackPublished="dataTrackPublished",i.DataTrackUnpublished="dataTrackUnpublished",i.LocalDataTrackPublished="localDataTrackPublished",i.LocalDataTrackUnpublished="localDataTrackUnpublished"})(C||(C={}));var I;(function(i){i.TrackPublished="trackPublished",i.TrackSubscribed="trackSubscribed",i.TrackSubscriptionFailed="trackSubscriptionFailed",i.TrackUnpublished="trackUnpublished",i.TrackUnsubscribed="trackUnsubscribed",i.TrackMuted="trackMuted",i.TrackUnmuted="trackUnmuted",i.LocalTrackPublished="localTrackPublished",i.LocalTrackUnpublished="localTrackUnpublished",i.LocalTrackCpuConstrained="localTrackCpuConstrained",i.LocalSenderCreated="localSenderCreated",i.ParticipantMetadataChanged="participantMetadataChanged",i.ParticipantNameChanged="participantNameChanged",i.DataReceived="dataReceived",i.SipDTMFReceived="sipDTMFReceived",i.TranscriptionReceived="transcriptionReceived",i.IsSpeakingChanged="isSpeakingChanged",i.ConnectionQualityChanged="connectionQualityChanged",i.TrackStreamStateChanged="trackStreamStateChanged",i.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",i.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",i.TrackCpuConstrained="trackCpuConstrained",i.MediaDevicesError="mediaDevicesError",i.AudioStreamAcquired="audioStreamAcquired",i.ParticipantPermissionsChanged="participantPermissionsChanged",i.PCTrackAdded="pcTrackAdded",i.AttributesChanged="attributesChanged",i.LocalTrackSubscribed="localTrackSubscribed",i.ChatMessage="chatMessage",i.Active="active"})(I||(I={}));var R;(function(i){i.TransportsCreated="transportsCreated",i.Connected="connected",i.Disconnected="disconnected",i.Resuming="resuming",i.Resumed="resumed",i.Restarting="restarting",i.Restarted="restarted",i.SignalResumed="signalResumed",i.SignalRestarted="signalRestarted",i.Closing="closing",i.MediaTrackAdded="mediaTrackAdded",i.ActiveSpeakersUpdate="activeSpeakersUpdate",i.DataPacketReceived="dataPacketReceived",i.RTPVideoMapUpdate="rtpVideoMapUpdate",i.DCBufferStatusChanged="dcBufferStatusChanged",i.ParticipantUpdate="participantUpdate",i.RoomUpdate="roomUpdate",i.SpeakersChanged="speakersChanged",i.StreamStateChanged="streamStateChanged",i.ConnectionQualityUpdate="connectionQualityUpdate",i.SubscriptionError="subscriptionError",i.SubscriptionPermissionUpdate="subscriptionPermissionUpdate",i.RemoteMute="remoteMute",i.SubscribedQualityUpdate="subscribedQualityUpdate",i.LocalTrackUnpublished="localTrackUnpublished",i.LocalTrackSubscribed="localTrackSubscribed",i.Offline="offline",i.SignalRequestResponse="signalRequestResponse",i.SignalConnected="signalConnected",i.RoomMoved="roomMoved",i.PublishDataTrackResponse="publishDataTrackResponse",i.UnPublishDataTrackResponse="unPublishDataTrackResponse",i.DataTrackSubscriberHandles="dataTrackSubscriberHandles",i.DataTrackPacketReceived="dataTrackPacketReceived",i.Joined="joined",i.TokenRefreshed="tokenRefreshed",i.ServerRegionsReported="serverRegionsReported"})(R||(R={}));var P;(function(i){i.Message="message",i.Muted="muted",i.Unmuted="unmuted",i.Restarted="restarted",i.Ended="ended",i.Subscribed="subscribed",i.Unsubscribed="unsubscribed",i.CpuConstrained="cpuConstrained",i.UpdateSettings="updateSettings",i.UpdateSubscription="updateSubscription",i.AudioPlaybackStarted="audioPlaybackStarted",i.AudioPlaybackFailed="audioPlaybackFailed",i.AudioSilenceDetected="audioSilenceDetected",i.VisibilityChanged="visibilityChanged",i.VideoDimensionsChanged="videoDimensionsChanged",i.VideoPlaybackStarted="videoPlaybackStarted",i.VideoPlaybackFailed="videoPlaybackFailed",i.ElementAttached="elementAttached",i.ElementDetached="elementDetached",i.UpstreamPaused="upstreamPaused",i.UpstreamResumed="upstreamResumed",i.SubscriptionPermissionChanged="subscriptionPermissionChanged",i.SubscriptionStatusChanged="subscriptionStatusChanged",i.SubscriptionFailed="subscriptionFailed",i.TrackProcessorUpdate="trackProcessorUpdate",i.AudioTrackFeatureUpdate="audioTrackFeatureUpdate",i.TranscriptionReceived="transcriptionReceived",i.TimeSyncUpdate="timeSyncUpdate",i.PreConnectBufferFlushed="preConnectBufferFlushed"})(P||(P={}));function Hh(i){return typeof i>"u"?i:typeof structuredClone=="function"?typeof i=="object"&&i!==null?structuredClone(Object.assign({},i)):structuredClone(i):JSON.parse(JSON.stringify(i))}var K=class{constructor(e,t,n,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&&n!==void 0)this.width=e,this.height=t,this.aspectRatio=e/t,this.encoding={maxBitrate:n,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}}};var Gh=["vp8","h264"],Kh=["vp8","h264","vp9","av1","h265"];function Bd(i){return!!Gh.find(e=>e===i)}var Wh=Bd,_o;(function(i){i[i.PREFER_REGRESSION=0]="PREFER_REGRESSION",i[i.SIMULCAST=1]="SIMULCAST",i[i.REGRESSION=2]="REGRESSION"})(_o||(_o={}));var ss;(function(i){i.telephone={maxBitrate:12e3},i.speech={maxBitrate:24e3},i.music={maxBitrate:48e3},i.musicStereo={maxBitrate:64e3},i.musicHighQuality={maxBitrate:96e3},i.musicHighQualityStereo={maxBitrate:128e3}})(ss||(ss={}));var On={h90:new K(160,90,9e4,20),h180:new K(320,180,16e4,20),h216:new K(384,216,18e4,20),h360:new K(640,360,45e4,20),h540:new K(960,540,8e5,25),h720:new K(1280,720,17e5,30),h1080:new K(1920,1080,3e6,30),h1440:new K(2560,1440,5e6,30),h2160:new K(3840,2160,8e6,30)},as={h120:new K(160,120,7e4,20),h180:new K(240,180,125e3,20),h240:new K(320,240,14e4,20),h360:new K(480,360,33e4,20),h480:new K(640,480,5e5,20),h540:new K(720,540,6e5,25),h720:new K(960,720,13e5,30),h1080:new K(1440,1080,23e5,30),h1440:new K(1920,1440,38e5,30)},Ia={h360fps3:new K(640,360,2e5,3,"medium"),h360fps15:new K(640,360,4e5,15,"medium"),h720fps5:new K(1280,720,8e5,5,"medium"),h720fps15:new K(1280,720,15e5,15,"medium"),h720fps30:new K(1280,720,2e6,30,"medium"),h1080fps15:new K(1920,1080,25e5,15,"medium"),h1080fps30:new K(1920,1080,5e6,30,"medium"),original:new K(0,0,7e6,30,"medium")};function qd(i,e,t){var n,r,s,a;let o=Hd(i??{}),d=o.optionsWithoutProcessor,c=o.audioProcessor,l=o.videoProcessor,u=e?.processor,h=t?.processor,m=d??{};return m.audio===!0&&(m.audio={}),m.video===!0&&(m.video={}),m.audio&&(os(m.audio,e),(n=(s=m.audio).deviceId)!==null&&n!==void 0||(s.deviceId={ideal:"default"}),(c||u)&&(m.audio.processor=c??u)),m.video&&(os(m.video,t),(r=(a=m.video).deviceId)!==null&&r!==void 0||(a.deviceId={ideal:"default"}),(l||h)&&(m.video.processor=l??h)),m}function os(i,e){return Object.keys(e).forEach(t=>{i[t]===void 0&&(i[t]=e[t])}),i}function Ma(i){var e,t,n,r;let s={};if(i.video)if(typeof i.video=="object"){let a={},o=a,d=i.video;Object.keys(d).forEach(c=>{switch(c){case"resolution":os(o,d.resolution);break;default:o[c]=d[c]}}),s.video=a,(e=(n=s.video).deviceId)!==null&&e!==void 0||(n.deviceId={ideal:"default"})}else s.video=i.video?{deviceId:{ideal:"default"}}:!1;else s.video=!1;return i.audio?typeof i.audio=="object"?(s.audio=i.audio,(t=(r=s.audio).deviceId)!==null&&t!==void 0||(r.deviceId={ideal:"default"})):s.audio={deviceId:{ideal:"default"}}:s.audio=!1,s}function jd(i){return p(this,arguments,void 0,function(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:200;return(function*(){let n=Vd();if(n){let r=n.createAnalyser();r.fftSize=2048;let s=r.frequencyBinCount,a=new Uint8Array(s);n.createMediaStreamSource(new MediaStream([e.mediaStreamTrack])).connect(r),yield ve(t),r.getByteTimeDomainData(a);let d=a.some(c=>c!==128&&c!==0);return n.close(),!d}return!1})()})}function Vd(){var i;let e=typeof window<"u"&&(window.AudioContext||window.webkitAudioContext);if(e){let t=new e({latencyHint:"interactive"});if(t.state==="suspended"&&typeof window<"u"&&(!((i=window.document)===null||i===void 0)&&i.body)){let n=()=>p(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",n)}});t.addEventListener("statechange",()=>{var r;t.state==="closed"&&((r=window.document.body)===null||r===void 0||r.removeEventListener("click",n))}),window.document.body.addEventListener("click",n)}return t}}function zh(i){return i==="audioinput"?_.Source.Microphone:i==="videoinput"?_.Source.Camera:_.Source.Unknown}function cs(i){return i===_.Source.Microphone?"audioinput":i===_.Source.Camera?"videoinput":void 0}function Jh(i){var e,t;let n=(e=i.video)!==null&&e!==void 0?e:!0;return i.resolution&&i.resolution.width>0&&i.resolution.height>0&&(n=typeof n=="boolean"?{}:n,Bt()?n=Object.assign(Object.assign({},n),{width:{max:i.resolution.width},height:{max:i.resolution.height},frameRate:i.resolution.frameRate}):n=Object.assign(Object.assign({},n),{width:{ideal:i.resolution.width},height:{ideal:i.resolution.height},frameRate:i.resolution.frameRate})),{audio:(t=i.audio)!==null&&t!==void 0?t:!1,video:n,controller:i.controller,selfBrowserSurface:i.selfBrowserSurface,surfaceSwitching:i.surfaceSwitching,systemAudio:i.systemAudio,preferCurrentTab:i.preferCurrentTab}}function _n(i){return i.split("/")[1].toLowerCase()}function $h(i){let e=[];return i.forEach(t=>{t.track!==void 0&&e.push(new Sa({cid:t.track.mediaStreamID,track:t.trackInfo}))}),e}function j(i){return"mediaStreamTrack"in i?{trackID:i.sid,source:i.source,muted:i.isMuted,enabled:i.mediaStreamTrack.enabled,kind:i.kind,streamID:i.mediaStreamID,streamTrackID:i.mediaStreamTrack.id}:{trackID:i.trackSid,enabled:i.isEnabled,muted:i.isMuted,trackInfo:Object.assign({mimeType:i.mimeType,name:i.trackName,encrypted:i.isEncrypted,kind:i.kind,source:i.source},i.track?j(i.track):{})}}function Qh(){return typeof RTCRtpReceiver<"u"&&typeof RTCRtpReceiver.prototype.getSynchronizationSources=="function"}function Yh(i,e){var t;i===void 0&&(i={}),e===void 0&&(e={});let n=[...Object.keys(e),...Object.keys(i)],r={};for(let s of n)i[s]!==e[s]&&(r[s]=(t=e[s])!==null&&t!==void 0?t:"");return r}function Hd(i){let e=Object.assign({},i),t,n;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&&(n=e.video.processor,e.video=Object.assign(Object.assign({},e.video),{processor:void 0})),{audioProcessor:t,videoProcessor:n,optionsWithoutProcessor:Hh(e)}}function Xh(i){switch(i){case ae.CAMERA:return _.Source.Camera;case ae.MICROPHONE:return _.Source.Microphone;case ae.SCREEN_SHARE:return _.Source.ScreenShare;case ae.SCREEN_SHARE_AUDIO:return _.Source.ScreenShareAudio;default:return _.Source.Unknown}}function wo(i,e){return i.width*i.height<e.width*e.height}function Zh(i,e){var t;return(t=i.layers)===null||t===void 0?void 0:t.find(n=>n.quality===e)}var em=5e3,gn=[],Re;(function(i){i[i.LOW=0]="LOW",i[i.MEDIUM=1]="MEDIUM",i[i.HIGH=2]="HIGH"})(Re||(Re={}));var _=class i extends Ee.EventEmitter{get streamState(){return this._streamState}setStreamState(e){this._streamState=e}constructor(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};var r;super(),this.attachedElements=[],this.isMuted=!1,this._streamState=i.StreamState.Active,this.isInBackground=!1,this._currentBitrate=0,this.log=F,this.appVisibilityChangedListener=()=>{this.backgroundTimeout&&clearTimeout(this.backgroundTimeout),document.visibilityState==="hidden"?this.backgroundTimeout=setTimeout(()=>this.handleAppVisibilityChanged(),em):this.handleAppVisibilityChanged()},this.log=_e((r=n.loggerName)!==null&&r!==void 0?r:ue.Track),this.loggerContextCb=n.loggerContextCb,this.setMaxListeners(100),this.kind=t,this._mediaStreamTrack=e,this._mediaStreamID=e.id,this.source=i.Source.Unknown}get logContext(){var e;return Object.assign(Object.assign({},(e=this.loggerContextCb)===null||e===void 0?void 0:e.call(this)),j(this))}get currentBitrate(){return this._currentBitrate}get mediaStreamTrack(){return this._mediaStreamTrack}get mediaStreamID(){return this._mediaStreamID}attach(e){let t="audio";this.kind===i.Kind.Video&&(t="video"),this.attachedElements.length===0&&this.kind===i.Kind.Video&&this.addAppVisibilityListener(),e||(t==="audio"&&(gn.forEach(s=>{s.parentElement===null&&!e&&(e=s)}),e&&gn.splice(gn.indexOf(e),1)),e||(e=document.createElement(t))),this.attachedElements.includes(e)||this.attachedElements.push(e),zt(this.mediaStreamTrack,e);let n=e.srcObject.getTracks(),r=n.some(s=>s.kind==="audio");return e.play().then(()=>{this.emit(r?P.AudioPlaybackStarted:P.VideoPlaybackStarted)}).catch(s=>{s.name==="NotAllowedError"?this.emit(r?P.AudioPlaybackFailed:P.VideoPlaybackFailed,s):s.name==="AbortError"?F.debug("".concat(r?"audio":"video"," playback aborted, likely due to new play request")):F.warn("could not playback ".concat(r?"audio":"video"),s),r&&e&&n.some(a=>a.kind==="video")&&s.name==="NotAllowedError"&&(e.muted=!0,e.play().catch(()=>{}))}),this.emit(P.ElementAttached,e),e}detach(e){try{if(e){Yt(this.mediaStreamTrack,e);let n=this.attachedElements.indexOf(e);return n>=0&&(this.attachedElements.splice(n,1),this.recycleElement(e),this.emit(P.ElementDetached,e)),e}let t=[];return this.attachedElements.forEach(n=>{Yt(this.mediaStreamTrack,n),t.push(n),this.recycleElement(n),this.emit(P.ElementDetached,n)}),this.attachedElements=[],t}finally{this.attachedElements.length===0&&this.removeAppVisibilityListener()}}stop(){this.stopMonitor(),this._mediaStreamTrack.stop()}enable(){this._mediaStreamTrack.enabled=!0}disable(){this._mediaStreamTrack.enabled=!1}stopMonitor(){this.monitorInterval&&clearInterval(this.monitorInterval),this.timeSyncHandle&&cancelAnimationFrame(this.timeSyncHandle)}updateLoggerOptions(e){e.loggerName&&(this.log=_e(e.loggerName)),e.loggerContextCb&&(this.loggerContextCb=e.loggerContextCb)}recycleElement(e){if(e instanceof HTMLAudioElement){let t=!0;e.pause(),gn.forEach(n=>{n.parentElement||(t=!1)}),t&&gn.push(e)}}handleAppVisibilityChanged(){return p(this,void 0,void 0,function*(){this.isInBackground=document.visibilityState==="hidden",!this.isInBackground&&this.kind===i.Kind.Video&&setTimeout(()=>this.attachedElements.forEach(e=>e.play().catch(()=>{})),0)})}addAppVisibilityListener(){Ce()?(this.isInBackground=document.visibilityState==="hidden",document.addEventListener("visibilitychange",this.appVisibilityChangedListener)):this.isInBackground=!1}removeAppVisibilityListener(){Ce()&&document.removeEventListener("visibilitychange",this.appVisibilityChangedListener)}};function zt(i,e){let t;e.srcObject instanceof MediaStream?t=e.srcObject:t=new MediaStream;let n;i.kind==="audio"?n=t.getAudioTracks():n=t.getVideoTracks(),n.includes(i)||(n.forEach(r=>{t.removeTrack(r)}),t.addTrack(i)),(!Bt()||!(e instanceof HTMLVideoElement))&&(e.autoplay=!0),e.muted=t.getAudioTracks().length===0,e instanceof HTMLVideoElement&&(e.playsInline=!0),e.srcObject!==t&&(e.srcObject=t,(Bt()||Ft())&&e instanceof HTMLVideoElement&&setTimeout(()=>{e.srcObject=t,e.play().catch(()=>{})},0))}function Yt(i,e){if(e.srcObject instanceof MediaStream){let t=e.srcObject;t.removeTrack(i),t.getTracks().length>0?e.srcObject=t:e.srcObject=null}}(function(i){let e;(function(c){c.Audio="audio",c.Video="video",c.Unknown="unknown"})(e=i.Kind||(i.Kind={}));let t;(function(c){c.Camera="camera",c.Microphone="microphone",c.ScreenShare="screen_share",c.ScreenShareAudio="screen_share_audio",c.Unknown="unknown"})(t=i.Source||(i.Source={}));let n;(function(c){c.Active="active",c.Paused="paused",c.Unknown="unknown"})(n=i.StreamState||(i.StreamState={}));function r(c){switch(c){case e.Audio:return Ue.AUDIO;case e.Video:return Ue.VIDEO;default:return Ue.DATA}}i.kindToProto=r;function s(c){switch(c){case Ue.AUDIO:return e.Audio;case Ue.VIDEO:return e.Video;default:return e.Unknown}}i.kindFromProto=s;function a(c){switch(c){case t.Camera:return ae.CAMERA;case t.Microphone:return ae.MICROPHONE;case t.ScreenShare:return ae.SCREEN_SHARE;case t.ScreenShareAudio:return ae.SCREEN_SHARE_AUDIO;default:return ae.UNKNOWN}}i.sourceToProto=a;function o(c){switch(c){case ae.CAMERA:return t.Camera;case ae.MICROPHONE:return t.Microphone;case ae.SCREEN_SHARE:return t.ScreenShare;case ae.SCREEN_SHARE_AUDIO:return t.ScreenShareAudio;default:return t.Unknown}}i.sourceFromProto=o;function d(c){switch(c){case Kr.ACTIVE:return n.Active;case Kr.PAUSED:return n.Paused;default:return n.Unknown}}i.streamStateFromProto=d})(_||(_={}));var tm="|",Eo="https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension";function nm(i){let e=i.split(tm);return e.length>1?[e[0],i.substr(e[0].length+1)]:[i,""]}function ve(i){return new pe(e=>re.setTimeout(e,i))}function ds(){return"addTransceiver"in RTCPeerConnection.prototype}function ls(){return"addTrack"in RTCPeerConnection.prototype}function im(){if(!("getCapabilities"in RTCRtpSender)||Bt()||Ft())return!1;let i=RTCRtpSender.getCapabilities("video"),e=!1;if(i){for(let t of i.codecs)if(t.mimeType.toLowerCase()==="video/av1"){e=!0;break}}return e}function rm(){if(!("getCapabilities"in RTCRtpSender)||Ft())return!1;if(Bt()){let t=ke();if(t?.version&&tt(t.version,"16")<0||t?.os==="iOS"&&t?.osVersion&&tt(t.osVersion,"16")<0)return!1}let i=RTCRtpSender.getCapabilities("video"),e=!1;if(i){for(let t of i.codecs)if(t.mimeType.toLowerCase()==="video/vp9"){e=!0;break}}return e}function je(i){return i==="av1"||i==="vp9"}function us(i){return!document||Ln()?!1:(i||(i=document.createElement("audio")),"setSinkId"in i)}function sm(){return typeof RTCPeerConnection>"u"?!1:ds()||ls()}function Ft(){var i;return((i=ke())===null||i===void 0?void 0:i.name)==="Firefox"}function am(){let i=ke();return!!i&&i.name==="Chrome"&&i.os!=="iOS"}function hs(){return typeof window<"u"&&typeof window.RTCRtpScriptTransform<"u"&&!am()}function Bt(){var i;return((i=ke())===null||i===void 0?void 0:i.name)==="Safari"}function Ln(){let i=ke();return i?.name==="Safari"||i?.os==="iOS"}function om(){let i=ke();return i?.name==="Safari"&&i.version.startsWith("17.")||i?.os==="iOS"&&!!i?.osVersion&&tt(i.osVersion,"17")>=0}function cm(i){return i||(i=ke()),i?.name==="Safari"&&tt(i.version,"18.3")>0||i?.os==="iOS"&&!!i?.osVersion&&tt(i.osVersion,"18.3")>0}function Gd(){var i,e;return Ce()?(e=(i=navigator.userAgentData)===null||i===void 0?void 0:i.mobile)!==null&&e!==void 0?e:/Tablet|iPad|Mobile|Android|BlackBerry/.test(navigator.userAgent):!1}function dm(){let i=ke(),e="17.2";if(i)return i.name!=="Safari"&&i.os!=="iOS"||i.os==="iOS"&&i.osVersion&&tt(i.osVersion,e)>=0?!0:i.name==="Safari"&&tt(i.version,e)>=0}function Ce(){return typeof document<"u"}function He(){return navigator.product=="ReactNative"}function sn(i){return i.hostname.endsWith(".livekit.cloud")||i.hostname.endsWith(".livekit.run")}function _r(i){return sn(i)?i.hostname.split(".")[0]:null}function Kd(){if(global&&global.LiveKitReactNativeGlobal)return global.LiveKitReactNativeGlobal}function Wd(){if(!He())return;let i=Kd();if(i)return i.platform}function Ro(){if(Ce())return window.devicePixelRatio;if(He()){let i=Kd();if(i)return i.devicePixelRatio}return 1}function tt(i,e){let t=i.split("."),n=e.split("."),r=Math.min(t.length,n.length);for(let s=0;s<r;++s){let a=parseInt(t[s],10),o=parseInt(n[s],10);if(a>o)return 1;if(a<o)return-1;if(s===r-1&&a===o)return 0}return i===""&&e!==""?-1:e===""?1:t.length==n.length?0:t.length<n.length?-1:1}function lm(i){for(let e of i)e.target.handleResize(e)}function um(i){for(let e of i)e.target.handleVisibilityChanged(e)}var wr=null,Po=()=>(wr||(wr=new ResizeObserver(lm)),wr),Er=null,Io=()=>(Er||(Er=new IntersectionObserver(um,{root:null,rootMargin:"0px"})),Er);function hm(i){var e;let t=new qc({capabilities:i,sdk:jc.JS,protocol:jh,clientProtocol:Vh,version:qh});return He()&&(t.os=(e=Wd())!==null&&e!==void 0?e:""),t}function Mo(){let i=arguments.length>0&&arguments[0]!==void 0?arguments[0]:16,e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:16,t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1,n=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1,r=document.createElement("canvas");r.width=i,r.height=e;let s=r.getContext("2d");s?.fillRect(0,0,r.width,r.height),n&&s&&(s.beginPath(),s.arc(i/2,e/2,50,0,Math.PI*2,!0),s.closePath(),s.fillStyle="grey",s.fill());let o=r.captureStream().getTracks(),d=O(o,1),c=d[0];if(!c)throw Error("Could not get empty media stream video track");return c.enabled=t,c}var vn;function Rr(){if(!vn){let t=new AudioContext,n=t.createOscillator(),r=t.createGain();r.gain.setValueAtTime(0,0);let s=t.createMediaStreamDestination();n.connect(r),r.connect(s),n.start();var i=s.stream.getAudioTracks(),e=O(i,1);if(vn=e[0],!vn)throw Error("Could not get empty media stream audio track");vn.enabled=!1}return vn.clone()}var ce=class{get isResolved(){return this._isResolved}constructor(e,t){this._isResolved=!1,this.onFinally=t,this.promise=new Promise((n,r)=>p(this,void 0,void 0,function*(){this.resolve=n,this.reject=r,e&&(yield e(n,r))})).finally(()=>{var n;this._isResolved=!0,(n=this.onFinally)===null||n===void 0||n.call(this)})}};function mm(i){return Kh.includes(i)}function Lt(i){if(typeof i=="string"||typeof i=="number")return i;if(Array.isArray(i))return i[0];if(i.exact!==void 0)return Array.isArray(i.exact)?i.exact[0]:i.exact;if(i.ideal!==void 0)return Array.isArray(i.ideal)?i.ideal[0]:i.ideal;throw Error("could not unwrap constraint")}function pm(i){return i.startsWith("http")?i.replace(/^(http)/,"ws"):i}function Nn(i){return i.startsWith("ws")?i.replace(/^(ws)/,"http"):i}function fm(i,e){return i.segments.map(t=>{let n=t.id,r=t.text,s=t.language,a=t.startTime,o=t.endTime,d=t.final;var c;let l=(c=e.get(n))!==null&&c!==void 0?c:Date.now(),u=Date.now();return d?e.delete(n):e.set(n,l),{id:n,text:r,startTime:Number.parseInt(a.toString()),endTime:Number.parseInt(o.toString()),final:d,language:s,firstReceivedTime:l,lastReceivedTime:u}})}function gm(i){let e=i.id,t=i.timestamp,n=i.message,r=i.editTimestamp;return{id:e,timestamp:Number.parseInt(t.toString()),editTimestamp:r?Number.parseInt(r.toString()):void 0,message:n}}function Ao(i){switch(i.reason){case z.LeaveRequest:return i.context;case z.Cancelled:return oe.CLIENT_INITIATED;case z.NotAllowed:return oe.USER_REJECTED;case z.ServerUnreachable:return oe.JOIN_FAILURE;default:return oe.UNKNOWN_REASON}}function pi(i){return i!==void 0?Number(i):void 0}function Pt(i){return i!==void 0?BigInt(i):void 0}function Xt(i){return!!i&&!(i instanceof MediaStreamTrack)&&i.isLocal}function et(i){return!!i&&i.kind==_.Kind.Audio}function ht(i){return!!i&&i.kind==_.Kind.Video}function Je(i){return Xt(i)&&ht(i)}function at(i){return Xt(i)&&et(i)}function ms(i){return!!i&&!i.isLocal}function vm(i){return!!i&&!i.isLocal}function Pr(i){return ms(i)&&ht(i)}function ym(i){return i.isLocal}function bm(i,e){let t=[],n=new TextEncoder().encode(i);for(;n.length>e;){let r=e;for(;r>0;){let s=n[r];if(s!==void 0&&(s&192)!==128)break;r--}t.push(n.slice(0,r)),n=n.slice(r)}return n.length>0&&t.push(n),t}function km(i){var e;let t=i.get("Cache-Control");if(t){let n=(e=t.match(/(?:^|[,\s])max-age=(\d+)/))===null||e===void 0?void 0:e[1];if(n)return parseInt(n,10)}}function zd(){return typeof CompressionStream<"u"}function Tm(){return zd()&&!Ft()}function Sm(i,e){let t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1,n=Cm(i,e);return t?n:Aa(n,"v1")}function Cm(i,e){let t=new URL(pm(i));return e.forEach((n,r)=>{t.searchParams.set(r,n)}),Aa(t,"rtc")}function _m(i){let e=new URL(Nn(i));return Aa(e,"validate")}function Jd(i){return i.endsWith("/")?i:"".concat(i,"/")}function Aa(i,e){return i.pathname="".concat(Jd(i.pathname)).concat(e),i}function xo(i){if(typeof i=="string")return mo.fromJson(JSON.parse(i),{ignoreUnknownFields:!0});if(i instanceof ArrayBuffer)return mo.fromBinary(new Uint8Array(i));throw new Error("could not decode websocket message: ".concat(typeof i))}function wm(i){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"Unknown reason";if(!(i instanceof AbortSignal))return e;let t=i.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}}var Em=10,yn="lk_e2ee",Rm="LKFrameEncryptionKey",Pm={sharedKey:!1,ratchetSalt:Rm,ratchetWindowSize:8,failureTolerance:Em,keyringSize:16,keySize:128},St;(function(i){i.SetKey="setKey",i.RatchetRequest="ratchetRequest",i.KeyRatcheted="keyRatcheted"})(St||(St={}));var Do;(function(i){i.KeyRatcheted="keyRatcheted"})(Do||(Do={}));var bt;(function(i){i.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",i.EncryptionError="encryptionError"})(bt||(bt={}));var Oo;(function(i){i.Error="cryptorError"})(Oo||(Oo={}));function Im(){return xa()||Mm()}function Mm(){return typeof window<"u"&&typeof window.RTCRtpScriptTransform<"u"}function xa(){return typeof window<"u"&&typeof window.RTCRtpSender<"u"&&typeof window.RTCRtpSender.prototype.createEncodedStreams<"u"}function Am(i){var e,t,n,r,s;if(((e=i.value)===null||e===void 0?void 0:e.case)!=="sipDtmf"&&((t=i.value)===null||t===void 0?void 0:t.case)!=="metrics"&&((n=i.value)===null||n===void 0?void 0:n.case)!=="speaker"&&((r=i.value)===null||r===void 0?void 0:r.case)!=="transcription"&&((s=i.value)===null||s===void 0?void 0:s.case)!=="encryptedPacket")return new Dc({value:i.value})}var Lo=class extends Ee.EventEmitter{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};super(),this.latestManuallySetKeyIndex=0,this.onKeyRatcheted=(t,n,r)=>{F.debug("key ratcheted event received",{ratchetResult:t,participantId:n,keyIndex:r})},this.keyInfoMap=new Map,this.options=Object.assign(Object.assign({},Pm),e),this.on(St.KeyRatcheted,this.onKeyRatcheted)}onSetEncryptionKey(e,t,n){let r={key:e,participantIdentity:t,keyIndex:n};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(n??0),r),n!==void 0&&(this.latestManuallySetKeyIndex=n),this.emit(St.SetKey,r,n!==void 0)}getKeys(){return Array.from(this.keyInfoMap.values())}getLatestManuallySetKeyIndex(){return this.latestManuallySetKeyIndex}getOptions(){return this.options}ratchetKey(e,t){this.emit(St.RatchetRequest,e,t)}};var No;(function(i){i[i.InvalidKey=0]="InvalidKey",i[i.MissingKey=1]="MissingKey",i[i.InternalError=2]="InternalError"})(No||(No={}));function Un(){return hs()}function Fn(i){return!!i?.worker&&(xa()||Un())}function Ei(i){return!!(i?.timestamp||i?.frameId)}function xm(i){let e=[];return i?.timestamp&&e.push(nn.PTF_USER_TIMESTAMP),i?.frameId&&e.push(nn.PTF_FRAME_ID),e}function Dm(i){if(!i||i.length===0)return;let e={};return i.includes(nn.PTF_USER_TIMESTAMP)&&(e.timestamp=!0),i.includes(nn.PTF_FRAME_ID)&&(e.frameId=!0),e.timestamp||e.frameId?e:void 0}function Da(i){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:50,t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};var n,r;let s,a=(n=t.isImmediate)!==null&&n!==void 0?n:!1,o=(r=t.callback)!==null&&r!==void 0?r:!1,d=t.maxWait,c=Date.now(),l=[];function u(){if(d!==void 0){let m=Date.now()-c;if(m+e>=d)return d-m}return e}let h=function(){for(var m=arguments.length,g=new Array(m),f=0;f<m;f++)g[f]=arguments[f];let T=this;return new Promise((k,S)=>{let L=function(){if(s=void 0,c=Date.now(),!a){let b=i.apply(T,g);o&&o(b),l.forEach(E=>{let M=E.resolve;return M(b)}),l=[]}},y=a&&s===void 0;if(s!==void 0&&re.clearTimeout(s),s=re.setTimeout(L,u()),y){let b=i.apply(T,g);return o&&o(b),k(b)}l.push({resolve:k,reject:S})})};return h.cancel=function(m){s!==void 0&&re.clearTimeout(s),l.forEach(g=>{let f=g.reject;return f(m)}),l=[]},h}var Oa=2e3;function ar(i,e){if(!e)return 0;let t,n;return"bytesReceived"in i?(t=i.bytesReceived,n=e.bytesReceived):"bytesSent"in i&&(t=i.bytesSent,n=e.bytesSent),t===void 0||n===void 0||i.timestamp===void 0||e.timestamp===void 0?0:(t-n)*8*1e3/(i.timestamp-e.timestamp)}var Ri=class extends _{constructor(e,t,n,r,s){super(e,n,s),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?P.Muted:P.Unmuted,this))}setMediaStream(e){this.mediaStream=e;let t=n=>{n.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(P.Ended,this))};e.addEventListener("removetrack",t)}start(){this.startMonitor(),super.enable()}stop(){this.stopMonitor(),super.disable()}getRTCStatsReport(){return p(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(),Oa)),Qh()&&this.registerTimeSyncUpdate()}registerTimeSyncUpdate(){let e=()=>{var t;this.timeSyncHandle=requestAnimationFrame(()=>e());let n=(t=this.receiver)===null||t===void 0?void 0:t.getSynchronizationSources()[0];if(n){let r=n.timestamp,s=n.rtpTimestamp;s&&this.rtpTimestamp!==s&&(this.emit(P.TimeSyncUpdate,{timestamp:r,rtpTimestamp:s}),this.rtpTimestamp=s)}};e()}},Ir=100,Bn=class extends Ri{constructor(e,t,n,r,s){super(e,t,_.Kind.Video,n,s),this.elementInfos=[],this.monitorReceiver=()=>p(this,void 0,void 0,function*(){if(!this.receiver){this._currentBitrate=0;return}let a=yield this.getReceiverStats();a&&this.prevStats&&this.receiver&&(this._currentBitrate=ar(a,this.prevStats)),this.prevStats=a}),this.debouncedHandleResize=Da(()=>{this.updateDimensions()},Ir),this.adaptiveStreamSettings=r}get isAdaptiveStream(){return this.adaptiveStreamSettings!==void 0}lookupFrameMetadata(e){let t=e.rtpTimestamp;var n;return(n=this.frameMetadataExtractor)===null||n===void 0?void 0:n.lookupMetadata(t)}setStreamState(e){super.setStreamState(e),this.log.debug("setStreamState",e),this.isAdaptiveStream&&e===_.StreamState.Active&&this.updateVisibility()}get mediaStreamTrack(){return this._mediaStreamTrack}setMuted(e){super.setMuted(e),this.attachedElements.forEach(t=>{e?Yt(this._mediaStreamTrack,t):zt(this._mediaStreamTrack,t)})}attach(e){if(e?super.attach(e):e=super.attach(),this.adaptiveStreamSettings&&this.elementInfos.find(t=>t.element===e)===void 0){let t=new ps(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}let t=this.elementInfos.filter(n=>n===e);for(let n of t)n.stopObserving();this.elementInfos=this.elementInfos.filter(n=>n!==e),this.updateVisibility(),this.debouncedHandleResize()}detach(e){if(e)return this.stopObservingElement(e),super.detach(e);let t=super.detach();for(let n of t)this.stopObservingElement(n);return t}getDecoderImplementation(){var e;return(e=this.prevStats)===null||e===void 0?void 0:e.decoderImplementation}getReceiverStats(){return p(this,void 0,void 0,function*(){if(!this.receiver||!this.receiver.getStats)return;let e=yield this.receiver.getStats(),t,n="",r=new Map;return e.forEach(s=>{s.type==="inbound-rtp"?(n=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&&n!==""&&r.get(n)&&(t.mimeType=r.get(n).mimeType),t})}stopObservingElement(e){let t=this.elementInfos.filter(n=>n.element===e);for(let n of t)this.stopObservingElementInfo(n)}handleAppVisibilityChanged(){let e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return p(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),this.isAdaptiveStream&&this.updateVisibility()})}updateVisibility(e){var t,n;let r=this.elementInfos.reduce((d,c)=>Math.max(d,c.visibilityChangedAt||0),0),s=!((n=(t=this.adaptiveStreamSettings)===null||t===void 0?void 0:t.pauseVideoInBackground)!==null&&n!==void 0)||n?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<Ir){re.setTimeout(()=>{this.updateVisibility()},Ir);return}this.lastVisible=o,this.emit(P.VisibilityChanged,o,this)}}updateDimensions(){var e,t;let n=0,r=0,s=this.getPixelDensity();for(let a of this.elementInfos){let o=a.width()*s,d=a.height()*s;o+d>n+r&&(n=o,r=d)}((e=this.lastDimensions)===null||e===void 0?void 0:e.width)===n&&((t=this.lastDimensions)===null||t===void 0?void 0:t.height)===r||(this.lastDimensions={width:n,height:r},this.emit(P.VideoDimensionsChanged,this.lastDimensions,this))}getPixelDensity(){var e;let t=(e=this.adaptiveStreamSettings)===null||e===void 0?void 0:e.pixelDensity;return t==="screen"?Ro():t||(Ro()>2?2:1)}},ps=class{get visible(){return this.isPiP||this.isIntersecting}get pictureInPicture(){return this.isPiP}constructor(e,t){this.onVisibilityChanged=n=>{var r;let s=n.target,a=n.isIntersecting;s===this.element&&(this.isIntersecting=a,this.isPiP=bn(this.element),this.visibilityChangedAt=Date.now(),(r=this.handleVisibilityChanged)===null||r===void 0||r.call(this))},this.onEnterPiP=()=>{var n,r;(r=(n=window.documentPictureInPicture)===null||n===void 0?void 0:n.window)===null||r===void 0||r.addEventListener("pagehide",this.onLeavePiP),queueMicrotask(()=>{requestAnimationFrame(()=>{var s;this.isPiP=bn(this.element),(s=this.handleVisibilityChanged)===null||s===void 0||s.call(this)})})},this.onLeavePiP=()=>{var n;this.isPiP=bn(this.element),(n=this.handleVisibilityChanged)===null||n===void 0||n.call(this)},this.element=e,this.isIntersecting=t??fs(e),this.isPiP=Ce()&&bn(e),this.visibilityChangedAt=0}width(){return this.element.clientWidth}height(){return this.element.clientHeight}observe(){var e,t,n;this.isIntersecting=fs(this.element),this.isPiP=bn(this.element),this.element.handleResize=()=>{var r;(r=this.handleResize)===null||r===void 0||r.call(this)},this.element.handleVisibilityChanged=this.onVisibilityChanged,Io().observe(this.element),Po().observe(this.element),this.element.addEventListener("enterpictureinpicture",this.onEnterPiP),this.element.addEventListener("leavepictureinpicture",this.onLeavePiP),(e=window.documentPictureInPicture)===null||e===void 0||e.addEventListener("enter",this.onEnterPiP),(n=(t=window.documentPictureInPicture)===null||t===void 0?void 0:t.window)===null||n===void 0||n.addEventListener("pagehide",this.onLeavePiP)}stopObserving(){var e,t,n,r,s;(e=Io())===null||e===void 0||e.unobserve(this.element),(t=Po())===null||t===void 0||t.unobserve(this.element),this.element.removeEventListener("enterpictureinpicture",this.onEnterPiP),this.element.removeEventListener("leavepictureinpicture",this.onLeavePiP),(n=window.documentPictureInPicture)===null||n===void 0||n.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 bn(i){var e,t;return document.pictureInPictureElement===i?!0:!((e=window.documentPictureInPicture)===null||e===void 0)&&e.window?fs(i,(t=window.documentPictureInPicture)===null||t===void 0?void 0:t.window):!1}function fs(i,e){let t=e||window,n=i.offsetTop,r=i.offsetLeft,s=i.offsetWidth,a=i.offsetHeight,o=i,d=o.hidden,c=getComputedStyle(i),l=c.display;for(;i.offsetParent;)i=i.offsetParent,n+=i.offsetTop,r+=i.offsetLeft;return n<t.pageYOffset+t.innerHeight&&r<t.pageXOffset+t.innerWidth&&n+a>t.pageYOffset&&r+s>t.pageXOffset&&!d&&l!=="none"}var gs=class extends Ee.EventEmitter{constructor(e,t){super(),this.decryptDataRequests=new Map,this.encryptDataRequests=new Map,this.onWorkerMessage=n=>{var r,s;let a=n.data,o=a.kind,d=a.data;switch(o){case"error":if(F.error(d.error.message),d.uuid){let u=this.decryptDataRequests.get(d.uuid);if(u?.reject){u.reject(d.error);break}let h=this.encryptDataRequests.get(d.uuid);if(h?.reject){h.reject(d.error);break}}this.emit(bt.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(bt.ParticipantEncryptionStatusChanged,d.enabled,this.room.localParticipant),this.encryptionEnabled=d.enabled;else if(d.participantIdentity){let 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(bt.ParticipantEncryptionStatusChanged,d.enabled,u)}break;case"ratchetKey":this.keyProvider.emit(St.KeyRatcheted,d.ratchetResult,d.participantIdentity,d.keyIndex);break;case"decryptDataResponse":let c=this.decryptDataRequests.get(d.uuid);c?.resolve&&c.resolve(d);break;case"encryptDataResponse":let l=this.encryptDataRequests.get(d.uuid);l?.resolve&&l.resolve(d);break;case"packetTrailerMetadata":this.handleFrameMetadata(d.trackId,d.rtpTimestamp,d.ssrc,d.metadata);break}},this.onWorkerError=n=>{F.error("e2ee worker encountered an error:",{error:n.error}),this.emit(bt.EncryptionError,n.error,void 0)},this.keyProvider=e.keyProvider,this.worker=e.worker,this.encryptionEnabled=!1,this.dataChannelEncryptionEnabled=t}get isEnabled(){return this.encryptionEnabled}get isDataChannelEncryptionEnabled(){return this.isEnabled&&this.dataChannelEncryptionEnabled}setup(e){if(!Im())throw new Dn("tried to setup end-to-end encryption on an unsupported browser");if(F.info("setting up e2ee"),e!==this.room){this.room=e,this.setupEventListeners(e,this.keyProvider);let t={kind:"init",data:{keyProviderOptions:this.keyProvider.getOptions(),loglevel:Ch.getLevel()}};this.worker&&(F.info("initializing worker",{worker:this.worker}),this.worker.onmessage=this.onWorkerMessage,this.worker.onerror=this.onWorkerError,this.worker.postMessage(t))}}setParticipantCryptorEnabled(e,t){F.debug("set e2ee to ".concat(e," for participant ").concat(t)),this.postEnable(e,t)}setSifTrailer(e){!e||e.length===0?F.warn("ignoring server sent trailer as it's empty"):this.postSifTrailer(e)}handleFrameMetadata(e,t,n,r){if(this.room){for(let s of[this.room.localParticipant,...this.room.remoteParticipants.values()])for(let a of s.trackPublications.values())if(a.track&&a.track.mediaStreamID===e&&a.track instanceof Bn&&a.track.frameMetadataExtractor){a.track.frameMetadataExtractor.storeMetadata(t,n,r);return}}}setupEngine(e){e.on(R.RTPVideoMapUpdate,t=>{this.postRTPMap(t)})}setupEventListeners(e,t){e.on(C.TrackPublished,(n,r)=>this.setParticipantCryptorEnabled(n.trackInfo.encryption!==J.NONE,r.identity)),e.on(C.ConnectionStateChanged,n=>{n===V.Connected&&e.remoteParticipants.forEach(r=>{r.trackPublications.forEach(s=>{this.setParticipantCryptorEnabled(s.trackInfo.encryption!==J.NONE,r.identity)})})}).on(C.TrackUnsubscribed,(n,r,s)=>{var a;let o={kind:"removeTransform",data:{participantIdentity:s.identity,trackId:n.mediaStreamID}};(a=this.worker)===null||a===void 0||a.postMessage(o)}).on(C.TrackSubscribed,(n,r,s)=>{this.setupE2EEReceiver(n,s.identity,r.trackInfo)}).on(C.SignalConnected,()=>{if(!this.room)throw new TypeError("expected room to be present on signal connect");let n=t.getLatestManuallySetKeyIndex();t.getKeys().forEach(r=>{var s;this.postKey(r,n===((s=r.keyIndex)!==null&&s!==void 0?s:0))}),this.setParticipantCryptorEnabled(this.room.localParticipant.isE2EEEnabled,this.room.localParticipant.identity)}),e.localParticipant.on(I.LocalSenderCreated,(n,r)=>p(this,void 0,void 0,function*(){this.setupE2EESender(r,n)})),e.localParticipant.on(I.LocalTrackPublished,n=>{if(!ht(n.track)||!Ln())return;let r={kind:"updateCodec",data:{trackId:n.track.mediaStreamID,codec:_n(n.trackInfo.codecs[0].mimeType),participantIdentity:this.room.localParticipant.identity,hasPacketTrailer:!1}};this.worker.postMessage(r)}),t.on(St.SetKey,(n,r)=>this.postKey(n,r??!0)).on(St.RatchetRequest,(n,r)=>this.postRatchetRequest(n,r))}encryptData(e){return p(this,void 0,void 0,function*(){if(!this.worker)throw Error("could not encrypt data, worker is missing");let t=crypto.randomUUID(),n={kind:"encryptDataRequest",data:{uuid:t,payload:e,participantIdentity:this.room.localParticipant.identity}},r=new ce;return r.onFinally=()=>{this.encryptDataRequests.delete(t)},this.encryptDataRequests.set(t,r),this.worker.postMessage(n),r.promise})}handleEncryptedData(e,t,n,r){if(!this.worker)throw Error("could not handle encrypted data, worker is missing");let s=crypto.randomUUID(),a={kind:"decryptDataRequest",data:{uuid:s,payload:e,iv:t,participantIdentity:n,keyIndex:r}},o=new ce;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");let n={kind:"ratchetRequest",data:{participantIdentity:e,keyIndex:t}};this.worker.postMessage(n)}postKey(e,t){let n=e.key,r=e.participantIdentity,s=e.keyIndex;var a;if(!this.worker)throw Error("could not set key, worker is missing");let o={kind:"setKey",data:{participantIdentity:r,isPublisher:r===((a=this.room)===null||a===void 0?void 0:a.localParticipant.identity),key:n,keyIndex:s,updateCurrentKeyIndex:t}};this.worker.postMessage(o)}postEnable(e,t){if(this.worker){let n={kind:"enable",data:{enabled:e,participantIdentity:t}};this.worker.postMessage(n)}else throw new ReferenceError("failed to enable e2ee, worker is not ready")}postRTPMap(e){var t;if(!this.worker)throw TypeError("could not post rtp map, worker is missing");if(!(!((t=this.room)===null||t===void 0)&&t.localParticipant.identity))throw TypeError("could not post rtp map, local participant identity is missing");let n={kind:"setRTPMap",data:{map:e,participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(n)}postSifTrailer(e){if(!this.worker)throw Error("could not post SIF trailer, worker is missing");let t={kind:"setSifTrailer",data:{trailer:e}};this.worker.postMessage(t)}setupE2EEReceiver(e,t,n){if(!e.receiver)return;if(!n?.mimeType||n.mimeType==="")throw new TypeError("MimeType missing from trackInfo, cannot set up E2EE cryptor");let r=e.kind==="video"&&!!n.packetTrailerFeatures&&n.packetTrailerFeatures.length>0;this.handleReceiver(e.receiver,e.mediaStreamID,t,e.kind==="video"?_n(n.mimeType):void 0,r)}setupE2EESender(e,t){var n,r,s;if(!Xt(e)||!t){t||F.warn("early return because sender is not ready");return}this.handleSender(t,e.mediaStreamID,void 0,ht(e)?(r=(n=e.publishOptions)===null||n===void 0?void 0:n.frameMetadata)!==null&&r!==void 0?r:(s=e.publishOptions)===null||s===void 0?void 0:s.packetTrailer:void 0)}handleReceiver(e,t,n,r,s){return p(this,void 0,void 0,function*(){if(this.worker){if(hs()){let a={kind:"decode",participantIdentity:n,trackId:t,codec:r,hasPacketTrailer:s};e.transform=new RTCRtpScriptTransform(this.worker,a)}else{if(yn in e&&r){let c={kind:"updateCodec",data:{trackId:t,codec:r,participantIdentity:n,hasPacketTrailer:s}};this.worker.postMessage(c);return}let a=e.writableStream,o=e.readableStream;if(!a||!o){let c=e.createEncodedStreams();e.writableStream=c.writable,a=c.writable,e.readableStream=c.readable,o=c.readable}let d={kind:"decode",data:{readableStream:o,writableStream:a,trackId:t,codec:r,participantIdentity:n,isReuse:yn in e,hasPacketTrailer:s}};this.worker.postMessage(d,[o,a])}e[yn]=!0}})}handleSender(e,t,n,r){var s;if(!(yn 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(hs()){F.info("initialize script transform");let a={kind:"encode",participantIdentity:this.room.localParticipant.identity,trackId:t,codec:n,hasPacketTrailer:Ei(r),packetTrailer:r};e.transform=new RTCRtpScriptTransform(this.worker,a)}else{F.info("initialize encoded streams");let a=e.createEncodedStreams(),o={kind:"encode",data:{readableStream:a.readable,writableStream:a.writable,codec:n,trackId:t,participantIdentity:this.room.localParticipant.identity,isReuse:!1,hasPacketTrailer:Ei(r),packetTrailer:r}};this.worker.postMessage(o,[a.readable,a.writable])}e[yn]=!0}}},Om=300,vs=class{constructor(){this.metadataMap=new Map,this.activeSsrc=0}storeMetadata(e,t,n){for(this.activeSsrc!==0&&this.activeSsrc!==t&&this.metadataMap.clear(),this.activeSsrc=t;this.metadataMap.size>=Om;){let r=this.metadataMap.keys().next().value;this.metadataMap.delete(r)}this.metadataMap.set(e,n)}lookupMetadata(e){return this.metadataMap.get(e)}dispose(){this.metadataMap.clear(),this.activeSsrc=0}},ys=class{constructor(e){this.extractors=new Map,this.workerPipelines=new Map,this.onWorkerMessage=t=>{let n=t.data;if(n.kind==="metadata"){let r=this.extractors.get(n.data.trackId);r&&r.storeMetadata(n.data.rtpTimestamp,n.data.ssrc,n.data.metadata)}},this.onWorkerError=t=>{F.error("frame metadata worker encountered an error:",{error:t.error})},this.worker=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(C.TrackSubscribed,(t,n,r)=>{t.kind==="video"&&this.setupReceiver(t,n.trackInfo)}).on(C.TrackUnsubscribed,t=>{this.teardownTrack(t)}).on(C.Disconnected,()=>{this.cleanup()}))}setupReceiver(e,t){var n,r,s;let a=e.receiver;if(!a)return;if(!(!!t?.packetTrailerFeatures&&t.packetTrailerFeatures.length>0)){!((n=this.room)===null||n===void 0)&&n.hasE2EESetup||this.setupPassthroughReceiver(a,e.mediaStreamID);return}if(!Fn(this.worker?{worker:this.worker}:void 0)&&!(!((r=this.room)===null||r===void 0)&&r.hasE2EESetup)){F.warn("frame metadata transform not supported; skipping extraction");return}let d=new vs,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(Un()){"transform"in e&&(e.transform=null);return}if(this.worker&&Fn({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 n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,r=this.worker;if(!r)return;if(Un()){e.transform=new RTCRtpScriptTransform(r,{kind:"decode",trackId:t});return}let s=this.workerPipelines.get(e);if(s){let d={kind:"updateTrackId",data:{oldTrackId:s,newTrackId:t,hasPacketTrailer:n}};r.postMessage(d),this.workerPipelines.set(e,t);return}if(!("createEncodedStreams"in e)){F.warn("createEncodedStreams not supported");return}let a;try{a=e.createEncodedStreams()}catch(d){F.warn("failed to create encoded streams",{error:d});return}let o={kind:"decode",data:{readableStream:a.readable,writableStream:a.writable,trackId:t,hasPacketTrailer:n}};r.postMessage(o,[a.readable,a.writable]),this.workerPipelines.set(e,t)}teardownTrack(e){let t=e.mediaStreamID,n=this.extractors.get(t);n&&(n.dispose(),this.extractors.delete(t)),e instanceof Bn&&(e.frameMetadataExtractor=void 0)}cleanup(){var e;for(let t of this.extractors.values())t.dispose();this.extractors.clear(),this.workerPipelines.clear(),(e=this.worker)===null||e===void 0||e.terminate()}};var Lm=500,Nm=15e3,Zt=class i{constructor(){this.failedConnectionAttempts=new Map,this.backOffPromises=new Map}static getInstance(){return this._instance||(this._instance=new i),this._instance}addFailedConnectionAttempt(e){var t;let n=new URL(e),r=_r(n);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,ve(Math.min(Lm*Math.pow(2,s),Nm)))}getBackOffPromise(e){let t=new URL(e),n=t&&_r(t);return n&&this.backOffPromises.get(n)||Promise.resolve()}resetFailedConnectionAttempts(e){let t=new URL(e),n=t&&_r(t);n&&(this.failedConnectionAttempts.set(n,0),this.backOffPromises.set(n,Promise.resolve()))}resetAll(){this.backOffPromises.clear(),this.failedConnectionAttempts.clear()}};Zt._instance=null;var Mr="default",Pe=class i{constructor(){this._previousDevices=[]}static getInstance(){return this.instance===void 0&&(this.instance=new i),this.instance}get previousDevices(){return this._previousDevices}getDevices(e){return p(this,arguments,void 0,function(t){var n=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return(function*(){var s;if(((s=i.userMediaPromiseMap)===null||s===void 0?void 0:s.size)>0){F.debug("awaiting getUserMedia promise");try{t?yield i.userMediaPromiseMap.get(t):yield Promise.all(i.userMediaPromiseMap.values())}catch{F.warn("error waiting for media permissons")}}let a=yield navigator.mediaDevices.enumerateDevices();if(r&&!(Bt()&&n.hasDeviceInUse(t))&&(a.filter(d=>d.kind===t).length===0||a.some(d=>{let c=d.label==="",l=t?d.kind===t:!0;return c&&l}))){let 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 n._previousDevices=a,t&&(a=a.filter(o=>o.kind===t)),a})()})}normalizeDeviceId(e,t,n){return p(this,void 0,void 0,function*(){if(t!==Mr)return t;let r=yield this.getDevices(e),s=r.find(o=>o.deviceId===Mr);if(!s){F.warn("could not reliably determine default device");return}let a=r.find(o=>o.deviceId!==Mr&&o.groupId===(n??s.groupId));if(!a){F.warn("could not reliably determine default device");return}return a?.deviceId})}hasDeviceInUse(e){return e?i.userMediaPromiseMap.has(e):i.userMediaPromiseMap.size>0}};Pe.mediaDeviceKinds=["audioinput","audiooutput","videoinput"];Pe.userMediaPromiseMap=new Map;var La=65535,$d=4294967295,Ct=class i{static u16(e){return new i(e,La)}static u32(e){return new i(e,$d)}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 i(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(){let e=this.value;return this.increment(),new i(e,this.maxSize)}isBefore(e){let t=this.value>>>0,r=(e.value>>>0)-t>>>0;return r!==0&&r<this.maxSize+1}},Pi=class i{static fromRtpTicks(e){return new i(e,9e4)}static rtpRandom(){let e=Math.round(Math.random()*$d);return i.fromRtpTicks(e)}constructor(e,t){this.timestamp=Ct.u32(e),this.rateInHz=t}asTicks(){return this.timestamp.value}clone(){return new i(this.timestamp.value,this.rateInHz)}wrappingAdd(e){this.timestamp.increment(e)}isBefore(e){return this.timestamp.isBefore(e.timestamp)}},bs=class i{constructor(e,t,n){this.epoch=t,this.base=n,this.previous=n.clone(),this.rateInHz=e}static startingNow(e,t){return new i(t,new Date,e)}static startingAtTime(e,t,n){return new i(n,e,t)}static rtpStartingNow(e){return i.startingNow(e,9e4)}static rtpStartingAtTime(e,t){return i.startingAtTime(e,t,9e4)}now(){return this.at(new Date)}at(e){let t=e.getTime()-this.epoch.getTime(),n=i.durationInMsToTicks(t,this.rateInHz),r=this.base.clone();return r.wrappingAdd(n),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 Na(i){if(i instanceof DataView)return i;if(i instanceof ArrayBuffer)return new DataView(i);if(i instanceof Uint8Array)return new DataView(i.buffer,i.byteOffset,i.byteLength);throw new Error("Error coercing ".concat(i," to DataView - input was not DataView, ArrayBuffer, or Uint8Array."))}var Nt;(function(i){i[i.Reserved=0]="Reserved",i[i.TooLarge=1]="TooLarge"})(Nt||(Nt={}));var qn=class i extends we{constructor(e,t){super(19,e),this.name="DataTrackHandleError",this.reason=t,this.reasonName=Nt[t]}isReason(e){return this.reason===e}static tooLarge(){return new i("Value too large to be a valid track handle",Nt.TooLarge)}static reserved(e){return new i("0x".concat(e.toString(16)," is a reserved value."),Nt.Reserved)}},Um={fromNumber(i){if(i===0)throw qn.reserved(i);if(i>La)throw qn.tooLarge();return i}},ks=class{constructor(){this.value=0}get(){return this.value+=1,this.value>La?null:this.value}reset(){this.value=0}},Ii={from(i){return{sid:i.sid,pubHandle:i.pubHandle,name:i.name,usesE2ee:i.encryption!==J.NONE}},toProtobuf(i){return new Zi({sid:i.sid,pubHandle:i.pubHandle,name:i.name,encryption:i.usesE2ee?J.GCM:J.NONE})}},wn;(function(i){i[i.WAITING=0]="WAITING",i[i.RUNNING=1]="RUNNING",i[i.COMPLETED=2]="COMPLETED"})(wn||(wn={}));var Ts=class{constructor(){this.pendingTasks=new Map,this.taskMutex=new de,this.nextTaskIndex=0}run(e){return p(this,void 0,void 0,function*(){let t={id:this.nextTaskIndex++,enqueuedAt:Date.now(),status:wn.WAITING};this.pendingTasks.set(t.id,t);let n=yield this.taskMutex.lock();try{return t.executedAt=Date.now(),t.status=wn.RUNNING,yield e()}finally{t.status=wn.COMPLETED,this.pendingTasks.delete(t.id),n()}})}flush(){return p(this,void 0,void 0,function*(){return this.run(()=>p(this,void 0,void 0,function*(){}))})}snapshot(){return Array.from(this.pendingTasks.values())}},Ss=class{get readyState(){return this.ws.readyState}constructor(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};var n,r;if(!((n=t.signal)===null||n===void 0)&&n.aborted)throw new DOMException("This operation was aborted","AbortError");this.url=e;let s=new WebSocket(e,(r=t.protocols)!==null&&r!==void 0?r:[]);s.binaryType="arraybuffer",this.ws=s;let 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 pe((o,d)=>{let c=()=>{d(N.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 pe((o,d)=>{let c=()=>p(this,void 0,void 0,function*(){let l=new pe(h=>{s.readyState!==WebSocket.CLOSED&&s.addEventListener("close",m=>{h(m)},{once:!0})}),u=yield pe.race([ve(250),l]);u?o(u):d(N.websocket("Encountered unspecified websocket error without a timely close event"))});s.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}},Fm=["syncState","trickle","offer","answer","simulate","leave"];function Bm(i){let e=Fm.indexOf(i.case)>=0;return F.trace("request allowed to bypass queue:",{canPass:e,req:i}),e}var W;(function(i){i[i.CONNECTING=0]="CONNECTING",i[i.CONNECTED=1]="CONNECTED",i[i.RECONNECTING=2]="RECONNECTING",i[i.DISCONNECTING=3]="DISCONNECTING",i[i.DISCONNECTED=4]="DISCONNECTED"})(W||(W={}));var qm=250,jn=class{get currentState(){return this.state}get isDisconnected(){return this.state===W.DISCONNECTING||this.state===W.DISCONNECTED}get isEstablishingConnection(){return this.state===W.CONNECTING||this.state===W.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 n;this.rtt=0,this.state=W.DISCONNECTED,this.log=F,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=_e((n=t.loggerName)!==null&&n!==void 0?n:ue.Signal,()=>this.logContext),this.useJSON=e,this.requestQueue=new Ts,this.queuedRequests=[],this.closingLock=new de,this.connectionLock=new de,this.state=W.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,n,r){return p(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=W.CONNECTING,c.options=o,yield c.connect(s,a,o,d,l,u)})()})}reconnect(e,t,n,r){return p(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=W.RECONNECTING,this.clearPingInterval(),yield this.connect(e,t,Object.assign(Object.assign({},this.options),{reconnect:!0,sid:n,reconnectReason:r}),void 0,this.useV0SignalPath)})}connect(e,t,n,r){return p(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*(){let h=yield c.connectionLock.lock();c.connectOptions=o,c.useV0SignalPath=l;let m=hm(o.clientInfoCapabilities),g=l?jm(a,m,o):yield Vm(a,m,o,u),f=Sm(s,g,l).toString(),T=_m(f).toString();return new Promise((k,S)=>p(c,void 0,void 0,function*(){var L,y;try{let b=!1,E=x=>p(this,void 0,void 0,function*(){if(b)return;b=!0;let B=x instanceof Event?x.currentTarget:x,Z=wm(B,"Abort handler called");this.streamWriter&&!this.isDisconnected?this.sendLeave().then(()=>this.close(Z)).catch(ee=>{this.log.error(ee),this.close()}):this.close(),M(),S(N.cancelled(Z))});d?.addEventListener("abort",E);let M=()=>{clearTimeout(D),d?.removeEventListener("abort",E)},D=setTimeout(()=>{E(N.timeout("room connection has timed out (signal)"))},o.websocketTimeout),q=(x,B)=>{this.handleSignalConnected(x,D,B)},A=new URL(f);if(A.searchParams.has("access_token")&&A.searchParams.set("access_token","<redacted>"),this.ws){let x=performance.now();yield this.close(!1),this.log.debug("closed previous ws connection in ".concat(performance.now()-x,"ms"))}this.log.info("signal connecting to ".concat(A),{reconnect:o.reconnect,reconnectReason:o.reconnectReason}),this.ws=new Ss(f);try{this.ws.closed.then(ye=>{var ft;this.isEstablishingConnection&&S(N.internal("Websocket got closed during a (re)connection attempt: ".concat(ye.reason))),ye.closeCode!==1e3&&(this.log.warn("websocket closed",{reason:ye.reason,code:ye.closeCode,wasClean:ye.closeCode===1e3,state:this.state}),this.state===W.CONNECTED&&this.handleOnClose((ft=ye.reason)!==null&&ft!==void 0?ft:"Unexpected WS error"))}).catch(ye=>{this.isEstablishingConnection&&S(N.internal("Websocket error during a (re)connection attempt: ".concat(ye)))});let x=yield this.ws.opened.catch(ye=>p(this,void 0,void 0,function*(){if(this.state!==W.CONNECTED){this.state=W.DISCONNECTED,clearTimeout(D);let ft=yield this.handleConnectionError(ye,T);S(ft);return}this.handleWSError(ye),S(ye)}));if(clearTimeout(D),!x)return;let B=x.readable.getReader();this.streamWriter=x.writable.getWriter();let Z=yield B.read();if(B.releaseLock(),!Z.value)throw N.internal("no message received as first message");let ee=xo(Z.value),ze=this.validateFirstMessage(ee,(L=o.reconnect)!==null&&L!==void 0?L:!1);if(!ze.isValid){S(ze.error);return}((y=ee.message)===null||y===void 0?void 0:y.case)==="join"&&(this.pingTimeoutDuration=ee.message.value.pingTimeout,this.pingIntervalDuration=ee.message.value.pingInterval,this.pingTimeoutDuration&&this.pingTimeoutDuration>0&&this.log.debug("ping config",{timeout:this.pingTimeoutDuration,interval:this.pingIntervalDuration}),this.onJoined&&this.onJoined(ee.message.value));let mn=ze.shouldProcessFirstMessage?ee:void 0;q(x,mn),k(ze.response)}catch(x){S(x)}finally{M()}}finally{h()}}))})()})}startReadingLoop(e,t){return p(this,void 0,void 0,function*(){for(t&&this.handleSignalResponse(t);;){this.signalLatency&&(yield ve(this.signalLatency));let n=yield e.read(),r=n.done,s=n.value;if(r)break;let a=xo(s);this.handleSignalResponse(a)}})}close(){return p(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0,n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"Close method called on signal client";return(function*(){if([W.DISCONNECTING||W.DISCONNECTED].includes(e.state)){e.log.debug("ignoring signal close as it's already in disconnecting state");return}let r=yield e.closingLock.lock();try{if(e.clearPingInterval(),t&&(e.state=W.DISCONNECTING),e.ws){e.ws.close({closeCode:1e3,reason:n});let s=e.ws.closed;e.ws=void 0,e.streamWriter=void 0,yield Promise.race([s,ve(qm)])}}catch(s){e.log.debug("websocket error while closing",{error:s})}finally{t&&(e.state=W.DISCONNECTED),r()}})()})}sendOffer(e,t){this.log.debug("sending offer",{offerSdp:e.sdp}),this.sendRequest({case:"offer",value:Mt(e,t)})}sendAnswer(e,t){return this.log.debug("sending answer",{answerSdp:e.sdp}),this.sendRequest({case:"answer",value:Mt(e,t)})}sendIceCandidate(e,t){return this.log.debug("sending ice candidate",{candidate:e}),this.sendRequest({case:"trickle",value:new tr({candidateInit:JSON.stringify(e),target:t})})}sendMuteTrack(e,t){return this.sendRequest({case:"mute",value:new nr({sid:e,muted:t})})}sendAddTrack(e){return this.sendRequest({case:"addTrack",value:e})}sendUpdateLocalMetadata(e,t){return p(this,arguments,void 0,function(n,r){var s=this;let a=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return(function*(){let o=s.getNextRequestId();return yield s.sendRequest({case:"updateMetadata",value:new _a({requestId:o,metadata:n,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 Yc({trackSid:e,layers:t})})}sendUpdateSubscriptionPermissions(e,t){return this.sendRequest({case:"subscriptionPermission",value:new ed({allParticipants:e,trackPermissions:t})})}sendSimulateScenario(e){return this.sendRequest({case:"simulate",value:e})}sendPing(){return Promise.all([this.sendRequest({case:"ping",value:Y.parse(Date.now())}),this.sendRequest({case:"pingReq",value:new id({timestamp:Y.parse(Date.now()),rtt:Y.parse(this.rtt)})})])}sendUpdateLocalAudioTrack(e,t){return this.sendRequest({case:"updateAudioTrack",value:new Ca({trackSid:e,features:t})})}sendLeave(){return this.sendRequest({case:"leave",value:new rr({reason:oe.CLIENT_INITIATED,action:$t.DISCONNECT})})}sendPublishDataTrackRequest(e,t,n){return this.sendRequest({case:"publishDataTrackRequest",value:new ba({pubHandle:e,name:t,encryption:n?J.GCM:J.NONE})})}sendUnPublishDataTrackRequest(e){return this.sendRequest({case:"unpublishDataTrackRequest",value:new Ta({pubHandle:e})})}sendUpdateDataSubscription(e,t){return this.sendRequest({case:"updateDataSubscription",value:new zc({updates:[new Jc({trackSid:e,subscribe:t})]})})}sendRequest(e){return p(this,arguments,void 0,function(t){var n=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1;return(function*(){if(!r&&!Bm(t)&&n.state===W.RECONNECTING){n.queuedRequests.push(()=>p(n,void 0,void 0,function*(){yield this.sendRequest(t,!0)}));return}if(r||(yield n.requestQueue.flush()),n.signalLatency&&(yield ve(n.signalLatency)),n.isDisconnected){n.log.debug("skipping signal request (type: ".concat(t.case,") - SignalClient disconnected"));return}if(!n.streamWriter){n.log.error("cannot send signal request before connected, type: ".concat(t?.case));return}let a=new Ku({message:t});try{n.useJSON?yield n.streamWriter.write(a.toJsonString()):yield n.streamWriter.write(a.toBinary().buffer)}catch(o){n.log.error("error sending signal message",{error:o})}})()})}handleSignalResponse(e){var t,n;let r=e.message;if(r==null){this.log.debug("received unsupported message");return}let s=!1;if(r.case==="answer"){let a=Uo(r.value);this.onAnswer&&this.onAnswer(a,r.value.id,r.value.midToTrackId)}else if(r.case==="offer"){let a=Uo(r.value);this.onOffer&&this.onOffer(a,r.value.id,r.value.midToTrackId)}else if(r.case==="trickle"){let a=JSON.parse(r.value.candidateInit);this.onTrickle&&this.onTrickle(a,r.value.target)}else r.case==="update"?this.onParticipantUpdate&&this.onParticipantUpdate((t=r.value.participants)!==null&&t!==void 0?t:[]):r.case==="trackPublished"?this.onLocalTrackPublished&&this.onLocalTrackPublished(r.value):r.case==="speakersChanged"?this.onSpeakersChanged&&this.onSpeakersChanged((n=r.value.speakers)!==null&&n!==void 0?n:[]):r.case==="leave"?this.onLeave&&this.onLeave(r.value):r.case==="mute"?this.onRemoteMuteChanged&&this.onRemoteMuteChanged(r.value.sid,r.value.muted):r.case==="roomUpdate"?this.onRoomUpdate&&r.value.room&&this.onRoomUpdate(r.value.room):r.case==="connectionQuality"?this.onConnectionQuality&&this.onConnectionQuality(r.value):r.case==="streamStateUpdate"?this.onStreamStateUpdate&&this.onStreamStateUpdate(r.value):r.case==="subscribedQualityUpdate"?this.onSubscribedQualityUpdate&&this.onSubscribedQualityUpdate(r.value):r.case==="subscriptionPermissionUpdate"?this.onSubscriptionPermissionUpdate&&this.onSubscriptionPermissionUpdate(r.value):r.case==="refreshToken"?this.onTokenRefresh&&this.onTokenRefresh(r.value):r.case==="trackUnpublished"?this.onLocalTrackUnpublished&&this.onLocalTrackUnpublished(r.value):r.case==="subscriptionResponse"?this.onSubscriptionError&&this.onSubscriptionError(r.value):r.case==="pong"||(r.case==="pongResp"?(this.rtt=Date.now()-Number.parseInt(r.value.lastPingTimestamp.toString()),this.resetPingTimeout(),s=!0):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(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;){let e=this.queuedRequests.shift();e&&this.requestQueue.run(e)}}handleOnClose(e){return p(this,void 0,void 0,function*(){if(this.state===W.DISCONNECTED)return;let t=this.onClose;yield this.close(void 0,e),this.log.info("websocket connection closed: ".concat(e),{reason:e}),t&&t(e)})}handleWSError(e){this.log.error("websocket error",{error:e})}resetPingTimeout(){if(this.clearPingTimeout(),!this.pingTimeoutDuration){this.log.warn("ping timeout duration not set");return}this.pingTimeout=re.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&&re.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=re.setInterval(()=>{this.sendPing()},this.pingIntervalDuration*1e3)}clearPingInterval(){this.log.debug("clearing ping interval"),this.clearPingTimeout(),this.pingInterval&&re.clearInterval(this.pingInterval)}handleSignalConnected(e,t,n){this.state=W.CONNECTED,this.log.info("signal connected"),clearTimeout(t),this.startPingInterval(),this.startReadingLoop(e.readable.getReader(),n)}validateFirstMessage(e,t){var n,r,s,a,o;return((n=e.message)===null||n===void 0?void 0:n.case)==="join"?{isValid:!0,response:e.message.value}:this.state===W.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:N.leaveRequest("Received leave request while trying to (re)connect",e.message.value.reason)}:t?{isValid:!1,error:N.internal("Unexpected first message")}:{isValid:!1,error:N.internal("did not receive join response, got ".concat((o=e.message)===null||o===void 0?void 0:o.case," instead"))}}handleConnectionError(e,t){return p(this,void 0,void 0,function*(){try{let n=yield fetch(t);switch(n.status){case 404:let r=yield n.text();return r.includes("requested room does not exist")?N.notAllowed(r,n.status):N.serviceNotFound("v1 RTC path not found. Consider upgrading your LiveKit server version","v0-rtc");case 401:case 403:let s=yield n.text();return N.notAllowed(s,n.status);default:break}return e instanceof N?e:N.internal("Encountered unknown websocket error during connection: ".concat(e),{status:n.status,statusText:n.statusText})}catch(n){return n instanceof N?n:N.serverUnreachable(n instanceof Error?n.message:"server was not reachable")}})}};function Uo(i){let e={type:"offer",sdp:i.sdp};switch(i.type){case"answer":case"offer":case"pranswer":case"rollback":e.type=i.type;break}return e}function Mt(i,e){return new wt({sdp:i.sdp,type:i.type,id:e})}function jm(i,e,t){var n;let r=new URLSearchParams;return r.set("access_token",i),t.reconnect&&(r.set("reconnect","1"),t.sid&&r.set("sid",t.sid)),r.set("auto_subscribe",t.autoSubscribe?"1":"0"),r.set("sdk",He()?"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()),!((n=navigator.connection)===null||n===void 0)&&n.type&&r.set("network",navigator.connection.type),r}function Vm(i,e,t,n){return p(this,void 0,void 0,function*(){let r=new URLSearchParams;r.set("access_token",i);let s=new gh({clientInfo:e,connectionSettings:new rd({autoSubscribe:!!t.autoSubscribe,adaptiveStream:!!t.adaptiveStream}),reconnect:!!t.reconnect,participantSid:t.sid?t.sid:void 0,publisherOffer:n});t.reconnectReason&&(s.reconnectReason=t.reconnectReason);let a=s.toBinary(),o,d;if(zd()){let h=new CompressionStream("gzip"),m=h.writable.getWriter();m.write(new Uint8Array(a)),m.close();let g=[],f=h.readable.getReader();for(;;){let L=yield f.read(),y=L.done,b=L.value;if(y)break;g.push(b)}let T=g.reduce((L,y)=>L+y.length,0),k=new Uint8Array(T),S=0;for(let L of g)k.set(L,S),S+=L.length;o=k,d=zr.GZIP}else o=a,d=zr.NONE;let l=new vh({joinRequest:o,compression:d}).toBinary(),u=h=>{let m=Array.from(h,g=>String.fromCodePoint(g)).join("");return btoa(m)};return r.set("join_request",u(l).replace(/\+/g,"-").replace(/\//g,"_")),r})}var Mi=class{constructor(){this.buffer=[],this._totalSize=0}push(e){this.buffer.push(e),this._totalSize+=e.data.byteLength}pop(){let e=this.buffer.shift();return e&&(this._totalSize-=e.data.byteLength),e}getAll(){return this.buffer.slice()}popToSequence(e){for(;this.buffer.length>0&&this.buffer[0].sequence<=e;)this.pop()}alignBufferedAmount(e){for(;this.buffer.length>0;){let t=this.buffer[0];if(this._totalSize-t.data.byteLength<=e)break;this.pop()}}get length(){return this.buffer.length}},Cs=class{constructor(e){this._map=new Map,this._lastCleanup=0,this.ttl=e}set(e,t){let n=Date.now();n-this._lastCleanup>this.ttl/2&&this.cleanup();let r=n+this.ttl;return this._map.set(e,{value:t,expiresAt:r}),this}get(e){let t=this._map.get(e);if(t){if(t.expiresAt<Date.now()){this._map.delete(e);return}return t.value}}has(e){let 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(){let e=Date.now();for(let n of this._map.entries()){var t=O(n,2);let 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(let n of this._map.entries()){var t=O(n,2);let r=t[0],s=t[1];s.expiresAt>=Date.now()&&e(s.value,r,this.asValueMap())}}map(e){this.cleanup();let t=[],n=this.asValueMap();for(let s of n.entries()){var r=O(s,2);let a=r[0],o=r[1];t.push(e(o,a,n))}return t}asValueMap(){let e=new Map;for(let n of this._map.entries()){var t=O(n,2);let r=t[0],s=t[1];s.expiresAt>=Date.now()&&e.set(r,s.value)}return e}},xe={},Ar={},xr={exports:{}},Fo;function Ua(){if(Fo)return xr.exports;Fo=1;var i=xr.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","maxMessageSize"],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(i).forEach(function(e){var t=i[e];t.forEach(function(n){n.reg||(n.reg=/(.*)/),n.format||(n.format="%s")})}),xr.exports}var Bo;function Hm(){return Bo||(Bo=1,(function(i){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]))},n=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=Ua(),s=RegExp.prototype.test.bind(/^([a-z])=(.*)/);i.parse=function(o){var d={},c=[],l=d;return o.split(/(\r\n|\r|\n)/).filter(s).forEach(function(u){var h=u[0],m=u.slice(2);h==="m"&&(c.push({rtp:[],fmtp:[]}),l=c[c.length-1]);for(var g=0;g<(r[h]||[]).length;g+=1){var f=r[h][g];if(f.reg.test(m))return n(f,l,m)}}),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};i.parseParams=function(o){return o.split(/;\s?/).reduce(a,{})},i.parseFmtpConfig=i.parseParams,i.parsePayloads=function(o){return o.toString().split(" ").map(Number)},i.parseRemoteCandidates=function(o){for(var 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},i.parseImageAttributes=function(o){return o.split(" ").map(function(d){return d.substring(1,d.length-1).split(",").reduce(a,{})})},i.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}})})}})(Ar)),Ar}var Dr,qo;function Gm(){if(qo)return Dr;qo=1;var i=Ua(),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""}})},n=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 Dr=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){i[u].forEach(function(h){h.name in a&&a[h.name]!=null?l.push(n(u,h,a)):h.push in a&&a[h.push]!=null&&a[h.push].forEach(function(m){l.push(n(u,h,m))})})}),a.media.forEach(function(u){l.push(n("m",i.m[0],u)),c.forEach(function(h){i[h].forEach(function(m){m.name in u&&u[m.name]!=null?l.push(n(h,m,u)):m.push in u&&u[m.push]!=null&&u[m.push].forEach(function(g){l.push(n(h,m,g))})})})}),l.join(`\r
37
+ `);i.RTCSessionDescription&&r instanceof i.RTCSessionDescription?arguments[0]=new i.RTCSessionDescription({type:r.type,sdp:s}):r.sdp=s}return t.apply(this,arguments)}}function ui(i,e){if(!(i.RTCPeerConnection&&i.RTCPeerConnection.prototype))return;let t=i.RTCPeerConnection.prototype.addIceCandidate;!t||t.length===0||(i.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?(e.browser==="chrome"&&e.version<78||e.browser==="firefox"&&e.version<68||e.browser==="safari")&&arguments[0]&&arguments[0].candidate===""?Promise.resolve():t.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}function hi(i,e){if(!(i.RTCPeerConnection&&i.RTCPeerConnection.prototype))return;let t=i.RTCPeerConnection.prototype.setLocalDescription;!t||t.length===0||(i.RTCPeerConnection.prototype.setLocalDescription=function(){let r=arguments[0]||{};if(typeof r!="object"||r.type&&r.sdp)return t.apply(this,arguments);if(r={type:r.type,sdp:r.sdp},!r.type)switch(this.signalingState){case"stable":case"have-local-offer":case"have-remote-pranswer":r.type="offer";break;default:r.type="answer";break}return r.sdp||r.type!=="offer"&&r.type!=="answer"?t.apply(this,[r]):(r.type==="offer"?this.createOffer:this.createAnswer).apply(this).then(a=>t.apply(this,[a]))})}var Fh=Object.freeze({__proto__:null,removeExtmapAllowMixed:ts,shimAddIceCandidateNullOrEmpty:ui,shimConnectionState:es,shimMaxMessageSize:di,shimParameterlessSetLocalDescription:hi,shimRTCIceCandidate:ci,shimRTCIceCandidateRelayProtocol:Zr,shimSendThrowTypeError:li});function Bh(){let i=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},e=i.window,t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{shimChrome:!0,shimFirefox:!0,shimSafari:!0},n=Ra,r=Oh(e),s={browserDetails:r,commonShim:Fh,extractVersion:Tn,disableLog:xh,disableWarnings:Dh,sdp:Uh};switch(r.browser){case"chrome":if(!So||!Yr||!t.shimChrome)return n("Chrome shim is not included in this adapter release."),s;if(r.version===null)return n("Chrome shim can not determine version, not shimming."),s;n("adapter.js shimming chrome."),s.browserShim=So,ui(e,r),hi(e),ld(e,r),ud(e),Yr(e,r),hd(e,r),gd(e,r),md(e),pd(e,r),vd(e,r),ci(e),Zr(e),es(e),di(e,r),li(e,r),ts(e,r);break;case"firefox":if(!Co||!Xr||!t.shimFirefox)return n("Firefox shim is not included in this adapter release."),s;n("adapter.js shimming firefox."),s.browserShim=Co,ui(e,r),hi(e),yd(e,r),Xr(e,r),kd(e,r),bd(e),Cd(e),Td(e),Sd(e),_d(e),wd(e),Ed(e),Rd(e),Pd(e),ci(e),es(e),di(e,r),li(e,r);break;case"safari":if(!_o||!t.shimSafari)return n("Safari shim is not included in this adapter release."),s;n("adapter.js shimming safari."),s.browserShim=_o,ui(e,r),hi(e),Od(e),Nd(e),Ad(e),Id(e),Md(e),Ld(e),xd(e),Ud(e),ci(e),Zr(e),di(e,r),li(e,r),ts(e,r);break;default:n("Unsupported browser!");break}return s}Bh({window:typeof window>"u"?void 0:window});var ns,Bd,pe=class extends(Bd=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)}};ns=pe;pe.resolve=i=>Reflect.get(Bd,"resolve",ns).call(ns,i);var qh=/version\/(\d+(\.?_?\d+)+)/i,Sr;function ke(i){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;if(typeof i>"u"&&typeof navigator>"u")return;let t=(i??navigator.userAgent).toLowerCase();if(Sr===void 0||e){let n=jh.find(r=>r.test.test(t));Sr=n?.describe(t)}return Sr}var jh=[{test:/firefox|iceweasel|fxios/i,describe(i){return{name:"Firefox",version:mi(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,i),os:i.toLowerCase().includes("fxios")?"iOS":void 0,osVersion:Cr(i)}}},{test:/chrom|crios|crmo/i,describe(i){return{name:"Chrome",version:mi(/(?:chrome|chromium|crios|crmo)\/(\d+(\.?_?\d+)+)/i,i),os:i.toLowerCase().includes("crios")?"iOS":void 0,osVersion:Cr(i)}}},{test:/safari|applewebkit/i,describe(i){return{name:"Safari",version:mi(qh,i),os:i.includes("mobile/")?"iOS":"macOS",osVersion:Cr(i)}}}];function mi(i,e){let t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:1,n=e.match(i);return n&&n.length>=t&&n[t]||""}function Cr(i){return i.includes("mac os")?mi(/\(.+?(\d+_\d+(:?_\d+)?)/,i,1).replace(/_/g,"."):void 0}var Vh="2.20.0",Hh=Vh,Gh=17,qd=0,Si=1,Kh=Si,Ve=class extends Error{constructor(e,t,n){super(t||"an error has occurred"),this.name="LiveKitError",this.code=e,typeof n?.cause<"u"&&(this.cause=n?.cause)}},we=class extends Ve{};var J;(function(i){i[i.NotAllowed=0]="NotAllowed",i[i.ServerUnreachable=1]="ServerUnreachable",i[i.InternalError=2]="InternalError",i[i.Cancelled=3]="Cancelled",i[i.LeaveRequest=4]="LeaveRequest",i[i.Timeout=5]="Timeout",i[i.WebSocket=6]="WebSocket",i[i.ServiceNotFound=7]="ServiceNotFound"})(J||(J={}));var N=class i extends we{constructor(e,t,n,r){super(1,e),this.name="ConnectionError",this.status=n,this.reason=t,this.context=r,this.reasonName=J[t]}static notAllowed(e,t,n){return new i(e,J.NotAllowed,t,n)}static timeout(e){return new i(e,J.Timeout)}static leaveRequest(e,t){return new i(e,J.LeaveRequest,void 0,t)}static internal(e,t){return new i(e,J.InternalError,void 0,t)}static cancelled(e){return new i(e,J.Cancelled)}static serverUnreachable(e,t){return new i(e,J.ServerUnreachable,t)}static websocket(e,t,n){return new i(e,J.WebSocket,t,n)}static serviceNotFound(e,t){return new i(e,J.ServiceNotFound,void 0,t)}},Dn=class extends Ve{constructor(e){super(21,e??"device is unsupported"),this.name="DeviceUnsupportedError"}},qe=class extends Ve{constructor(e){super(20,e??"track is invalid"),this.name="TrackInvalidError"}},is=class extends Ve{constructor(e){super(10,e??"unsupported server"),this.name="UnsupportedServer"}},W=class extends Ve{constructor(e){super(12,e??"unexpected connection state"),this.name="UnexpectedConnectionState"}},lt=class extends Ve{constructor(e){super(13,e??"unable to negotiate"),this.name="NegotiationError"}},rs=class extends Ve{constructor(e){super(14,e??"unable to publish data"),this.name="PublishDataError"}},Ci=class extends Ve{constructor(e,t){super(15,e),this.name="PublishTrackError",this.status=t}},_i=class extends we{constructor(e,t){super(15,e),this.name="SignalRequestError",this.reason=t,this.reasonName=typeof t=="string"?t:It[t]}},be;(function(i){i[i.AlreadyOpened=0]="AlreadyOpened",i[i.AbnormalEnd=1]="AbnormalEnd",i[i.DecodeFailed=2]="DecodeFailed",i[i.LengthExceeded=3]="LengthExceeded",i[i.Incomplete=4]="Incomplete",i[i.HandlerAlreadyRegistered=7]="HandlerAlreadyRegistered",i[i.EncryptionTypeMismatch=8]="EncryptionTypeMismatch"})(be||(be={}));var Se=class extends we{constructor(e,t){super(16,e),this.name="DataStreamError",this.reason=t,this.reasonName=be[t]}},vt=class extends Ve{constructor(e){super(18,e),this.name="SignalReconnectError"}},wi;(function(i){i.PermissionDenied="PermissionDenied",i.NotFound="NotFound",i.DeviceInUse="DeviceInUse",i.Other="Other"})(wi||(wi={}));(function(i){function e(t){if(t&&"name"in t)return t.name==="NotFoundError"||t.name==="DevicesNotFoundError"?i.NotFound:t.name==="NotAllowedError"||t.name==="PermissionDeniedError"?i.PermissionDenied:t.name==="NotReadableError"||t.name==="TrackStartError"?i.DeviceInUse:i.Other}i.getFailure=e})(wi||(wi={}));var se=class{};se.setTimeout=function(){return setTimeout(...arguments)};se.setInterval=function(){return setInterval(...arguments)};se.clearTimeout=function(){return clearTimeout(...arguments)};se.clearInterval=function(){return clearInterval(...arguments)};var C;(function(i){i.Connected="connected",i.Reconnecting="reconnecting",i.SignalReconnecting="signalReconnecting",i.Reconnected="reconnected",i.Disconnected="disconnected",i.ConnectionStateChanged="connectionStateChanged",i.Moved="moved",i.MediaDevicesChanged="mediaDevicesChanged",i.ParticipantConnected="participantConnected",i.ParticipantDisconnected="participantDisconnected",i.TrackPublished="trackPublished",i.TrackSubscribed="trackSubscribed",i.TrackSubscriptionFailed="trackSubscriptionFailed",i.TrackUnpublished="trackUnpublished",i.TrackUnsubscribed="trackUnsubscribed",i.TrackMuted="trackMuted",i.TrackUnmuted="trackUnmuted",i.LocalTrackPublished="localTrackPublished",i.LocalTrackUnpublished="localTrackUnpublished",i.LocalAudioSilenceDetected="localAudioSilenceDetected",i.ActiveSpeakersChanged="activeSpeakersChanged",i.ParticipantMetadataChanged="participantMetadataChanged",i.ParticipantNameChanged="participantNameChanged",i.ParticipantAttributesChanged="participantAttributesChanged",i.ParticipantActive="participantActive",i.RoomMetadataChanged="roomMetadataChanged",i.DataReceived="dataReceived",i.SipDTMFReceived="sipDTMFReceived",i.TranscriptionReceived="transcriptionReceived",i.ConnectionQualityChanged="connectionQualityChanged",i.TrackStreamStateChanged="trackStreamStateChanged",i.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",i.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",i.AudioPlaybackStatusChanged="audioPlaybackChanged",i.VideoPlaybackStatusChanged="videoPlaybackChanged",i.MediaDevicesError="mediaDevicesError",i.ParticipantPermissionsChanged="participantPermissionsChanged",i.SignalConnected="signalConnected",i.RecordingStatusChanged="recordingStatusChanged",i.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",i.EncryptionError="encryptionError",i.DCBufferStatusChanged="dcBufferStatusChanged",i.ActiveDeviceChanged="activeDeviceChanged",i.ChatMessage="chatMessage",i.LocalTrackSubscribed="localTrackSubscribed",i.MetricsReceived="metricsReceived",i.DataTrackPublished="dataTrackPublished",i.DataTrackUnpublished="dataTrackUnpublished",i.LocalDataTrackPublished="localDataTrackPublished",i.LocalDataTrackUnpublished="localDataTrackUnpublished"})(C||(C={}));var I;(function(i){i.TrackPublished="trackPublished",i.TrackSubscribed="trackSubscribed",i.TrackSubscriptionFailed="trackSubscriptionFailed",i.TrackUnpublished="trackUnpublished",i.TrackUnsubscribed="trackUnsubscribed",i.TrackMuted="trackMuted",i.TrackUnmuted="trackUnmuted",i.LocalTrackPublished="localTrackPublished",i.LocalTrackUnpublished="localTrackUnpublished",i.LocalTrackCpuConstrained="localTrackCpuConstrained",i.LocalSenderCreated="localSenderCreated",i.ParticipantMetadataChanged="participantMetadataChanged",i.ParticipantNameChanged="participantNameChanged",i.DataReceived="dataReceived",i.SipDTMFReceived="sipDTMFReceived",i.TranscriptionReceived="transcriptionReceived",i.IsSpeakingChanged="isSpeakingChanged",i.ConnectionQualityChanged="connectionQualityChanged",i.TrackStreamStateChanged="trackStreamStateChanged",i.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",i.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",i.TrackCpuConstrained="trackCpuConstrained",i.MediaDevicesError="mediaDevicesError",i.AudioStreamAcquired="audioStreamAcquired",i.ParticipantPermissionsChanged="participantPermissionsChanged",i.PCTrackAdded="pcTrackAdded",i.AttributesChanged="attributesChanged",i.LocalTrackSubscribed="localTrackSubscribed",i.ChatMessage="chatMessage",i.Active="active"})(I||(I={}));var R;(function(i){i.TransportsCreated="transportsCreated",i.Connected="connected",i.Disconnected="disconnected",i.Resuming="resuming",i.Resumed="resumed",i.Restarting="restarting",i.Restarted="restarted",i.SignalResumed="signalResumed",i.SignalRestarted="signalRestarted",i.Closing="closing",i.MediaTrackAdded="mediaTrackAdded",i.ActiveSpeakersUpdate="activeSpeakersUpdate",i.DataPacketReceived="dataPacketReceived",i.RTPVideoMapUpdate="rtpVideoMapUpdate",i.DCBufferStatusChanged="dcBufferStatusChanged",i.ParticipantUpdate="participantUpdate",i.RoomUpdate="roomUpdate",i.SpeakersChanged="speakersChanged",i.StreamStateChanged="streamStateChanged",i.ConnectionQualityUpdate="connectionQualityUpdate",i.SubscriptionError="subscriptionError",i.SubscriptionPermissionUpdate="subscriptionPermissionUpdate",i.RemoteMute="remoteMute",i.SubscribedQualityUpdate="subscribedQualityUpdate",i.LocalTrackUnpublished="localTrackUnpublished",i.LocalTrackSubscribed="localTrackSubscribed",i.Offline="offline",i.SignalRequestResponse="signalRequestResponse",i.SignalConnected="signalConnected",i.RoomMoved="roomMoved",i.PublishDataTrackResponse="publishDataTrackResponse",i.UnPublishDataTrackResponse="unPublishDataTrackResponse",i.DataTrackSubscriberHandles="dataTrackSubscriberHandles",i.DataTrackPacketReceived="dataTrackPacketReceived",i.Joined="joined",i.TokenRefreshed="tokenRefreshed",i.ServerRegionsReported="serverRegionsReported"})(R||(R={}));var P;(function(i){i.Message="message",i.Muted="muted",i.Unmuted="unmuted",i.Restarted="restarted",i.Ended="ended",i.Subscribed="subscribed",i.Unsubscribed="unsubscribed",i.CpuConstrained="cpuConstrained",i.UpdateSettings="updateSettings",i.UpdateSubscription="updateSubscription",i.AudioPlaybackStarted="audioPlaybackStarted",i.AudioPlaybackFailed="audioPlaybackFailed",i.AudioSilenceDetected="audioSilenceDetected",i.VisibilityChanged="visibilityChanged",i.VideoDimensionsChanged="videoDimensionsChanged",i.VideoPlaybackStarted="videoPlaybackStarted",i.VideoPlaybackFailed="videoPlaybackFailed",i.ElementAttached="elementAttached",i.ElementDetached="elementDetached",i.UpstreamPaused="upstreamPaused",i.UpstreamResumed="upstreamResumed",i.SubscriptionPermissionChanged="subscriptionPermissionChanged",i.SubscriptionStatusChanged="subscriptionStatusChanged",i.SubscriptionFailed="subscriptionFailed",i.TrackProcessorUpdate="trackProcessorUpdate",i.AudioTrackFeatureUpdate="audioTrackFeatureUpdate",i.TranscriptionReceived="transcriptionReceived",i.TimeSyncUpdate="timeSyncUpdate",i.PreConnectBufferFlushed="preConnectBufferFlushed"})(P||(P={}));function Wh(i){return typeof i>"u"?i:typeof structuredClone=="function"?typeof i=="object"&&i!==null?structuredClone(Object.assign({},i)):structuredClone(i):JSON.parse(JSON.stringify(i))}var K=class{constructor(e,t,n,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&&n!==void 0)this.width=e,this.height=t,this.aspectRatio=e/t,this.encoding={maxBitrate:n,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}}};var zh=["vp8","h264"],Jh=["vp8","h264","vp9","av1","h265"];function jd(i){return!!zh.find(e=>e===i)}var $h=jd,Eo;(function(i){i[i.PREFER_REGRESSION=0]="PREFER_REGRESSION",i[i.SIMULCAST=1]="SIMULCAST",i[i.REGRESSION=2]="REGRESSION"})(Eo||(Eo={}));var ss;(function(i){i.telephone={maxBitrate:12e3},i.speech={maxBitrate:24e3},i.music={maxBitrate:48e3},i.musicStereo={maxBitrate:64e3},i.musicHighQuality={maxBitrate:96e3},i.musicHighQualityStereo={maxBitrate:128e3}})(ss||(ss={}));var On={h90:new K(160,90,9e4,20),h180:new K(320,180,16e4,20),h216:new K(384,216,18e4,20),h360:new K(640,360,45e4,20),h540:new K(960,540,8e5,25),h720:new K(1280,720,17e5,30),h1080:new K(1920,1080,3e6,30),h1440:new K(2560,1440,5e6,30),h2160:new K(3840,2160,8e6,30)},as={h120:new K(160,120,7e4,20),h180:new K(240,180,125e3,20),h240:new K(320,240,14e4,20),h360:new K(480,360,33e4,20),h480:new K(640,480,5e5,20),h540:new K(720,540,6e5,25),h720:new K(960,720,13e5,30),h1080:new K(1440,1080,23e5,30),h1440:new K(1920,1440,38e5,30)},Ia={h360fps3:new K(640,360,2e5,3,"medium"),h360fps15:new K(640,360,4e5,15,"medium"),h720fps5:new K(1280,720,8e5,5,"medium"),h720fps15:new K(1280,720,15e5,15,"medium"),h720fps30:new K(1280,720,2e6,30,"medium"),h1080fps15:new K(1920,1080,25e5,15,"medium"),h1080fps30:new K(1920,1080,5e6,30,"medium"),original:new K(0,0,7e6,30,"medium")};function Vd(i,e,t){var n,r,s,a;let o=Kd(i??{}),d=o.optionsWithoutProcessor,c=o.audioProcessor,l=o.videoProcessor,u=e?.processor,h=t?.processor,m=d??{};return m.audio===!0&&(m.audio={}),m.video===!0&&(m.video={}),m.audio&&(os(m.audio,e),(n=(s=m.audio).deviceId)!==null&&n!==void 0||(s.deviceId={ideal:"default"}),(c||u)&&(m.audio.processor=c??u)),m.video&&(os(m.video,t),(r=(a=m.video).deviceId)!==null&&r!==void 0||(a.deviceId={ideal:"default"}),(l||h)&&(m.video.processor=l??h)),m}function os(i,e){return Object.keys(e).forEach(t=>{i[t]===void 0&&(i[t]=e[t])}),i}function Ma(i){var e,t,n,r;let s={};if(i.video)if(typeof i.video=="object"){let a={},o=a,d=i.video;Object.keys(d).forEach(c=>{switch(c){case"resolution":os(o,d.resolution);break;default:o[c]=d[c]}}),s.video=a,(e=(n=s.video).deviceId)!==null&&e!==void 0||(n.deviceId={ideal:"default"})}else s.video=i.video?{deviceId:{ideal:"default"}}:!1;else s.video=!1;return i.audio?typeof i.audio=="object"?(s.audio=i.audio,(t=(r=s.audio).deviceId)!==null&&t!==void 0||(r.deviceId={ideal:"default"})):s.audio={deviceId:{ideal:"default"}}:s.audio=!1,s}function Hd(i){return p(this,arguments,void 0,function(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:200;return(function*(){let n=Gd();if(n){let r=n.createAnalyser();r.fftSize=2048;let s=r.frequencyBinCount,a=new Uint8Array(s);n.createMediaStreamSource(new MediaStream([e.mediaStreamTrack])).connect(r),yield ve(t),r.getByteTimeDomainData(a);let d=a.some(c=>c!==128&&c!==0);return n.close(),!d}return!1})()})}function Gd(){var i;let e=typeof window<"u"&&(window.AudioContext||window.webkitAudioContext);if(e){let t=new e({latencyHint:"interactive"});if(t.state==="suspended"&&typeof window<"u"&&(!((i=window.document)===null||i===void 0)&&i.body)){let n=()=>p(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",n)}});t.addEventListener("statechange",()=>{var r;t.state==="closed"&&((r=window.document.body)===null||r===void 0||r.removeEventListener("click",n))}),window.document.body.addEventListener("click",n)}return t}}function Qh(i){return i==="audioinput"?_.Source.Microphone:i==="videoinput"?_.Source.Camera:_.Source.Unknown}function cs(i){return i===_.Source.Microphone?"audioinput":i===_.Source.Camera?"videoinput":void 0}function Yh(i){var e,t;let n=(e=i.video)!==null&&e!==void 0?e:!0;return i.resolution&&i.resolution.width>0&&i.resolution.height>0&&(n=typeof n=="boolean"?{}:n,Bt()?n=Object.assign(Object.assign({},n),{width:{max:i.resolution.width},height:{max:i.resolution.height},frameRate:i.resolution.frameRate}):n=Object.assign(Object.assign({},n),{width:{ideal:i.resolution.width},height:{ideal:i.resolution.height},frameRate:i.resolution.frameRate})),{audio:(t=i.audio)!==null&&t!==void 0?t:!1,video:n,controller:i.controller,selfBrowserSurface:i.selfBrowserSurface,surfaceSwitching:i.surfaceSwitching,systemAudio:i.systemAudio,preferCurrentTab:i.preferCurrentTab}}function _n(i){return i.split("/")[1].toLowerCase()}function Xh(i){let e=[];return i.forEach(t=>{t.track!==void 0&&e.push(new Sa({cid:t.track.mediaStreamID,track:t.trackInfo}))}),e}function j(i){return"mediaStreamTrack"in i?{trackID:i.sid,source:i.source,muted:i.isMuted,enabled:i.mediaStreamTrack.enabled,kind:i.kind,streamID:i.mediaStreamID,streamTrackID:i.mediaStreamTrack.id}:{trackID:i.trackSid,enabled:i.isEnabled,muted:i.isMuted,trackInfo:Object.assign({mimeType:i.mimeType,name:i.trackName,encrypted:i.isEncrypted,kind:i.kind,source:i.source},i.track?j(i.track):{})}}function Zh(){return typeof RTCRtpReceiver<"u"&&typeof RTCRtpReceiver.prototype.getSynchronizationSources=="function"}function em(i,e){var t;i===void 0&&(i={}),e===void 0&&(e={});let n=[...Object.keys(e),...Object.keys(i)],r={};for(let s of n)i[s]!==e[s]&&(r[s]=(t=e[s])!==null&&t!==void 0?t:"");return r}function Kd(i){let e=Object.assign({},i),t,n;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&&(n=e.video.processor,e.video=Object.assign(Object.assign({},e.video),{processor:void 0})),{audioProcessor:t,videoProcessor:n,optionsWithoutProcessor:Wh(e)}}function tm(i){switch(i){case oe.CAMERA:return _.Source.Camera;case oe.MICROPHONE:return _.Source.Microphone;case oe.SCREEN_SHARE:return _.Source.ScreenShare;case oe.SCREEN_SHARE_AUDIO:return _.Source.ScreenShareAudio;default:return _.Source.Unknown}}function Ro(i,e){return i.width*i.height<e.width*e.height}function nm(i,e){var t;return(t=i.layers)===null||t===void 0?void 0:t.find(n=>n.quality===e)}var im=5e3,gn=[],Re;(function(i){i[i.LOW=0]="LOW",i[i.MEDIUM=1]="MEDIUM",i[i.HIGH=2]="HIGH"})(Re||(Re={}));var _=class i extends Ee.EventEmitter{get streamState(){return this._streamState}setStreamState(e){this._streamState=e}constructor(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};var r;super(),this.attachedElements=[],this.isMuted=!1,this._streamState=i.StreamState.Active,this.isInBackground=!1,this._currentBitrate=0,this.log=F,this.appVisibilityChangedListener=()=>{this.backgroundTimeout&&clearTimeout(this.backgroundTimeout),document.visibilityState==="hidden"?this.backgroundTimeout=setTimeout(()=>this.handleAppVisibilityChanged(),im):this.handleAppVisibilityChanged()},this.log=_e((r=n.loggerName)!==null&&r!==void 0?r:ue.Track),this.loggerContextCb=n.loggerContextCb,this.setMaxListeners(100),this.kind=t,this._mediaStreamTrack=e,this._mediaStreamID=e.id,this.source=i.Source.Unknown}get logContext(){var e;return Object.assign(Object.assign({},(e=this.loggerContextCb)===null||e===void 0?void 0:e.call(this)),j(this))}get currentBitrate(){return this._currentBitrate}get mediaStreamTrack(){return this._mediaStreamTrack}get mediaStreamID(){return this._mediaStreamID}attach(e){let t="audio";this.kind===i.Kind.Video&&(t="video"),this.attachedElements.length===0&&this.kind===i.Kind.Video&&this.addAppVisibilityListener(),e||(t==="audio"&&(gn.forEach(s=>{s.parentElement===null&&!e&&(e=s)}),e&&gn.splice(gn.indexOf(e),1)),e||(e=document.createElement(t))),this.attachedElements.includes(e)||this.attachedElements.push(e),zt(this.mediaStreamTrack,e);let n=e.srcObject.getTracks(),r=n.some(s=>s.kind==="audio");return e.play().then(()=>{this.emit(r?P.AudioPlaybackStarted:P.VideoPlaybackStarted)}).catch(s=>{s.name==="NotAllowedError"?this.emit(r?P.AudioPlaybackFailed:P.VideoPlaybackFailed,s):s.name==="AbortError"?F.debug("".concat(r?"audio":"video"," playback aborted, likely due to new play request")):F.warn("could not playback ".concat(r?"audio":"video"),s),r&&e&&n.some(a=>a.kind==="video")&&s.name==="NotAllowedError"&&(e.muted=!0,e.play().catch(()=>{}))}),this.emit(P.ElementAttached,e),e}detach(e){try{if(e){Yt(this.mediaStreamTrack,e);let n=this.attachedElements.indexOf(e);return n>=0&&(this.attachedElements.splice(n,1),this.recycleElement(e),this.emit(P.ElementDetached,e)),e}let t=[];return this.attachedElements.forEach(n=>{Yt(this.mediaStreamTrack,n),t.push(n),this.recycleElement(n),this.emit(P.ElementDetached,n)}),this.attachedElements=[],t}finally{this.attachedElements.length===0&&this.removeAppVisibilityListener()}}stop(){this.stopMonitor(),this._mediaStreamTrack.stop()}enable(){this._mediaStreamTrack.enabled=!0}disable(){this._mediaStreamTrack.enabled=!1}stopMonitor(){this.monitorInterval&&clearInterval(this.monitorInterval),this.timeSyncHandle&&cancelAnimationFrame(this.timeSyncHandle)}updateLoggerOptions(e){e.loggerName&&(this.log=_e(e.loggerName)),e.loggerContextCb&&(this.loggerContextCb=e.loggerContextCb)}recycleElement(e){if(e instanceof HTMLAudioElement){let t=!0;e.pause(),gn.forEach(n=>{n.parentElement||(t=!1)}),t&&gn.push(e)}}handleAppVisibilityChanged(){return p(this,void 0,void 0,function*(){this.isInBackground=document.visibilityState==="hidden",!this.isInBackground&&this.kind===i.Kind.Video&&setTimeout(()=>this.attachedElements.forEach(e=>e.play().catch(()=>{})),0)})}addAppVisibilityListener(){Ce()?(this.isInBackground=document.visibilityState==="hidden",document.addEventListener("visibilitychange",this.appVisibilityChangedListener)):this.isInBackground=!1}removeAppVisibilityListener(){Ce()&&document.removeEventListener("visibilitychange",this.appVisibilityChangedListener)}};function zt(i,e){let t;e.srcObject instanceof MediaStream?t=e.srcObject:t=new MediaStream;let n;i.kind==="audio"?n=t.getAudioTracks():n=t.getVideoTracks(),n.includes(i)||(n.forEach(r=>{t.removeTrack(r)}),t.addTrack(i)),(!Bt()||!(e instanceof HTMLVideoElement))&&(e.autoplay=!0),e.muted=t.getAudioTracks().length===0,e instanceof HTMLVideoElement&&(e.playsInline=!0),e.srcObject!==t&&(e.srcObject=t,(Bt()||Ft())&&e instanceof HTMLVideoElement&&setTimeout(()=>{e.srcObject=t,e.play().catch(()=>{})},0))}function Yt(i,e){if(e.srcObject instanceof MediaStream){let t=e.srcObject;t.removeTrack(i),t.getTracks().length>0?e.srcObject=t:e.srcObject=null}}(function(i){let e;(function(c){c.Audio="audio",c.Video="video",c.Unknown="unknown"})(e=i.Kind||(i.Kind={}));let t;(function(c){c.Camera="camera",c.Microphone="microphone",c.ScreenShare="screen_share",c.ScreenShareAudio="screen_share_audio",c.Unknown="unknown"})(t=i.Source||(i.Source={}));let n;(function(c){c.Active="active",c.Paused="paused",c.Unknown="unknown"})(n=i.StreamState||(i.StreamState={}));function r(c){switch(c){case e.Audio:return Ue.AUDIO;case e.Video:return Ue.VIDEO;default:return Ue.DATA}}i.kindToProto=r;function s(c){switch(c){case Ue.AUDIO:return e.Audio;case Ue.VIDEO:return e.Video;default:return e.Unknown}}i.kindFromProto=s;function a(c){switch(c){case t.Camera:return oe.CAMERA;case t.Microphone:return oe.MICROPHONE;case t.ScreenShare:return oe.SCREEN_SHARE;case t.ScreenShareAudio:return oe.SCREEN_SHARE_AUDIO;default:return oe.UNKNOWN}}i.sourceToProto=a;function o(c){switch(c){case oe.CAMERA:return t.Camera;case oe.MICROPHONE:return t.Microphone;case oe.SCREEN_SHARE:return t.ScreenShare;case oe.SCREEN_SHARE_AUDIO:return t.ScreenShareAudio;default:return t.Unknown}}i.sourceFromProto=o;function d(c){switch(c){case Kr.ACTIVE:return n.Active;case Kr.PAUSED:return n.Paused;default:return n.Unknown}}i.streamStateFromProto=d})(_||(_={}));var rm="|",Po="https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension";function sm(i){let e=i.split(rm);return e.length>1?[e[0],i.substr(e[0].length+1)]:[i,""]}function ve(i){return new pe(e=>se.setTimeout(e,i))}function ds(){return"addTransceiver"in RTCPeerConnection.prototype}function ls(){return"addTrack"in RTCPeerConnection.prototype}function am(){if(!("getCapabilities"in RTCRtpSender)||Bt()||Ft())return!1;let i=RTCRtpSender.getCapabilities("video"),e=!1;if(i){for(let t of i.codecs)if(t.mimeType.toLowerCase()==="video/av1"){e=!0;break}}return e}function om(){if(!("getCapabilities"in RTCRtpSender)||Ft())return!1;if(Bt()){let t=ke();if(t?.version&&tt(t.version,"16")<0||t?.os==="iOS"&&t?.osVersion&&tt(t.osVersion,"16")<0)return!1}let i=RTCRtpSender.getCapabilities("video"),e=!1;if(i){for(let t of i.codecs)if(t.mimeType.toLowerCase()==="video/vp9"){e=!0;break}}return e}function je(i){return i==="av1"||i==="vp9"}function us(i){return!document||Ln()?!1:(i||(i=document.createElement("audio")),"setSinkId"in i)}function cm(){return typeof RTCPeerConnection>"u"?!1:ds()||ls()}function Ft(){var i;return((i=ke())===null||i===void 0?void 0:i.name)==="Firefox"}function dm(){let i=ke();return!!i&&i.name==="Chrome"&&i.os!=="iOS"}function hs(){return typeof window<"u"&&typeof window.RTCRtpScriptTransform<"u"&&!dm()}function Bt(){var i;return((i=ke())===null||i===void 0?void 0:i.name)==="Safari"}function Ln(){let i=ke();return i?.name==="Safari"||i?.os==="iOS"}function lm(){let i=ke();return i?.name==="Safari"&&i.version.startsWith("17.")||i?.os==="iOS"&&!!i?.osVersion&&tt(i.osVersion,"17")>=0}function um(i){return i||(i=ke()),i?.name==="Safari"&&tt(i.version,"18.3")>0||i?.os==="iOS"&&!!i?.osVersion&&tt(i.osVersion,"18.3")>0}function Wd(){var i,e;return Ce()?(e=(i=navigator.userAgentData)===null||i===void 0?void 0:i.mobile)!==null&&e!==void 0?e:/Tablet|iPad|Mobile|Android|BlackBerry/.test(navigator.userAgent):!1}function hm(){let i=ke(),e="17.2";if(i)return i.name!=="Safari"&&i.os!=="iOS"||i.os==="iOS"&&i.osVersion&&tt(i.osVersion,e)>=0?!0:i.name==="Safari"&&tt(i.version,e)>=0}function Ce(){return typeof document<"u"}function He(){return navigator.product=="ReactNative"}function sn(i){return i.hostname.endsWith(".livekit.cloud")||i.hostname.endsWith(".livekit.run")}function _r(i){return sn(i)?i.hostname.split(".")[0]:null}function zd(){if(global&&global.LiveKitReactNativeGlobal)return global.LiveKitReactNativeGlobal}function Jd(){if(!He())return;let i=zd();if(i)return i.platform}function Io(){if(Ce())return window.devicePixelRatio;if(He()){let i=zd();if(i)return i.devicePixelRatio}return 1}function tt(i,e){let t=i.split("."),n=e.split("."),r=Math.min(t.length,n.length);for(let s=0;s<r;++s){let a=parseInt(t[s],10),o=parseInt(n[s],10);if(a>o)return 1;if(a<o)return-1;if(s===r-1&&a===o)return 0}return i===""&&e!==""?-1:e===""?1:t.length==n.length?0:t.length<n.length?-1:1}function mm(i){for(let e of i)e.target.handleResize(e)}function pm(i){for(let e of i)e.target.handleVisibilityChanged(e)}var wr=null,Mo=()=>(wr||(wr=new ResizeObserver(mm)),wr),Er=null,Ao=()=>(Er||(Er=new IntersectionObserver(pm,{root:null,rootMargin:"0px"})),Er);function fm(i){var e;let t=new Vc({capabilities:i,sdk:Hc.JS,protocol:Gh,clientProtocol:Kh,version:Hh});return He()&&(t.os=(e=Jd())!==null&&e!==void 0?e:""),t}function xo(){let i=arguments.length>0&&arguments[0]!==void 0?arguments[0]:16,e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:16,t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1,n=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1,r=document.createElement("canvas");r.width=i,r.height=e;let s=r.getContext("2d");s?.fillRect(0,0,r.width,r.height),n&&s&&(s.beginPath(),s.arc(i/2,e/2,50,0,Math.PI*2,!0),s.closePath(),s.fillStyle="grey",s.fill());let o=r.captureStream().getTracks(),d=O(o,1),c=d[0];if(!c)throw Error("Could not get empty media stream video track");return c.enabled=t,c}var vn;function Rr(){if(!vn){let t=new AudioContext,n=t.createOscillator(),r=t.createGain();r.gain.setValueAtTime(0,0);let s=t.createMediaStreamDestination();n.connect(r),r.connect(s),n.start();var i=s.stream.getAudioTracks(),e=O(i,1);if(vn=e[0],!vn)throw Error("Could not get empty media stream audio track");vn.enabled=!1}return vn.clone()}var ce=class{get isResolved(){return this._isResolved}constructor(e,t){this._isResolved=!1,this.onFinally=t,this.promise=new Promise((n,r)=>p(this,void 0,void 0,function*(){this.resolve=n,this.reject=r,e&&(yield e(n,r))})).finally(()=>{var n;this._isResolved=!0,(n=this.onFinally)===null||n===void 0||n.call(this)})}};function gm(i){return Jh.includes(i)}function Lt(i){if(typeof i=="string"||typeof i=="number")return i;if(Array.isArray(i))return i[0];if(i.exact!==void 0)return Array.isArray(i.exact)?i.exact[0]:i.exact;if(i.ideal!==void 0)return Array.isArray(i.ideal)?i.ideal[0]:i.ideal;throw Error("could not unwrap constraint")}function vm(i){return i.startsWith("http")?i.replace(/^(http)/,"ws"):i}function Nn(i){return i.startsWith("ws")?i.replace(/^(ws)/,"http"):i}function ym(i,e){return i.segments.map(t=>{let n=t.id,r=t.text,s=t.language,a=t.startTime,o=t.endTime,d=t.final;var c;let l=(c=e.get(n))!==null&&c!==void 0?c:Date.now(),u=Date.now();return d?e.delete(n):e.set(n,l),{id:n,text:r,startTime:Number.parseInt(a.toString()),endTime:Number.parseInt(o.toString()),final:d,language:s,firstReceivedTime:l,lastReceivedTime:u}})}function bm(i){let e=i.id,t=i.timestamp,n=i.message,r=i.editTimestamp;return{id:e,timestamp:Number.parseInt(t.toString()),editTimestamp:r?Number.parseInt(r.toString()):void 0,message:n}}function Do(i){switch(i.reason){case J.LeaveRequest:return i.context;case J.Cancelled:return re.CLIENT_INITIATED;case J.NotAllowed:return re.USER_REJECTED;case J.ServerUnreachable:return re.JOIN_FAILURE;default:return re.UNKNOWN_REASON}}function pi(i){return i!==void 0?Number(i):void 0}function Pt(i){return i!==void 0?BigInt(i):void 0}function Xt(i){return!!i&&!(i instanceof MediaStreamTrack)&&i.isLocal}function et(i){return!!i&&i.kind==_.Kind.Audio}function ht(i){return!!i&&i.kind==_.Kind.Video}function Je(i){return Xt(i)&&ht(i)}function at(i){return Xt(i)&&et(i)}function ms(i){return!!i&&!i.isLocal}function km(i){return!!i&&!i.isLocal}function Pr(i){return ms(i)&&ht(i)}function Tm(i){return i.isLocal}function Sm(i,e){let t=[],n=new TextEncoder().encode(i);for(;n.length>e;){let r=e;for(;r>0;){let s=n[r];if(s!==void 0&&(s&192)!==128)break;r--}t.push(n.slice(0,r)),n=n.slice(r)}return n.length>0&&t.push(n),t}function Cm(i){var e;let t=i.get("Cache-Control");if(t){let n=(e=t.match(/(?:^|[,\s])max-age=(\d+)/))===null||e===void 0?void 0:e[1];if(n)return parseInt(n,10)}}function $d(){return typeof CompressionStream<"u"}function _m(){return $d()&&!Ft()}function wm(i,e){let t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1,n=Em(i,e);return t?n:Aa(n,"v1")}function Em(i,e){let t=new URL(vm(i));return e.forEach((n,r)=>{t.searchParams.set(r,n)}),Aa(t,"rtc")}function Rm(i){let e=new URL(Nn(i));return Aa(e,"validate")}function Qd(i){return i.endsWith("/")?i:"".concat(i,"/")}function Aa(i,e){return i.pathname="".concat(Qd(i.pathname)).concat(e),i}function Oo(i){if(typeof i=="string")return fo.fromJson(JSON.parse(i),{ignoreUnknownFields:!0});if(i instanceof ArrayBuffer)return fo.fromBinary(new Uint8Array(i));throw new Error("could not decode websocket message: ".concat(typeof i))}function Pm(i){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"Unknown reason";if(!(i instanceof AbortSignal))return e;let t=i.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}}var Im=10,yn="lk_e2ee",Mm="LKFrameEncryptionKey",Am={sharedKey:!1,ratchetSalt:Mm,ratchetWindowSize:8,failureTolerance:Im,keyringSize:16,keySize:128},St;(function(i){i.SetKey="setKey",i.RatchetRequest="ratchetRequest",i.KeyRatcheted="keyRatcheted"})(St||(St={}));var Lo;(function(i){i.KeyRatcheted="keyRatcheted"})(Lo||(Lo={}));var bt;(function(i){i.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",i.EncryptionError="encryptionError"})(bt||(bt={}));var No;(function(i){i.Error="cryptorError"})(No||(No={}));function xm(){return xa()||Dm()}function Dm(){return typeof window<"u"&&typeof window.RTCRtpScriptTransform<"u"}function xa(){return typeof window<"u"&&typeof window.RTCRtpSender<"u"&&typeof window.RTCRtpSender.prototype.createEncodedStreams<"u"}function Om(i){var e,t,n,r,s;if(((e=i.value)===null||e===void 0?void 0:e.case)!=="sipDtmf"&&((t=i.value)===null||t===void 0?void 0:t.case)!=="metrics"&&((n=i.value)===null||n===void 0?void 0:n.case)!=="speaker"&&((r=i.value)===null||r===void 0?void 0:r.case)!=="transcription"&&((s=i.value)===null||s===void 0?void 0:s.case)!=="encryptedPacket")return new Lc({value:i.value})}var Uo=class extends Ee.EventEmitter{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};super(),this.latestManuallySetKeyIndex=0,this.onKeyRatcheted=(t,n,r)=>{F.debug("key ratcheted event received",{ratchetResult:t,participantId:n,keyIndex:r})},this.keyInfoMap=new Map,this.options=Object.assign(Object.assign({},Am),e),this.on(St.KeyRatcheted,this.onKeyRatcheted)}onSetEncryptionKey(e,t,n){let r={key:e,participantIdentity:t,keyIndex:n};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(n??0),r),n!==void 0&&(this.latestManuallySetKeyIndex=n),this.emit(St.SetKey,r,n!==void 0)}getKeys(){return Array.from(this.keyInfoMap.values())}getLatestManuallySetKeyIndex(){return this.latestManuallySetKeyIndex}getOptions(){return this.options}ratchetKey(e,t){this.emit(St.RatchetRequest,e,t)}};var Fo;(function(i){i[i.InvalidKey=0]="InvalidKey",i[i.MissingKey=1]="MissingKey",i[i.InternalError=2]="InternalError"})(Fo||(Fo={}));function Un(){return hs()}function Fn(i){return!!i?.worker&&(xa()||Un())}function Ei(i){return!!(i?.timestamp||i?.frameId)}function Lm(i){let e=[];return i?.timestamp&&e.push(nn.PTF_USER_TIMESTAMP),i?.frameId&&e.push(nn.PTF_FRAME_ID),e}function Nm(i){if(!i||i.length===0)return;let e={};return i.includes(nn.PTF_USER_TIMESTAMP)&&(e.timestamp=!0),i.includes(nn.PTF_FRAME_ID)&&(e.frameId=!0),e.timestamp||e.frameId?e:void 0}function Da(i){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:50,t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};var n,r;let s,a=(n=t.isImmediate)!==null&&n!==void 0?n:!1,o=(r=t.callback)!==null&&r!==void 0?r:!1,d=t.maxWait,c=Date.now(),l=[];function u(){if(d!==void 0){let m=Date.now()-c;if(m+e>=d)return d-m}return e}let h=function(){for(var m=arguments.length,f=new Array(m),g=0;g<m;g++)f[g]=arguments[g];let k=this;return new Promise((T,S)=>{let L=function(){if(s=void 0,c=Date.now(),!a){let b=i.apply(k,f);o&&o(b),l.forEach(E=>{let M=E.resolve;return M(b)}),l=[]}},y=a&&s===void 0;if(s!==void 0&&se.clearTimeout(s),s=se.setTimeout(L,u()),y){let b=i.apply(k,f);return o&&o(b),T(b)}l.push({resolve:T,reject:S})})};return h.cancel=function(m){s!==void 0&&se.clearTimeout(s),l.forEach(f=>{let g=f.reject;return g(m)}),l=[]},h}var Oa=2e3;function ar(i,e){if(!e)return 0;let t,n;return"bytesReceived"in i?(t=i.bytesReceived,n=e.bytesReceived):"bytesSent"in i&&(t=i.bytesSent,n=e.bytesSent),t===void 0||n===void 0||i.timestamp===void 0||e.timestamp===void 0?0:(t-n)*8*1e3/(i.timestamp-e.timestamp)}var Ri=class extends _{constructor(e,t,n,r,s){super(e,n,s),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?P.Muted:P.Unmuted,this))}setMediaStream(e){this.mediaStream=e;let t=n=>{n.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(P.Ended,this))};e.addEventListener("removetrack",t)}start(){this.startMonitor(),super.enable()}stop(){this.stopMonitor(),super.disable()}getRTCStatsReport(){return p(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(),Oa)),Zh()&&this.registerTimeSyncUpdate()}registerTimeSyncUpdate(){let e=()=>{var t;this.timeSyncHandle=requestAnimationFrame(()=>e());let n=(t=this.receiver)===null||t===void 0?void 0:t.getSynchronizationSources()[0];if(n){let r=n.timestamp,s=n.rtpTimestamp;s&&this.rtpTimestamp!==s&&(this.emit(P.TimeSyncUpdate,{timestamp:r,rtpTimestamp:s}),this.rtpTimestamp=s)}};e()}},Ir=100,Bn=class extends Ri{constructor(e,t,n,r,s){super(e,t,_.Kind.Video,n,s),this.elementInfos=[],this.monitorReceiver=()=>p(this,void 0,void 0,function*(){if(!this.receiver){this._currentBitrate=0;return}let a=yield this.getReceiverStats();a&&this.prevStats&&this.receiver&&(this._currentBitrate=ar(a,this.prevStats)),this.prevStats=a}),this.debouncedHandleResize=Da(()=>{this.updateDimensions()},Ir),this.adaptiveStreamSettings=r}get isAdaptiveStream(){return this.adaptiveStreamSettings!==void 0}lookupFrameMetadata(e){let t=e.rtpTimestamp;var n;return(n=this.frameMetadataExtractor)===null||n===void 0?void 0:n.lookupMetadata(t)}setStreamState(e){super.setStreamState(e),this.log.debug("setStreamState",e),this.isAdaptiveStream&&e===_.StreamState.Active&&this.updateVisibility()}get mediaStreamTrack(){return this._mediaStreamTrack}setMuted(e){super.setMuted(e),this.attachedElements.forEach(t=>{e?Yt(this._mediaStreamTrack,t):zt(this._mediaStreamTrack,t)})}attach(e){if(e?super.attach(e):e=super.attach(),this.adaptiveStreamSettings&&this.elementInfos.find(t=>t.element===e)===void 0){let t=new ps(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}let t=this.elementInfos.filter(n=>n===e);for(let n of t)n.stopObserving();this.elementInfos=this.elementInfos.filter(n=>n!==e),this.updateVisibility(),this.debouncedHandleResize()}detach(e){if(e)return this.stopObservingElement(e),super.detach(e);let t=super.detach();for(let n of t)this.stopObservingElement(n);return t}getDecoderImplementation(){var e;return(e=this.prevStats)===null||e===void 0?void 0:e.decoderImplementation}getReceiverStats(){return p(this,void 0,void 0,function*(){if(!this.receiver||!this.receiver.getStats)return;let e=yield this.receiver.getStats(),t,n="",r=new Map;return e.forEach(s=>{s.type==="inbound-rtp"?(n=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&&n!==""&&r.get(n)&&(t.mimeType=r.get(n).mimeType),t})}stopObservingElement(e){let t=this.elementInfos.filter(n=>n.element===e);for(let n of t)this.stopObservingElementInfo(n)}handleAppVisibilityChanged(){let e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return p(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),this.isAdaptiveStream&&this.updateVisibility()})}updateVisibility(e){var t,n;let r=this.elementInfos.reduce((d,c)=>Math.max(d,c.visibilityChangedAt||0),0),s=!((n=(t=this.adaptiveStreamSettings)===null||t===void 0?void 0:t.pauseVideoInBackground)!==null&&n!==void 0)||n?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<Ir){se.setTimeout(()=>{this.updateVisibility()},Ir);return}this.lastVisible=o,this.emit(P.VisibilityChanged,o,this)}}updateDimensions(){var e,t;let n=0,r=0,s=this.getPixelDensity();for(let a of this.elementInfos){let o=a.width()*s,d=a.height()*s;o+d>n+r&&(n=o,r=d)}((e=this.lastDimensions)===null||e===void 0?void 0:e.width)===n&&((t=this.lastDimensions)===null||t===void 0?void 0:t.height)===r||(this.lastDimensions={width:n,height:r},this.emit(P.VideoDimensionsChanged,this.lastDimensions,this))}getPixelDensity(){var e;let t=(e=this.adaptiveStreamSettings)===null||e===void 0?void 0:e.pixelDensity;return t==="screen"?Io():t||(Io()>2?2:1)}},ps=class{get visible(){return this.isPiP||this.isIntersecting}get pictureInPicture(){return this.isPiP}constructor(e,t){this.onVisibilityChanged=n=>{var r;let s=n.target,a=n.isIntersecting;s===this.element&&(this.isIntersecting=a,this.isPiP=bn(this.element),this.visibilityChangedAt=Date.now(),(r=this.handleVisibilityChanged)===null||r===void 0||r.call(this))},this.onEnterPiP=()=>{var n,r;(r=(n=window.documentPictureInPicture)===null||n===void 0?void 0:n.window)===null||r===void 0||r.addEventListener("pagehide",this.onLeavePiP),queueMicrotask(()=>{requestAnimationFrame(()=>{var s;this.isPiP=bn(this.element),(s=this.handleVisibilityChanged)===null||s===void 0||s.call(this)})})},this.onLeavePiP=()=>{var n;this.isPiP=bn(this.element),(n=this.handleVisibilityChanged)===null||n===void 0||n.call(this)},this.element=e,this.isIntersecting=t??fs(e),this.isPiP=Ce()&&bn(e),this.visibilityChangedAt=0}width(){return this.element.clientWidth}height(){return this.element.clientHeight}observe(){var e,t,n;this.isIntersecting=fs(this.element),this.isPiP=bn(this.element),this.element.handleResize=()=>{var r;(r=this.handleResize)===null||r===void 0||r.call(this)},this.element.handleVisibilityChanged=this.onVisibilityChanged,Ao().observe(this.element),Mo().observe(this.element),this.element.addEventListener("enterpictureinpicture",this.onEnterPiP),this.element.addEventListener("leavepictureinpicture",this.onLeavePiP),(e=window.documentPictureInPicture)===null||e===void 0||e.addEventListener("enter",this.onEnterPiP),(n=(t=window.documentPictureInPicture)===null||t===void 0?void 0:t.window)===null||n===void 0||n.addEventListener("pagehide",this.onLeavePiP)}stopObserving(){var e,t,n,r,s;(e=Ao())===null||e===void 0||e.unobserve(this.element),(t=Mo())===null||t===void 0||t.unobserve(this.element),this.element.removeEventListener("enterpictureinpicture",this.onEnterPiP),this.element.removeEventListener("leavepictureinpicture",this.onLeavePiP),(n=window.documentPictureInPicture)===null||n===void 0||n.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 bn(i){var e,t;return document.pictureInPictureElement===i?!0:!((e=window.documentPictureInPicture)===null||e===void 0)&&e.window?fs(i,(t=window.documentPictureInPicture)===null||t===void 0?void 0:t.window):!1}function fs(i,e){let t=e||window,n=i.offsetTop,r=i.offsetLeft,s=i.offsetWidth,a=i.offsetHeight,o=i,d=o.hidden,c=getComputedStyle(i),l=c.display;for(;i.offsetParent;)i=i.offsetParent,n+=i.offsetTop,r+=i.offsetLeft;return n<t.pageYOffset+t.innerHeight&&r<t.pageXOffset+t.innerWidth&&n+a>t.pageYOffset&&r+s>t.pageXOffset&&!d&&l!=="none"}var gs=class extends Ee.EventEmitter{constructor(e,t){super(),this.decryptDataRequests=new Map,this.encryptDataRequests=new Map,this.onWorkerMessage=n=>{var r,s;let a=n.data,o=a.kind,d=a.data;switch(o){case"error":if(F.error(d.error.message),d.uuid){let u=this.decryptDataRequests.get(d.uuid);if(u?.reject){u.reject(d.error);break}let h=this.encryptDataRequests.get(d.uuid);if(h?.reject){h.reject(d.error);break}}this.emit(bt.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(bt.ParticipantEncryptionStatusChanged,d.enabled,this.room.localParticipant),this.encryptionEnabled=d.enabled;else if(d.participantIdentity){let 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(bt.ParticipantEncryptionStatusChanged,d.enabled,u)}break;case"ratchetKey":this.keyProvider.emit(St.KeyRatcheted,d.ratchetResult,d.participantIdentity,d.keyIndex);break;case"decryptDataResponse":let c=this.decryptDataRequests.get(d.uuid);c?.resolve&&c.resolve(d);break;case"encryptDataResponse":let l=this.encryptDataRequests.get(d.uuid);l?.resolve&&l.resolve(d);break;case"packetTrailerMetadata":this.handleFrameMetadata(d.trackId,d.rtpTimestamp,d.ssrc,d.metadata);break}},this.onWorkerError=n=>{F.error("e2ee worker encountered an error:",{error:n.error}),this.emit(bt.EncryptionError,n.error,void 0)},this.keyProvider=e.keyProvider,this.worker=e.worker,this.encryptionEnabled=!1,this.dataChannelEncryptionEnabled=t}get isEnabled(){return this.encryptionEnabled}get isDataChannelEncryptionEnabled(){return this.isEnabled&&this.dataChannelEncryptionEnabled}setup(e){if(!xm())throw new Dn("tried to setup end-to-end encryption on an unsupported browser");if(F.info("setting up e2ee"),e!==this.room){this.room=e,this.setupEventListeners(e,this.keyProvider);let t={kind:"init",data:{keyProviderOptions:this.keyProvider.getOptions(),loglevel:Eh.getLevel()}};this.worker&&(F.info("initializing worker",{worker:this.worker}),this.worker.onmessage=this.onWorkerMessage,this.worker.onerror=this.onWorkerError,this.worker.postMessage(t))}}setParticipantCryptorEnabled(e,t){F.debug("set e2ee to ".concat(e," for participant ").concat(t)),this.postEnable(e,t)}setSifTrailer(e){!e||e.length===0?F.warn("ignoring server sent trailer as it's empty"):this.postSifTrailer(e)}handleFrameMetadata(e,t,n,r){if(this.room){for(let s of[this.room.localParticipant,...this.room.remoteParticipants.values()])for(let a of s.trackPublications.values())if(a.track&&a.track.mediaStreamID===e&&a.track instanceof Bn&&a.track.frameMetadataExtractor){a.track.frameMetadataExtractor.storeMetadata(t,n,r);return}}}setupEngine(e){e.on(R.RTPVideoMapUpdate,t=>{this.postRTPMap(t)})}setupEventListeners(e,t){e.on(C.TrackPublished,(n,r)=>this.setParticipantCryptorEnabled(n.trackInfo.encryption!==$.NONE,r.identity)),e.on(C.ConnectionStateChanged,n=>{n===V.Connected&&e.remoteParticipants.forEach(r=>{r.trackPublications.forEach(s=>{this.setParticipantCryptorEnabled(s.trackInfo.encryption!==$.NONE,r.identity)})})}).on(C.TrackUnsubscribed,(n,r,s)=>{var a;let o={kind:"removeTransform",data:{participantIdentity:s.identity,trackId:n.mediaStreamID}};(a=this.worker)===null||a===void 0||a.postMessage(o)}).on(C.TrackSubscribed,(n,r,s)=>{this.setupE2EEReceiver(n,s.identity,r.trackInfo)}).on(C.SignalConnected,()=>{if(!this.room)throw new TypeError("expected room to be present on signal connect");let n=t.getLatestManuallySetKeyIndex();t.getKeys().forEach(r=>{var s;this.postKey(r,n===((s=r.keyIndex)!==null&&s!==void 0?s:0))}),this.setParticipantCryptorEnabled(this.room.localParticipant.isE2EEEnabled,this.room.localParticipant.identity)}),e.localParticipant.on(I.LocalSenderCreated,(n,r)=>p(this,void 0,void 0,function*(){this.setupE2EESender(r,n)})),e.localParticipant.on(I.LocalTrackPublished,n=>{if(!ht(n.track)||!Ln())return;let r={kind:"updateCodec",data:{trackId:n.track.mediaStreamID,codec:_n(n.trackInfo.codecs[0].mimeType),participantIdentity:this.room.localParticipant.identity,hasPacketTrailer:!1}};this.worker.postMessage(r)}),t.on(St.SetKey,(n,r)=>this.postKey(n,r??!0)).on(St.RatchetRequest,(n,r)=>this.postRatchetRequest(n,r))}encryptData(e){return p(this,void 0,void 0,function*(){if(!this.worker)throw Error("could not encrypt data, worker is missing");let t=crypto.randomUUID(),n={kind:"encryptDataRequest",data:{uuid:t,payload:e,participantIdentity:this.room.localParticipant.identity}},r=new ce;return r.onFinally=()=>{this.encryptDataRequests.delete(t)},this.encryptDataRequests.set(t,r),this.worker.postMessage(n),r.promise})}handleEncryptedData(e,t,n,r){if(!this.worker)throw Error("could not handle encrypted data, worker is missing");let s=crypto.randomUUID(),a={kind:"decryptDataRequest",data:{uuid:s,payload:e,iv:t,participantIdentity:n,keyIndex:r}},o=new ce;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");let n={kind:"ratchetRequest",data:{participantIdentity:e,keyIndex:t}};this.worker.postMessage(n)}postKey(e,t){let n=e.key,r=e.participantIdentity,s=e.keyIndex;var a;if(!this.worker)throw Error("could not set key, worker is missing");let o={kind:"setKey",data:{participantIdentity:r,isPublisher:r===((a=this.room)===null||a===void 0?void 0:a.localParticipant.identity),key:n,keyIndex:s,updateCurrentKeyIndex:t}};this.worker.postMessage(o)}postEnable(e,t){if(this.worker){let n={kind:"enable",data:{enabled:e,participantIdentity:t}};this.worker.postMessage(n)}else throw new ReferenceError("failed to enable e2ee, worker is not ready")}postRTPMap(e){var t;if(!this.worker)throw TypeError("could not post rtp map, worker is missing");if(!(!((t=this.room)===null||t===void 0)&&t.localParticipant.identity))throw TypeError("could not post rtp map, local participant identity is missing");let n={kind:"setRTPMap",data:{map:e,participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(n)}postSifTrailer(e){if(!this.worker)throw Error("could not post SIF trailer, worker is missing");let t={kind:"setSifTrailer",data:{trailer:e}};this.worker.postMessage(t)}setupE2EEReceiver(e,t,n){if(!e.receiver)return;if(!n?.mimeType||n.mimeType==="")throw new TypeError("MimeType missing from trackInfo, cannot set up E2EE cryptor");let r=e.kind==="video"&&!!n.packetTrailerFeatures&&n.packetTrailerFeatures.length>0;this.handleReceiver(e.receiver,e.mediaStreamID,t,e.kind==="video"?_n(n.mimeType):void 0,r)}setupE2EESender(e,t){var n,r,s;if(!Xt(e)||!t){t||F.warn("early return because sender is not ready");return}this.handleSender(t,e.mediaStreamID,void 0,ht(e)?(r=(n=e.publishOptions)===null||n===void 0?void 0:n.frameMetadata)!==null&&r!==void 0?r:(s=e.publishOptions)===null||s===void 0?void 0:s.packetTrailer:void 0)}handleReceiver(e,t,n,r,s){return p(this,void 0,void 0,function*(){if(this.worker){if(hs()){let a={kind:"decode",participantIdentity:n,trackId:t,codec:r,hasPacketTrailer:s};e.transform=new RTCRtpScriptTransform(this.worker,a)}else{if(yn in e&&r){let c={kind:"updateCodec",data:{trackId:t,codec:r,participantIdentity:n,hasPacketTrailer:s}};this.worker.postMessage(c);return}let a=e.writableStream,o=e.readableStream;if(!a||!o){let c=e.createEncodedStreams();e.writableStream=c.writable,a=c.writable,e.readableStream=c.readable,o=c.readable}let d={kind:"decode",data:{readableStream:o,writableStream:a,trackId:t,codec:r,participantIdentity:n,isReuse:yn in e,hasPacketTrailer:s}};this.worker.postMessage(d,[o,a])}e[yn]=!0}})}handleSender(e,t,n,r){var s;if(!(yn 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(hs()){F.info("initialize script transform");let a={kind:"encode",participantIdentity:this.room.localParticipant.identity,trackId:t,codec:n,hasPacketTrailer:Ei(r),packetTrailer:r};e.transform=new RTCRtpScriptTransform(this.worker,a)}else{F.info("initialize encoded streams");let a=e.createEncodedStreams(),o={kind:"encode",data:{readableStream:a.readable,writableStream:a.writable,codec:n,trackId:t,participantIdentity:this.room.localParticipant.identity,isReuse:!1,hasPacketTrailer:Ei(r),packetTrailer:r}};this.worker.postMessage(o,[a.readable,a.writable])}e[yn]=!0}}},Um=300,vs=class{constructor(){this.metadataMap=new Map,this.activeSsrc=0}storeMetadata(e,t,n){for(this.activeSsrc!==0&&this.activeSsrc!==t&&this.metadataMap.clear(),this.activeSsrc=t;this.metadataMap.size>=Um;){let r=this.metadataMap.keys().next().value;this.metadataMap.delete(r)}this.metadataMap.set(e,n)}lookupMetadata(e){return this.metadataMap.get(e)}dispose(){this.metadataMap.clear(),this.activeSsrc=0}},ys=class{constructor(e){this.extractors=new Map,this.workerPipelines=new Map,this.onWorkerMessage=t=>{let n=t.data;if(n.kind==="metadata"){let r=this.extractors.get(n.data.trackId);r&&r.storeMetadata(n.data.rtpTimestamp,n.data.ssrc,n.data.metadata)}},this.onWorkerError=t=>{F.error("frame metadata worker encountered an error:",{error:t.error})},this.worker=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(C.TrackSubscribed,(t,n,r)=>{t.kind==="video"&&this.setupReceiver(t,n.trackInfo)}).on(C.TrackUnsubscribed,t=>{this.teardownTrack(t)}).on(C.Disconnected,()=>{this.cleanup()}))}setupReceiver(e,t){var n,r,s;let a=e.receiver;if(!a)return;if(!(!!t?.packetTrailerFeatures&&t.packetTrailerFeatures.length>0)){!((n=this.room)===null||n===void 0)&&n.hasE2EESetup||this.setupPassthroughReceiver(a,e.mediaStreamID);return}if(!Fn(this.worker?{worker:this.worker}:void 0)&&!(!((r=this.room)===null||r===void 0)&&r.hasE2EESetup)){F.warn("frame metadata transform not supported; skipping extraction");return}let d=new vs,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(Un()){"transform"in e&&(e.transform=null);return}if(this.worker&&Fn({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 n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,r=this.worker;if(!r)return;if(Un()){e.transform=new RTCRtpScriptTransform(r,{kind:"decode",trackId:t});return}let s=this.workerPipelines.get(e);if(s){let d={kind:"updateTrackId",data:{oldTrackId:s,newTrackId:t,hasPacketTrailer:n}};r.postMessage(d),this.workerPipelines.set(e,t);return}if(!("createEncodedStreams"in e)){F.warn("createEncodedStreams not supported");return}let a;try{a=e.createEncodedStreams()}catch(d){F.warn("failed to create encoded streams",{error:d});return}let o={kind:"decode",data:{readableStream:a.readable,writableStream:a.writable,trackId:t,hasPacketTrailer:n}};r.postMessage(o,[a.readable,a.writable]),this.workerPipelines.set(e,t)}teardownTrack(e){let t=e.mediaStreamID,n=this.extractors.get(t);n&&(n.dispose(),this.extractors.delete(t)),e instanceof Bn&&(e.frameMetadataExtractor=void 0)}cleanup(){var e;for(let t of this.extractors.values())t.dispose();this.extractors.clear(),this.workerPipelines.clear(),(e=this.worker)===null||e===void 0||e.terminate()}};var Fm=500,Bm=15e3,Zt=class i{constructor(){this.failedConnectionAttempts=new Map,this.backOffPromises=new Map}static getInstance(){return this._instance||(this._instance=new i),this._instance}addFailedConnectionAttempt(e){var t;let n=new URL(e),r=_r(n);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,ve(Math.min(Fm*Math.pow(2,s),Bm)))}getBackOffPromise(e){let t=new URL(e),n=t&&_r(t);return n&&this.backOffPromises.get(n)||Promise.resolve()}resetFailedConnectionAttempts(e){let t=new URL(e),n=t&&_r(t);n&&(this.failedConnectionAttempts.set(n,0),this.backOffPromises.set(n,Promise.resolve()))}resetAll(){this.backOffPromises.clear(),this.failedConnectionAttempts.clear()}};Zt._instance=null;var Mr="default",Pe=class i{constructor(){this._previousDevices=[]}static getInstance(){return this.instance===void 0&&(this.instance=new i),this.instance}get previousDevices(){return this._previousDevices}getDevices(e){return p(this,arguments,void 0,function(t){var n=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return(function*(){var s;if(((s=i.userMediaPromiseMap)===null||s===void 0?void 0:s.size)>0){F.debug("awaiting getUserMedia promise");try{t?yield i.userMediaPromiseMap.get(t):yield Promise.all(i.userMediaPromiseMap.values())}catch{F.warn("error waiting for media permissons")}}let a=yield navigator.mediaDevices.enumerateDevices();if(r&&!(Bt()&&n.hasDeviceInUse(t))&&(a.filter(d=>d.kind===t).length===0||a.some(d=>{let c=d.label==="",l=t?d.kind===t:!0;return c&&l}))){let 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 n._previousDevices=a,t&&(a=a.filter(o=>o.kind===t)),a})()})}normalizeDeviceId(e,t,n){return p(this,void 0,void 0,function*(){if(t!==Mr)return t;let r=yield this.getDevices(e),s=r.find(o=>o.deviceId===Mr);if(!s){F.warn("could not reliably determine default device");return}let a=r.find(o=>o.deviceId!==Mr&&o.groupId===(n??s.groupId));if(!a){F.warn("could not reliably determine default device");return}return a?.deviceId})}hasDeviceInUse(e){return e?i.userMediaPromiseMap.has(e):i.userMediaPromiseMap.size>0}};Pe.mediaDeviceKinds=["audioinput","audiooutput","videoinput"];Pe.userMediaPromiseMap=new Map;var La=65535,Yd=4294967295,Ct=class i{static u16(e){return new i(e,La)}static u32(e){return new i(e,Yd)}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 i(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(){let e=this.value;return this.increment(),new i(e,this.maxSize)}isBefore(e){let t=this.value>>>0,r=(e.value>>>0)-t>>>0;return r!==0&&r<this.maxSize+1}},Pi=class i{static fromRtpTicks(e){return new i(e,9e4)}static rtpRandom(){let e=Math.round(Math.random()*Yd);return i.fromRtpTicks(e)}constructor(e,t){this.timestamp=Ct.u32(e),this.rateInHz=t}asTicks(){return this.timestamp.value}clone(){return new i(this.timestamp.value,this.rateInHz)}wrappingAdd(e){this.timestamp.increment(e)}isBefore(e){return this.timestamp.isBefore(e.timestamp)}},bs=class i{constructor(e,t,n){this.epoch=t,this.base=n,this.previous=n.clone(),this.rateInHz=e}static startingNow(e,t){return new i(t,new Date,e)}static startingAtTime(e,t,n){return new i(n,e,t)}static rtpStartingNow(e){return i.startingNow(e,9e4)}static rtpStartingAtTime(e,t){return i.startingAtTime(e,t,9e4)}now(){return this.at(new Date)}at(e){let t=e.getTime()-this.epoch.getTime(),n=i.durationInMsToTicks(t,this.rateInHz),r=this.base.clone();return r.wrappingAdd(n),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 Na(i){if(i instanceof DataView)return i;if(i instanceof ArrayBuffer)return new DataView(i);if(i instanceof Uint8Array)return new DataView(i.buffer,i.byteOffset,i.byteLength);throw new Error("Error coercing ".concat(i," to DataView - input was not DataView, ArrayBuffer, or Uint8Array."))}var Nt;(function(i){i[i.Reserved=0]="Reserved",i[i.TooLarge=1]="TooLarge"})(Nt||(Nt={}));var qn=class i extends we{constructor(e,t){super(19,e),this.name="DataTrackHandleError",this.reason=t,this.reasonName=Nt[t]}isReason(e){return this.reason===e}static tooLarge(){return new i("Value too large to be a valid track handle",Nt.TooLarge)}static reserved(e){return new i("0x".concat(e.toString(16)," is a reserved value."),Nt.Reserved)}},qm={fromNumber(i){if(i===0)throw qn.reserved(i);if(i>La)throw qn.tooLarge();return i}},ks=class{constructor(){this.value=0}get(){return this.value+=1,this.value>La?null:this.value}reset(){this.value=0}},Ii={from(i){return{sid:i.sid,pubHandle:i.pubHandle,name:i.name,usesE2ee:i.encryption!==$.NONE}},toProtobuf(i){return new Zi({sid:i.sid,pubHandle:i.pubHandle,name:i.name,encryption:i.usesE2ee?$.GCM:$.NONE})}},wn;(function(i){i[i.WAITING=0]="WAITING",i[i.RUNNING=1]="RUNNING",i[i.COMPLETED=2]="COMPLETED"})(wn||(wn={}));var Ts=class{constructor(){this.pendingTasks=new Map,this.taskMutex=new de,this.nextTaskIndex=0}run(e){return p(this,void 0,void 0,function*(){let t={id:this.nextTaskIndex++,enqueuedAt:Date.now(),status:wn.WAITING};this.pendingTasks.set(t.id,t);let n=yield this.taskMutex.lock();try{return t.executedAt=Date.now(),t.status=wn.RUNNING,yield e()}finally{t.status=wn.COMPLETED,this.pendingTasks.delete(t.id),n()}})}flush(){return p(this,void 0,void 0,function*(){return this.run(()=>p(this,void 0,void 0,function*(){}))})}snapshot(){return Array.from(this.pendingTasks.values())}},Ss=class{get readyState(){return this.ws.readyState}constructor(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};var n,r;if(!((n=t.signal)===null||n===void 0)&&n.aborted)throw new DOMException("This operation was aborted","AbortError");this.url=e;let s=new WebSocket(e,(r=t.protocols)!==null&&r!==void 0?r:[]);s.binaryType="arraybuffer",this.ws=s;let 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 pe((o,d)=>{let c=()=>{d(N.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 pe((o,d)=>{let c=()=>p(this,void 0,void 0,function*(){let l=new pe(h=>{s.readyState!==WebSocket.CLOSED&&s.addEventListener("close",m=>{h(m)},{once:!0})}),u=yield pe.race([ve(250),l]);u?o(u):d(N.websocket("Encountered unspecified websocket error without a timely close event"))});s.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}},jm=["syncState","trickle","offer","answer","simulate","leave"];function Vm(i){let e=jm.indexOf(i.case)>=0;return F.trace("request allowed to bypass queue:",{canPass:e,req:i}),e}var z;(function(i){i[i.CONNECTING=0]="CONNECTING",i[i.CONNECTED=1]="CONNECTED",i[i.RECONNECTING=2]="RECONNECTING",i[i.DISCONNECTING=3]="DISCONNECTING",i[i.DISCONNECTED=4]="DISCONNECTED"})(z||(z={}));var Hm=250,jn=class{get currentState(){return this.state}get isDisconnected(){return this.state===z.DISCONNECTING||this.state===z.DISCONNECTED}get isEstablishingConnection(){return this.state===z.CONNECTING||this.state===z.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 n;this.rtt=0,this.state=z.DISCONNECTED,this.log=F,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=_e((n=t.loggerName)!==null&&n!==void 0?n:ue.Signal,()=>this.logContext),this.useJSON=e,this.requestQueue=new Ts,this.queuedRequests=[],this.closingLock=new de,this.connectionLock=new de,this.state=z.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,n,r){return p(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=z.CONNECTING,c.options=o,yield c.connect(s,a,o,d,l,u)})()})}reconnect(e,t,n,r){return p(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=z.RECONNECTING,this.clearPingInterval(),yield this.connect(e,t,Object.assign(Object.assign({},this.options),{reconnect:!0,sid:n,reconnectReason:r}),void 0,this.useV0SignalPath)})}connect(e,t,n,r){return p(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*(){let h=yield c.connectionLock.lock();c.connectOptions=o,c.useV0SignalPath=l;let m=fm(o.clientInfoCapabilities),f=l?Gm(a,m,o):yield Km(a,m,o,u),g=wm(s,f,l).toString(),k=Rm(g).toString();return new Promise((T,S)=>p(c,void 0,void 0,function*(){var L,y;try{let b=!1,E=x=>p(this,void 0,void 0,function*(){if(b)return;b=!0;let B=x instanceof Event?x.currentTarget:x,Z=Pm(B,"Abort handler called");this.streamWriter&&!this.isDisconnected?this.sendLeave().then(()=>this.close(Z)).catch(ee=>{this.log.error(ee),this.close()}):this.close(),M(),S(N.cancelled(Z))});d?.addEventListener("abort",E);let M=()=>{clearTimeout(D),d?.removeEventListener("abort",E)},D=setTimeout(()=>{E(N.timeout("room connection has timed out (signal)"))},o.websocketTimeout),q=(x,B)=>{this.handleSignalConnected(x,D,B)},A=new URL(g);if(A.searchParams.has("access_token")&&A.searchParams.set("access_token","<redacted>"),this.ws){let x=performance.now();yield this.close(!1),this.log.debug("closed previous ws connection in ".concat(performance.now()-x,"ms"))}this.log.info("signal connecting to ".concat(A),{reconnect:o.reconnect,reconnectReason:o.reconnectReason}),this.ws=new Ss(g);try{this.ws.closed.then(ye=>{var ft;this.isEstablishingConnection&&S(N.internal("Websocket got closed during a (re)connection attempt: ".concat(ye.reason))),ye.closeCode!==1e3&&(this.log.warn("websocket closed",{reason:ye.reason,code:ye.closeCode,wasClean:ye.closeCode===1e3,state:this.state}),this.state===z.CONNECTED&&this.handleOnClose((ft=ye.reason)!==null&&ft!==void 0?ft:"Unexpected WS error"))}).catch(ye=>{this.isEstablishingConnection&&S(N.internal("Websocket error during a (re)connection attempt: ".concat(ye)))});let x=yield this.ws.opened.catch(ye=>p(this,void 0,void 0,function*(){if(this.state!==z.CONNECTED){this.state=z.DISCONNECTED,clearTimeout(D);let ft=yield this.handleConnectionError(ye,k);S(ft);return}this.handleWSError(ye),S(ye)}));if(clearTimeout(D),!x)return;let B=x.readable.getReader();this.streamWriter=x.writable.getWriter();let Z=yield B.read();if(B.releaseLock(),!Z.value)throw N.internal("no message received as first message");let ee=Oo(Z.value),ze=this.validateFirstMessage(ee,(L=o.reconnect)!==null&&L!==void 0?L:!1);if(!ze.isValid){S(ze.error);return}((y=ee.message)===null||y===void 0?void 0:y.case)==="join"&&(this.pingTimeoutDuration=ee.message.value.pingTimeout,this.pingIntervalDuration=ee.message.value.pingInterval,this.pingTimeoutDuration&&this.pingTimeoutDuration>0&&this.log.debug("ping config",{timeout:this.pingTimeoutDuration,interval:this.pingIntervalDuration}),this.onJoined&&this.onJoined(ee.message.value));let mn=ze.shouldProcessFirstMessage?ee:void 0;q(x,mn),T(ze.response)}catch(x){S(x)}finally{M()}}finally{h()}}))})()})}startReadingLoop(e,t){return p(this,void 0,void 0,function*(){for(t&&this.handleSignalResponse(t);;){this.signalLatency&&(yield ve(this.signalLatency));let n=yield e.read(),r=n.done,s=n.value;if(r)break;let a=Oo(s);this.handleSignalResponse(a)}})}close(){return p(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0,n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"Close method called on signal client";return(function*(){if([z.DISCONNECTING||z.DISCONNECTED].includes(e.state)){e.log.debug("ignoring signal close as it's already in disconnecting state");return}let r=yield e.closingLock.lock();try{if(e.clearPingInterval(),t&&(e.state=z.DISCONNECTING),e.ws){e.ws.close({closeCode:1e3,reason:n});let s=e.ws.closed;e.ws=void 0,e.streamWriter=void 0,yield Promise.race([s,ve(Hm)])}}catch(s){e.log.debug("websocket error while closing",{error:s})}finally{t&&(e.state=z.DISCONNECTED),r()}})()})}sendOffer(e,t){this.log.debug("sending offer",{offerSdp:e.sdp}),this.sendRequest({case:"offer",value:Mt(e,t)})}sendAnswer(e,t){return this.log.debug("sending answer",{answerSdp:e.sdp}),this.sendRequest({case:"answer",value:Mt(e,t)})}sendIceCandidate(e,t){return this.log.debug("sending ice candidate",{candidate:e}),this.sendRequest({case:"trickle",value:new tr({candidateInit:JSON.stringify(e),target:t})})}sendMuteTrack(e,t){return this.sendRequest({case:"mute",value:new nr({sid:e,muted:t})})}sendAddTrack(e){return this.sendRequest({case:"addTrack",value:e})}sendUpdateLocalMetadata(e,t){return p(this,arguments,void 0,function(n,r){var s=this;let a=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return(function*(){let o=s.getNextRequestId();return yield s.sendRequest({case:"updateMetadata",value:new _a({requestId:o,metadata:n,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 Zc({trackSid:e,layers:t})})}sendUpdateSubscriptionPermissions(e,t){return this.sendRequest({case:"subscriptionPermission",value:new nd({allParticipants:e,trackPermissions:t})})}sendSimulateScenario(e){return this.sendRequest({case:"simulate",value:e})}sendPing(){return Promise.all([this.sendRequest({case:"ping",value:Y.parse(Date.now())}),this.sendRequest({case:"pingReq",value:new sd({timestamp:Y.parse(Date.now()),rtt:Y.parse(this.rtt)})})])}sendUpdateLocalAudioTrack(e,t){return this.sendRequest({case:"updateAudioTrack",value:new Ca({trackSid:e,features:t})})}sendLeave(){return this.sendRequest({case:"leave",value:new rr({reason:re.CLIENT_INITIATED,action:$t.DISCONNECT})})}sendPublishDataTrackRequest(e,t,n){return this.sendRequest({case:"publishDataTrackRequest",value:new ba({pubHandle:e,name:t,encryption:n?$.GCM:$.NONE})})}sendUnPublishDataTrackRequest(e){return this.sendRequest({case:"unpublishDataTrackRequest",value:new Ta({pubHandle:e})})}sendUpdateDataSubscription(e,t){return this.sendRequest({case:"updateDataSubscription",value:new $c({updates:[new Qc({trackSid:e,subscribe:t})]})})}sendRequest(e){return p(this,arguments,void 0,function(t){var n=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1;return(function*(){if(!r&&!Vm(t)&&n.state===z.RECONNECTING){n.queuedRequests.push(()=>p(n,void 0,void 0,function*(){yield this.sendRequest(t,!0)}));return}if(r||(yield n.requestQueue.flush()),n.signalLatency&&(yield ve(n.signalLatency)),n.isDisconnected){n.log.debug("skipping signal request (type: ".concat(t.case,") - SignalClient disconnected"));return}if(!n.streamWriter){n.log.error("cannot send signal request before connected, type: ".concat(t?.case));return}let a=new Ju({message:t});try{n.useJSON?yield n.streamWriter.write(a.toJsonString()):yield n.streamWriter.write(a.toBinary().buffer)}catch(o){n.log.error("error sending signal message",{error:o})}})()})}handleSignalResponse(e){var t,n;let r=e.message;if(r==null){this.log.debug("received unsupported message");return}let s=!1;if(r.case==="answer"){let a=Bo(r.value);this.onAnswer&&this.onAnswer(a,r.value.id,r.value.midToTrackId)}else if(r.case==="offer"){let a=Bo(r.value);this.onOffer&&this.onOffer(a,r.value.id,r.value.midToTrackId)}else if(r.case==="trickle"){let a=JSON.parse(r.value.candidateInit);this.onTrickle&&this.onTrickle(a,r.value.target)}else r.case==="update"?this.onParticipantUpdate&&this.onParticipantUpdate((t=r.value.participants)!==null&&t!==void 0?t:[]):r.case==="trackPublished"?this.onLocalTrackPublished&&this.onLocalTrackPublished(r.value):r.case==="speakersChanged"?this.onSpeakersChanged&&this.onSpeakersChanged((n=r.value.speakers)!==null&&n!==void 0?n:[]):r.case==="leave"?this.onLeave&&this.onLeave(r.value):r.case==="mute"?this.onRemoteMuteChanged&&this.onRemoteMuteChanged(r.value.sid,r.value.muted):r.case==="roomUpdate"?this.onRoomUpdate&&r.value.room&&this.onRoomUpdate(r.value.room):r.case==="connectionQuality"?this.onConnectionQuality&&this.onConnectionQuality(r.value):r.case==="streamStateUpdate"?this.onStreamStateUpdate&&this.onStreamStateUpdate(r.value):r.case==="subscribedQualityUpdate"?this.onSubscribedQualityUpdate&&this.onSubscribedQualityUpdate(r.value):r.case==="subscriptionPermissionUpdate"?this.onSubscriptionPermissionUpdate&&this.onSubscriptionPermissionUpdate(r.value):r.case==="refreshToken"?this.onTokenRefresh&&this.onTokenRefresh(r.value):r.case==="trackUnpublished"?this.onLocalTrackUnpublished&&this.onLocalTrackUnpublished(r.value):r.case==="subscriptionResponse"?this.onSubscriptionError&&this.onSubscriptionError(r.value):r.case==="pong"||(r.case==="pongResp"?(this.rtt=Date.now()-Number.parseInt(r.value.lastPingTimestamp.toString()),this.resetPingTimeout(),s=!0):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(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;){let e=this.queuedRequests.shift();e&&this.requestQueue.run(e)}}handleOnClose(e){return p(this,void 0,void 0,function*(){if(this.state===z.DISCONNECTED)return;let t=this.onClose;yield this.close(void 0,e),this.log.info("websocket connection closed: ".concat(e),{reason:e}),t&&t(e)})}handleWSError(e){this.log.error("websocket error",{error:e})}resetPingTimeout(){if(this.clearPingTimeout(),!this.pingTimeoutDuration){this.log.warn("ping timeout duration not set");return}this.pingTimeout=se.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&&se.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=se.setInterval(()=>{this.sendPing()},this.pingIntervalDuration*1e3)}clearPingInterval(){this.log.debug("clearing ping interval"),this.clearPingTimeout(),this.pingInterval&&se.clearInterval(this.pingInterval)}handleSignalConnected(e,t,n){this.state=z.CONNECTED,this.log.info("signal connected"),clearTimeout(t),this.startPingInterval(),this.startReadingLoop(e.readable.getReader(),n)}validateFirstMessage(e,t){var n,r,s,a,o;return((n=e.message)===null||n===void 0?void 0:n.case)==="join"?{isValid:!0,response:e.message.value}:this.state===z.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:N.leaveRequest("Received leave request while trying to (re)connect",e.message.value.reason)}:t?{isValid:!1,error:N.internal("Unexpected first message")}:{isValid:!1,error:N.internal("did not receive join response, got ".concat((o=e.message)===null||o===void 0?void 0:o.case," instead"))}}handleConnectionError(e,t){return p(this,void 0,void 0,function*(){try{let n=yield fetch(t);switch(n.status){case 404:let r=yield n.text();return r.includes("requested room does not exist")?N.notAllowed(r,n.status):N.serviceNotFound("v1 RTC path not found. Consider upgrading your LiveKit server version","v0-rtc");case 401:case 403:let s=yield n.text();return N.notAllowed(s,n.status);default:break}return e instanceof N?e:N.internal("Encountered unknown websocket error during connection: ".concat(e),{status:n.status,statusText:n.statusText})}catch(n){return n instanceof N?n:N.serverUnreachable(n instanceof Error?n.message:"server was not reachable")}})}};function Bo(i){let e={type:"offer",sdp:i.sdp};switch(i.type){case"answer":case"offer":case"pranswer":case"rollback":e.type=i.type;break}return e}function Mt(i,e){return new wt({sdp:i.sdp,type:i.type,id:e})}function Gm(i,e,t){var n;let r=new URLSearchParams;return r.set("access_token",i),t.reconnect&&(r.set("reconnect","1"),t.sid&&r.set("sid",t.sid)),r.set("auto_subscribe",t.autoSubscribe?"1":"0"),r.set("sdk",He()?"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()),!((n=navigator.connection)===null||n===void 0)&&n.type&&r.set("network",navigator.connection.type),r}function Km(i,e,t,n){return p(this,void 0,void 0,function*(){let r=new URLSearchParams;r.set("access_token",i);let s=new bh({clientInfo:e,connectionSettings:new ad({autoSubscribe:!!t.autoSubscribe,adaptiveStream:!!t.adaptiveStream}),reconnect:!!t.reconnect,participantSid:t.sid?t.sid:void 0,publisherOffer:n});t.reconnectReason&&(s.reconnectReason=t.reconnectReason);let a=s.toBinary(),o,d;if($d()){let h=new CompressionStream("gzip"),m=h.writable.getWriter();m.write(new Uint8Array(a)),m.close();let f=[],g=h.readable.getReader();for(;;){let L=yield g.read(),y=L.done,b=L.value;if(y)break;f.push(b)}let k=f.reduce((L,y)=>L+y.length,0),T=new Uint8Array(k),S=0;for(let L of f)T.set(L,S),S+=L.length;o=T,d=zr.GZIP}else o=a,d=zr.NONE;let l=new kh({joinRequest:o,compression:d}).toBinary(),u=h=>{let m=Array.from(h,f=>String.fromCodePoint(f)).join("");return btoa(m)};return r.set("join_request",u(l).replace(/\+/g,"-").replace(/\//g,"_")),r})}var Mi=class{constructor(){this.buffer=[],this._totalSize=0}push(e){this.buffer.push(e),this._totalSize+=e.data.byteLength}pop(){let e=this.buffer.shift();return e&&(this._totalSize-=e.data.byteLength),e}getAll(){return this.buffer.slice()}popToSequence(e){for(;this.buffer.length>0&&this.buffer[0].sequence<=e;)this.pop()}alignBufferedAmount(e){for(;this.buffer.length>0;){let t=this.buffer[0];if(this._totalSize-t.data.byteLength<=e)break;this.pop()}}get length(){return this.buffer.length}},Cs=class{constructor(e){this._map=new Map,this._lastCleanup=0,this.ttl=e}set(e,t){let n=Date.now();n-this._lastCleanup>this.ttl/2&&this.cleanup();let r=n+this.ttl;return this._map.set(e,{value:t,expiresAt:r}),this}get(e){let t=this._map.get(e);if(t){if(t.expiresAt<Date.now()){this._map.delete(e);return}return t.value}}has(e){let 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(){let e=Date.now();for(let n of this._map.entries()){var t=O(n,2);let 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(let n of this._map.entries()){var t=O(n,2);let r=t[0],s=t[1];s.expiresAt>=Date.now()&&e(s.value,r,this.asValueMap())}}map(e){this.cleanup();let t=[],n=this.asValueMap();for(let s of n.entries()){var r=O(s,2);let a=r[0],o=r[1];t.push(e(o,a,n))}return t}asValueMap(){let e=new Map;for(let n of this._map.entries()){var t=O(n,2);let r=t[0],s=t[1];s.expiresAt>=Date.now()&&e.set(r,s.value)}return e}},xe={},Ar={},xr={exports:{}},qo;function Ua(){if(qo)return xr.exports;qo=1;var i=xr.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","maxMessageSize"],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(i).forEach(function(e){var t=i[e];t.forEach(function(n){n.reg||(n.reg=/(.*)/),n.format||(n.format="%s")})}),xr.exports}var jo;function Wm(){return jo||(jo=1,(function(i){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]))},n=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=Ua(),s=RegExp.prototype.test.bind(/^([a-z])=(.*)/);i.parse=function(o){var d={},c=[],l=d;return o.split(/(\r\n|\r|\n)/).filter(s).forEach(function(u){var h=u[0],m=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(m))return n(g,l,m)}}),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};i.parseParams=function(o){return o.split(/;\s?/).reduce(a,{})},i.parseFmtpConfig=i.parseParams,i.parsePayloads=function(o){return o.toString().split(" ").map(Number)},i.parseRemoteCandidates=function(o){for(var 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},i.parseImageAttributes=function(o){return o.split(" ").map(function(d){return d.substring(1,d.length-1).split(",").reduce(a,{})})},i.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}})})}})(Ar)),Ar}var Dr,Vo;function zm(){if(Vo)return Dr;Vo=1;var i=Ua(),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""}})},n=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 Dr=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){i[u].forEach(function(h){h.name in a&&a[h.name]!=null?l.push(n(u,h,a)):h.push in a&&a[h.push]!=null&&a[h.push].forEach(function(m){l.push(n(u,h,m))})})}),a.media.forEach(function(u){l.push(n("m",i.m[0],u)),c.forEach(function(h){i[h].forEach(function(m){m.name in u&&u[m.name]!=null?l.push(n(h,m,u)):m.push in u&&u[m.push]!=null&&u[m.push].forEach(function(f){l.push(n(h,m,f))})})})}),l.join(`\r
38
38
  `)+`\r
39
- `},Dr}var jo;function Km(){if(jo)return xe;jo=1;var i=Hm(),e=Gm(),t=Ua();return xe.grammar=t,xe.write=e,xe.parse=i.parse,xe.parseParams=i.parseParams,xe.parseFmtpConfig=i.parseFmtpConfig,xe.parsePayloads=i.parsePayloads,xe.parseRemoteCandidates=i.parseRemoteCandidates,xe.parseImageAttributes=i.parseImageAttributes,xe.parseSimulcastStreamList=i.parseSimulcastStreamList,xe}var Ie=Km(),Wm=.7,zm=20,kt={NegotiationStarted:"negotiationStarted",NegotiationComplete:"negotiationComplete",OfferAnswered:"offerAnswered",RTPVideoPayloadTypes:"rtpVideoPayloadTypes"},Ai=class extends Ee.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 n;super(),this.log=F,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=Da(r=>p(this,void 0,void 0,function*(){this.emit(kt.NegotiationStarted);try{yield this.createAndSendOffer()}catch(s){if(r)r(s);else throw s}}),zm),this.close=()=>{this._pc&&(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.log=_e((n=t.loggerName)!==null&&n!==void 0?n:ue.PCTransport),this.loggerOptions=t,this.config=e,this._pc=this.createPC(),this.offerLock=new de}createPC(){let e=new RTCPeerConnection(this.config);return e.onicecandidate=t=>{var n;t.candidate&&((n=this.onIceCandidate)===null||n===void 0||n.call(this,t.candidate))},e.onicecandidateerror=t=>{var n;(n=this.onIceCandidateError)===null||n===void 0||n.call(this,t)},e.oniceconnectionstatechange=()=>{var t;(t=this.onIceConnectionStateChange)===null||t===void 0||t.call(this,e.iceConnectionState)},e.onsignalingstatechange=()=>{var t;(t=this.onSignalingStatechange)===null||t===void 0||t.call(this,e.signalingState)},e.onconnectionstatechange=()=>{var t;(t=this.onConnectionStateChange)===null||t===void 0||t.call(this,e.connectionState)},e.ondatachannel=t=>{var n;(n=this.onDataChannel)===null||n===void 0||n.call(this,t)},e.ontrack=t=>{var n;(n=this.onTrack)===null||n===void 0||n.call(this,t)},e}get 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 p(this,void 0,void 0,function*(){if(this.pc.remoteDescription&&!this.restartingIce)return this.pc.addIceCandidate(e);this.pendingCandidates.push(e)})}setRemoteDescription(e,t){return p(this,void 0,void 0,function*(){var n,r;if(e.type==="answer"&&this.latestOfferId>0&&t>0&&t!==this.latestOfferId)return this.log.warn("ignoring answer for old offer",Object.assign(Object.assign({},this.logContext),{offerId:t,latestOfferId:this.latestOfferId})),!1;let s;if(e.type==="offer"){let a=Jm(e),o=a.stereoMids,d=a.nackMids;this.remoteStereoMids=o,this.remoteNackMids=d}else if(e.type==="answer"){if(this.pendingInitialOffer&&this._pc){let o=this.pendingInitialOffer;this.pendingInitialOffer=void 0;let d=Ie.parse((n=o.sdp)!==null&&n!==void 0?n:"");d.media.forEach(c=>{ei(c)}),this.log.debug("setting pending initial offer before processing answer",this.logContext),yield this.setMungedSDP(o,Ie.write(d))}let a=Ie.parse((r=e.sdp)!==null&&r!==void 0?r:"");a.media.forEach(o=>{let d=Fa(o.mid);o.type==="audio"&&this.trackBitrates.some(c=>{if(!c.transceiver||d!=c.transceiver.mid)return!1;let l=0;if(o.rtp.some(h=>h.codec.toUpperCase()===c.codec.toUpperCase()?(l=h.payload,!0):!1),l===0)return!0;let u=!1;for(let h of o.fmtp)if(h.payload===l){h.config=h.config.split(";").filter(m=>!m.includes("maxaveragebitrate")).join(";"),c.maxbr>0&&(h.config+=";maxaveragebitrate=".concat(c.maxbr*1e3)),u=!0;break}return u||c.maxbr>0&&o.fmtp.push({payload:l,config:"maxaveragebitrate=".concat(c.maxbr*1e3)}),!0})}),s=Ie.write(a)}return yield this.setMungedSDP(e,s,!0),this.pendingCandidates.forEach(a=>{this.pc.addIceCandidate(a)}),this.pendingCandidates=[],this.restartingIce=!1,e.type==="answer"&&(this.latestAcknowledgedOfferId=t,this.emit(kt.OfferAnswered,t)),this.renegotiate?(this.renegotiate=!1,yield this.createAndSendOffer()):e.type==="answer"&&(this.emit(kt.NegotiationComplete),e.sdp&&Ie.parse(e.sdp).media.forEach(o=>{o.type==="video"&&this.emit(kt.RTPVideoPayloadTypes,o.rtp)})),!0})}createInitialOffer(){return p(this,void 0,void 0,function*(){var e;let t=yield this.offerLock.lock();try{if(this.pc.signalingState!=="stable"){this.log.warn("signaling state is not stable, cannot create initial offer",this.logContext);return}let n=this.latestOfferId+1;this.latestOfferId=n;let r=yield this.pc.createOffer();this.pendingInitialOffer={sdp:r.sdp,type:r.type};let s=Ie.parse((e=r.sdp)!==null&&e!==void 0?e:"");return s.media.forEach(a=>{ei(a)}),r.sdp=Ie.write(s),{offer:r,offerId:n}}finally{t()}})}createAndSendOffer(e){return p(this,void 0,void 0,function*(){var t;let n=yield this.offerLock.lock();try{if(this.onOffer===void 0)return;if(e?.iceRestart&&(this.log.debug("restarting ICE",this.logContext),this.restartingIce=!0),this._pc&&(this._pc.signalingState==="have-local-offer"||this.pendingInitialOffer)){let o=this._pc.remoteDescription;if(e?.iceRestart&&o)yield this._pc.setRemoteDescription(o);else{this.renegotiate=!0,this.log.debug("requesting renegotiation",Object.assign({},this.logContext));return}}else if(!this._pc||this._pc.signalingState==="closed"){this.log.warn("could not createOffer with closed peer connection",this.logContext);return}this.log.debug("starting to negotiate",this.logContext);let r=this.latestOfferId+1;this.latestOfferId=r;let s=yield this.pc.createOffer(e);this.log.debug("original offer",Object.assign({sdp:s.sdp},this.logContext));let a=Ie.parse((t=s.sdp)!==null&&t!==void 0?t:"");if(a.media.forEach(o=>{ei(o),o.type==="audio"?Vo(o,["all"],[]):o.type==="video"&&this.trackBitrates.some(d=>{if(!o.msid||!d.cid||!o.msid.includes(d.cid))return!1;let c=0;if(o.rtp.some(u=>u.codec.toUpperCase()===d.codec.toUpperCase()?(c=u.payload,!0):!1),c===0||(je(d.codec)&&!Bt()&&this.ensureVideoDDExtensionForSVC(o,a),!je(d.codec)))return!0;let l=Math.round(d.maxbr*Wm);for(let u of o.fmtp)if(u.payload===c){u.config.includes("x-google-start-bitrate")||(u.config+=";x-google-start-bitrate=".concat(l));break}return!0})}),this.latestOfferId>r){this.log.warn("latestOfferId mismatch",Object.assign(Object.assign({},this.logContext),{latestOfferId:this.latestOfferId,offerId:r}));return}yield this.setMungedSDP(s,Ie.write(a)),this.onOffer(s,this.latestOfferId)}finally{n()}})}createAndSetAnswer(){return p(this,void 0,void 0,function*(){var e;let t=yield this.pc.createAnswer(),n=Ie.parse((e=t.sdp)!==null&&e!==void 0?e:"");return n.media.forEach(r=>{ei(r),r.type==="audio"&&Vo(r,this.remoteStereoMids,this.remoteNackMids)}),yield this.setMungedSDP(t,Ie.write(n)),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 $("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 $("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 p(this,void 0,void 0,function*(){var e;if(!this._pc)return;let t="",n=new Map,r=new Map;if((yield this._pc.getStats()).forEach(o=>{switch(o.type){case"transport":t=o.selectedCandidatePairId;break;case"candidate-pair":t===""&&o.selected&&(t=o.id),n.set(o.id,o);break;case"remote-candidate":r.set(o.id,"".concat(o.address,":").concat(o.port));break}}),t==="")return;let a=(e=n.get(t))===null||e===void 0?void 0:e.remoteCandidateId;if(a!==void 0)return r.get(a)})}setMungedSDP(e,t,n){return p(this,void 0,void 0,function*(){var r,s;let a=e.sdp;if(t){e.sdp=t;try{this.log.debug("setting munged ".concat(n?"remote":"local"," description"),this.logContext),n?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"),Object.assign(Object.assign({},this.logContext),{error:o,mungedSdp:t,originalSdp:a})),e.sdp=a}}try{n?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);let c={error:d,sdp:e.sdp};throw t&&t!==a&&(c.mungedSdp=t),!n&&this.pc.remoteDescription&&(c.remoteSdp=this.pc.remoteDescription),this.log.error("unable to set ".concat(e.type),Object.assign(Object.assign({},this.logContext),{fields:c})),new lt(d)}})}ensureVideoDDExtensionForSVC(e,t){var n,r;if(!((n=e.ext)===null||n===void 0?void 0:n.some(a=>a.uri===Eo))){if(this.ddExtID===0){let a=0;t.media.forEach(o=>{var d;(d=o.ext)===null||d===void 0||d.forEach(c=>{c.value>a&&(a=c.value)})}),this.ddExtID=a+1}(r=e.ext)===null||r===void 0||r.push({value:this.ddExtID,uri:Eo})}}};function Vo(i,e,t){let n=Fa(i.mid),r=0;i.rtp.some(s=>s.codec==="opus"?(r=s.payload,!0):!1),r>0&&(i.rtcpFb||(i.rtcpFb=[]),t.includes(n)&&!i.rtcpFb.some(s=>s.payload===r&&s.type==="nack")&&i.rtcpFb.push({payload:r,type:"nack"}),(e.includes(n)||e.length===1&&e[0]==="all")&&i.fmtp.some(s=>s.payload===r?(s.config.includes("stereo=1")||(s.config+=";stereo=1"),!0):!1))}function Jm(i){var e;let t=[],n=[],r=Ie.parse((e=i.sdp)!==null&&e!==void 0?e:""),s=0;return r.media.forEach(a=>{var o;let d=Fa(a.mid);a.type==="audio"&&(a.rtp.some(c=>c.codec==="opus"?(s=c.payload,!0):!1),!((o=a.rtcpFb)===null||o===void 0)&&o.some(c=>c.payload===s&&c.type==="nack")&&n.push(d),a.fmtp.some(c=>c.payload===s?(c.config.includes("sprop-stereo=1")&&t.push(d),!0):!1))}),{stereoMids:t,nackMids:n}}function ei(i){if(i.connection){let e=i.connection.ip.indexOf(":")>=0;(i.connection.version===4&&e||i.connection.version===6&&!e)&&(i.connection.ip="0.0.0.0",i.connection.version=4)}}function Fa(i){return typeof i=="number"?i.toFixed(0):i}var _s="vp8",$m={audioPreset:ss.music,dtx:!0,red:!0,forceStereo:!1,simulcast:!0,screenShareEncoding:Ia.h1080fps15.encoding,stopMicTrackOnMute:!1,videoCodec:_s,backupCodec:!0,preConnectBuffer:!1},Qd={deviceId:{ideal:"default"},autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0,voiceIsolation:!0},Yd={deviceId:{ideal:"default"},resolution:On.h720.resolution},Qm={adaptiveStream:!1,dynacast:!1,stopLocalTrackOnUnpublish:!0,reconnectPolicy:new $r,disconnectOnPageLeave:!0,webAudioMix:!1,singlePeerConnection:!0},Ba={autoSubscribe:!0,maxRetries:1,peerConnectionTimeout:15e3,websocketTimeout:15e3},te;(function(i){i[i.NEW=0]="NEW",i[i.CONNECTING=1]="CONNECTING",i[i.CONNECTED=2]="CONNECTED",i[i.FAILED=3]="FAILED",i[i.CLOSING=4]="CLOSING",i[i.CLOSED=5]="CLOSED"})(te||(te={}));var xi=class{get needsPublisher(){return this.isPublisherConnectionRequired}get needsSubscriber(){return this.isSubscriberConnectionRequired}get currentState(){return this.state}get mode(){return this._mode}constructor(e,t,n){var r;this.peerConnectionTimeout=Ba.peerConnectionTimeout,this.log=F,this.updateState=()=>{var s,a;let o=this.state,d=this.requiredTransports.map(c=>c.getConnectionState());d.every(c=>c==="connected")?this.state=te.CONNECTED:d.some(c=>c==="failed")?this.state=te.FAILED:d.some(c=>c==="connecting")?this.state=te.CONNECTING:d.every(c=>c==="closed")?this.state=te.CLOSED:d.some(c=>c==="closed")?this.state=te.CLOSING:d.every(c=>c==="new")&&(this.state=te.NEW),o!==this.state&&(this.log.debug("pc state change: from ".concat(te[o]," to ").concat(te[this.state]),this.logContext),(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.log=_e((r=t.loggerName)!==null&&r!==void 0?r:ue.PCManager),this.loggerOptions=t,this.isPublisherConnectionRequired=e!=="subscriber-primary",this.isSubscriberConnectionRequired=e==="subscriber-primary",this.publisher=new Ai(n,t),this._mode=e,e!=="publisher-only"&&(this.subscriber=new Ai(n,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,Fe.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,Fe.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=te.NEW,this.connectionLock=new de,this.remoteOfferLock=new de}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 p(this,void 0,void 0,function*(){var e;if(this.publisher&&this.publisher.getSignallingState()!=="closed"){let t=this.publisher;for(let n of t.getSenders())try{t.canRemoveTrack()&&t.removeTrack(n)}catch(r){this.log.warn("could not removeTrack",Object.assign(Object.assign({},this.logContext),{error:r}))}}yield Promise.all([this.publisher.close(),(e=this.subscriber)===null||e===void 0?void 0:e.close()]),this.updateState()})}triggerIceRestart(){return p(this,void 0,void 0,function*(){this.subscriber&&(this.subscriber.restartingIce=!0),this.needsPublisher&&(yield this.createAndSendPublisherOffer({iceRestart:!0}))})}addIceCandidate(e,t){return p(this,void 0,void 0,function*(){var n;t===Fe.PUBLISHER?yield this.publisher.addIceCandidate(e):yield(n=this.subscriber)===null||n===void 0?void 0:n.addIceCandidate(e)})}createSubscriberAnswerFromOffer(e,t){return p(this,void 0,void 0,function*(){var n,r,s;this.log.debug("received server offer",Object.assign(Object.assign({},this.logContext),{RTCSdpType:e.type,sdp:e.sdp,signalingState:(n=this.subscriber)===null||n===void 0?void 0:n.getSignallingState().toString()}));let 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 n;this.publisher.setConfiguration(e),(n=this.subscriber)===null||n===void 0||n.setConfiguration(e),t&&this.triggerIceRestart()}ensurePCTransportConnection(e,t){return p(this,void 0,void 0,function*(){var n;let r=yield this.connectionLock.lock();try{this.isPublisherConnectionRequired&&this.publisher.getConnectionState()!=="connected"&&this.publisher.getConnectionState()!=="connecting"&&(this.log.debug("negotiation required, start negotiating",this.logContext),this.publisher.negotiate()),yield Promise.all((n=this.requiredTransports)===null||n===void 0?void 0:n.map(s=>this.ensureTransportConnected(s,e,t)))}finally{r()}})}negotiate(e){return p(this,void 0,void 0,function*(){return new pe((t,n)=>{let 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,a=()=>{s||(s=!0,clearTimeout(c),this.publisher.off(kt.OfferAnswered,o),e.signal.removeEventListener("abort",d))},o=l=>{l>r&&(a(),t())},d=()=>{a(),n(new lt("negotiation aborted"))},c=setTimeout(()=>{a(),n(new lt("negotiation timed out"))},this.peerConnectionTimeout);e.signal.addEventListener("abort",d),this.publisher.on(kt.OfferAnswered,o),this.publisher.negotiate(l=>{a(),l instanceof Error?n(l):n(new Error(String(l)))})})})}addPublisherTransceiver(e,t){return this.publisher.addTransceiver(e,t)}addPublisherTransceiverOfKind(e,t){return this.publisher.addTransceiverOfKind(e,t)}getMidForReceiver(e){let n=(this.subscriber?this.subscriber.getTransceivers():this.publisher.getTransceivers()).find(r=>r.receiver===e);return n?.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===Fe.PUBLISHER?this.publisher.getConnectedAddress():e===Fe.SUBSCRIBER?this.publisher.getConnectedAddress():this.requiredTransports[0].getConnectedAddress()}get requiredTransports(){let e=[];return this.isPublisherConnectionRequired&&e.push(this.publisher),this.isSubscriberConnectionRequired&&this.subscriber&&e.push(this.subscriber),e}ensureTransportConnected(e,t){return p(this,arguments,void 0,function(n,r){var s=this;let a=arguments.length>2&&arguments[2]!==void 0?arguments[2]:this.peerConnectionTimeout;return(function*(){if(n.getConnectionState()!=="connected")return new Promise((d,c)=>p(s,void 0,void 0,function*(){let l=()=>{this.log.warn("abort transport connection",this.logContext),re.clearTimeout(u),c(N.cancelled("room connection has been cancelled"))};r?.signal.aborted&&l(),r?.signal.addEventListener("abort",l);let u=re.setTimeout(()=>{r?.signal.removeEventListener("abort",l),c(N.internal("could not establish pc connection"))},a);for(;this.state!==te.CONNECTED;)if(yield ve(50),r?.signal.aborted){c(N.cancelled("room connection has been cancelled"));return}re.clearTimeout(u),r?.signal.removeEventListener("abort",l),d()}))})()})}},qa=typeof MediaRecorder<"u",ws=class{constructor(){throw new Error("MediaRecorder is not available in this environment")}},Ym=qa?MediaRecorder:ws,Es=class extends Ym{constructor(e,t){if(!qa)throw new Error("MediaRecorder is not available in this environment");super(new MediaStream([e.mediaStreamTrack]),t);let n,r,s=()=>r===void 0,a=()=>{this.removeEventListener("dataavailable",n),this.removeEventListener("stop",a),this.removeEventListener("error",o),r?.close(),r=void 0},o=d=>{r?.error(d),this.removeEventListener("dataavailable",n),this.removeEventListener("stop",a),this.removeEventListener("error",o),r=void 0};this.byteStream=new ReadableStream({start:d=>{r=d,n=c=>p(this,void 0,void 0,function*(){let l;if(c.data.arrayBuffer){let 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",n)},cancel:()=>{a()}}),this.addEventListener("stop",a),this.addEventListener("error",o)}};function Xm(){return qa}var Zm=1e3,ep=1e4,Di=class extends _{get sender(){return this._sender}set sender(e){this._sender=e}get constraints(){return this._constraints}get hasPreConnectBuffer(){return!!this.localTrackRecorder}constructor(e,t,n){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=Da(()=>p(this,void 0,void 0,function*(){yield this.pauseUpstream()}),5e3),this.handleTrackUnmuteEvent=()=>p(this,void 0,void 0,function*(){this.debouncedTrackMuteHandler.cancel("unmute"),yield this.resumeUpstream()}),this.handleEnded=()=>{this.isInBackground&&(this.reacquireTrack=!0),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent),this.emit(P.Ended,this)},this.reacquireTrack=!1,this.providedByUser=r,this.muteLock=new de,this.pauseUpstreamLock=new de,this.trackChangeLock=new de,this.trackChangeLock.lock().then(a=>p(this,void 0,void 0,function*(){try{yield this.setMediaStreamTrack(e,!0)}finally{a()}})),this._constraints=e.getConstraints(),n&&(this._constraints=n)}get id(){return this._mediaStreamTrack.id}get dimensions(){if(this.kind!==_.Kind.Video)return;let e=this._mediaStreamTrack.getSettings(),t=e.width,n=e.height;if(t&&n)return{width:t,height:n}}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,n){return p(this,void 0,void 0,function*(){var r;if(e===this._mediaStreamTrack&&!t)return;this._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&&(zt(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=n?!0:!this.isMuted,yield this.resumeUpstream(),this.attachedElements.forEach(a=>{zt(s??e,a)}))})}waitForDimensions(){return p(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:Zm;return(function*(){var n;if(e.kind===_.Kind.Audio)throw new Error("cannot get dimensions for audio tracks");((n=ke())===null||n===void 0?void 0:n.os)==="iOS"&&(yield ve(10));let r=Date.now();for(;Date.now()-r<t;){let s=e.dimensions;if(s)return s;yield ve(50)}throw new qe("unable to get track dimensions after timeout")})()})}setDeviceId(e){return p(this,void 0,void 0,function*(){return this._constraints.deviceId===e&&this._mediaStreamTrack.getSettings().deviceId===Lt(e)?!0:(this._constraints.deviceId=e,this.isMuted?(this.pendingDeviceChange=!0,!0):(yield this.restartTrack(),Lt(e)===this._mediaStreamTrack.getSettings().deviceId))})}getDeviceId(){return p(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===_.Source.ScreenShare)return;let n=e._mediaStreamTrack.getSettings(),r=n.deviceId,s=n.groupId,a=e.kind===_.Kind.Audio?"audioinput":"videoinput";return t?Pe.getInstance().normalizeDeviceId(a,r,s):r})()})}mute(){return p(this,void 0,void 0,function*(){return this.setTrackMuted(!0),this})}unmute(){return p(this,void 0,void 0,function*(){return this.setTrackMuted(!1),this})}replaceTrack(e,t){return p(this,void 0,void 0,function*(){let n=yield this.trackChangeLock.lock();try{if(!this.sender)throw new qe("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{n()}return yield this.onSenderTrackSwapped(),this})}onSenderTrackSwapped(){return p(this,void 0,void 0,function*(){})}restart(e,t){return p(this,void 0,void 0,function*(){this.manuallyStopped=!1;let n=yield this.trackChangeLock.lock();try{e||(e=this._constraints);let r=e,s=r.deviceId,a=r.facingMode,o=wh(e,["deviceId","facingMode"]);this.log.debug("restarting track with constraints",Object.assign(Object.assign({},this.logContext),{constraints:e}));let d={audio:!1,video:!1};this.kind===_.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();let l=(yield navigator.mediaDevices.getUserMedia(d)).getTracks()[0];return this.kind===_.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(P.Restarted,this),this.manuallyStopped&&(this.log.warn("track was stopped during a restart, stopping restarted track",this.logContext),this.stop()),this}finally{n()}})}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?P.Muted:P.Unmuted,this))}get needsReAcquisition(){return this._mediaStreamTrack.readyState!=="live"||this._mediaStreamTrack.muted||!this._mediaStreamTrack.enabled||this.reacquireTrack}handleAppVisibilityChanged(){let e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return p(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),Gd()&&(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 p(this,void 0,void 0,function*(){var e;let 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(P.UpstreamPaused,this);let n=ke();if(n?.name==="Safari"&&tt(n.version,"12.0")<0)throw new Dn("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 p(this,void 0,void 0,function*(){var e;let 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(P.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 p(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 p(this,arguments,void 0,function(t){var n=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return(function*(){var s;let a=yield n.trackChangeLock.lock();try{n.log.debug("setting up processor",n.logContext);let o=document.createElement(n.kind),d={kind:n.kind,track:n._mediaStreamTrack,element:o,audioContext:n.audioContext,localTrack:n};if(yield t.init(d),n.log.debug("processor initialized",n.logContext),n.processor&&(yield n.internalStopProcessor()),n.kind==="unknown")throw TypeError("cannot set processor on track of unknown kind");if(zt(n._mediaStreamTrack,o),o.muted=!0,o.play().catch(c=>{c instanceof DOMException&&c.name==="AbortError"?(n.log.warn("failed to play processor element, retrying",Object.assign(Object.assign({},n.logContext),{error:c})),setTimeout(()=>{o.play().catch(l=>{n.log.error("failed to play processor element",Object.assign(Object.assign({},n.logContext),{err:l}))})},100)):n.log.error("failed to play processor element",Object.assign(Object.assign({},n.logContext),{error:c}))}),n.processor=t,n.processorElement=o,n.processor.processedTrack){for(let c of n.attachedElements)c!==n.processorElement&&r&&(Yt(n._mediaStreamTrack,c),zt(n.processor.processedTrack,c));yield(s=n.sender)===null||s===void 0?void 0:s.replaceTrack(n.processor.processedTrack)}n.emit(P.TrackProcessorUpdate,n.processor)}finally{a()}yield n.onSenderTrackSwapped()})()})}getProcessor(){return this.processor}stopProcessor(){return p(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return(function*(){let n=yield e.trackChangeLock.lock();try{yield e.internalStopProcessor(t)}finally{n()}yield e.onSenderTrackSwapped()})()})}internalStopProcessor(){return p(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return(function*(){var n,r;e.processor&&(e.log.debug("stopping processor",e.logContext),(n=e.processor.processedTrack)===null||n===void 0||n.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(P.TrackProcessorUpdate))})()})}startPreConnectBuffer(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:100;if(!Xm()){this.log.warn("MediaRecorder is not available, cannot start preconnect 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 Es(this,{mimeType:t})}this.localTrackRecorder.start(e),this.autoStopPreConnectBuffer=setTimeout(()=>{this.log.warn("preconnect buffer timed out, stopping recording automatically",this.logContext),this.stopPreConnectBuffer()},ep)}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}},Et=class extends Di{get enhancedNoiseCancellation(){return this.isKrispNoiseFilterEnabled}constructor(e,t){let n=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,_.Kind.Audio,t,n,s),this.stopOnMute=!1,this.isKrispNoiseFilterEnabled=!1,this.monitorSender=()=>p(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=ar(a,this.prevStats)),this.prevStats=a}),this.handleKrispNoiseFilterEnable=()=>{this.isKrispNoiseFilterEnabled=!0,this.log.debug("Krisp noise filter enabled",this.logContext),this.emit(P.AudioTrackFeatureUpdate,this,le.TF_ENHANCED_NOISE_CANCELLATION,!0)},this.handleKrispNoiseFilterDisable=()=>{this.isKrispNoiseFilterEnabled=!1,this.log.debug("Krisp noise filter disabled",this.logContext),this.emit(P.AudioTrackFeatureUpdate,this,le.TF_ENHANCED_NOISE_CANCELLATION,!1)},this.audioContext=r,this.checkForSilence()}mute(){let e=Object.create(null,{mute:{get:()=>super.mute}});return p(this,void 0,void 0,function*(){let t=yield this.muteLock.lock();try{return this.isMuted?(this.log.debug("Track already muted",this.logContext),this):(this.source===_.Source.Microphone&&this.stopOnMute&&!this.isUserProvided&&(this.log.debug("stopping mic track",this.logContext),this._mediaStreamTrack.stop()),yield e.mute.call(this),this)}finally{t()}})}unmute(){let e=Object.create(null,{unmute:{get:()=>super.unmute}});return p(this,void 0,void 0,function*(){let t=yield this.muteLock.lock();try{return this.isMuted?(this.source===_.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 p(this,void 0,void 0,function*(){let t;if(e){let n=Ma({audio:e});typeof n.audio!="boolean"&&(t=n.audio)}yield this.restart(t)})}restart(e,t){let n=Object.create(null,{restart:{get:()=>super.restart}});return p(this,void 0,void 0,function*(){let r=yield n.restart.call(this,e,t);return this.checkForSilence(),r})}startMonitor(){Ce()&&(this.monitorInterval||(this.monitorInterval=setInterval(()=>{this.monitorSender()},Oa)))}setProcessor(e){return p(this,void 0,void 0,function*(){var t;let n=yield this.trackChangeLock.lock();try{if(!He()&&!this.audioContext)throw Error("Audio context needs to be set on LocalAudioTrack in order to enable processors");this.processor&&(yield this.internalStopProcessor());let 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(P.TrackProcessorUpdate,this.processor)}finally{n()}})}setAudioContext(e){this.audioContext=e}getSenderStats(){return p(this,void 0,void 0,function*(){var e;if(!(!((e=this.sender)===null||e===void 0)&&e.getStats))return;let t=yield this.sender.getStats(),n;return t.forEach(r=>{r.type==="outbound-rtp"&&(n={type:"audio",streamId:r.id,packetsSent:r.packetsSent,packetsLost:r.packetsLost,bytesSent:r.bytesSent,timestamp:r.timestamp,roundTripTime:r.roundTripTime,jitter:r.jitter})}),n})}checkForSilence(){return p(this,void 0,void 0,function*(){let e=yield jd(this);return e&&(this.isMuted||this.log.debug("silence detected on local audio track",this.logContext),this.emit(P.AudioSilenceDetected)),e})}};function tp(i,e,t){switch(i.kind){case"audio":return new Et(i,e,!1,void 0,t);case"video":return new an(i,e,!1,t);default:throw new qe("unsupported track type: ".concat(i.kind))}}var np=Object.values(On),ip=Object.values(as),rp=Object.values(Ia),sp=[On.h180,On.h360],ap=[as.h180,as.h360],op=i=>[{scaleResolutionDownBy:2,fps:i.encoding.maxFramerate}].map(t=>{var n,r;return new K(Math.floor(i.width/t.scaleResolutionDownBy),Math.floor(i.height/t.scaleResolutionDownBy),Math.max(15e4,Math.floor(i.encoding.maxBitrate/(Math.pow(t.scaleResolutionDownBy,2)*(((n=i.encoding.maxFramerate)!==null&&n!==void 0?n:30)/((r=t.fps)!==null&&r!==void 0?r:30))))),t.fps,i.encoding.priority)}),Rs=["q","h","f"];function Oi(i,e,t,n){var r,s;let a=n?.videoEncoding;i&&(a=n?.screenShareEncoding);let o=n?.simulcast,d=n?.scalabilityMode,c=n?.videoCodec;if(!a&&!o&&!d||!e||!t)return[{}];a||(a=cp(i,e,t,c),F.debug("using video encoding",a));let l=a.maxFramerate,u=new K(e,t,a.maxBitrate,a.maxFramerate,a.priority);if(d&&je(c)){let T=new Li(d),k=[];if(T.spatial>3)throw new Error("unsupported scalabilityMode: ".concat(d));let S=ke();if(Ln()||He()||S?.name==="Chrome"&&tt(S?.version,"113")<0){let L=T.suffix=="h"?2:3,y=cm(S);for(let b=0;b<T.spatial;b+=1)k.push({rid:Rs[2-b],maxBitrate:a.maxBitrate/Math.pow(L,b),maxFramerate:u.encoding.maxFramerate,scaleResolutionDownBy:y?Math.pow(2,b):void 0});k[0].scalabilityMode=d}else k.push({maxBitrate:a.maxBitrate,maxFramerate:u.encoding.maxFramerate,scalabilityMode:d});return u.encoding.priority&&(k[0].priority=u.encoding.priority,k[0].networkPriority=u.encoding.priority),F.debug("using svc encoding",{encodings:k}),k}if(!o)return[a];let h;i?h=(r=Go(n?.screenShareSimulcastLayers))!==null&&r!==void 0?r:Ho(i,u):h=(s=Go(n?.videoSimulcastLayers))!==null&&s!==void 0?s:Ho(i,u);let m;if(h.length>0){let T=h[0];if(h.length>1){var g=h,f=O(g,2);m=f[1]}let k=Math.max(e,t);if(k>=960&&m)return Or(e,t,[T,m,u],l);if(k>=480)return Or(e,t,[T,u],l)}return Or(e,t,[u])}function Xd(i,e,t){var n,r,s,a;if(!t.backupCodec||t.backupCodec===!0||t.backupCodec.codec===t.videoCodec)return;e!==t.backupCodec.codec&&F.warn("requested a different codec than specified as backup",{serverRequested:e,backup:t.backupCodec.codec}),t.videoCodec=e,t.videoEncoding=t.backupCodec.encoding;let o=i.mediaStreamTrack.getSettings(),d=(n=o.width)!==null&&n!==void 0?n:(r=i.dimensions)===null||r===void 0?void 0:r.width,c=(s=o.height)!==null&&s!==void 0?s:(a=i.dimensions)===null||a===void 0?void 0:a.height;return i.source===_.Source.ScreenShare&&t.simulcast&&(t.simulcast=!1),Oi(i.source===_.Source.ScreenShare,d,c,t)}function cp(i,e,t,n){let r=dp(i,e,t),s=r[0].encoding,a=Math.max(e,t);for(let o=0;o<r.length;o+=1){let d=r[o];if(s=d.encoding,d.width>=a)break}if(n)switch(n){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 dp(i,e,t){if(i)return rp;let n=e>t?e/t:t/e;return Math.abs(n-16/9)<Math.abs(n-4/3)?np:ip}function Ho(i,e){if(i)return op(e);let t=e.width,n=e.height,r=t>n?t/n:n/t;return Math.abs(r-16/9)<Math.abs(r-4/3)?sp:ap}function Or(i,e,t,n){let r=[];if(t.forEach((s,a)=>{if(a>=Rs.length)return;let o=Math.min(i,e),c={rid:Rs[a],scaleResolutionDownBy:Math.max(1,o/Math.min(s.width,s.height)),maxBitrate:s.encoding.maxBitrate},l=n&&s.encoding.maxFramerate?Math.min(n,s.encoding.maxFramerate):s.encoding.maxFramerate;l&&(c.maxFramerate=l);let u=ke(),h=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)}),He()&&Wd()==="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,F.info("Simulcast on iOS React-Native requires all encodings to share the same framerate.")),F.info('Setting framerate of encoding "'.concat((d=o.rid)!==null&&d!==void 0?d:"",'" to ').concat(s)),o.maxFramerate=s)})}return r}function Go(i){if(i)return i.slice().sort((e,t)=>{let n=e.encoding,r=t.encoding;return n.maxBitrate>r.maxBitrate?1:n.maxBitrate<r.maxBitrate?-1:n.maxBitrate===r.maxBitrate&&n.maxFramerate&&r.maxFramerate?n.maxFramerate>r.maxFramerate?1:-1:0})}var Li=class{constructor(e){let 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 lp(i){return i.source===_.Source.ScreenShare||i.constraints.height&&Lt(i.constraints.height)>=1080?"maintain-resolution":"balanced"}var up=5e3,an=class extends Di{get sender(){return this._sender}set sender(e){this._sender=e,this.degradationPreference&&this.setDegradationPreference(this.degradationPreference)}constructor(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,r=arguments.length>3?arguments[3]:void 0;super(e,_.Kind.Video,t,n,r),this.simulcastCodecs=new Map,this.degradationPreference="balanced",this.isCpuConstrained=!1,this.optimizeForPerformance=!1,this.monitorSender=()=>p(this,void 0,void 0,function*(){if(!this.sender){this._currentBitrate=0;return}let s;try{s=yield this.getSenderStats()}catch(d){this.log.error("could not get video sender stats",Object.assign(Object.assign({},this.logContext),{error:d}));return}let 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(P.CpuConstrained)),this.prevStats){let d=0;a.forEach((c,l)=>{var u;let h=(u=this.prevStats)===null||u===void 0?void 0:u.get(l);d+=ar(c,h)}),this._currentBitrate=d}this.prevStats=a}),this.senderLock=new de}get isSimulcast(){return!!(this.sender&&this.sender.getParameters().encodings.length>1)}startMonitor(e){var t;if(this.signalClient=e,!Ce())return;let n=(t=this.sender)===null||t===void 0?void 0:t.getParameters();n&&(this.encodings=n.encodings),!this.monitorInterval&&(this.monitorInterval=setInterval(()=>{this.monitorSender()},Oa))}stop(){this._mediaStreamTrack.getConstraints(),this.simulcastCodecs.forEach(e=>{e.mediaStreamTrack.stop()}),super.stop()}pauseUpstream(){let e=Object.create(null,{pauseUpstream:{get:()=>super.pauseUpstream}});return p(this,void 0,void 0,function*(){var t,n,r,s,a;yield e.pauseUpstream.call(this);try{for(var o=!0,d=Be(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){n={error:l}}finally{try{!o&&!t&&(r=d.return)&&(yield r.call(d))}finally{if(n)throw n.error}}})}resumeUpstream(){let e=Object.create(null,{resumeUpstream:{get:()=>super.resumeUpstream}});return p(this,void 0,void 0,function*(){var t,n,r,s,a;yield e.resumeUpstream.call(this);try{for(var o=!0,d=Be(this.simulcastCodecs.values()),c;c=yield d.next(),t=c.done,!t;o=!0){s=c.value,o=!1;let l=s;yield(a=l.sender)===null||a===void 0?void 0:a.replaceTrack(l.mediaStreamTrack)}}catch(l){n={error:l}}finally{try{!o&&!t&&(r=d.return)&&(yield r.call(d))}finally{if(n)throw n.error}}})}mute(){let e=Object.create(null,{mute:{get:()=>super.mute}});return p(this,void 0,void 0,function*(){let t=yield this.muteLock.lock();try{return this.isMuted?(this.log.debug("Track already muted",this.logContext),this):(this.source===_.Source.Camera&&!this.isUserProvided&&(this.log.debug("stopping camera track",this.logContext),this._mediaStreamTrack.stop()),yield e.mute.call(this),this)}finally{t()}})}unmute(){let e=Object.create(null,{unmute:{get:()=>super.unmute}});return p(this,void 0,void 0,function*(){let t=yield this.muteLock.lock();try{return this.isMuted?(this.source===_.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(let t of this.simulcastCodecs.values())t.mediaStreamTrack.enabled=!e}getSenderStats(){return p(this,void 0,void 0,function*(){var e;if(!(!((e=this.sender)===null||e===void 0)&&e.getStats))return[];let t=[],n=yield this.sender.getStats();return n.forEach(r=>{var s;if(r.type==="outbound-rtp"){let 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=n.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){let t=[];for(let n=Re.LOW;n<=Re.HIGH;n+=1)t.push(new wa({quality:n,enabled:n<=e}));this.log.debug("setting publishing quality. max quality ".concat(e),this.logContext),this.setPublishingLayers(je(this.codec),t)}restartTrack(e){return p(this,void 0,void 0,function*(){var t,n,r,s,a;let o;if(e){let u=Ma({video:e});typeof u.video!="boolean"&&(o=u.video)}yield this.restart(o),this.isCpuConstrained=!1;try{for(var d=!0,c=Be(this.simulcastCodecs.values()),l;l=yield c.next(),t=l.done,!t;d=!0){s=l.value,d=!1;let 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){n={error:u}}finally{try{!d&&!t&&(r=c.return)&&(yield r.call(c))}finally{if(n)throw n.error}}yield this.onSenderTrackSwapped()})}onSenderTrackSwapped(){return p(this,void 0,void 0,function*(){yield this.refreshSenderEncodings()})}refreshSenderEncodings(){return p(this,void 0,void 0,function*(){var e;if(!this.sender||!this.publishOptions||this.optimizeForPerformance)return;let 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;let s=this.source===_.Source.ScreenShare,a=Oi(s,r.width,r.height,Object.assign({},this.publishOptions));yield this.applyEncodingsToSender(this.sender,a),this.encodings=a,this.lastEncodedDimensions=r;for(let o of this.simulcastCodecs){var n=O(o,2);let d=n[0],c=n[1];if(!c.sender||((e=c.sender.transport)===null||e===void 0?void 0:e.state)==="closed"||!Bd(d))continue;let l=Object.assign({},this.publishOptions),u=Xd(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 p(this,void 0,void 0,function*(){let n=e.getParameters();!n.encodings||n.encodings.length!==t.length||(n.encodings.forEach((r,s)=>{if(r.active===!1)return;let 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:n.encodings})),yield e.setParameters(n))})}setProcessor(e){let t=Object.create(null,{setProcessor:{get:()=>super.setProcessor}});return p(this,arguments,void 0,function(n){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,n,s),!((l=r.processor)===null||l===void 0)&&l.processedTrack)try{for(var h=!0,m=Be(r.simulcastCodecs.values()),g;g=yield m.next(),a=g.done,!a;h=!0)c=g.value,h=!1,yield(u=c.sender)===null||u===void 0?void 0:u.replaceTrack(r.processor.processedTrack)}catch(f){o={error:f}}finally{try{!h&&!a&&(d=m.return)&&(yield d.call(m))}finally{if(o)throw o.error}}})()})}setDegradationPreference(e){return p(this,void 0,void 0,function*(){if(this.degradationPreference=e,this.sender)try{this.log.debug("setting degradationPreference to ".concat(e),this.logContext);let t=this.sender.getParameters();t.degradationPreference=e,this.sender.setParameters(t)}catch(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}let n={codec:e,mediaStreamTrack:this.mediaStreamTrack.clone(),sender:void 0,encodings:t};return this.simulcastCodecs.set(e,n),n}setSimulcastTrackSender(e,t){let n=this.simulcastCodecs.get(e);n&&(n.sender=t,setTimeout(()=>{this.subscribedCodecs&&this.setPublishingCodecs(this.subscribedCodecs)},up))}setPublishingCodecs(e){return p(this,void 0,void 0,function*(){var t,n,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(je(e[0].codec),e[0].qualities),[];this.subscribedCodecs=e;let c=[];try{for(t=!0,n=Be(e);r=yield n.next(),s=r.done,!s;t=!0){d=r.value,t=!1;let l=d;if(!this.codec||this.codec===l.codec)yield this.setPublishingLayers(je(l.codec),l.qualities);else{let 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(let 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 Ko(u.sender,u.encodings,l.qualities,this.senderLock,je(l.codec),this.log,this.logContext))}}}catch(l){a={error:l}}finally{try{!t&&!s&&(o=n.return)&&(yield o.call(n))}finally{if(a)throw a.error}}return c})}setPublishingLayers(e,t){return p(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 Ko(this.sender,this.encodings,t,this.senderLock,e,this.log,this.logContext))})}prioritizePerformance(){return p(this,void 0,void 0,function*(){if(!this.sender)throw new Error("sender not found");let e=yield this.senderLock.lock();try{this.optimizeForPerformance=!0;let t=this.sender.getParameters();t.encodings=t.encodings.map((n,r)=>{var s;return Object.assign(Object.assign({},n),{active:r===0,scaleResolutionDownBy:Math.max(1,Math.ceil(((s=this.mediaStreamTrack.getSettings().height)!==null&&s!==void 0?s:360)/360)),scalabilityMode:r===0&&je(this.codec)?"L1T3":void 0,maxFramerate:r===0?15:0,maxBitrate:r===0?n.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(){let e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return p(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),Gd()&&this.isInBackground&&this.source===_.Source.Camera&&(this._mediaStreamTrack.enabled=!1)})}};function Ko(i,e,t,n,r,s,a){return p(this,void 0,void 0,function*(){let o=yield n.lock();s.debug("setPublishingLayersForSender",Object.assign(Object.assign({},a),{sender:i,qualities:t,senderEncodings:e}));try{let d=i.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(m=>m.enabled)&&t.forEach(m=>m.enabled=!0),c.forEach((h,m)=>{var g;let f=(g=h.rid)!==null&&g!==void 0?g:"";f===""&&(f="q");let T=Zd(f),k=t.find(S=>S.quality===T);k&&h.active!==k.enabled&&(l=!0,h.active=k.enabled,s.debug("setting layer ".concat(k.quality," to ").concat(h.active?"enabled":"disabled"),a),Ft()&&(k.enabled?(h.scaleResolutionDownBy=e[m].scaleResolutionDownBy,h.maxBitrate=e[m].maxBitrate,h.maxFrameRate=e[m].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 i.setParameters(d))}finally{o()}})}function Zd(i){switch(i){case"f":return Re.HIGH;case"h":return Re.MEDIUM;case"q":return Re.LOW;default:return Re.HIGH}}function Wo(i,e,t,n){if(!t)return[new Tt({quality:Re.HIGH,width:i,height:e,bitrate:0,ssrc:0})];if(n){let r=t[0].scalabilityMode,s=new Li(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 Tt({quality:Math.min(Re.HIGH,s.spatial-1)-c,width:Math.ceil(i/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;let d=(s=r.scaleResolutionDownBy)!==null&&s!==void 0?s:1,c=Zd((a=r.rid)!==null&&a!==void 0?a:"");return new Tt({quality:c,width:Math.ceil(i/d),height:Math.ceil(e/d),bitrate:(o=r.maxBitrate)!==null&&o!==void 0?o:0,ssrc:0})})}var zo="_lossy",Jo="_reliable",$o="_data_track",hp=2*1e3,Lr="leave-reconnect",mp=3e4,pp=8*1024,fp=256*1024,gp=3,vp=3,Me;(function(i){i[i.New=0]="New",i[i.Connected=1]="Connected",i[i.Disconnected=2]="Disconnected",i[i.Reconnecting=3]="Reconnecting",i[i.Closed=4]="Closed"})(Me||(Me={}));var U;(function(i){i[i.RELIABLE=0]="RELIABLE",i[i.LOSSY=1]="LOSSY",i[i.DATA_TRACK_LOSSY=2]="DATA_TRACK_LOSSY"})(U||(U={}));var Qo=64e3,Ps=class extends Ee.EventEmitter{get isClosed(){return this._isClosed}get isNewlyCreated(){return this._isNewlyCreated}get pendingReconnect(){return!!this.reconnectTimeout}constructor(e){var t;super(),this.options=e,this.rtcConfig={},this.peerConnectionTimeout=Ba.peerConnectionTimeout,this.fullReconnectOnNext=!1,this.latestRemoteOfferId=0,this.subscriberPrimary=!1,this.pcState=Me.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=F,this.reliableDataSequence=1,this.reliableMessageBuffer=new Mi,this.reliableReceivedState=new Cs(mp),this.lossyDataStatCurrentBytes=0,this.lossyDataStatByterate=0,this.lossyDataDropCount=0,this.midToTrackId={},this.isWaitingForNetworkReconnect=!1,this.bufferStatusLowClosingFuture=new ce,this.handleDataChannel=n=>p(this,[n],void 0,function(r){var s=this;let a=r.channel;return(function*(){if(!a)return;let o;if(a.label===Jo)s.reliableDCSub=a,o=s.handleDataMessage;else if(a.label===zo)s.lossyDCSub=a,o=s.handleDataMessage;else if(a.label===$o)s.dataTrackDCSub=a,o=s.handleDataTrackMessage;else return;s.log.debug("on data channel ".concat(a.id,", ").concat(a.label)),a.onmessage=o})()}),this.handleDataMessage=n=>p(this,void 0,void 0,function*(){var r,s,a,o,d;let c=yield this.dataProcessLock.lock();try{let l;if(n.data instanceof ArrayBuffer)l=n.data;else if(n.data instanceof Blob)l=yield n.data.arrayBuffer();else{this.log.error("unsupported data type",{data:n.data});return}let u=ge.fromBinary(new Uint8Array(l));if(u.sequence>0&&u.participantSid!==""){let 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(R.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}let 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),m=Dc.fromBinary(h.payload),g=new ge({value:m.value,participantIdentity:u.participantIdentity,participantSid:u.participantSid});((o=g.value)===null||o===void 0?void 0:o.case)==="user"&&Yo(g,g.value.value),this.emit(R.DataPacketReceived,g,u.value.value.encryptionType)}else((d=u.value)===null||d===void 0?void 0:d.case)==="user"&&Yo(u,u.value.value),this.emit(R.DataPacketReceived,u,J.NONE)}finally{c()}}),this.handleDataTrackMessage=n=>p(this,void 0,void 0,function*(){let r;if(n.data instanceof ArrayBuffer)r=n.data;else if(n.data instanceof Blob)r=yield n.data.arrayBuffer();else{this.log.error("unsupported data type",{data:n.data});return}this.emit("dataTrackPacketReceived",new Uint8Array(r))}),this.handleDataError=n=>{if(this._isClosed)return;let s=n.currentTarget.maxRetransmits===0?"lossy":"reliable";if(typeof RTCErrorEvent<"u"&&n instanceof RTCErrorEvent&&n.error){let a=n.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:n})},this.handleDataChannelClose=n=>()=>{var r;!this._isClosed&&((r=this.pcManager)===null||r===void 0?void 0:r.publisher.getConnectionState())==="connected"&&this.log.error("publisher data channel '".concat(U[n],"' closed unexpectedly"),this.logContext)},this.handleBufferedAmountLow=n=>{this.updateAndEmitDCBufferStatus(n)},this.handleDisconnect=(n,r)=>{if(this._isClosed)return;this.log.warn("".concat(n," disconnected")),this.reconnectAttempts===0&&(this.reconnectStart=Date.now());let s=d=>{this.log.warn("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(d,"ms. giving up")),this.emit(R.Disconnected),this.close()},a=Date.now()-this.reconnectStart,o=this.getNextRetryDelay({elapsedMs:a,retryCount:this.reconnectAttempts});if(o===null){s(a);return}n===Lr&&(o=0),this.log.debug("reconnecting in ".concat(o,"ms")),this.clearReconnectTimeout(),this.token&&this.emit(R.TokenRefreshed,this.token),this.reconnectTimeout=re.setTimeout(()=>this.attemptReconnect(r).finally(()=>this.reconnectTimeout=void 0),o)},this.waitForRestarted=()=>new Promise((n,r)=>{this.pcState===Me.Connected&&n();let s=()=>{this.off(R.Disconnected,a),n()},a=()=>{this.off(R.Restarted,s),r()};this.once(R.Restarted,s),this.once(R.Disconnected,a)}),this.updateAndEmitDCBufferStatus=n=>{if(n===U.RELIABLE){let s=this.dataChannelForKind(n);s&&this.reliableMessageBuffer.alignBufferedAmount(s.bufferedAmount)}let r=this.isBufferStatusLow(n);typeof r<"u"&&r!==this.dcBufferStatus.get(n)&&(this.dcBufferStatus.set(n,r),this.emit(R.DCBufferStatusChanged,r,n))},this.isBufferStatusLow=n=>{let r=this.dataChannelForKind(n);if(r)return r.bufferedAmount<=r.bufferedAmountLowThreshold},this.onRtpMapAvailable=n=>{let r=new Map;n.forEach(s=>{let a=s.codec.toLowerCase();mm(a)&&r.set(s.payload,a)}),this.emit(R.RTPVideoMapUpdate,r)},this.handleBrowserOnLine=()=>p(this,void 0,void 0,function*(){!this.url||!(yield fetch(Nn(this.url),{method:"HEAD"}).then(r=>r.ok).catch(()=>!1))||(this.log.info("detected network reconnected"),(this.client.currentState===W.RECONNECTING||this.isWaitingForNetworkReconnect&&this.client.currentState===W.CONNECTED)&&(this.clearReconnectTimeout(),this.attemptReconnect(Rt.RR_SIGNAL_DISCONNECTED),this.isWaitingForNetworkReconnect=!1))}),this.handleBrowserOffline=()=>p(this,void 0,void 0,function*(){if(this.url)try{yield Promise.race([fetch(Nn(this.url),{method:"HEAD"}),ve(4e3).then(()=>Promise.reject())])}catch{window.navigator.onLine===!1&&(this.log.info("detected network interruption"),this.isWaitingForNetworkReconnect=!0)}}),this.log=_e((t=e.loggerName)!==null&&t!==void 0?t:ue.Engine,()=>this.logContext),this.loggerOptions={loggerName:e.loggerName,loggerContextCb:()=>this.logContext},this.client=new jn(void 0,this.loggerOptions),this.client.signalLatency=this.options.expSignalLatency,this.reconnectPolicy=this.options.reconnectPolicy,this.closingLock=new de,this.dataProcessLock=new de,this.dcBufferStatus=new Map([[U.RELIABLE,!0],[U.LOSSY,!0],[U.DATA_TRACK_LOSSY,!0]]),this.client.onParticipantUpdate=n=>this.emit(R.ParticipantUpdate,n),this.client.onConnectionQuality=n=>this.emit(R.ConnectionQualityUpdate,n),this.client.onRoomUpdate=n=>this.emit(R.RoomUpdate,n),this.client.onSubscriptionError=n=>this.emit(R.SubscriptionError,n),this.client.onSubscriptionPermissionUpdate=n=>this.emit(R.SubscriptionPermissionUpdate,n),this.client.onSpeakersChanged=n=>this.emit(R.SpeakersChanged,n),this.client.onStreamStateUpdate=n=>this.emit(R.StreamStateChanged,n),this.client.onRequestResponse=n=>this.emit(R.SignalRequestResponse,n),this.client.onParticipantUpdate=n=>this.emit(R.ParticipantUpdate,n),this.client.onJoined=n=>this.emit(R.Joined,n),this.on(R.Closing,()=>{var n,r;(r=(n=this.bufferStatusLowClosingFuture).reject)===null||r===void 0||r.call(n,new $("engine closed"))}),this.bufferStatusLowClosingFuture.promise.catch(()=>{})}get logContext(){var e,t,n,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=(n=this.latestJoinResponse)===null||n===void 0?void 0:n.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,n,r){return p(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,m;c._isNewlyCreated=!1,c.url=s,c.token=a,c.signalOpts=o,c.maxJoinAttempts=o.maxRetries;try{c.joinAttempts+=1,c.setupSignalClientCallbacks();let g=!l&&Tm(),f;if(g){c.pcManager||(yield c.configure(),c.applyInitialPublisherLayout());let S=yield(u=c.pcManager)===null||u===void 0?void 0:u.publisher.createInitialOffer();S&&(f=Mt(S.offer,S.offerId))}if(d?.aborted)throw N.cancelled("Connection aborted");if(!l&&c.shouldFailOnV1Path)throw c.shouldFailOnV1Path=!1,N.serviceNotFound("Simulated v1 path failure","v0-rtc");let T=yield c.client.join(s,a,o,d,l,f);c._isClosed=!1,c.latestJoinResponse=T,c.participantSid=(h=T.participant)===null||h===void 0?void 0:h.sid,c.subscriberPrimary=T.subscriberPrimary,g?(m=c.pcManager)===null||m===void 0||m.updateConfiguration(c.makeRTCConfiguration(T)):(c.pcManager||(yield c.configure(T,!l),l||c.applyInitialPublisherLayout()),(!c.subscriberPrimary||T.fastPublish)&&c.negotiate().catch(S=>{c.log.error(S)})),c.registerOnLineListener(),c.clientConfiguration=T.clientConfiguration,c.emit(R.SignalConnected,T);let k=T.serverInfo;return k||(k={version:T.serverVersion,region:T.serverRegion}),c.log.info("connected to Livekit Server ".concat(Object.entries(k).map(S=>{let L=O(S,2),y=L[0],b=L[1];return"".concat(y,": ").concat(b)}).join(", "))),{joinResponse:T,serverInfo:k}}catch(g){if(g instanceof N){if(g.reason===z.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(g.reason===z.ServiceNotFound)return c.log.warn("Initial connection failed: ".concat(g.message," \u2013 Retrying")),c.pcManager&&(c.pcManager.onStateChange=void 0,yield c.cleanupPeerConnections()),c.join(s,a,o,d,!0)}throw g}})()})}close(){return p(this,void 0,void 0,function*(){let e=yield this.closingLock.lock();if(this.isClosed){e();return}try{this._isClosed=!0,this.joinAttempts=0,this.emit(R.Closing),this.removeAllListeners(),this.deregisterOnLineListener(),this.clearPendingReconnect(),this.cleanupLossyDataStats(),yield this.cleanupPeerConnections(),yield this.cleanupClient()}finally{e()}})}cleanupPeerConnections(){return p(this,void 0,void 0,function*(){var e;let t=n=>{n&&(n.onbufferedamountlow=null,n.onclose=null,n.onclosing=null,n.onerror=null,n.onmessage=null,n.onopen=null,n.close())};t(this.lossyDC),t(this.lossyDCSub),t(this.reliableDC),t(this.reliableDCSub),t(this.dataTrackDC),t(this.dataTrackDCSub),yield(e=this.pcManager)===null||e===void 0?void 0:e.close(),this.pcManager=void 0,this.lossyDC=void 0,this.lossyDCSub=void 0,this.reliableDC=void 0,this.reliableDCSub=void 0,this.dataTrackDC=void 0,this.dataTrackDCSub=void 0,this.reliableMessageBuffer=new Mi,this.reliableDataSequence=1,this.reliableReceivedState.clear()})}cleanupLossyDataStats(){this.lossyDataStatByterate=0,this.lossyDataStatCurrentBytes=0,this.lossyDataStatInterval&&(clearInterval(this.lossyDataStatInterval),this.lossyDataStatInterval=void 0),this.lossyDataDropCount=0}cleanupClient(){return p(this,void 0,void 0,function*(){yield this.client.close(),this.client.resetCallbacks();for(let e of Object.keys(this.pendingTrackResolvers))this.pendingTrackResolvers[e].reject();this.pendingTrackResolvers={}})}addTrack(e){if(this.pendingTrackResolvers[e.cid])throw new qe("a track with the same ID has already been published");return new Promise((t,n)=>{let r=setTimeout(()=>{delete this.pendingTrackResolvers[e.cid],n(N.timeout("publication of local track timed out, no response from server"))},1e4);this.pendingTrackResolvers[e.cid]={resolve:s=>{clearTimeout(r),t(s)},reject:()=>{clearTimeout(r),n(new Error("Cancelled publication by calling unpublish"))}},this.client.sendAddTrack(e)})}removeTrack(e){if(e.track&&this.pendingTrackResolvers[e.track.id]){let 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.reliableDCSub)===null||e===void 0?void 0:e.readyState}getConnectedServerAddress(){return p(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 p(this,void 0,void 0,function*(){var n;if(!(this.pcManager&&this.pcManager.currentState!==te.NEW)){if(e){this.participantSid=(n=e.participant)===null||n===void 0?void 0:n.sid;let r=this.makeRTCConfiguration(e);this.pcManager=new xi(t?"publisher-only":e.subscriberPrimary?"subscriber-primary":"publisher-primary",this.loggerOptions,r)}else{let r=this.makeRTCConfiguration();this.pcManager=new xi("publisher-only",this.loggerOptions,r)}this.emit(R.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)=>p(this,void 0,void 0,function*(){if(this.log.debug("primary PC state changed ".concat(r)),["closed","disconnected","failed"].includes(s)&&(this.publisherConnectionPromise=void 0),r===te.CONNECTED){let c=this.pcState===Me.New;this.pcState=Me.Connected,c&&this.emit(R.Connected,this.latestJoinResponse)}else r===te.FAILED&&(this.pcState===Me.Connected||this.pcState===Me.Reconnecting)&&(this.pcState=Me.Disconnected,this.handleDisconnect("peerconnection failed",a==="failed"?Rt.RR_SUBSCRIBER_FAILED:Rt.RR_PUBLISHER_FAILED));let o=this.client.isDisconnected||this.client.currentState===W.RECONNECTING,d=[te.FAILED,te.CLOSING,te.CLOSED].includes(r);o&&d&&!this._isClosed&&this.emit(R.Offline)}),this.pcManager.onTrack=r=>{r.streams.length!==0&&this.emit(R.MediaTrackAdded,r.track,r.streams[0],r.receiver)}}})}setupSignalClientCallbacks(){this.client.onAnswer=(e,t,n)=>p(this,void 0,void 0,function*(){this.pcManager&&(this.log.debug("received server answer",{RTCSdpType:e.type,sdp:e.sdp,midToTrackId:n}),this.midToTrackId=n,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,n)=>p(this,void 0,void 0,function*(){if(this.latestRemoteOfferId=t,!this.pcManager)return;this.midToTrackId=n;let 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}let n=this.pendingTrackResolvers[e.cid].resolve;delete this.pendingTrackResolvers[e.cid],n(e.track)},this.client.onLocalTrackUnpublished=e=>{this.emit(R.LocalTrackUnpublished,e)},this.client.onLocalTrackSubscribed=e=>{this.emit(R.LocalTrackSubscribed,e)},this.client.onTokenRefresh=e=>{this.token=e,this.emit(R.TokenRefreshed,e)},this.client.onRemoteMuteChanged=(e,t)=>{this.emit(R.RemoteMute,e,t)},this.client.onSubscribedQualityUpdate=e=>{this.emit(R.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(R.RoomMoved,e)},this.client.onMediaSectionsRequirement=e=>{this.addMediaSections(e.numAudios,e.numVideos),this.negotiate()},this.client.onPublishDataTrackResponse=e=>{this.emit(R.PublishDataTrackResponse,e)},this.client.onUnPublishDataTrackResponse=e=>{this.emit(R.UnPublishDataTrackResponse,e)},this.client.onDataTrackSubscriberHandles=e=>{this.emit(R.DataTrackSubscriberHandles,e)},this.client.onClose=()=>{this.handleDisconnect("signal",Rt.RR_SIGNAL_DISCONNECTED)},this.client.onLeave=e=>{switch(this.log.info("client leave request received (action=".concat(e?.action,")"),{reason:e?.reason}),e.regions&&(this.log.debug("updating regions"),this.emit(R.ServerRegionsReported,e.regions)),e.action){case $t.DISCONNECT:this.emit(R.Disconnected,e?.reason),this.close();break;case $t.RECONNECT:this.fullReconnectOnNext=!0,this.handleDisconnect(Lr);break;case $t.RESUME:this.handleDisconnect(Lr)}}}makeRTCConfiguration(e){var t;let n=Object.assign({},this.rtcConfig);if((((t=this.signalOpts)===null||t===void 0?void 0:t.e2eeEnabled)||this.frameMetadataWorker&&!Un())&&xa()&&(this.log.debug("E2EE - setting up transports with insertable streams"),n.encodedInsertableStreams=!0),n.sdpSemantics="unified-plan",n.continualGatheringPolicy="gather_continually",!e)return n;if(e.iceServers&&!n.iceServers){let s=[];e.iceServers.forEach(a=>{let o={urls:a.urls};a.username&&(o.username=a.username),a.credential&&(o.credential=a.credential),s.push(o)}),n.iceServers=s}return e.clientConfiguration&&e.clientConfiguration.forceRelay===Mn.ENABLED&&(n.iceTransportPolicy="relay"),n}applyInitialPublisherLayout(){this.createDataChannels(),He()||this.addMediaSections(gp,vp)}addMediaSections(e,t){var n,r;let s={direction:"recvonly"};for(let a=0;a<e;a++)(n=this.pcManager)===null||n===void 0||n.addPublisherTransceiverOfKind("audio",s);for(let a=0;a<t;a++)(r=this.pcManager)===null||r===void 0||r.addPublisherTransceiverOfKind("video",s)}createDataChannels(){this.pcManager&&(this.lossyDC&&(this.lossyDC.onmessage=null,this.lossyDC.onerror=null,this.lossyDC.onclose=null),this.reliableDC&&(this.reliableDC.onmessage=null,this.reliableDC.onerror=null,this.reliableDC.onclose=null),this.dataTrackDC&&(this.dataTrackDC.onmessage=null,this.dataTrackDC.onerror=null,this.dataTrackDC.onclose=null),this.lossyDC=this.pcManager.createPublisherDataChannel(zo,{ordered:!1,maxRetransmits:0}),this.reliableDC=this.pcManager.createPublisherDataChannel(Jo,{ordered:!0}),this.dataTrackDC=this.pcManager.createPublisherDataChannel($o,{ordered:!1,maxRetransmits:0}),this.lossyDC.onmessage=this.handleDataMessage,this.reliableDC.onmessage=this.handleDataMessage,this.dataTrackDC.onmessage=this.handleDataTrackMessage,this.lossyDC.onerror=this.handleDataError,this.reliableDC.onerror=this.handleDataError,this.dataTrackDC.onerror=this.handleDataError,this.lossyDC.onclose=this.handleDataChannelClose(U.LOSSY),this.reliableDC.onclose=this.handleDataChannelClose(U.RELIABLE),this.dataTrackDC.onclose=this.handleDataChannelClose(U.DATA_TRACK_LOSSY),this.lossyDC.bufferedAmountLowThreshold=65535,this.reliableDC.bufferedAmountLowThreshold=65535,this.dataTrackDC.bufferedAmountLowThreshold=65535,this.lossyDC.onbufferedamountlow=()=>this.handleBufferedAmountLow(U.LOSSY),this.reliableDC.onbufferedamountlow=()=>this.handleBufferedAmountLow(U.RELIABLE),this.dataTrackDC.onbufferedamountlow=()=>this.handleBufferedAmountLow(U.DATA_TRACK_LOSSY),this.cleanupLossyDataStats(),this.lossyDataStatInterval=setInterval(()=>{this.lossyDataStatByterate=this.lossyDataStatCurrentBytes,this.lossyDataStatCurrentBytes=0;let e=this.dataChannelForKind(U.LOSSY);if(e){let t=this.lossyDataStatByterate/10;e.bufferedAmountLowThreshold=Math.min(Math.max(t,pp),fp)}},1e3))}createSender(e,t,n){return p(this,void 0,void 0,function*(){let r;if(ds())r=yield this.createTransceiverRTCRtpSender(e,t,n);else if(ls())this.log.warn("using add-track fallback"),r=yield this.createRTCRtpSender(e.mediaStreamTrack);else throw new $("Required webRTC APIs not supported on this device");return this.setupFrameMetadataSender(r,t),r})}createSimulcastSender(e,t,n,r){return p(this,void 0,void 0,function*(){let s;if(ds())s=yield this.createSimulcastTransceiverSender(e,t,n,r);else if(ls())this.log.debug("using add-track fallback"),s=yield this.createRTCRtpSender(e.mediaStreamTrack);else throw new $("Cannot stream on this device");return s&&this.setupFrameMetadataSender(s,n),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 n,r,s;let a=this.frameMetadataWorker;if(!a||!((n=this.signalOpts)===null||n===void 0)&&n.e2eeEnabled)return;let o=(r=t.frameMetadata)!==null&&r!==void 0?r:t.packetTrailer,d=Ei(o);if(Un()){d&&(e.transform=new RTCRtpScriptTransform(a,{kind:"encode",packetTrailer:o}));return}if(!Fn((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}let 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,n){return p(this,void 0,void 0,function*(){if(!this.pcManager)throw new $("publisher is closed");let r=[];e.mediaStream&&r.push(e.mediaStream),ht(e)&&(e.codec=t.videoCodec);let s={direction:"sendonly",streams:r};return n&&(s.sendEncodings=n),(yield this.pcManager.addPublisherTransceiver(e.mediaStreamTrack,s)).sender})}createSimulcastTransceiverSender(e,t,n,r){return p(this,void 0,void 0,function*(){if(!this.pcManager)throw new $("publisher is closed");let s={direction:"sendonly"};r&&(s.sendEncodings=r);let a=yield this.pcManager.addPublisherTransceiver(t.mediaStreamTrack,s);if(n.videoCodec)return e.setSimulcastTrackSender(n.videoCodec,a.sender),a.sender})}createRTCRtpSender(e){return p(this,void 0,void 0,function*(){if(!this.pcManager)throw new $("publisher is closed");return this.pcManager.addPublisherTrack(e)})}attemptReconnect(e){return p(this,void 0,void 0,function*(){var t,n,r;if(!this._isClosed){if(this.attemptingReconnect){this.log.warn("already attempting reconnect, returning early");return}(((t=this.clientConfiguration)===null||t===void 0?void 0:t.resumeConnection)===Mn.DISABLED||((r=(n=this.pcManager)===null||n===void 0?void 0:n.currentState)!==null&&r!==void 0?r:te.NEW)===te.NEW)&&(this.fullReconnectOnNext=!0);try{this.attemptingReconnect=!0,this.fullReconnectOnNext?yield this.restartConnection():yield this.resumeConnection(e),this.clearPendingReconnect(),this.fullReconnectOnNext=!1}catch(s){this.reconnectAttempts+=1;let a=!0;s instanceof $?(this.log.debug("received unrecoverable error",{error:s}),a=!1):s instanceof vt||(this.fullReconnectOnNext=!0),a?this.handleDisconnect("reconnect",Rt.RR_UNKNOWN):(this.log.info("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(Date.now()-this.reconnectStart,"ms. giving up")),this.emit(R.Disconnected),yield this.close())}finally{this.attemptingReconnect=!1}}})}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 p(this,void 0,void 0,function*(){var t,n,r;try{if(!this.url||!this.token)throw new $("could not reconnect, url or token not saved");this.log.info("reconnecting, attempt: ".concat(this.reconnectAttempts)),this.emit(R.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 vt;s=(yield this.join(e??this.url,this.token,this.signalOpts,void 0,!this.options.singlePeerConnection)).joinResponse}catch(a){throw a instanceof N&&a.reason===z.NotAllowed?new $("could not reconnect, token might be expired"):new vt}if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(this.client.setReconnected(),this.emit(R.SignalRestarted,s),yield this.waitForPCReconnected(),this.client.currentState!==W.CONNECTED)throw new vt("Signal connection got severed during reconnect");(t=this.regionStrategy)===null||t===void 0||t.resetAttempts(),this.emit(R.Restarted)}catch(s){let a=yield(n=this.regionStrategy)===null||n===void 0?void 0:n.getNextUrl();if(a){yield this.restartConnection(a);return}else throw(r=this.regionStrategy)===null||r===void 0||r.resetAttempts(),s}})}resumeConnection(e){return p(this,void 0,void 0,function*(){var t;if(!this.url||!this.token)throw new $("could not reconnect, url or token not saved");if(!this.pcManager)throw new $("publisher and subscriber connections unset");this.log.info("resuming signal connection, attempt ".concat(this.reconnectAttempts)),this.emit(R.Resuming);let n;try{this.setupSignalClientCallbacks(),n=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 N&&r.reason===z.NotAllowed?new $("could not reconnect, token might be expired"):r instanceof N&&r.reason===z.LeaveRequest?r:new vt(s)}if(this.emit(R.SignalResumed),n){let r=this.makeRTCConfiguration(n);this.pcManager.updateConfiguration(r),this.latestJoinResponse&&(this.latestJoinResponse.serverInfo=n.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!==W.CONNECTED)throw new vt("Signal connection got severed during reconnect");this.client.setReconnected(),((t=this.reliableDC)===null||t===void 0?void 0:t.readyState)==="open"&&this.reliableDC.id===null&&this.createDataChannels(),n?.lastMessageSeq&&this.resendReliableMessagesForResume(n.lastMessageSeq),this.emit(R.Resumed)})}waitForPCInitialConnection(e,t){return p(this,void 0,void 0,function*(){if(!this.pcManager)throw new $("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(t,e)})}waitForPCReconnected(){return p(this,void 0,void 0,function*(){this.pcState=Me.Reconnecting,this.log.debug("waiting for peer connection to reconnect");try{if(yield ve(hp),!this.pcManager)throw new $("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(void 0,this.peerConnectionTimeout),this.pcState=Me.Connected}catch(e){throw this.pcState=Me.Disconnected,N.internal("could not establish PC connection, ".concat(e.message))}})}publishRpcAck(e,t){return p(this,void 0,void 0,function*(){let n=new ge({destinationIdentities:[e],kind:Ze.RELIABLE,value:{case:"rpcAck",value:new er({requestId:t})}});yield this.sendDataPacket(n,U.RELIABLE)})}sendDataPacket(e,t){return p(this,void 0,void 0,function*(){var n,r;if(yield this.ensurePublisherConnected(t),this.e2eeManager&&this.e2eeManager.isDataChannelEncryptionEnabled){let d=Am(e);if(d){let c=yield this.e2eeManager.encryptData(d.toBinary());e.value={case:"encryptedPacket",value:new xc({encryptedValue:c.payload,iv:c.iv,keyIndex:c.keyIndex})}}}let s=t===U.RELIABLE?this.dataChannelForKind(t):void 0;s&&(yield this.waitForBufferStatusLow(t)),t===U.RELIABLE&&(e.sequence=this.reliableDataSequence,this.reliableDataSequence+=1);let a=e.toBinary(),o=Math.min((r=(n=this.pcManager)===null||n===void 0?void 0:n.getMaxPublisherMessageSize())!==null&&r!==void 0?r:Qo,Qo);if(typeof o<"u"&&o!==0&&a.byteLength>o)throw new rs("cannot publish data packet larger than ".concat(o," bytes (got ").concat(a.byteLength,")"));switch(t){case U.LOSSY:case U.DATA_TRACK_LOSSY:return this.sendLossyBytes(a,t);case U.RELIABLE:let d=s;if(d){if(this.reliableMessageBuffer.push({data:a,sequence:e.sequence}),this.attemptingReconnect)return;d.send(a)}this.updateAndEmitDCBufferStatus(t);break}})}sendLossyBytes(e,t){return p(this,arguments,void 0,function(n,r){var s=this;let a=arguments.length>2&&arguments[2]!==void 0?arguments[2]:"drop";return(function*(){yield s.ensurePublisherConnected(r);let o=s.dataChannelForKind(r);if(o){if(!s.isBufferStatusLow(r))switch(a){case"wait":yield s.waitForBufferStatusLow(r);break;case"drop":s.lossyDataDropCount+=1,s.lossyDataDropCount%100===0&&s.log.warn("dropping lossy data channel messages, total dropped: ".concat(s.lossyDataDropCount));return}if(s.lossyDataStatCurrentBytes+=n.byteLength,s.attemptingReconnect)return;o.send(n)}s.updateAndEmitDCBufferStatus(r)})()})}resendReliableMessagesForResume(e){return p(this,void 0,void 0,function*(){yield this.ensurePublisherConnected(U.RELIABLE);let t=this.dataChannelForKind(U.RELIABLE);t&&(this.reliableMessageBuffer.popToSequence(e),this.reliableMessageBuffer.getAll().forEach(n=>{t.send(n.data)})),this.updateAndEmitDCBufferStatus(U.RELIABLE)})}waitForBufferStatusLow(e){return p(this,void 0,void 0,function*(){return new pe((t,n)=>p(this,void 0,void 0,function*(){if(this.isClosed&&n(new $("engine closed")),this.isBufferStatusLow(e))t();else{let r=this.dataChannelForKind(e);if(!r){n(new $("DataChannel not found, kind: ".concat(e)));return}this.bufferStatusLowClosingFuture.promise.catch(s=>n(s)),r.addEventListener("bufferedamountlow",()=>t(),{once:!0})}}))})}ensureDataTransportConnected(e){return p(this,arguments,void 0,function(t){var n=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.subscriberPrimary;return(function*(){var s;if(!n.pcManager)throw new $("PC manager is closed");let a=r?n.pcManager.subscriber:n.pcManager.publisher,o=r?"Subscriber":"Publisher";if(!a)throw N.internal("".concat(o," connection not set"));let d=!1;!r&&!n.dataChannelForKind(t,r)&&(n.createDataChannels(),d=!0),!d&&!r&&!n.pcManager.publisher.isICEConnected&&n.pcManager.publisher.getICEConnectionState()!=="checking"&&(d=!0),d&&n.negotiate().catch(u=>{n.log.error(u)});let c=n.dataChannelForKind(t,r);if(c?.readyState==="open")return;let l=new Date().getTime()+n.peerConnectionTimeout;for(;new Date().getTime()<l;){if(a.isICEConnected&&((s=n.dataChannelForKind(t,r))===null||s===void 0?void 0:s.readyState)==="open")return;yield ve(50)}throw N.internal("could not establish ".concat(o," connection, state: ").concat(a.getICEConnectionState()))})()})}ensurePublisherConnected(e){return p(this,void 0,void 0,function*(){this.publisherConnectionPromise||(this.publisherConnectionPromise=this.ensureDataTransportConnected(e,!1)),yield this.publisherConnectionPromise})}verifyTransport(){return!(!this.pcManager||![te.CONNECTING,te.CONNECTED].includes(this.pcManager.currentState)||!this.client.ws||this.client.ws.readyState===WebSocket.CLOSED)}negotiate(){return p(this,void 0,void 0,function*(){return new pe((e,t)=>p(this,void 0,void 0,function*(){if(!this.pcManager){t(new lt("PC manager is closed"));return}this.pcManager.requirePublisher(),this.pcManager.publisher.getTransceivers().length==0&&!this.lossyDC&&!this.reliableDC&&!this.dataTrackDC&&this.createDataChannels();let n=new AbortController,r=()=>{n.abort(),this.log.debug("engine disconnected while negotiation was ongoing"),e()};this.isClosed&&t(new lt("cannot negotiate on closed engine")),this.on(R.Closing,r),this.on(R.Restarting,r),this.pcManager.publisher.off(kt.RTPVideoPayloadTypes,this.onRtpMapAvailable),this.pcManager.publisher.once(kt.RTPVideoPayloadTypes,this.onRtpMapAvailable);try{yield this.pcManager.negotiate(n),e()}catch(s){if(n.signal.aborted){e();return}s instanceof lt&&(this.fullReconnectOnNext=!0),this.handleDisconnect("negotiation",Rt.RR_UNKNOWN),s instanceof Error?t(s):t(new Error(String(s)))}finally{this.off(R.Closing,r),this.off(R.Restarting,r)}}))})}dataChannelForKind(e,t){switch(e){case U.RELIABLE:return t?this.reliableDCSub:this.reliableDC;case U.LOSSY:return t?this.lossyDCSub:this.lossyDC;case U.DATA_TRACK_LOSSY:return t?this.dataTrackDCSub:this.dataTrackDC}}sendSyncState(e,t,n){var r,s,a,o;if(!this.pcManager){this.log.warn("sync state cannot be sent without peer connection setup");return}let 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,m=new Array,g=new Array;e.forEach(f=>{f.isDesired!==h&&m.push(f.trackSid),f.isEnabled||g.push(f.trackSid)}),this.client.sendSyncState(new Ea({answer:this.pcManager.mode==="publisher-only"?c?Mt({sdp:c.sdp,type:c.type}):void 0:u?Mt({sdp:u.sdp,type:u.type}):void 0,offer:this.pcManager.mode==="publisher-only"?d?Mt({sdp:d.sdp,type:d.type}):void 0:l?Mt({sdp:l.sdp,type:l.type}):void 0,subscription:new ir({trackSids:m,subscribe:!h,participantTracks:[]}),publishTracks:$h(t),dataChannels:this.dataChannelsInfo(),trackSidsDisabled:g,datachannelReceiveStates:this.reliableReceivedState.map((f,T)=>new td({publisherSid:T,lastSeq:f})),publishDataTracks:n.map(f=>new ka({info:Ii.toProtobuf(f)}))}))}failNext(){this.shouldFailNext=!0}failNextV1Path(){this.shouldFailOnV1Path=!0}dataChannelsInfo(){let e=[],t=(n,r)=>{n?.id!==void 0&&n.id!==null&&e.push(new nd({label:n.label,id:n.id,target:r}))};return t(this.dataChannelForKind(U.LOSSY),Fe.PUBLISHER),t(this.dataChannelForKind(U.RELIABLE),Fe.PUBLISHER),t(this.dataChannelForKind(U.LOSSY,!0),Fe.SUBSCRIBER),t(this.dataChannelForKind(U.RELIABLE,!0),Fe.SUBSCRIBER),e}clearReconnectTimeout(){this.reconnectTimeout&&re.clearTimeout(this.reconnectTimeout)}clearPendingReconnect(){this.clearReconnectTimeout(),this.reconnectAttempts=0}registerOnLineListener(){Ce()&&(window.addEventListener("online",this.handleBrowserOnLine),window.addEventListener("offline",this.handleBrowserOffline))}deregisterOnLineListener(){Ce()&&(window.removeEventListener("online",this.handleBrowserOnLine),window.removeEventListener("offline",this.handleBrowserOffline))}getTrackIdForReceiver(e){var t;let n=(t=this.pcManager)===null||t===void 0?void 0:t.getMidForReceiver(e);if(n){let r=Object.entries(this.midToTrackId).find(s=>O(s,1)[0]===n);if(r)return r[1]}}};function Yo(i,e){let t=i.participantIdentity?i.participantIdentity:e.participantIdentity;i.participantIdentity=t,e.participantIdentity=t;let n=i.destinationIdentities.length!==0?i.destinationIdentities:e.destinationIdentities;i.destinationIdentities=n,e.destinationIdentities=n}var Is=5e3,yp=3e4,Ge=class i{static fetchRegionSettings(e,t,n){return p(this,void 0,void 0,function*(){let r=yield i.fetchLock.lock();try{let s=yield fetch("".concat(bp(e),"/regions"),{headers:{authorization:"Bearer ".concat(t)},signal:n});if(s.ok){let a=km(s.headers),o=a?a*1e3:Is;return{regionSettings:yield s.json(),updatedAtInMs:Date.now(),maxAgeInMs:o}}else throw s.status===401?N.notAllowed("Could not fetch region settings: ".concat(s.statusText),s.status):N.internal("Could not fetch region settings: ".concat(s.statusText))}catch(s){throw s instanceof N?s:n?.aborted?N.cancelled("Region fetching was aborted"):N.serverUnreachable("Could not fetch region settings, ".concat(s instanceof Error?"".concat(s.name,": ").concat(s.message):s))}finally{r()}})}static scheduleRefetch(e,t,n){return p(this,void 0,void 0,function*(){let r=i.settingsTimeouts.get(e.hostname);clearTimeout(r),i.settingsTimeouts.set(e.hostname,setTimeout(()=>p(this,void 0,void 0,function*(){try{let s=yield i.fetchRegionSettings(e,t);i.updateCachedRegionSettings(e,t,s)}catch(s){if(s instanceof N&&s.reason===z.NotAllowed){F.debug("token is not valid, cancelling auto region refresh");return}F.debug("auto refetching of region settings failed",{error:s}),i.scheduleRefetch(e,t,n)}}),n))})}static updateCachedRegionSettings(e,t,n){i.cache.set(e.hostname,n),i.scheduleRefetch(e,t,n.maxAgeInMs)}static stopRefetch(e){let t=i.settingsTimeouts.get(e);t&&(clearTimeout(t),i.settingsTimeouts.delete(e))}static scheduleCleanup(e){let t=i.connectionTrackers.get(e);t&&(t.cleanupTimeout&&clearTimeout(t.cleanupTimeout),t.cleanupTimeout=setTimeout(()=>{let n=i.connectionTrackers.get(e);n&&n.connectionCount===0&&(F.debug("stopping region refetch after disconnect delay",{hostname:e}),i.stopRefetch(e)),n&&(n.cleanupTimeout=void 0)},yp))}static cancelCleanup(e){let t=i.connectionTrackers.get(e);t?.cleanupTimeout&&(clearTimeout(t.cleanupTimeout),t.cleanupTimeout=void 0)}notifyConnected(){let e=this.serverUrl.hostname,t=i.connectionTrackers.get(e);t||(t={connectionCount:0},i.connectionTrackers.set(e,t)),t.connectionCount++,i.cancelCleanup(e)}notifyDisconnected(){let e=this.serverUrl.hostname,t=i.connectionTrackers.get(e);t&&(t.connectionCount=Math.max(0,t.connectionCount-1),t.connectionCount===0&&i.scheduleCleanup(e))}constructor(e,t){this.attemptedRegions=[],this.serverUrl=new URL(e),this.token=t}updateToken(e){var t;this.token=e;let n=this.getServerUrl(),r=i.cache.get(n.hostname);i.scheduleRefetch(this.serverUrl,this.token,(t=r?.maxAgeInMs)!==null&&t!==void 0?t:Is)}isCloud(){return sn(this.serverUrl)}getServerUrl(){return this.serverUrl}fetchRegionSettings(e){return p(this,void 0,void 0,function*(){return i.fetchRegionSettings(this.serverUrl,this.token,e)})}getNextBestRegionUrl(e){return p(this,void 0,void 0,function*(){if(!this.isCloud())throw Error("region availability is only supported for LiveKit Cloud domains");let t=i.cache.get(this.serverUrl.hostname);(!t||Date.now()-t.updatedAtInMs>t.maxAgeInMs)&&(t=yield this.fetchRegionSettings(e),i.updateCachedRegionSettings(this.serverUrl,this.token,t));let n=t.regionSettings.regions.filter(r=>!this.attemptedRegions.find(s=>s.url===r.url));if(n.length>0){let r=n[0];return this.attemptedRegions.push(r),F.debug("next region: ".concat(r.region)),r.url}else return null})}resetAttempts(){this.attemptedRegions=[]}setServerReportedRegions(e){i.updateCachedRegionSettings(this.serverUrl,this.token,e)}};Ge.cache=new Map;Ge.settingsTimeouts=new Map;Ge.connectionTrackers=new Map;Ge.fetchLock=new de;function bp(i){return"".concat(i.protocol.replace("ws","http"),"//").concat(i.host,"/settings")}var Ni=class{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 Se("Not enough chunk(s) received - expected ".concat(this.totalByteSize," bytes of data total, only received ").concat(this.bytesReceived," bytes"),be.Incomplete);if(this.bytesReceived>this.totalByteSize)throw new Se("Extra chunk(s) received - expected ".concat(this.totalByteSize," bytes of data total, received ").concat(this.bytesReceived," bytes"),be.LengthExceeded)}}constructor(e,t,n){this.reader=t,this.totalByteSize=n,this._info=e,this.bytesReceived=0}},Ms=class extends Ni{handleChunkReceived(e){var t;this.bytesReceived+=e.content.byteLength,this.validateBytesReceived();let n=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;(t=this.onProgress)===null||t===void 0||t.call(this,n)}[Symbol.asyncIterator](){let e=this.reader.getReader();e.closed.catch(()=>{});let t=()=>{e.releaseLock(),this.signal=void 0};return{next:()=>p(this,void 0,void 0,function*(){try{let n=this.signal;if(n?.aborted)throw n.reason;let r=yield new Promise((s,a)=>{if(n){let o=()=>a(n.reason);n.addEventListener("abort",o,{once:!0}),e.read().then(s,a).finally(()=>{n.removeEventListener("abort",o)})}else e.read().then(s,a)});return r.done?(this.validateBytesReceived(!0),{done:!0,value:void 0}):(this.handleChunkReceived(r.value),{done:!1,value:r.value.content})}catch(n){throw t(),n}}),return(){return p(this,void 0,void 0,function*(){return t(),{done:!0,value:void 0}})}}}withAbortSignal(e){return this.signal=e,this}readAll(){return p(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return(function*(){var n,r,s,a;let o=new Set,d=t.signal?e.withAbortSignal(t.signal):e;try{for(var c=!0,l=Be(d),u;u=yield l.next(),n=u.done,!n;c=!0){a=u.value,c=!1;let h=a;o.add(h)}}catch(h){r={error:h}}finally{try{!c&&!n&&(s=l.return)&&(yield s.call(l))}finally{if(r)throw r.error}}return Array.from(o)})()})}},As=class extends Ni{constructor(e,t,n){super(e,t,n),this.receivedChunks=new Map}handleChunkReceived(e){var t;let n=pi(e.chunkIndex),r=this.receivedChunks.get(n);if(r&&r.version>e.version)return;this.receivedChunks.set(n,e),this.bytesReceived+=e.content.byteLength,this.validateBytesReceived();let s=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;(t=this.onProgress)===null||t===void 0||t.call(this,s)}[Symbol.asyncIterator](){let e=this.reader.getReader();e.closed.catch(()=>{});let t=new TextDecoder("utf-8",{fatal:!0}),n=this.signal,r=()=>{e.releaseLock(),this.signal=void 0};return{next:()=>p(this,void 0,void 0,function*(){try{if(n?.aborted)throw n.reason;let s=yield new Promise((a,o)=>{if(n){let d=()=>o(n.reason);n.addEventListener("abort",d,{once:!0}),e.read().then(a,o).finally(()=>{n.removeEventListener("abort",d)})}else e.read().then(a,o)});if(s.done)return this.validateBytesReceived(!0),{done:!0,value:void 0};{this.handleChunkReceived(s.value);let a;try{a=t.decode(s.value.content)}catch(o){throw new Se("Cannot decode datastream chunk ".concat(s.value.chunkIndex," as text: ").concat(o),be.DecodeFailed)}return{done:!1,value:a}}}catch(s){throw r(),s}}),return(){return p(this,void 0,void 0,function*(){return r(),{done:!0,value:void 0}})}}}withAbortSignal(e){return this.signal=e,this}readAll(){return p(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return(function*(){var n,r,s,a;let o="",d=t.signal?e.withAbortSignal(t.signal):e;try{for(var c=!0,l=Be(d),u;u=yield l.next(),n=u.done,!n;c=!0)a=u.value,c=!1,o+=a}catch(h){r={error:h}}finally{try{!c&&!n&&(s=l.return)&&(yield s.call(l))}finally{if(r)throw r.error}}return o})()})}},xs=class{constructor(){this.log=F,this.byteStreamControllers=new Map,this.textStreamControllers=new Map,this.byteStreamHandlers=new Map,this.textStreamHandlers=new Map,this.isConnected=!1,this.bufferedPackets=[]}setConnected(e){this.isConnected=e,e&&this.flushBufferedPackets()}flushBufferedPackets(){let e=this.bufferedPackets;this.bufferedPackets=[];for(let t of e){let n=t.packet,r=t.encryptionType;this.handleDataStreamPacket(n,r)}}registerTextStreamHandler(e,t){if(this.textStreamHandlers.has(e))throw new Se('A text stream handler for topic "'.concat(e,'" has already been set.'),be.HandlerAlreadyRegistered);this.textStreamHandlers.set(e,t)}unregisterTextStreamHandler(e){this.textStreamHandlers.delete(e)}registerByteStreamHandler(e,t){if(this.byteStreamHandlers.has(e))throw new Se('A byte stream handler for topic "'.concat(e,'" has already been set.'),be.HandlerAlreadyRegistered);this.byteStreamHandlers.set(e,t)}unregisterByteStreamHandler(e){this.byteStreamHandlers.delete(e)}clearControllers(){this.byteStreamControllers.clear(),this.textStreamControllers.clear(),this.bufferedPackets=[]}validateParticipantHasNoActiveDataStreams(e){let t=Array.from(this.textStreamControllers.entries()).filter(a=>a[1].sendingParticipantIdentity===e),n=Array.from(this.byteStreamControllers.entries()).filter(a=>a[1].sendingParticipantIdentity===e);if(t.length>0||n.length>0){let a=new Se("Participant ".concat(e," unexpectedly disconnected in the middle of sending data"),be.AbnormalEnd);for(let o of n){var r=O(o,2);let d=r[0];r[1].controller.error(a),this.byteStreamControllers.delete(d)}for(let o of t){var s=O(o,2);let 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,n){var r;if(e.contentHeader.case==="byteHeader"){let 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,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:pi(e.timestamp),attributes:e.attributes,encryptionType:n},d=new ReadableStream({start:c=>{if(a=c,this.textStreamControllers.has(e.streamId))throw new Se("A data stream read is already in progress for a stream with id ".concat(e.streamId,"."),be.AlreadyOpened);this.byteStreamControllers.set(e.streamId,{info:o,controller:a,startTime:Date.now(),sendingParticipantIdentity:t})}});s(new Ms(o,d,pi(e.totalLength)),{identity:t})}else if(e.contentHeader.case==="textHeader"){let 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,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:n,attachedStreamIds:e.contentHeader.value.attachedStreamIds},d=new ReadableStream({start:c=>{if(a=c,this.textStreamControllers.has(e.streamId))throw new Se("A data stream read is already in progress for a stream with id ".concat(e.streamId,"."),be.AlreadyOpened);this.textStreamControllers.set(e.streamId,{info:o,controller:a,startTime:Date.now(),sendingParticipantIdentity:t})}});s(new As(o,d,pi(e.totalLength)),{identity:t})}}handleStreamChunk(e,t){let n=this.byteStreamControllers.get(e.streamId);n&&(n.info.encryptionType!==t?(n.controller.error(new Se("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(n.info.encryptionType),be.EncryptionTypeMismatch)),this.byteStreamControllers.delete(e.streamId)):e.content.length>0&&n.controller.enqueue(e));let r=this.textStreamControllers.get(e.streamId);r&&(r.info.encryptionType!==t?(r.controller.error(new Se("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(r.info.encryptionType),be.EncryptionTypeMismatch)),this.textStreamControllers.delete(e.streamId)):e.content.length>0&&r.controller.enqueue(e))}handleStreamTrailer(e,t){let n=this.textStreamControllers.get(e.streamId);n&&(n.info.encryptionType!==t?n.controller.error(new Se("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(n.info.encryptionType),be.EncryptionTypeMismatch)):(n.info.attributes=Object.assign(Object.assign({},n.info.attributes),e.attributes),n.controller.close(),this.textStreamControllers.delete(e.streamId)));let r=this.byteStreamControllers.get(e.streamId);r&&(r.info.encryptionType!==t?r.controller.error(new Se("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(r.info.encryptionType),be.EncryptionTypeMismatch)):(r.info.attributes=Object.assign(Object.assign({},r.info.attributes),e.attributes),r.controller.close()),this.byteStreamControllers.delete(e.streamId))}},Ui=class{constructor(e,t,n){this.writableStream=e,this.defaultWriter=e.getWriter(),this.onClose=n,this.info=t}write(e){return this.defaultWriter.write(e)}close(){return p(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)})}},Ds=class extends Ui{},Os=class extends Ui{},Xo=15e3,Ls=class{constructor(e,t){this.engine=e,this.log=t}setupEngine(e){this.engine=e}sendText(e,t){return p(this,void 0,void 0,function*(){var n;let r=crypto.randomUUID(),a=new TextEncoder().encode(e).byteLength,o=(n=t?.attachments)===null||n===void 0?void 0:n.map(()=>crypto.randomUUID()),d=new Array(o?o.length+1:1).fill(0),c=(u,h)=>{var m;d[h]=u;let g=d.reduce((f,T)=>f+T,0);(m=t?.onProgress)===null||m===void 0||m.call(t,g)},l=yield this.streamText({streamId:r,totalSize:a,destinationIdentities:t?.destinationIdentities,topic:t?.topic,attachedStreamIds:o,attributes:t?.attributes});return yield l.write(e),c(1,0),yield l.close(),t?.attachments&&o&&(yield Promise.all(t.attachments.map((u,h)=>p(this,void 0,void 0,function*(){return this._sendFile(o[h],u,{topic:t.topic,mimeType:u.type,onProgress:m=>{c(m,h+1)}})})))),l.info})}streamText(e){return p(this,void 0,void 0,function*(){var t,n,r;let s=(t=e?.streamId)!==null&&t!==void 0?t:crypto.randomUUID(),a={id:s,mimeType:"text/plain",timestamp:Date.now(),topic:(n=e?.topic)!==null&&n!==void 0?n:"",size:e?.totalSize,attributes:e?.attributes,encryptionType:!((r=this.engine.e2eeManager)===null||r===void 0)&&r.isDataChannelEncryptionEnabled?J.GCM:J.NONE,attachedStreamIds:e?.attachedStreamIds},o=new bi({streamId:s,mimeType:a.mimeType,topic:a.topic,timestamp:Pt(a.timestamp),totalLength:Pt(a.size),attributes:a.attributes,contentHeader:{case:"textHeader",value:new Kc({version:e?.version,attachedStreamIds:a.attachedStreamIds,replyToStreamId:e?.replyToStreamId,operationType:e?.type==="update"?Gr.UPDATE:Gr.CREATE})}}),d=e?.destinationIdentities,c=new ge({destinationIdentities:d,value:{case:"streamHeader",value:o}});yield this.engine.sendDataPacket(c,U.RELIABLE);let l=0,u=this.engine,h=new WritableStream({write(f){return p(this,void 0,void 0,function*(){for(let T of bm(f,Xo)){let k=new ki({content:T,streamId:s,chunkIndex:Pt(l)}),S=new ge({destinationIdentities:d,value:{case:"streamChunk",value:k}});yield u.sendDataPacket(S,U.RELIABLE),l+=1}})},close(){return p(this,void 0,void 0,function*(){let f=new Ti({streamId:s}),T=new ge({destinationIdentities:d,value:{case:"streamTrailer",value:f}});yield u.sendDataPacket(T,U.RELIABLE)})},abort(f){console.log("Sink error:",f)}}),m=()=>p(this,void 0,void 0,function*(){yield g.close()});u.once(R.Closing,m);let g=new Ds(h,a,()=>this.engine.off(R.Closing,m));return g})}sendFile(e,t){return p(this,void 0,void 0,function*(){let n=crypto.randomUUID();return yield this._sendFile(n,e,t),{id:n}})}_sendFile(e,t,n){return p(this,void 0,void 0,function*(){var r;let s=yield this.streamBytes({streamId:e,totalSize:t.size,name:t.name,mimeType:(r=n?.mimeType)!==null&&r!==void 0?r:t.type,topic:n?.topic,destinationIdentities:n?.destinationIdentities}),a=t.stream().getReader();for(;;){let o=yield a.read(),d=o.done,c=o.value;if(d)break;yield s.write(c)}return yield s.close(),s.info})}streamBytes(e){return p(this,void 0,void 0,function*(){var t,n,r,s,a;let o=(t=e?.streamId)!==null&&t!==void 0?t:crypto.randomUUID(),d=e?.destinationIdentities,c={id:o,mimeType:(n=e?.mimeType)!==null&&n!==void 0?n:"application/octet-stream",topic:(r=e?.topic)!==null&&r!==void 0?r:"",timestamp:Date.now(),attributes:e?.attributes,size:e?.totalSize,name:(s=e?.name)!==null&&s!==void 0?s:"unknown",encryptionType:!((a=this.engine.e2eeManager)===null||a===void 0)&&a.isDataChannelEncryptionEnabled?J.GCM:J.NONE},l=new bi({totalLength:Pt(c.size),mimeType:c.mimeType,streamId:o,topic:c.topic,timestamp:Pt(Date.now()),attributes:c.attributes,contentHeader:{case:"byteHeader",value:new Wc({name:c.name})}}),u=new ge({destinationIdentities:d,value:{case:"streamHeader",value:l}});yield this.engine.sendDataPacket(u,U.RELIABLE);let h=0,m=new de,g=this.engine,f=this.log,T=new WritableStream({write(S){return p(this,void 0,void 0,function*(){let L=yield m.lock(),y=0;try{for(;y<S.byteLength;){let b=S.slice(y,y+Xo),E=new ge({destinationIdentities:d,value:{case:"streamChunk",value:new ki({content:b,streamId:o,chunkIndex:Pt(h)})}});yield g.sendDataPacket(E,U.RELIABLE),h+=1,y+=b.byteLength}}finally{L()}})},close(){return p(this,void 0,void 0,function*(){let S=new Ti({streamId:o}),L=new ge({destinationIdentities:d,value:{case:"streamTrailer",value:S}});yield g.sendDataPacket(L,U.RELIABLE)})},abort(S){f.error("Sink error:",S)}});return new Os(T,c)})}};function el(i){if(i.length===0)return new AbortController().signal;if(i.length===1)return i[0];for(let r of i)if(r.aborted)return r;let e=new AbortController,t=Array(i.length),n=()=>{for(let r of t)r()};return i.forEach((r,s)=>{let a=()=>{e.abort(r.reason),n()};r.addEventListener("abort",a),t[s]=()=>r.removeEventListener("abort",a)}),e.signal}function tl(i){let e=new AbortController;return setTimeout(()=>{e.abort(new DOMException("signal timed out after ".concat(i," ms"),"TimeoutError"))},i),e.signal}var ie=1,st=2,Zo=4,kp=8,ec=0,tc=12,nc=5,Tp=7,ic=3,Sp=3,rc=2,sc=1,ac=0,oc=3,ti=2,cc=2,Cp=1,_p=0,ot;(function(i){i[i.TooShort=0]="TooShort",i[i.HeaderOverrun=1]="HeaderOverrun",i[i.MissingExtWords=2]="MissingExtWords",i[i.UnsupportedVersion=3]="UnsupportedVersion",i[i.InvalidHandle=4]="InvalidHandle",i[i.MalformedExt=5]="MalformedExt"})(ot||(ot={}));var Xe=class i extends we{constructor(e,t,n){super(19,e,n),this.name="DataTrackDeserializeError",this.reason=t,this.reasonName=ot[t]}static tooShort(){return new i("Too short to contain a valid header",ot.TooShort)}static headerOverrun(){return new i("Header exceeds total packet length",ot.HeaderOverrun)}static missingExtWords(){return new i("Extension word indicator is missing",ot.MissingExtWords)}static unsupportedVersion(e){return new i("Unsupported version ".concat(e),ot.UnsupportedVersion)}static invalidHandle(e){return new i("invalid track handle: ".concat(e.message),ot.InvalidHandle,{cause:e})}static malformedExt(e){return new i("Extension with tag ".concat(e," is malformed"),ot.MalformedExt)}},En;(function(i){i[i.TooSmallForHeader=0]="TooSmallForHeader",i[i.TooSmallForPayload=1]="TooSmallForPayload"})(En||(En={}));var Fi=class i extends we{constructor(e,t,n){super(19,e,n),this.name="DataTrackSerializeError",this.reason=t,this.reasonName=En[t]}static tooSmallForHeader(){return new i("Buffer cannot fit header",En.TooSmallForHeader)}static tooSmallForPayload(){return new i("Buffer cannot fit payload",En.TooSmallForPayload)}},on=class{toBinary(){let e=this.toBinaryLengthBytes(),t=new ArrayBuffer(e),n=new DataView(t),r=this.toBinaryInto(n);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)}},cn;(function(i){i[i.UserTimestamp=2]="UserTimestamp",i[i.E2ee=1]="E2ee"})(cn||(cn={}));var Bi=class extends on{},qt=class i extends Bi{constructor(e){super(),this.timestamp=e}toBinaryLengthBytes(){return ie+ie+i.lengthBytes}toBinaryInto(e){let t=0;e.setUint8(t,i.tag),t+=ie,e.setUint8(t,i.lengthBytes),t+=ie,e.setBigUint64(t,this.timestamp),t+=kp;let n=this.toBinaryLengthBytes();if(t!==n)throw new Error("DataTrackUserTimestampExtension.toBinaryInto: Wrote ".concat(t," bytes but expected length was ").concat(n," bytes"));return t}toJSON(){return{tag:i.tag,lengthBytes:i.lengthBytes,timestamp:this.timestamp}}};qt.tag=cn.UserTimestamp;qt.lengthBytes=8;var jt=class i extends Bi{constructor(e,t){super(),this.keyIndex=e,this.iv=t}toBinaryLengthBytes(){return ie+ie+i.lengthBytes}toBinaryInto(e){let t=0;e.setUint8(t,i.tag),t+=ie,e.setUint8(t,i.lengthBytes),t+=ie,e.setUint8(t,this.keyIndex),t+=ie;for(let r=0;r<this.iv.length;r+=1)e.setUint8(t,this.iv[r]),t+=ie;let n=this.toBinaryLengthBytes();if(t!==n)throw new Error("DataTrackE2eeExtension.toBinaryInto: Wrote ".concat(t," bytes but expected length was ").concat(n," bytes"));return t}toJSON(){return{tag:i.tag,lengthBytes:i.lengthBytes,keyIndex:this.keyIndex,iv:this.iv}}};jt.tag=cn.E2ee;jt.lengthBytes=13;var en=class i extends on{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){let r=this.e2ee.toBinaryInto(e);t+=r}if(this.userTimestamp){let r=this.userTimestamp.toBinaryInto(new DataView(e.buffer,e.byteOffset+t));t+=r}let n=this.toBinaryLengthBytes();if(t!==n)throw new Error("DataTrackExtensions.toBinaryInto: Wrote ".concat(t," bytes but expected length was ").concat(n," bytes"));return t}static fromBinary(e){let t=Na(e),n,r,s=0;for(;t.byteLength-s>=ie+ie;){let a=t.getUint8(s);s+=ie;let o=t.getUint8(s);if(s+=ie,a!==_p)switch(a){case cn.UserTimestamp:if(t.byteLength-s<qt.lengthBytes)throw Xe.malformedExt(a);n=new qt(t.getBigUint64(s)),s+=o;break;case cn.E2ee:if(t.byteLength-s<jt.lengthBytes)throw Xe.malformedExt(a);let d=t.getUint8(s),c=new Uint8Array(12);for(let l=0;l<c.length;l+=1){let u=s;u+=ie,u+=l*ie,c[l]=t.getUint8(u)}r=new jt(d,c),s+=o;break;default:if(t.byteLength-s<o)throw Xe.malformedExt(a);s+=o;break}}return[new i({userTimestamp:n,e2ee:r}),t.byteLength]}toJSON(){var e,t,n,r;return{userTimestamp:(t=(e=this.userTimestamp)===null||e===void 0?void 0:e.toJSON())!==null&&t!==void 0?t:null,e2ee:(r=(n=this.e2ee)===null||n===void 0?void 0:n.toJSON())!==null&&r!==void 0?r:null}}},nl={from(i){return{payload:i.payload,extensions:new en({userTimestamp:i.userTimestamp?new qt(i.userTimestamp):void 0})}},lossyIntoFrame(i){var e;return{payload:i.payload,userTimestamp:(e=i.extensions.userTimestamp)===null||e===void 0?void 0:e.timestamp}}},il=Symbol.for("lk.track"),rl=Symbol.for("lk.data-track"),qi=class{constructor(e,t,n){this.trackSymbol=il,this.isLocal=!1,this.typeSymbol=rl,this.info=e,this.manager=t,this.publisherIdentity=n.publisherIdentity}subscribe(e){try{let t=this.manager.openSubscriptionStream(this.info.sid,e?.signal,e?.bufferSize),n=O(t,2),r=n[0];return n[1].catch(()=>{}),r}catch(t){throw t}}setPipelineOptions(e){this.manager.setPipelineOptions(this.info.sid,e)}},Vn=class i extends on{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 en}extensionsMetrics(){let e=this.extensions.toBinaryLengthBytes(),t=Math.ceil((ti+e)/4),n=t*4-ti-e;return{lengthBytes:e,lengthWords:t,paddingLengthBytes:n}}toBinaryLengthBytes(){let e=this.extensionsMetrics(),t=e.lengthBytes,n=e.paddingLengthBytes,r=tc;return t>0&&(r+=ti+t+n),r}toBinaryInto(e){if(e.byteLength<this.toBinaryLengthBytes())throw Fi.tooSmallForHeader();let t=ec<<nc,n;switch(this.marker){case Q.Inter:n=ac;break;case Q.Final:n=sc;break;case Q.Start:n=rc;break;case Q.Single:n=oc;break}t|=n<<ic;let r=this.extensionsMetrics(),s=r.lengthBytes,a=r.lengthWords,o=r.paddingLengthBytes;s>0&&(t|=1<<cc);let d=0;if(e.setUint8(d,t),d+=ie,e.setUint8(d,0),d+=ie,e.setUint16(d,this.trackHandle),d+=st,e.setUint16(d,this.sequence.value),d+=st,e.setUint16(d,this.frameNumber.value),d+=st,e.setUint32(d,this.timestamp.asTicks()),d+=Zo,s>0){let l=a-1;e.setUint16(d,l),d+=st;let 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+=ie}let c=this.toBinaryLengthBytes();if(d!==c)throw new Error("DataTrackPacketHeader.toBinaryInto: Wrote ".concat(d," bytes but expected length was ").concat(c," bytes"));return c}static fromBinary(e){let t=Na(e);if(t.byteLength<tc)throw Xe.tooShort();let n=0,r=t.getUint8(n);n+=ie;let s=r>>nc&Tp;if(s>ec)throw Xe.unsupportedVersion(s);let a;switch(r>>ic&Sp){case rc:a=Q.Start;break;case sc:a=Q.Final;break;case oc:a=Q.Single;break;case ac:default:a=Q.Inter;break}let o=(r>>cc&Cp)>0;n+=ie;let d;try{d=Um.fromNumber(t.getUint16(n))}catch(m){throw m instanceof qn&&(m.isReason(Nt.Reserved)||m.isReason(Nt.TooLarge))?Xe.invalidHandle(m):m}n+=st;let c=Ct.u16(t.getUint16(n));n+=st;let l=Ct.u16(t.getUint16(n));n+=st;let u=Pi.fromRtpTicks(t.getUint32(n));n+=Zo;let h=new en;if(o){if(t.byteLength-n<st)throw Xe.missingExtWords();let m=t.getUint16(n);n+=st;let f=4*(m+1)-ti;if(n+f>t.byteLength)throw Xe.headerOverrun();let T=new DataView(t.buffer,t.byteOffset+n,f),k=en.fromBinary(T),S=O(k,2),L=S[0],y=S[1];h=L,n+=y}return[new i({marker:a,trackHandle:d,sequence:c,frameNumber:l,timestamp:u,extensions:h}),n]}toJSON(){return{marker:this.marker,trackHandle:this.trackHandle,sequence:this.sequence.value,frameNumber:this.frameNumber.value,timestamp:this.timestamp.asTicks(),extensions:this.extensions.toJSON()}}},Q;(function(i){i[i.Start=0]="Start",i[i.Inter=1]="Inter",i[i.Final=2]="Final",i[i.Single=3]="Single"})(Q||(Q={}));var ji=class i extends on{constructor(e,t){super(),this.header=e,this.payload=t}toBinaryLengthBytes(){return this.header.toBinaryLengthBytes()+this.payload.byteLength}toBinaryInto(e){let t=0,n=this.header.toBinaryInto(e);if(t+=n,e.byteLength-t<this.payload.byteLength)throw Fi.tooSmallForPayload();for(let s=0;s<this.payload.length;s+=1)e.setUint8(t,this.payload[s]),t+=ie;let 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){let t=Na(e),n=Vn.fromBinary(t),r=O(n,2),s=r[0],a=r[1],o=t.buffer.slice(t.byteOffset+a,t.byteOffset+t.byteLength);return[new i(s,new Uint8Array(o)),t.byteLength]}toJSON(){return{header:this.header.toJSON(),payload:this.payload}}},Nr=_e(ue.DataTracks),At=class i extends we{constructor(e,t,n,r){super(19,"Frame ".concat(n," dropped: ").concat(e),r),this.name="DataTrackDepacketizerDropError",this.reason=t,this.reasonName=xt[t],this.frameNumber=n}static interrupted(e,t){return new i("Interrupted by the start of a new frame ".concat(t),xt.Interrupted,e)}static unknownFrame(e){return new i("Initial packet was never received.",xt.UnknownFrame,e)}static bufferFull(e){return new i("Reorder buffer is full.",xt.BufferFull,e)}static incomplete(e,t,n){return new i("Not all packets received before final packet. Received ".concat(t," packets, expected ").concat(n," packets."),xt.Incomplete,e)}},xt;(function(i){i[i.Interrupted=0]="Interrupted",i[i.UnknownFrame=1]="UnknownFrame",i[i.BufferFull=2]="BufferFull",i[i.Incomplete=3]="Incomplete"})(xt||(xt={}));var Vi=class i{constructor(){this.partials=new Map}push(e,t){switch(e.header.marker){case Q.Single:return this.frameFromSingle(e,t);case Q.Start:return this.beginPartial(e,t);case Q.Inter:case Q.Final:return this.pushToPartial(e)}}reset(){this.partials.clear()}peekOldestPartialFrameNumber(){let e=this.partials.keys().next();return e.done?null:e.value}frameFromSingle(e,t){var n;if(e.header.marker!==Q.Single)throw new Error("Depacketizer.frameFromSingle: packet.header.marker was not FrameMarker.Single, found ".concat(e.header.marker,"."));let r=(n=t?.maxPartialFrames)!==null&&n!==void 0?n:1;if(this.partials.size>=r){let s=this.peekOldestPartialFrameNumber();if(typeof s!="number")throw new Error("Depacketizer.frameFromSingle: no oldest frame number found, but partials.size is ".concat(this.partials.size,"."));if(this.partials.delete(s),t?.throwOnInterruption)throw At.interrupted(s,e.header.frameNumber.value);Nr.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 n;if(e.header.marker!==Q.Start)throw new Error("Depacketizer.beginPartial: packet.header.marker was not FrameMarker.Start, found ".concat(e.header.marker,"."));let r=e.header.sequence,s=e.header.frameNumber.value,a={startSequence:r,extensions:e.header.extensions,payloads:new Map([[r.value,e.payload]])},o=(n=t?.maxPartialFrames)!==null&&n!==void 0?n:1;for(;this.partials.size>=o;){let d=this.peekOldestPartialFrameNumber();if(typeof d!="number")break;if(this.partials.delete(d),t?.throwOnInterruption)throw At.interrupted(d,s);Nr.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!==Q.Inter&&e.header.marker!==Q.Final)throw new Error("Depacketizer.pushToPartial: packet.header.marker was not FrameMarker.Inter or FrameMarker.Final, found ".concat(e.header.marker,"."));let t=e.header.frameNumber.value,n=this.partials.get(t);if(!n)throw this.partials.delete(t),At.unknownFrame(t);if(n.payloads.size>=i.MAX_BUFFER_PACKETS)throw this.partials.delete(t),At.bufferFull(t);return n.payloads.has(e.header.sequence.value)&&Nr.warn("Data track frame ".concat(t," received duplicate packet for sequence ").concat(e.header.sequence.value,", so replacing with newly received packet.")),n.payloads.set(e.header.sequence.value,e.payload),e.header.marker===Q.Final?this.finalize(t,n,e.header.sequence.value):null}finalize(e,t,n){let r=t.payloads.size,s=0;for(let c of t.payloads.values())s+=c.length;let a=new Uint8Array(s),o=t.startSequence.clone(),d=0;for(;;){let c=t.payloads.get(o.value);if(!c)break;t.payloads.delete(o.value);let 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!=n){o.increment();continue}return this.partials.delete(e),{payload:a,extensions:t.extensions}}throw this.partials.delete(e),At.incomplete(e,r,n-t.startSequence.value+1)}};Vi.MAX_BUFFER_PACKETS=128;var Dt;(function(i){i[i.Unpublished=0]="Unpublished",i[i.Timeout=1]="Timeout",i[i.Disconnected=2]="Disconnected",i[i.Cancelled=4]="Cancelled"})(Dt||(Dt={}));var De=class i extends we{constructor(e,t,n){super(22,e,n),this.name="DataTrackSubscribeError",this.reason=t,this.reasonName=Dt[t]}static unpublished(){return new i("The track has been unpublished and is no longer available",Dt.Unpublished)}static timeout(){return new i("Request to subscribe to data track timed-out",Dt.Timeout)}static disconnected(){return new i("Cannot subscribe to data track when disconnected",Dt.Disconnected)}static cancelled(){return new i("Subscription to data track cancelled by caller",Dt.Cancelled)}},Ur=_e(ue.DataTracks),Ns=class{constructor(e){var t,n;let r=e.e2eeManager!==null;if(e.info.usesE2ee!==r)throw new Error("IncomingDataTrackPipeline: DataTrackInfo.usesE2ee must match presence of decryptionProvider");let s=new Vi;this.publisherIdentity=e.publisherIdentity,this.e2eeManager=(t=e.e2eeManager)!==null&&t!==void 0?t:null,this.depacketizer=s,this.options=(n=e.pipelineOptions)!==null&&n!==void 0?n:{}}updateE2eeManager(e){this.e2eeManager=e}setOptions(e){this.options=e}processPacket(e){return p(this,void 0,void 0,function*(){let t=this.depacketize(e);if(!t)return null;let n=yield this.decryptIfNeeded(t);return n||null})}depacketize(e){let t;try{t=this.depacketizer.push(e,{throwOnInterruption:!1,maxPartialFrames:this.options.maxPartialFrames})}catch(n){return Ur.warn("Data frame depacketize error: ".concat(n)),null}return t}decryptIfNeeded(e){return p(this,void 0,void 0,function*(){var t,n;let r=this.e2eeManager;if(!r)return e;let s=(n=(t=e.extensions)===null||t===void 0?void 0:t.e2ee)!==null&&n!==void 0?n:null;if(!s)return Ur.error("Missing E2EE meta"),null;let a;try{a=yield r.handleEncryptedData(e.payload,s.iv,this.publisherIdentity,s.keyIndex)}catch(o){return Ur.error("Error decrypting packet: ".concat(o)),null}return e.payload=a.payload,e})}},he=_e(ue.DataTracks),wp=1e4,Ep=16,Us=class extends Ee.EventEmitter{constructor(e){var t;super(),this.descriptors=new Map,this.subscriptionHandles=new Map,this.e2eeManager=(t=e?.e2eeManager)!==null&&t!==void 0?t:null}updateE2eeManager(e){this.e2eeManager=e;for(let t of this.descriptors.values())t.subscription.type==="active"&&t.subscription.pipeline.updateE2eeManager(e)}setPipelineOptions(e,t){let n=this.descriptors.get(e);if(!n){he.warn("Unknown track ".concat(e,", cannot set pipeline options."));return}n.pipelineOptions=t,n.subscription.type==="active"&&n.subscription.pipeline.setOptions(t)}openSubscriptionStream(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:Ep,r=null,s=new ce,a=()=>{t?.removeEventListener("abort",d)},o=()=>{if(a(),!r){he.warn("ReadableStream subscribed to ".concat(e," was not started."));return}let l=this.descriptors.get(e);if(!l){he.warn("Unknown track ".concat(e,", skipping cancel..."));return}if(l.subscription.type!=="active"){he.warn("Subscription for track ".concat(e," is not active, skipping cancel..."));return}l.subscription.streamControllers.delete(r),l.subscription.streamControllers.size===0&&this.unSubscribeRequest(l.info.sid)},d=()=>{var l;if(!r)return;let u=this.descriptors.get(e);u?.subscription.type==="active"&&u.subscription.streamControllers.delete(r),r.error(De.cancelled()),(l=s.reject)===null||l===void 0||l.call(s,De.cancelled()),o()};return[new ReadableStream({start:l=>{r=l,this.subscribeRequest(e,t).then(()=>p(this,void 0,void 0,function*(){var u,h,m;let g=this.descriptors.get(e);if(!g){he.error("Unknown track ".concat(e));let f=De.disconnected();l.error(f),(u=s.reject)===null||u===void 0||u.call(s,f);return}if(g.subscription.type!=="active"){he.error("Subscription for track ".concat(e," is not active"));let f=De.disconnected();l.error(f),(h=s.reject)===null||h===void 0||h.call(s,f);return}if(t?.aborted){d();return}t?.addEventListener("abort",d),g.subscription.streamControllers.set(l,a),(m=s.resolve)===null||m===void 0||m.call(s)})).catch(u=>{var h;l.error(u),(h=s.reject)===null||h===void 0||h.call(s,u)})},cancel:()=>{o()}},new CountQueuingStrategy({highWaterMark:n})),s.promise]}subscribeRequest(e,t){return p(this,void 0,void 0,function*(){let n=this.descriptors.get(e);if(!n)throw new Error("Cannot subscribe to unknown track");let r=(s,a,o)=>p(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));let d=el([a,o].filter(u=>typeof u<"u")),c=new ce;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)});let l=()=>{var u;if(s.subscription.type==="pending"){if(s.subscription.pendingRequestCount-=1,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,De.cancelled())}};d.aborted&&l(),d.addEventListener("abort",l),yield c.promise,d.removeEventListener("abort",l)});switch(n.subscription.type){case"none":{n.subscription={type:"pending",completionFuture:new ce,pendingRequestCount:1,cancel:()=>{var a,o;let d=n.subscription;n.subscription={type:"none"},this.emit("sfuUpdateSubscription",{sid:e,subscribe:!1}),d.type==="pending"&&((o=(a=d.completionFuture).reject)===null||o===void 0||o.call(a,s.aborted?De.timeout():De.cancelled()))}},this.emit("sfuUpdateSubscription",{sid:e,subscribe:!0});let s=tl(wp);yield r(n,t,s);return}case"pending":{n.subscription.pendingRequestCount+=1,yield r(n,t);return}case"active":return}})}querySubscribed(){return p(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;let n=this.descriptors.get(e);if(!n)throw new Error("Cannot subscribe to unknown track");if(n.subscription.type!=="active"){he.warn("Unexpected descriptor state in unSubscribeRequest, expected active, found ".concat((t=n.subscription)===null||t===void 0?void 0:t.type));return}this.closeStreamControllers(n.subscription.streamControllers,e);let r=n.subscription;n.subscription={type:"none"},this.subscriptionHandles.delete(r.subcriptionHandle),this.emit("sfuUpdateSubscription",{sid:e,subscribe:!1})}closeStreamControllers(e,t){for(let r of e){var n=O(r,2);let s=n[0],a=n[1];a();try{s.close()}catch(o){he.warn("Failed to close readable stream for track ".concat(t,": ").concat(o))}}}receiveSfuPublicationUpdates(e){return p(this,void 0,void 0,function*(){if(e.size===0)return;let t=new Map;for(let s of e.entries()){var n=O(s,2);let a=n[0],o=n[1],d=new Set;for(let c of o)d.add(c.sid),!this.descriptors.has(c.sid)&&(yield this.handleTrackPublished(a,c));t.set(a,d)}for(let s of t.entries()){var r=O(s,2);let a=r[0],o=r[1],c=Array.from(this.descriptors.entries()).filter(l=>{let u=O(l,2);return u[0],u[1].publisherIdentity===a}).map(l=>O(l,1)[0]).filter(l=>!o.has(l));for(let l of c)this.handleTrackUnpublished(l)}})}queryPublications(){return p(this,void 0,void 0,function*(){return Array.from(this.descriptors.values()).map(e=>e.info)})}handleTrackPublished(e,t){return p(this,void 0,void 0,function*(){if(this.descriptors.has(t.sid)){he.error("Existing descriptor for track ".concat(t.sid));return}let n={info:t,publisherIdentity:e,subscription:{type:"none"},pipelineOptions:{}};this.descriptors.set(n.info.sid,n);let r=new qi(n.info,this,{publisherIdentity:e});this.emit("trackPublished",{track:r})})}handleTrackUnpublished(e){let t=this.descriptors.get(e);if(!t){he.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(let n of e.entries()){var t=O(n,2);let r=t[0],s=t[1];this.registerSubscriberHandle(r,s)}}registerSubscriberHandle(e,t){var n,r;let s=this.descriptors.get(t);if(!s){he.error("Unknown track ".concat(t));return}switch(s.subscription.type){case"none":{he.warn("No subscription for ".concat(t));return}case"active":{s.subscription.subcriptionHandle=e,this.subscriptionHandles.set(e,t);return}case"pending":{let a=new Ns({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=(n=o.completionFuture).resolve)===null||r===void 0||r.call(n)}}}packetReceived(e){return p(this,void 0,void 0,function*(){let t;try{var n=ji.fromBinary(e),r=O(n,1);t=r[0]}catch(d){he.error("Failed to deserialize packet: ".concat(d));return}let s=this.subscriptionHandles.get(t.header.trackHandle);if(!s){he.warn("Unknown subscriber handle ".concat(t.header.trackHandle));return}let a=this.descriptors.get(s);if(!a){he.error("Missing descriptor for track ".concat(s));return}if(a.subscription.type!=="active"){he.warn("Received packet for track ".concat(s," without active subscription"));return}let o=yield a.subscription.pipeline.processPacket(t);if(o)for(let d of a.subscription.streamControllers.keys()){if(d.desiredSize!==null&&d.desiredSize<=0){he.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}let c=nl.lossyIntoFrame(o);d.enqueue(c)}})}resendSubscriptionUpdates(){for(let t of this.descriptors){var e=O(t,2);let n=e[0];e[1].subscription.type!=="none"&&this.emit("sfuUpdateSubscription",{sid:n,subscribe:!0})}}handleRemoteParticipantDisconnected(e){var t,n;for(let r of this.descriptors.values())if(r.publisherIdentity===e)switch(r.subscription.type){case"none":break;case"pending":(n=(t=r.subscription.completionFuture).reject)===null||n===void 0||n.call(t,De.disconnected());break;case"active":this.unSubscribeRequest(r.info.sid);break}}reset(){var e,t;for(let n of this.descriptors.values())this.emit("trackUnpublished",{sid:n.info.sid,publisherIdentity:n.publisherIdentity}),n.subscription.type==="pending"&&((t=(e=n.subscription.completionFuture).reject)===null||t===void 0||t.call(e,De.disconnected())),n.subscription.type==="active"&&this.closeStreamControllers(n.subscription.streamControllers,n.info.sid);this.descriptors.clear(),this.subscriptionHandles.clear()}},Hi=class i extends we{constructor(e,t,n){super(19,e,n),this.name="DataTrackPacketizerError",this.reason=t,this.reasonName=Gi[t]}static mtuTooShort(){return new i("MTU is too short to send frame",Gi.MtuTooShort)}},Gi;(function(i){i[i.MtuTooShort=0]="MtuTooShort"})(Gi||(Gi={}));var Fs=class i{constructor(e,t){this.sequence=Ct.u16(0),this.frameNumber=Ct.u16(0),this.clock=bs.rtpStartingNow(Pi.rtpRandom()),this.handle=e,this.mtuSizeBytes=t}static computeFrameMarker(e,t){return t<=1?Q.Single:e===0?Q.Start:e===t-1?Q.Final:Q.Inter}*packetize(e,t){var n;let r=this.frameNumber.getThenIncrement(),s={marker:Q.Inter,trackHandle:this.handle,sequence:Ct.u16(0),frameNumber:r,timestamp:(n=t?.now)!==null&&n!==void 0?n:this.clock.now(),extensions:e.extensions},a=new Vn(s).toBinaryLengthBytes();if(a>=this.mtuSizeBytes)throw Hi.mtuTooShort();let 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;let h=this.sequence.getThenIncrement(),m=new Vn(Object.assign(Object.assign({},s),{marker:i.computeFrameMarker(l,d),sequence:h})),g=Math.min(o,e.payload.byteLength-u),f=new Uint8Array(e.payload.buffer,e.payload.byteOffset+u,g);yield new ji(m,f)}}},Oe;(function(i){i[i.NotAllowed=0]="NotAllowed",i[i.DuplicateName=1]="DuplicateName",i[i.Timeout=2]="Timeout",i[i.LimitReached=3]="LimitReached",i[i.Disconnected=4]="Disconnected",i[i.Cancelled=5]="Cancelled",i[i.InvalidName=6]="InvalidName",i[i.Unknown=7]="Unknown"})(Oe||(Oe={}));var Ae=class i extends we{constructor(e,t,n){super(21,e,n),this.name="DataTrackPublishError",this.reason=t,this.reasonName=Oe[t],this.rawMessage=n?.rawMessage}static notAllowed(e){return new i("Data track publishing unauthorized",Oe.NotAllowed,{rawMessage:e})}static duplicateName(e){return new i("Track name already taken",Oe.DuplicateName,{rawMessage:e})}static invalidName(e){return new i("Track name is invalid",Oe.InvalidName,{rawMessage:e})}static timeout(){return new i("Publish data track timed-out. Does the LiveKit server support data tracks?",Oe.Timeout)}static limitReached(e){return new i("Data track publication limit reached",Oe.LimitReached,{rawMessage:e})}static unknown(e,t){return new i("Received RequestResponse for publishDataTrack, but reason was unrecognised (".concat(e,", ").concat(t,")"),Oe.Unknown)}static disconnected(){return new i("Room disconnected",Oe.Disconnected)}static cancelled(){return new i("Publish data track cancelled by caller",Oe.Cancelled)}},Rn;(function(i){i[i.TrackUnpublished=0]="TrackUnpublished",i[i.Dropped=1]="Dropped"})(Rn||(Rn={}));var Ot=class i extends we{constructor(e,t,n){super(22,e,n),this.name="DataTrackPushFrameError",this.reason=t,this.reasonName=Rn[t]}static trackUnpublished(){return new i("Track is no longer published",Rn.TrackUnpublished)}static dropped(e){return new i("Frame was dropped",Rn.Dropped,{cause:e})}},Pn;(function(i){i[i.Packetizer=0]="Packetizer",i[i.Encryption=1]="Encryption"})(Pn||(Pn={}));var Ki=class i extends we{constructor(e,t,n){super(21,e,n),this.name="DataTrackOutgoingPipelineError",this.reason=t,this.reasonName=Pn[t]}static packetizer(e){return new i("Error packetizing frame",Pn.Packetizer,{cause:e})}static encryption(e){return new i("Error encrypting frame",Pn.Encryption,{cause:e})}},Wi=class i{constructor(e,t){this.trackSymbol=il,this.isLocal=!0,this.typeSymbol=rl,this.handle=null,this.log=F,this.flushedFuture=new ce,this.isFlushed=!0,this.handleManagerReset=()=>{var n,r;(r=(n=this.flushedFuture).resolve)===null||r===void 0||r.call(n),this.manager.off("packetsFlushedChange",this.handleManagerPacketsFlushedChange),this.manager.off("reset",this.handleManagerReset)},this.handleManagerPacketsFlushedChange=n=>{var r,s;this.isFlushed=n.isFlushed,n.isFlushed&&((s=(r=this.flushedFuture).resolve)===null||s===void 0||s.call(r),this.flushedFuture=new ce)},this.options=e,this.manager=t,this.log=_e(ue.DataTracks),this.manager.on("packetsFlushedChange",this.handleManagerPacketsFlushedChange),this.manager.on("reset",this.handleManagerReset)}static withExplicitHandle(e,t,n){let r=new i(e,t);return r.handle=n,r}get info(){let e=this.descriptor;if(e?.type==="active")return e.info}get descriptor(){return this.handle?this.manager.getDescriptor(this.handle):null}publish(e){return p(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 Ot.trackUnpublished();let t=nl.from(e);try{return this.manager.tryProcessAndSend(this.handle,t)}catch(n){throw n}}flush(){return p(this,void 0,void 0,function*(){if(!this.isFlushed)return this.flushedFuture.promise})}unpublish(){return p(this,void 0,void 0,function*(){if(!this.handle){F.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}})}},zi=class i{constructor(e){this.e2eeManager=e.e2eeManager,this.packetizer=new Fs(e.info.pubHandle,i.TRANSPORT_MTU_BYTES)}updateE2eeManager(e){this.e2eeManager=e}processFrame(e){return Eh(this,arguments,function*(){let n=yield rn(this.encryptIfNeeded(e));try{yield rn(yield*Rh(Be(this.packetizer.packetize(n))))}catch(r){throw r instanceof Hi?Ki.packetizer(r):r}})}encryptIfNeeded(e){return p(this,void 0,void 0,function*(){if(!this.e2eeManager)return e;let t;try{t=yield this.e2eeManager.encryptData(e.payload)}catch(n){throw Ki.encryption(n)}return e.payload=t.payload,e.extensions.e2ee=new jt(t.keyIndex,t.iv),e})}};zi.TRANSPORT_MTU_BYTES=16e3;var $e=_e(ue.DataTracks),dc={pending(){return{type:"pending",completionFuture:new ce}},active(i,e){return{type:"active",info:i,publishState:"published",pipeline:new zi({info:i,e2eeManager:e}),unpublishingFuture:new ce}}},Rp=1e4,Bs=class i extends Ee.EventEmitter{constructor(e){var t;super(),this.handleAllocator=new ks,this.descriptors=new Map,this.inFlightPacketCounter=new Map,this.e2eeManager=(t=e?.e2eeManager)!==null&&t!==void 0?t:null}static withDescriptors(e){let t=new i;return t.descriptors=e,t}updateE2eeManager(e){this.e2eeManager=e;for(let t of this.descriptors.values())t.type==="active"&&t.pipeline.updateE2eeManager(e)}getDescriptor(e){var t;return(t=this.descriptors.get(e))!==null&&t!==void 0?t:null}tryProcessAndSend(e,t){return p(this,void 0,void 0,function*(){var n,r,s,a,o;let d=this.getDescriptor(e);if(d?.type!=="active"||d.publishState==="unpublished")throw Ot.trackUnpublished();if(d.publishState==="republishing")throw Ot.dropped("Data track republishing");try{try{for(var c=!0,l=Be(d.pipeline.processFrame(t)),u;u=yield l.next(),n=u.done,!n;c=!0){a=u.value,c=!1;let h=a,m=(o=this.inFlightPacketCounter.get(e))!==null&&o!==void 0?o:0;this.inFlightPacketCounter.set(e,m+1),m===0&&this.emit("packetsFlushedChange",{handle:e,isFlushed:!1}),this.emit("packetAvailable",{handle:e,bytes:h.toBinary()})}}catch(h){r={error:h}}finally{try{!c&&!n&&(s=l.return)&&(yield s.call(l))}finally{if(r)throw r.error}}}catch(h){throw Ot.dropped(h)}})}handlePacketSendComplete(e){var t;let r=((t=this.inFlightPacketCounter.get(e))!==null&&t!==void 0?t:0)-1;r<0&&($e.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 p(this,void 0,void 0,function*(){let n=this.handleAllocator.get();if(!n)throw Ae.limitReached();let r=tl(Rp),s=t?el([t,r]):r;if(this.descriptors.has(n))throw new Error("Descriptor for handle already exists");let a=dc.pending();this.descriptors.set(n,a);let o=()=>{var d,c;let l=this.descriptors.get(n);if(!l){$e.warn("No descriptor for ".concat(n));return}this.descriptors.delete(n),this.emit("sfuUnpublishRequest",{handle:n}),l.type==="pending"&&((c=(d=l.completionFuture).reject)===null||c===void 0||c.call(d,r.aborted?Ae.timeout():Ae.cancelled()))};return s.aborted?(o(),a.completionFuture.promise.then(()=>n)):(s.addEventListener("abort",o),this.emit("sfuPublishRequest",{handle:n,name:e.name,usesE2ee:this.e2eeManager!==null}),yield a.completionFuture.promise,s.removeEventListener("abort",o),this.emit("trackPublished",{track:Wi.withExplicitHandle(e,this,n)}),n)})}queryPublished(){return Array.from(this.descriptors.values()).filter(t=>t.type==="active").map(t=>t.info)}unpublishRequest(e){return p(this,void 0,void 0,function*(){let t=this.descriptors.get(e);if(!t){$e.warn("No descriptor for ".concat(e));return}if(t.type!=="active"){$e.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 n,r,s,a;let o=this.descriptors.get(e);if(!o){$e.warn("No descriptor for ".concat(e));return}switch(this.descriptors.delete(e),o.type){case"pending":{if(t.type==="ok"){let d=t.data,c=d.usesE2ee?this.e2eeManager:null;this.descriptors.set(d.pubHandle,dc.active(d,c)),(r=(n=o.completionFuture).resolve)===null||r===void 0||r.call(n)}else(a=(s=o.completionFuture).reject)===null||a===void 0||a.call(s,t.error);return}case"active":{if(o.publishState!=="republishing"){$e.warn("Track ".concat(e," already active"));return}if(t.type==="error"){$e.warn("Republish failed for track ".concat(e));return}$e.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,n;let r=this.descriptors.get(e);if(!r){$e.warn("No descriptor for ".concat(e));return}if(this.descriptors.delete(e),r.type!=="active"){$e.warn("Track ".concat(e," not active"));return}r.publishState="unpublished",(n=(t=r.unpublishingFuture).resolve)===null||n===void 0||n.call(t)}sfuWillRepublishTracks(){var e,t;for(let r of this.descriptors.entries()){var n=O(r,2);let s=n[0],a=n[1];switch(a.type){case"pending":this.descriptors.delete(s),(t=(e=a.completionFuture).reject)===null||t===void 0||t.call(e,Ae.disconnected());break;case"active":a.publishState="republishing",this.emit("sfuPublishRequest",{handle:a.info.pubHandle,name:a.info.name,usesE2ee:a.info.usesE2ee})}}}reset(){return p(this,void 0,void 0,function*(){var e,t,n,r;this.handleAllocator.reset();for(let s of this.descriptors.values())switch(s.type){case"pending":(t=(e=s.completionFuture).reject)===null||t===void 0||t.call(e,Ae.disconnected());break;case"active":(r=(n=s.unpublishingFuture).resolve)===null||r===void 0||r.call(n),yield this.unpublishRequest(s.info.pubHandle);break}this.descriptors.clear(),this.inFlightPacketCounter.clear(),this.emit("reset")})}},G=class i extends Error{constructor(e,t,n,r){super(t),this.code=e,this.message=lc(t,i.MAX_MESSAGE_BYTES),this.data=n?lc(n,i.MAX_DATA_BYTES):void 0,typeof r?.cause<"u"&&(this.cause=r?.cause)}static fromProto(e){return new i(e.code,e.message,e.data)}toProto(){return new Nc({code:this.code,message:this.message,data:this.data})}static builtIn(e,t,n){return new i(i.ErrorCode[e],i.ErrorMessage[e],t,n)}};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"};var sl=15360,al="lk.rpc_request",ol="lk.rpc_response",me;(function(i){i.RPC_REQUEST_ID="lk.rpc_request_id",i.RPC_REQUEST_METHOD="lk.rpc_request_method",i.RPC_REQUEST_RESPONSE_TIMEOUT_MS="lk.rpc_request_response_timeout_ms",i.RPC_REQUEST_VERSION="lk.rpc_request_version"})(me||(me={}));var Pp=1,cl=2;function ja(i){return new TextEncoder().encode(i).length}function lc(i,e){if(ja(i)<=e)return i;let t=0,n=i.length,r=new TextEncoder;for(;t<n;){let s=Math.floor((t+n+1)/2);r.encode(i.slice(0,s)).length<=e?t=s:n=s-1}return i.slice(0,t)}var qs=class extends Ee.EventEmitter{constructor(e,t,n,r){super(),this.pendingAcks=new Map,this.pendingResponses=new Map,this.log=e,this.outgoingDataStreamManager=t,this.getRemoteParticipantClientProtocol=n,this.getServerVersion=r}performRpc(e){return p(this,arguments,void 0,function(t){var n=this;let r=t.destinationIdentity,s=t.method,a=t.payload,o=t.responseTimeout,d=o===void 0?15e3:o;return(function*(){let u=n.getRemoteParticipantClientProtocol(r);if(ja(a)>sl&&u<Si)throw G.builtIn("REQUEST_PAYLOAD_TOO_LARGE");let m=n.getServerVersion();if(m&&tt(m,"1.8.0")<0)throw G.builtIn("UNSUPPORTED_SERVER");let g=Math.max(d,8e3),f=crypto.randomUUID(),T=new ce,k=null,S=setTimeout(()=>{var y;n.pendingAcks.delete(f),(y=T.reject)===null||y===void 0||y.call(T,G.builtIn("CONNECTION_TIMEOUT")),n.pendingResponses.delete(f),k!==null&&clearTimeout(k)},7e3);n.pendingAcks.set(f,{resolve:()=>{clearTimeout(S)},participantIdentity:r}),n.pendingResponses.set(f,{completionFuture:T,participantIdentity:r}),yield n.publishRpcRequest(r,f,s,a,g,u),k=setTimeout(()=>{var y;n.pendingResponses.delete(f),(y=T.reject)===null||y===void 0||y.call(T,G.builtIn("RESPONSE_TIMEOUT"))},d);let L=T.promise.finally(()=>{clearTimeout(k),n.pendingAcks.has(f)&&(n.log.warn("RPC response received before ack",f),n.pendingAcks.delete(f),clearTimeout(S))});return[f,L]})()})}publishRpcRequest(e,t,n,r,s,a){return p(this,void 0,void 0,function*(){if(a>=Si){let o=yield this.outgoingDataStreamManager.streamText({topic:al,destinationIdentities:[e],attributes:{[me.RPC_REQUEST_ID]:t,[me.RPC_REQUEST_METHOD]:n,[me.RPC_REQUEST_RESPONSE_TIMEOUT_MS]:"".concat(s),[me.RPC_REQUEST_VERSION]:"".concat(cl)}});yield o.write(r),yield o.close();return}this.emit("sendDataPacket",{packet:new ge({destinationIdentities:[e],kind:Ze.RELIABLE,value:{case:"rpcRequest",value:new va({id:t,method:n,payload:r,responseTimeoutMs:s,version:Pp})}})})})}handleIncomingDataStream(e,t,n){return p(this,void 0,void 0,function*(){let r=n[me.RPC_REQUEST_ID];if(!r){this.log.warn("RPC data stream malformed: ".concat(me.RPC_REQUEST_ID," not set."));return}let 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 n,r;let s=this.pendingResponses.get(e);s?((r=(n=s.completionFuture).resolve)===null||r===void 0||r.call(n,t),this.pendingResponses.delete(e)):this.log.error("Response received for unexpected RPC request",e)}handleIncomingRpcResponseFailure(e,t){var n,r;let s=this.pendingResponses.get(e);s?((r=(n=s.completionFuture).reject)===null||r===void 0||r.call(n,t),this.pendingResponses.delete(e)):this.log.error("Response received for unexpected RPC request",e)}handleIncomingRpcAck(e){let t=this.pendingAcks.get(e);t?(t.resolve(),this.pendingAcks.delete(e)):this.log.error("Ack received for unexpected RPC request: ".concat(e))}handleParticipantDisconnected(e){var t;for(let a of this.pendingAcks){var n=O(a,2);let o=n[0];n[1].participantIdentity===e&&this.pendingAcks.delete(o)}for(let a of this.pendingResponses){var r=O(a,2);let o=r[0];var s=r[1];let 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))}}},js=class extends Ee.EventEmitter{constructor(e,t,n){super(),this.rpcHandlers=new Map,this.log=e,this.outgoingDataStreamManager=t,this.getRemoteParticipantClientProtocol=n}registerRpcMethod(e,t){if(this.rpcHandlers.has(e))throw Error("RPC handler already registered for method ".concat(e,", unregisterRpcMethod before trying to register again"));this.rpcHandlers.set(e,t)}unregisterRpcMethod(e){this.rpcHandlers.delete(e)}handleIncomingRpcRequest(e,t){return p(this,void 0,void 0,function*(){var n;if(this.publishRpcAck(e,t.id),t.version!==1){this.publishRpcResponsePacket(e,t.id,null,G.builtIn("UNSUPPORTED_VERSION"));return}let 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((n=a?.message)!==null&&n!==void 0?n:a),{cause:a})),this.publishRpcResponsePacket(e,t.id,null,o);return}yield this.publishRpcResponse(e,t.id,s??"")})}handleIncomingDataStream(e,t,n){return p(this,void 0,void 0,function*(){let r=n[me.RPC_REQUEST_ID],s=n[me.RPC_REQUEST_METHOD],a=parseInt(n[me.RPC_REQUEST_RESPONSE_TIMEOUT_MS],10),o=parseInt(n[me.RPC_REQUEST_VERSION],10);if(!r||!s||Number.isNaN(a)||Number.isNaN(o)){this.log.warn("RPC data stream malformed: ".concat(me.RPC_REQUEST_ID," / ").concat(me.RPC_REQUEST_METHOD," / ").concat(me.RPC_REQUEST_RESPONSE_TIMEOUT_MS," / ").concat(me.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!==cl){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}let 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 ge({destinationIdentities:[e],kind:Ze.RELIABLE,value:{case:"rpcAck",value:new er({requestId:t})}})})}publishRpcResponsePacket(e,t,n,r){this.emit("sendDataPacket",{packet:new ge({destinationIdentities:[e],kind:Ze.RELIABLE,value:{case:"rpcResponse",value:new ya({requestId:t,value:r?{case:"error",value:r.toProto()}:{case:"payload",value:n??""}})}})})}publishRpcResponse(e,t,n){return p(this,void 0,void 0,function*(){if(this.getRemoteParticipantClientProtocol(e)>=Si){let a=yield this.outgoingDataStreamManager.streamText({topic:ol,destinationIdentities:[e],attributes:{[me.RPC_REQUEST_ID]:t}});yield a.write(n),yield a.close();return}if(ja(n)>sl){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,n,null)})}},Vs=class extends Ri{constructor(e,t,n,r,s,a){super(e,t,_.Kind.Audio,n,a),this.monitorReceiver=()=>p(this,void 0,void 0,function*(){if(!this.receiver){this._currentBitrate=0;return}let o=yield this.getReceiverStats();o&&this.prevStats&&this.receiver&&(this._currentBitrate=ar(o,this.prevStats)),this.prevStats=o}),this.audioContext=r,this.webAudioPluginNodes=[],s&&(this.sinkId=s.deviceId)}setVolume(e){var t;for(let n of this.attachedElements)this.audioContext?(t=this.gainNode)===null||t===void 0||t.gain.setTargetAtTime(e,0,.1):n.volume=e;He()&&this._mediaStreamTrack._setVolume(e),this.elementVolume=e}getVolume(){if(this.elementVolume)return this.elementVolume;if(He())return 1;let e=0;return this.attachedElements.forEach(t=>{t.volume>e&&(e=t.volume)}),e}setSinkId(e){return p(this,void 0,void 0,function*(){this.sinkId=e,yield Promise.all(this.attachedElements.map(t=>{if(us(t))return t.setSinkId(e)}))})}attach(e){let t=this.attachedElements.length===0;return e?super.attach(e):e=super.attach(),this.sinkId&&us(e)&&e.setSinkId(this.sinkId).catch(n=>{this.log.error("Failed to set sink id on remote audio track",n,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 n=this.sourceNode;this.webAudioPluginNodes.forEach(r=>{n.connect(r),n=r}),this.gainNode=e.createGain(),n.connect(this.gainNode),this.gainNode.connect(e.destination),this.elementVolume&&this.gainNode.gain.setTargetAtTime(this.elementVolume,0,.1),e.state!=="running"&&e.resume().then(()=>{e.state!=="running"&&this.emit(P.AudioPlaybackFailed,new Error("Audio Context couldn't be started automatically"))}).catch(r=>{this.emit(P.AudioPlaybackFailed,r)})}disconnectWebAudio(){var e,t;(e=this.gainNode)===null||e===void 0||e.disconnect(),(t=this.sourceNode)===null||t===void 0||t.disconnect(),this.gainNode=void 0,this.sourceNode=void 0}getReceiverStats(){return p(this,void 0,void 0,function*(){if(!this.receiver||!this.receiver.getStats)return;let e=yield this.receiver.getStats(),t;return e.forEach(n=>{n.type==="inbound-rtp"&&(t={type:"audio",streamId:n.id,timestamp:n.timestamp,jitter:n.jitter,bytesReceived:n.bytesReceived,concealedSamples:n.concealedSamples,concealmentEvents:n.concealmentEvents,silentConcealedSamples:n.silentConcealedSamples,silentConcealmentEvents:n.silentConcealmentEvents,totalAudioEnergy:n.totalAudioEnergy,totalSamplesDuration:n.totalSamplesDuration})}),t})}},Ne=class extends Ee.EventEmitter{constructor(e,t,n,r){var s;super(),this.metadataMuted=!1,this.encryption=J.NONE,this.log=F,this.handleMuted=()=>{this.emit(P.Muted)},this.handleUnmuted=()=>{this.emit(P.Unmuted)},this.log=_e((s=r?.loggerName)!==null&&s!==void 0?s:ue.Publication),this.loggerContextCb=this.loggerContextCb,this.setMaxListeners(100),this.kind=e,this.trackSid=t,this.trackName=n,this.source=_.Source.Unknown}setTrack(e){this.track&&(this.track.off(P.Muted,this.handleMuted),this.track.off(P.Unmuted,this.handleUnmuted)),this.track=e,e&&(e.on(P.Muted,this.handleMuted),e.on(P.Unmuted,this.handleUnmuted))}get logContext(){var e;return Object.assign(Object.assign({},(e=this.loggerContextCb)===null||e===void 0?void 0:e.call(this)),j(this))}get isMuted(){return this.metadataMuted}get isEnabled(){return!0}get isSubscribed(){return this.track!==void 0}get isEncrypted(){return this.encryption!==J.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=_.sourceFromProto(e.source),this.mimeType=e.mimeType,this.kind===_.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(i){(function(e){e.Desired="desired",e.Subscribed="subscribed",e.Unsubscribed="unsubscribed"})(i.SubscriptionStatus||(i.SubscriptionStatus={})),(function(e){e.Allowed="allowed",e.NotAllowed="not_allowed"})(i.PermissionStatus||(i.PermissionStatus={}))})(Ne||(Ne={}));var Hn=class extends Ne{get isUpstreamPaused(){var e;return(e=this.track)===null||e===void 0?void 0:e.isUpstreamPaused}constructor(e,t,n,r){super(e,t.sid,t.name,r),this.track=void 0,this.handleTrackEnded=()=>{this.emit(P.Ended)},this.handleCpuConstrained=()=>{this.track&&ht(this.track)&&this.emit(P.CpuConstrained,this.track)},this.updateInfo(t),this.setTrack(n)}setTrack(e){this.track&&(this.track.off(P.Ended,this.handleTrackEnded),this.track.off(P.CpuConstrained,this.handleCpuConstrained)),super.setTrack(e),e&&(e.on(P.Ended,this.handleTrackEnded),e.on(P.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 p(this,void 0,void 0,function*(){var e;return(e=this.track)===null||e===void 0?void 0:e.mute()})}unmute(){return p(this,void 0,void 0,function*(){var e;return(e=this.track)===null||e===void 0?void 0:e.unmute()})}pauseUpstream(){return p(this,void 0,void 0,function*(){var e;yield(e=this.track)===null||e===void 0?void 0:e.pauseUpstream()})}resumeUpstream(){return p(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)){let t=this.track.getSourceTrackSettings(),n=new Set;return t.autoGainControl&&n.add(le.TF_AUTO_GAIN_CONTROL),t.echoCancellation&&n.add(le.TF_ECHO_CANCELLATION),t.noiseSuppression&&n.add(le.TF_NOISE_SUPPRESSION),t.channelCount&&t.channelCount>1&&n.add(le.TF_STEREO),!((e=this.options)===null||e===void 0)&&e.dtx||n.add(le.TF_NO_DTX),this.track.enhancedNoiseCancellation&&n.add(le.TF_ENHANCED_NOISE_CANCELLATION),Array.from(n.values())}else return[]}};function or(i,e){return p(this,void 0,void 0,function*(){i??(i={});let t=!1,n=Hd(i),r=n.audioProcessor,s=n.videoProcessor,a=n.optionsWithoutProcessor,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),i.audio&&typeof a.audio=="object"&&typeof a.audio.deviceId=="string"){let 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"){let 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");let c=qd(a,Qd,Yd),l=Ma(c),u=navigator.mediaDevices.getUserMedia(l);a.audio&&(Pe.userMediaPromiseMap.set("audioinput",u),u.catch(()=>Pe.userMediaPromiseMap.delete("audioinput"))),a.video&&(Pe.userMediaPromiseMap.set("videoinput",u),u.catch(()=>Pe.userMediaPromiseMap.delete("videoinput")));try{let h=yield u;return yield Promise.all(h.getTracks().map(m=>p(this,void 0,void 0,function*(){let g=m.kind==="audio",f,T=g?l.audio:l.video;typeof T!="boolean"&&(f=T);let k=m.getSettings().deviceId;f?.deviceId&&Lt(f.deviceId)!==k?f.deviceId=k:f||(f={deviceId:k});let S=tp(m,f,e);return S.kind===_.Kind.Video?S.source=_.Source.Camera:S.kind===_.Kind.Audio&&(S.source=_.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 or(Object.assign(Object.assign({},i),{audio:o,video:d}),e)}})}function Ip(i){return p(this,void 0,void 0,function*(){return(yield or({audio:!1,video:i??!0}))[0]})}function Mp(i){return p(this,void 0,void 0,function*(){return(yield or({audio:i??!0,video:!1}))[0]})}var yt;(function(i){i.Excellent="excellent",i.Good="good",i.Poor="poor",i.Lost="lost",i.Unknown="unknown"})(yt||(yt={}));function Ap(i){switch(i){case kn.EXCELLENT:return yt.Excellent;case kn.GOOD:return yt.Good;case kn.POOR:return yt.Poor;case kn.LOST:return yt.Lost;default:return yt.Unknown}}var Ji=class extends Ee.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===An.AGENT}get isActive(){var e;return((e=this.participantInfo)===null||e===void 0?void 0:e.state)===Jt.ACTIVE}get kind(){return this._kind}get attributes(){return Object.freeze(Object.assign({},this._attributes))}constructor(e,t,n,r,s,a){let o=arguments.length>6&&arguments[6]!==void 0?arguments[6]:An.STANDARD;var d;super(),this.audioLevel=0,this.isSpeaking=!1,this._connectionQuality=yt.Unknown,this.log=F,this.loggerOptions=a,this.log=_e((d=a?.loggerName)!==null&&d!==void 0?d:ue.Participant,()=>this.logContext),this.setMaxListeners(100),this.sid=e,this.identity=t,this.name=n,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(let n of this.trackPublications){var t=O(n,2);let r=t[1];if(r.source===e)return r}}getTrackPublicationByName(e){for(let n of this.trackPublications){var t=O(n,2);let r=t[1];if(r.trackName===e)return r}}waitUntilActive(){return this.isActive?Promise.resolve():this.activeFuture?this.activeFuture.promise:(this.activeFuture=new ce,this.once(I.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;let t=this.getTrackPublication(_.Source.Camera);return!(!((e=t?.isMuted)!==null&&e!==void 0)||e)}get isMicrophoneEnabled(){var e;let t=this.getTrackPublication(_.Source.Microphone);return!(!((e=t?.isMuted)!==null&&e!==void 0)||e)}get isScreenShareEnabled(){return!!this.getTrackPublication(_.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===Jt.ACTIVE&&((t=this.participantInfo)===null||t===void 0?void 0:t.state)!==Jt.ACTIVE&&this.emit(I.Active),e.permission&&this.setPermissions(e.permission),this.participantInfo=e,!0)}_setMetadata(e){let t=this.metadata!==e,n=this.metadata;this.metadata=e,t&&this.emit(I.ParticipantMetadataChanged,n)}_setName(e){let t=this.name!==e;this.name=e,t&&this.emit(I.ParticipantNameChanged,e)}_setAttributes(e){let t=Yh(this.attributes,e);this._attributes=e,Object.keys(t).length>0&&this.emit(I.AttributesChanged,t)}setPermissions(e){var t,n,r,s,a,o;let d=this.permissions,c=e.canPublish!==((t=this.permissions)===null||t===void 0?void 0:t.canPublish)||e.canSubscribe!==((n=this.permissions)===null||n===void 0?void 0:n.canSubscribe)||e.canPublishData!==((r=this.permissions)===null||r===void 0?void 0:r.canPublishData)||e.hidden!==((s=this.permissions)===null||s===void 0?void 0:s.hidden)||e.recorder!==((a=this.permissions)===null||a===void 0?void 0:a.recorder)||e.canPublishSources.length!==this.permissions.canPublishSources.length||e.canPublishSources.some((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);return this.permissions=e,c&&this.emit(I.ParticipantPermissionsChanged,d),c}setIsSpeaking(e){e!==this.isSpeaking&&(this.isSpeaking=e,e&&(this.lastSpokeAt=new Date),this.emit(I.IsSpeakingChanged,e))}setConnectionQuality(e){let t=this._connectionQuality;this._connectionQuality=Ap(e),t!==this._connectionQuality&&this.emit(I.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){e.on(P.Muted,()=>{this.emit(I.TrackMuted,e)}),e.on(P.Unmuted,()=>{this.emit(I.TrackUnmuted,e)});let t=e;switch(t.track&&(t.track.sid=e.trackSid),this.trackPublications.set(e.trackSid,e),e.kind){case _.Kind.Audio:this.audioTrackPublications.set(e.trackSid,e);break;case _.Kind.Video:this.videoTrackPublications.set(e.trackSid,e);break}}};function xp(i){var e,t,n;if(!i.participantSid&&!i.participantIdentity)throw new Error("Invalid track permission, must provide at least one of participantIdentity and participantSid");return new Zc({participantIdentity:(e=i.participantIdentity)!==null&&e!==void 0?e:"",participantSid:(t=i.participantSid)!==null&&t!==void 0?t:"",allTracks:(n=i.allowAll)!==null&&n!==void 0?n:!1,trackSids:i.allowedTrackSids||[]})}var Hs=class extends Ji{constructor(e,t,n,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=J.NONE,this.e2eeStateMutex=new de,this.enabledPublishVideoCodecs=[],this.handleReconnecting=()=>{this.reconnectFuture||(this.reconnectFuture=new ce)},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,m,g;this.reconnectFuture&&(this.reconnectFuture.promise.catch(f=>this.log.warn(f.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),(g=(m=this.activeAgentFuture)===null||m===void 0?void 0:m.reject)===null||g===void 0||g.call(m,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 ce),(u=(l=this.signalConnectedFuture).resolve)===null||u===void 0||u.call(l)},this.handleSignalRequestResponse=c=>{let l=c.requestId,u=c.reason,h=c.message,m=this.pendingSignalRequests.get(l);switch(m&&(u!==It.OK&&m.reject(new _i(h,u)),this.pendingSignalRequests.delete(l)),c.request.case){case"publishDataTrack":{let g;switch(c.reason){case It.NOT_ALLOWED:g=Ae.notAllowed(c.message);break;case It.DUPLICATE_NAME:g=Ae.duplicateName(c.message);break;case It.INVALID_NAME:g=Ae.invalidName(c.message);break;case It.LIMIT_EXCEEDED:g=Ae.limitReached(c.message);break;default:g=Ae.unknown(c.reason,c.message);break}this.roomOutgoingDataTrackManager.receivedSfuPublishResponse(c.request.value.pubHandle,{type:"error",error:g});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=>xp(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",j(c));return}this.engine.updateMuteStatus(c.sid,l)},this.onTrackUpstreamPaused=c=>{this.log.debug("upstream paused",j(c)),this.onTrackMuted(c,!0)},this.onTrackUpstreamResumed=c=>{this.log.debug("upstream resumed",j(c)),this.onTrackMuted(c,c.isMuted)},this.onTrackFeatureUpdate=c=>{let 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)=>{this.log.debug("track cpu constrained",j(l)),this.emit(I.LocalTrackCpuConstrained,c,l)},this.handleSubscribedQualityUpdate=c=>p(this,void 0,void 0,function*(){var l,u,h,m,g;if(!(!((g=this.roomOptions)===null||g===void 0)&&g.dynacast))return;let f=this.videoTrackPublications.get(c.trackSid);if(!f){this.log.warn("received subscribed quality update for unknown track",{trackSid:c.trackSid});return}if(!f.videoTrack)return;let T=yield f.videoTrack.setPublishingCodecs(c.subscribedCodecs);try{for(var k=!0,S=Be(T),L;L=yield S.next(),l=L.done,!l;k=!0){m=L.value,k=!1;let y=m;Wh(y)&&(this.log.debug("publish ".concat(y," for ").concat(f.videoTrack.sid),j(f)),yield this.publishAdditionalCodecForTrack(f.videoTrack,y,f.options))}}catch(y){u={error:y}}finally{try{!k&&!l&&(h=S.return)&&(yield h.call(S))}finally{if(u)throw u.error}}}),this.handleLocalTrackUnpublished=c=>{let 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=>p(this,void 0,void 0,function*(){if(c.source===_.Source.ScreenShare||c.source===_.Source.ScreenShareAudio)this.log.debug("unpublishing local track due to TrackEnded",j(c)),this.unpublishTrack(c);else if(c.isUserProvided)yield c.mute();else if(at(c)||Je(c))try{if(Ce())try{let l=yield navigator?.permissions.query({name:c.source===_.Source.Camera?"camera":"microphone"});if(l&&l.state==="denied")throw this.log.warn("user has revoked access to ".concat(c.source),j(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",j(c)),at(c)?yield c.restartTrack({deviceId:"default"}):yield c.restartTrack())}catch{this.log.warn("could not restart track, muting instead",j(c)),yield c.mute()}}),this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this.engine=n,this.roomOptions=r,this.setupEngine(n),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!==J.NONE}getTrackPublication(e){let t=super.getTrackPublication(e);if(t)return t}getTrackPublicationByName(e){let t=super.getTrackPublicationByName(e);if(t)return t}setupEngine(e){var t;this.engine=e,this.engine.on(R.RemoteMute,(n,r)=>{let s=this.trackPublications.get(n);!s||!s.track||(r?s.mute():s.unmute())}),!((t=this.signalConnectedFuture)===null||t===void 0)&&t.isResolved&&(this.signalConnectedFuture=void 0),this.engine.on(R.Connected,this.handleReconnected).on(R.SignalConnected,this.handleSignalConnected).on(R.SignalRestarted,this.handleReconnected).on(R.SignalResumed,this.handleReconnected).on(R.Restarting,this.handleReconnecting).on(R.Resuming,this.handleReconnecting).on(R.LocalTrackUnpublished,this.handleLocalTrackUnpublished).on(R.SubscribedQualityUpdate,this.handleSubscribedQualityUpdate).on(R.Closing,this.handleClosing).on(R.SignalRequestResponse,this.handleSignalRequestResponse)}setMetadata(e){return p(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({metadata:e})})}setName(e){return p(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({name:e})})}setAttributes(e){return p(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({attributes:e})})}requestMetadataUpdate(e){return p(this,arguments,void 0,function(t){var n=this;let r=t.metadata,s=t.name,a=t.attributes;return(function*(){return new pe((o,d)=>p(n,void 0,void 0,function*(){var c,l;try{let u=!1,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),m=performance.now();for(this.pendingSignalRequests.set(h,{resolve:o,reject:g=>{d(g),u=!0},values:{name:s,metadata:r,attributes:a}});performance.now()-m<5e3&&!u;){if((!s||this.name===s)&&(!r||this.metadata===r)&&(!a||Object.entries(a).every(g=>{let f=O(g,2),T=f[0],k=f[1];return this.attributes[T]===k||k===""&&!this.attributes[T]}))){this.pendingSignalRequests.delete(h),o();return}yield ve(50)}d(new _i("Request to update local metadata timed out","TimeoutError"))}catch(u){u instanceof Error?d(u):d(new Error(String(u)))}}))})()})}setCameraEnabled(e,t,n){return this.setTrackEnabled(_.Source.Camera,e,t,n)}setMicrophoneEnabled(e,t,n){return this.setTrackEnabled(_.Source.Microphone,e,t,n)}setScreenShareEnabled(e,t,n){return this.setTrackEnabled(_.Source.ScreenShare,e,t,n)}setE2EEEnabled(e){return p(this,void 0,void 0,function*(){let t=yield this.e2eeStateMutex.lock();try{if(this.encryptionType=e?J.GCM:J.NONE,yield Promise.all(this.pendingPublishPromises.values()),this.trackPublications.size===0||Array.from(this.trackPublications.values()).every(n=>n.isEncrypted===e))return;yield this.republishAllTracks(void 0,!1)}finally{t()}})}setTrackEnabled(e,t,n,r){return p(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)){let h=yield this.waitForPendingPublicationOfSource(e);return h||this.log.info("waiting for pending publication promise timed out",{source:e}),yield h?.unmute(),h}this.pendingPublishing.add(e);try{switch(e){case _.Source.Camera:u=yield this.createTracks({video:(s=n)!==null&&s!==void 0?s:!0});break;case _.Source.Microphone:u=yield this.createTracks({audio:(a=n)!==null&&a!==void 0?a:!0});break;case _.Source.ScreenShare:u=yield this.createScreenTracks(Object.assign({},n));break;default:throw new qe(e)}}catch(h){throw u?.forEach(m=>{m.stop()}),h instanceof Error&&this.emit(I.MediaDevicesError,h,cs(e)),this.pendingPublishing.delete(e),h}for(let h of u){let m=Object.assign(Object.assign({},this.roomOptions.publishDefaults),n);e===_.Source.Microphone&&et(h)&&m.preConnectBuffer&&(this.log.info("starting preconnect buffer for microphone"),h.startPreConnectBuffer())}try{let h=[];for(let g of u)this.log.info("publishing track",j(g)),h.push(this.publishTrack(g,r));let m=yield Promise.all(h);var d=O(m,1);o=d[0]}catch(h){throw u?.forEach(m=>{m.stop()}),h}finally{this.pendingPublishing.delete(e)}}else if(!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===_.Source.ScreenShare){let u=[this.unpublishTrack(o.track)],h=this.getTrackPublication(_.Source.ScreenShareAudio);h&&h.track&&u.push(this.unpublishTrack(h.track));var c=yield Promise.all(u),l=O(c,1);o=l[0]}else yield o.mute();return o})}enableCameraAndMicrophone(){return p(this,void 0,void 0,function*(){if(!(this.pendingPublishing.has(_.Source.Camera)||this.pendingPublishing.has(_.Source.Microphone))){this.pendingPublishing.add(_.Source.Camera),this.pendingPublishing.add(_.Source.Microphone);try{let e=yield this.createTracks({audio:!0,video:!0});yield Promise.all(e.map(t=>this.publishTrack(t)))}finally{this.pendingPublishing.delete(_.Source.Camera),this.pendingPublishing.delete(_.Source.Microphone)}}})}createTracks(e){return p(this,void 0,void 0,function*(){var t,n;e??(e={});let r=qd(e,(t=this.roomOptions)===null||t===void 0?void 0:t.audioCaptureDefaults,(n=this.roomOptions)===null||n===void 0?void 0:n.videoCaptureDefaults);try{return(yield or(r,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext})).map(o=>(et(o)&&(this.microphoneError=void 0,o.setAudioContext(this.audioContext),o.source=_.Source.Microphone,this.emit(I.AudioStreamAcquired)),ht(o)&&(this.cameraError=void 0,o.source=_.Source.Camera),o))}catch(s){throw s instanceof Error&&(e.audio&&(this.microphoneError=s),e.video&&(this.cameraError=s)),s}})}createScreenTracks(e){return p(this,void 0,void 0,function*(){if(e===void 0&&(e={}),navigator.mediaDevices.getDisplayMedia===void 0)throw new Dn("getDisplayMedia not supported");e.resolution===void 0&&!om()&&(e.resolution=Ia.h1080fps30.resolution);let t=Jh(e),n=yield navigator.mediaDevices.getDisplayMedia(t),r=n.getVideoTracks();if(r.length===0)throw new qe("no video track found");let s=new an(r[0],void 0,!1,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});s.source=_.Source.ScreenShare,e.contentHint&&(s.mediaStreamTrack.contentHint=e.contentHint);let a=[s];if(n.getAudioTracks().length>0){this.emit(I.AudioStreamAcquired);let o=new Et(n.getAudioTracks()[0],void 0,!1,this.audioContext,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});o.source=_.Source.ScreenShareAudio,a.push(o)}return a})}publishTrack(e,t){return p(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,n)=>{let r=()=>{clearTimeout(o),this.engine.off(R.Restarted,s),this.engine.off(R.Closing,a)},s=()=>{r(),t()},a=()=>{r(),n(new Error("engine closed before restart completed"))},o=setTimeout(()=>{r(),n(new Error("timed out waiting for engine restart"))},e);this.engine.once(R.Restarted,s),this.engine.once(R.Closing,a)})}publishOrRepublishTrack(e,t){return p(this,arguments,void 0,function(n,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;at(n)&&n.setAudioContext(s.audioContext),yield(d=s.reconnectFuture)===null||d===void 0?void 0:d.promise,s.republishPromise&&!a&&(yield s.republishPromise),Xt(n)&&s.pendingPublishPromises.has(n)&&(yield s.pendingPublishPromises.get(n));let h;if(n instanceof MediaStreamTrack)h=n.getConstraints();else{h=n.constraints;let S;switch(n.source){case _.Source.Microphone:S="audioinput";break;case _.Source.Camera:S="videoinput"}S&&s.activeDeviceMap.has(S)&&(h=Object.assign(Object.assign({},h),{deviceId:s.activeDeviceMap.get(S)}))}if(n instanceof MediaStreamTrack)switch(n.kind){case"audio":n=new Et(n,h,!0,s.audioContext,{loggerName:s.roomOptions.loggerName,loggerContextCb:()=>s.logContext});break;case"video":n=new an(n,h,!0,{loggerName:s.roomOptions.loggerName,loggerContextCb:()=>s.logContext});break;default:throw new qe("unsupported MediaStreamTrack kind ".concat(n.kind))}else n.updateLoggerOptions({loggerName:s.roomOptions.loggerName,loggerContextCb:()=>s.logContext});let m;if(s.trackPublications.forEach(S=>{S.track&&S.track===n&&(m=S)}),m)return s.log.warn("track has already been published, skipping",j(m)),m;let g=Object.assign(Object.assign({},s.roomOptions.publishDefaults),r),f="channelCount"in n.mediaStreamTrack.getSettings()&&n.mediaStreamTrack.getSettings().channelCount===2||n.mediaStreamTrack.getConstraints().channelCount===2,T=(c=g.forceStereo)!==null&&c!==void 0?c:f;T&&(g.dtx===void 0&&s.log.debug("Opus DTX will be disabled for stereo tracks by default. Enable them explicitly to make it work.",j(n)),g.red===void 0&&s.log.debug("Opus RED will be disabled for stereo tracks by default. Enable them explicitly to make it work."),(l=g.dtx)!==null&&l!==void 0||(g.dtx=!1),(u=g.red)!==null&&u!==void 0||(g.red=!1)),!dm()&&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"),g.simulcast=!1),g.source&&(n.source=g.source);let k=new Promise((S,L)=>p(s,void 0,void 0,function*(){try{if(this.engine.client.currentState!==W.CONNECTED){this.log.debug("deferring track publication until signal is connected",{track:j(n)});let y=!1,b=setTimeout(()=>{y=!0,n.stop(),L(new Ci("publishing rejected as engine not connected within timeout",408))},15e3);if(yield this.waitUntilEngineConnected(),clearTimeout(b),y)return;let E=yield this.publish(n,g,T);S(E)}else try{let y=yield this.publish(n,g,T);S(y)}catch(y){L(y)}}catch(y){L(y)}}));s.pendingPublishPromises.set(n,k);try{return yield k}catch(S){if(!o&&S instanceof lt)return s.log.warn("negotiation due to track publish failed, retrying after reconnect",{error:S}),s.pendingPublishPromises.delete(n),yield s.waitForNextEngineRestart(),yield s.publishOrRepublishTrack(n,r,a,!0);throw S}finally{s.pendingPublishPromises.delete(n)}})()})}waitUntilEngineConnected(){return this.signalConnectedFuture||(this.signalConnectedFuture=new ce),this.signalConnectedFuture.promise}hasPermissionsToPublish(e){if(!this.permissions)return this.log.warn("no permissions present for publishing track",j(e)),!1;let t=this.permissions,n=t.canPublish,r=t.canPublishSources;return n&&(r.length===0||r.map(s=>Xh(s)).includes(e.source))?!0:(this.log.warn("insufficient permissions to publish",j(e)),!1)}publish(e,t,n){return p(this,void 0,void 0,function*(){var r,s,a,o,d,c,l,u,h,m;if(!this.hasPermissionsToPublish(e))throw new Ci("failed to publish track, insufficient permissions",403);Array.from(this.trackPublications.values()).find(A=>Xt(e)&&A.source===e.source)&&e.source!==_.Source.Unknown&&this.log.info("publishing a second track with the same source: ".concat(e.source),j(e)),t.stopMicTrackOnMute&&et(e)&&(e.stopOnMute=!0),e.source===_.Source.ScreenShare&&Ft()&&(t.simulcast=!1),t.videoCodec==="av1"&&!im()&&(t.videoCodec=void 0),t.videoCodec==="vp9"&&!rm()&&(t.videoCodec=void 0),t.videoCodec===void 0&&(t.videoCodec=_s),this.enabledPublishVideoCodecs.length>0&&(this.enabledPublishVideoCodecs.some(A=>t.videoCodec===_n(A.mime))||(t.videoCodec=_n(this.enabledPublishVideoCodecs[0].mime)));let f=t.videoCodec;e.on(P.Muted,this.onTrackMuted),e.on(P.Unmuted,this.onTrackUnmuted),e.on(P.Ended,this.handleTrackEnded),e.on(P.UpstreamPaused,this.onTrackUpstreamPaused),e.on(P.UpstreamResumed,this.onTrackUpstreamResumed),e.on(P.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate);let T=[],k=!(!((r=t.dtx)!==null&&r!==void 0)||r),S=e.getSourceTrackSettings();S.autoGainControl&&T.push(le.TF_AUTO_GAIN_CONTROL),S.echoCancellation&&T.push(le.TF_ECHO_CANCELLATION),S.noiseSuppression&&T.push(le.TF_NOISE_SUPPRESSION),S.channelCount&&S.channelCount>1&&T.push(le.TF_STEREO),k&&T.push(le.TF_NO_DTX),at(e)&&e.hasPreConnectBuffer&&T.push(le.TF_PRECONNECT_BUFFER);let L=this.normalizeRequestedFrameMetadataOptions(e,t),y=new xn({cid:e.mediaStreamTrack.id,name:t.name,type:_.kindToProto(e.kind),muted:e.isMuted,source:_.sourceToProto(e.source),disableDtx:k,encryption:this.encryptionType,stereo:n,disableRed:this.isE2EEEnabled||!(!((s=t.red)!==null&&s!==void 0)||s),stream:t?.stream,backupCodecPolicy:t?.backupCodecPolicy,audioFeatures:T,packetTrailerFeatures:L}),b;if(e.kind===_.Kind.Video){let A;try{A=yield e.waitForDimensions()}catch{let B=(o=(a=this.roomOptions.videoCaptureDefaults)===null||a===void 0?void 0:a.resolution)!==null&&o!==void 0?o:On.h720.resolution;A={width:B.width,height:B.height},this.log.error("could not determine track dimensions, using defaults",Object.assign(Object.assign({},j(e)),{dims:A}))}y.width=A.width,y.height=A.height,Je(e)&&(je(f)&&(e.source===_.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",j(e)))),t.scalabilityMode=(d=t.scalabilityMode)!==null&&d!==void 0?d:"L3T3_KEY"),y.simulcastCodecs=[new Wr({codec:f,cid:e.mediaStreamTrack.id})],t.backupCodec===!0&&(t.backupCodec={codec:_s}),t.backupCodec&&f!==t.backupCodec.codec&&y.encryption===J.NONE&&(this.roomOptions.dynacast||(this.roomOptions.dynacast=!0),y.simulcastCodecs.push(new Wr({codec:t.backupCodec.codec,cid:""})))),b=Oi(e.source===_.Source.ScreenShare,y.width,y.height,t),y.layers=Wo(y.width,y.height,b,je(t.videoCodec))}else e.kind===_.Kind.Audio&&(b=[{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:(m=(h=t.audioPreset)===null||h===void 0?void 0:h.priority)!==null&&m!==void 0?m:"high"}]);if(!this.engine||this.engine.isClosed)throw new $("cannot publish track when not connected");let E=()=>p(this,void 0,void 0,function*(){var A,x,B;if(!this.engine.pcManager)throw new $("pcManager is not ready");if(e.sender=yield this.engine.createSender(e,t,b),Je(e)&&(e.publishOptions=t),this.emit(I.LocalSenderCreated,e.sender,e),Je(e)&&((A=t.degradationPreference)!==null&&A!==void 0||(t.degradationPreference=lp(e)),e.setDegradationPreference(t.degradationPreference)),b)if(Ft()&&e.kind===_.Kind.Audio){let Z;for(let ee of this.engine.pcManager.publisher.getTransceivers())if(ee.sender===e.sender){Z=ee;break}Z&&this.engine.pcManager.publisher.setTrackCodecBitrate({transceiver:Z,codec:"opus",maxbr:!((x=b[0])===null||x===void 0)&&x.maxBitrate?b[0].maxBitrate/1e3:0})}else e.codec&&je(e.codec)&&(!((B=b[0])===null||B===void 0)&&B.maxBitrate)&&this.engine.pcManager.publisher.setTrackCodecBitrate({cid:y.cid,codec:e.codec,maxbr:b[0].maxBitrate/1e3});yield this.engine.negotiate()}),M,D=new Promise((A,x)=>p(this,void 0,void 0,function*(){var B;try{M=yield this.engine.addTrack(y),A(M)}catch(Z){if(e.sender&&(!((B=this.engine.pcManager)===null||B===void 0)&&B.publisher)){try{this.engine.pcManager.publisher.removeTrack(e.sender)}catch(ee){this.log.error(ee)}yield this.engine.negotiate().catch(ee=>{this.log.error("failed to negotiate after removing track due to failed add track request",Object.assign(Object.assign({},j(e)),{error:ee}))})}x(Z)}}));if(this.enabledPublishVideoCodecs.length>0&&L.length===0)M=(yield Promise.all([D,E()]))[0];else{M=yield D;let A;if(M.codecs.forEach(x=>{A===void 0&&(A=x.mimeType)}),A&&e.kind===_.Kind.Video){let x=_n(A);x!==f&&(this.log.debug("falling back to server selected codec",Object.assign(Object.assign({},j(e)),{codec:x})),t.videoCodec=x,b=Oi(e.source===_.Source.ScreenShare,y.width,y.height,t))}yield E()}let q=new Hn(e.kind,M,e,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});if(q.on(P.CpuConstrained,A=>this.onTrackCpuConstrained(A,q)),q.options=t,e.sid=M.sid,Je(e)&&(e.publishOptions=t,y.width&&y.height&&(e.lastEncodedDimensions={width:y.width,height:y.height})),this.log.debug("publishing ".concat(e.kind," with encodings"),{encodings:b,trackInfo:M}),Je(e)?e.startMonitor(this.engine.client):at(e)&&e.startMonitor(),this.addTrackPublication(q),this.emit(I.LocalTrackPublished,q),at(e)&&M.audioFeatures.includes(le.TF_PRECONNECT_BUFFER)){let A=e.getPreConnectBuffer(),x=e.getPreConnectBufferMimeType();this.on(I.LocalTrackSubscribed,B=>{if(B.trackSid===M.sid){if(!e.hasPreConnectBuffer){this.log.warn("subscribe event came to late, buffer already closed");return}this.log.debug("finished recording preconnect buffer",j(e)),e.stopPreConnectBuffer()}}),A&&new Promise((Z,ee)=>p(this,void 0,void 0,function*(){var ze,mn,ye,ft,ur,hr;try{this.log.debug("waiting for agent",j(e));let gr=setTimeout(()=>{ee(new Error("agent not active within 10 seconds"))},1e4),Ll=yield this.waitUntilActiveAgentPresent();clearTimeout(gr),this.log.debug("sending preconnect buffer",j(e));let $a=yield this.streamBytes({name:"preconnect-buffer",mimeType:x,topic:"lk.agent.pre-connect-audio-buffer",destinationIdentities:[Ll.identity],attributes:{trackId:q.trackSid,sampleRate:String((ur=S.sampleRate)!==null&&ur!==void 0?ur:"48000"),channels:String((hr=S.channelCount)!==null&&hr!==void 0?hr:"1")}});try{for(var mr=!0,pr=Be(A),fr;fr=yield pr.next(),ze=fr.done,!ze;mr=!0){ft=fr.value,mr=!1;let vr=ft;yield $a.write(vr)}}catch(vr){mn={error:vr}}finally{try{!mr&&!ze&&(ye=pr.return)&&(yield ye.call(pr))}finally{if(mn)throw mn.error}}yield $a.close(),Z()}catch(gr){ee(gr)}})).then(()=>{this.log.debug("preconnect buffer sent successfully",j(e))}).catch(Z=>{this.log.error("error sending preconnect buffer",Object.assign(Object.assign({},j(e)),{error:Z}))})}return q})}canPublishFrameMetadata(){var e;return!!(this.roomOptions.e2ee||this.roomOptions.encryption||Fn((e=this.roomOptions.frameMetadata)!==null&&e!==void 0?e:this.roomOptions.packetTrailer))}normalizeRequestedFrameMetadataOptions(e,t){var n;let r=(n=t.frameMetadata)!==null&&n!==void 0?n:t.packetTrailer;if(e.kind!==_.Kind.Video||!Ei(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),j(e))),t.frameMetadata=void 0,t.packetTrailer=void 0,[];let s=xm(r),a=Dm(s);return t.frameMetadata=a,t.packetTrailer=a,s}get isLocal(){return!0}publishAdditionalCodecForTrack(e,t,n){return p(this,void 0,void 0,function*(){var r;if(this.encryptionType!==J.NONE)return;let s;if(this.trackPublications.forEach(g=>{g.track&&g.track===e&&(s=g)}),!s)throw new qe("track is not published");if(!Je(e))throw new qe("track is not a video track");let a=Object.assign(Object.assign({},(r=this.roomOptions)===null||r===void 0?void 0:r.publishDefaults),n),o=Xd(e,t,a);if(!o){this.log.info("backup codec has been disabled, ignoring request to add additional codec for track",j(e));return}let d=e.addSimulcastTrack(t,o);if(!d)return;let c=this.normalizeRequestedFrameMetadataOptions(e,a),l=new xn({cid:d.mediaStreamTrack.id,type:_.kindToProto(e.kind),muted:e.isMuted,source:_.sourceToProto(e.source),sid:e.sid,packetTrailerFeatures:c,simulcastCodecs:[{codec:a.videoCodec,cid:d.mediaStreamTrack.id}]});if(l.layers=Wo(l.width,l.height,o),!this.engine||this.engine.isClosed)throw new $("cannot publish track when not connected");let u=()=>p(this,void 0,void 0,function*(){yield this.engine.createSimulcastSender(e,d,a,o),yield this.engine.negotiate()}),m=(yield Promise.all([this.engine.addTrack(l),u()]))[0];this.log.debug("published ".concat(t," for track ").concat(e.sid),{encodings:o,trackInfo:m})})}unpublishTrack(e,t){return p(this,void 0,void 0,function*(){var n,r;if(Xt(e)){let l=this.pendingPublishPromises.get(e);l&&(this.log.debug("awaiting publish promise before attempting to unpublish",j(e)),yield l)}let s=this.getPublicationForTrack(e),a=s?j(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(P.Muted,this.onTrackMuted),e.off(P.Unmuted,this.onTrackUnmuted),e.off(P.Ended,this.handleTrackEnded),e.off(P.UpstreamPaused,this.onTrackUpstreamPaused),e.off(P.UpstreamResumed,this.onTrackUpstreamResumed),e.off(P.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate),t===void 0&&(t=(r=(n=this.roomOptions)===null||n===void 0?void 0:n.stopLocalTrackOnUnpublish)!==null&&r!==void 0?r:!0),t?e.stop():e.stopMonitor();let o=!1,d=e.sender;if(e.sender=void 0,this.engine.pcManager&&this.engine.pcManager.currentState<te.FAILED&&d)try{for(let 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}if(Je(e)){for(let l of e.simulcastCodecs){var c=O(l,2);let 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 _.Kind.Audio:this.audioTrackPublications.delete(s.trackSid);break;case _.Kind.Video:this.videoTrackPublications.delete(s.trackSid);break}return this.emit(I.LocalTrackUnpublished,s),s.setTrack(void 0),o&&(yield this.engine.negotiate()),s})}unpublishTracks(e){return p(this,void 0,void 0,function*(){return(yield Promise.all(e.map(n=>this.unpublishTrack(n)))).filter(n=>!!n)})}republishAllTracks(e){return p(this,arguments,void 0,function(t){var n=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return(function*(){n.republishPromise&&(yield n.republishPromise),n.republishPromise=new pe((s,a)=>p(n,void 0,void 0,function*(){try{let 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=>p(this,void 0,void 0,function*(){let c=d.track;yield this.unpublishTrack(c,!1),r&&!c.isMuted&&c.source!==_.Source.ScreenShare&&c.source!==_.Source.ScreenShareAudio&&(at(c)||Je(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 n.republishPromise})()})}publishData(e){return p(this,arguments,void 0,function(t){var n=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return(function*(){let s=r.reliable?U.RELIABLE:U.LOSSY,a=r.reliable?Ze.RELIABLE:Ze.LOSSY,o=r.destinationIdentities,d=r.topic,c=new ga({participantIdentity:n.identity,payload:t,destinationIdentities:o,topic:d}),l=new ge({kind:a,value:{case:"user",value:c}});yield n.engine.sendDataPacket(l,s)})()})}publishDtmf(e,t){return p(this,void 0,void 0,function*(){let n=new ge({kind:Ze.RELIABLE,value:{case:"sipDtmf",value:new Lc({code:e,digit:t})}});yield this.engine.sendDataPacket(n,U.RELIABLE)})}sendChatMessage(e,t){return p(this,void 0,void 0,function*(){let n={id:crypto.randomUUID(),message:e,timestamp:Date.now(),attachedFiles:t?.attachments},r=new ge({value:{case:"chatMessage",value:new yi(Object.assign(Object.assign({},n),{timestamp:Y.parse(n.timestamp)}))}});return yield this.engine.sendDataPacket(r,U.RELIABLE),this.emit(I.ChatMessage,n),n})}editChatMessage(e,t){return p(this,void 0,void 0,function*(){let n=Object.assign(Object.assign({},t),{message:e,editTimestamp:Date.now()}),r=new ge({value:{case:"chatMessage",value:new yi(Object.assign(Object.assign({},n),{timestamp:Y.parse(n.timestamp),editTimestamp:Y.parse(n.editTimestamp)}))}});return yield this.engine.sendDataPacket(r,U.RELIABLE),this.emit(I.ChatMessage,n),n})}sendText(e,t){return p(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.sendText(e,t)})}streamText(e){return p(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.streamText(e)})}sendFile(e,t){return p(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.sendFile(e,t)})}streamBytes(e){return p(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.streamBytes(e)})}performRpc(e){return this.rpcClientManager.performRpc(e).then(t=>{let n=O(t,2);return n[0],n[1]})}registerRpcMethod(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 n,r;let s=this.trackPublications.get(t.sid);if(s){let a=s.isMuted||((r=(n=s.track)===null||n===void 0?void 0:n.isUpstreamPaused)!==null&&r!==void 0?r:!1);a!==t.muted&&(this.log.debug("updating server mute state after reconcile",Object.assign(Object.assign({},j(s)),{mutedOnServer:a})),this.engine.client.sendMuteTrack(t.sid,a))}}),!0):!1}setActiveAgent(e){var t,n,r,s;this.firstActiveAgent=e,e&&!this.firstActiveAgent&&(this.firstActiveAgent=e),e?(n=(t=this.activeAgentFuture)===null||t===void 0?void 0:t.resolve)===null||n===void 0||n.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 ce),this.activeAgentFuture.promise)}getPublicationForTrack(e){let t;return this.trackPublications.forEach(n=>{let r=n.track;r&&(e instanceof MediaStreamTrack?(at(r)||Je(r))&&r.mediaStreamTrack===e&&(t=n):e===r&&(t=n))}),t}waitForPendingPublicationOfSource(e){return p(this,void 0,void 0,function*(){let n=Date.now();for(;Date.now()<n+1e4;){let r=Array.from(this.pendingPublishPromises.entries()).find(s=>O(s,1)[0].source===e);if(r)return r[1];yield ve(20)}})}publishDataTrack(e){return p(this,void 0,void 0,function*(){let t=new Wi(e,this.roomOutgoingDataTrackManager);return yield t.publish(),t})}},$i=class extends DOMException{constructor(e,t){super(e,"AbortError"),this.reason=t}},Gs=class extends Map{constructor(){super(...arguments),this.pending=new Map}set(e,t){var n,r;super.set(e,t);let s=(n=this.pending)===null||n===void 0?void 0:n.get(e);if(s){for(let 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 p(this,void 0,void 0,function*(){let n=this.get(e);if(typeof n<"u")return n;if(t?.aborted)throw new $i("The operation was aborted.",t.reason);let r=new ce(void 0,()=>{let a=this.pending.get(e);if(!a)return;let 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){let a=()=>{var o;r.isResolved||(o=r.reject)===null||o===void 0||o.call(r,new $i("The operation was aborted.",t.reason))};t.addEventListener("abort",a,{once:!0}),r.promise.finally(()=>{t.removeEventListener("abort",a)})}return r.promise})}},Ks=class extends Ne{constructor(e,t,n,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(P.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=n,this.updateInfo(t)}setSubscribed(e){let t=this.subscriptionStatus,n=this.permissionStatus;this.subscribed=e,e&&(this.allowed=!0);let r=new ir({trackSids:[this.trackSid],subscribe:this.subscribed,participantTracks:[new Uc({participantSid:"",trackSids:[this.trackSid]})]});this.emit(P.UpdateSubscription,r),this.emitSubscriptionUpdateIfChanged(t),this.emitPermissionUpdateIfChanged(n)}get subscriptionStatus(){return this.subscribed===!1?Ne.SubscriptionStatus.Unsubscribed:super.isSubscribed?Ne.SubscriptionStatus.Subscribed:Ne.SubscriptionStatus.Desired}get permissionStatus(){return this.allowed?Ne.PermissionStatus.Allowed:Ne.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,n;this.isManualOperationAllowed()&&(((t=this.requestedVideoDimensions)===null||t===void 0?void 0:t.width)===e.width&&((n=this.requestedVideoDimensions)===null||n===void 0?void 0:n.height)===e.height||(Pr(this.track)&&(this.requestedVideoDimensions=e),this.requestedMaxQuality=void 0,this.emitTrackUpdate()))}setVideoFPS(e){this.isManualOperationAllowed()&&Pr(this.track)&&this.fps!==e&&(this.fps=e,this.emitTrackUpdate())}get videoQuality(){var e;return(e=this.requestedMaxQuality)!==null&&e!==void 0?e:Re.HIGH}setTrack(e){let t=this.subscriptionStatus,n=this.permissionStatus,r=this.track;r!==e&&(r&&(r.off(P.VideoDimensionsChanged,this.handleVideoDimensionsChange),r.off(P.VisibilityChanged,this.handleVisibilityChange),r.off(P.Ended,this.handleEnded),r.detach(),r.stopMonitor(),this.emit(P.Unsubscribed,r)),super.setTrack(e),e&&(e.sid=this.trackSid,e.on(P.VideoDimensionsChanged,this.handleVideoDimensionsChange),e.on(P.VisibilityChanged,this.handleVisibilityChange),e.on(P.Ended,this.handleEnded),this.emit(P.Subscribed,e)),this.emitPermissionUpdateIfChanged(n),this.emitSubscriptionUpdateIfChanged(t))}setAllowed(e){let t=this.subscriptionStatus,n=this.permissionStatus;this.allowed=e,this.emitPermissionUpdateIfChanged(n),this.emitSubscriptionUpdateIfChanged(t)}setSubscriptionError(e){this.emit(P.SubscriptionFailed,e)}updateInfo(e){super.updateInfo(e);let t=this.metadataMuted;this.metadataMuted=e.muted,this.track?this.track.setMuted(e.muted):t!==e.muted&&this.emit(e.muted?P.Muted:P.Unmuted)}emitSubscriptionUpdateIfChanged(e){let t=this.subscriptionStatus;e!==t&&this.emit(P.SubscriptionStatusChanged,t,e)}emitPermissionUpdateIfChanged(e){this.permissionStatus!==e&&this.emit(P.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 Pr(this.track)&&this.track.isAdaptiveStream}emitTrackUpdate(){let e=new $c({trackSids:[this.trackSid],disabled:!this.isEnabled,fps:this.fps});if(this.kind===_.Kind.Video){let t=this.requestedVideoDimensions;if(this.videoDimensionsAdaptiveStream!==void 0)if(t)wo(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){let n=Zh(this.trackInfo,this.requestedMaxQuality);n&&wo(this.videoDimensionsAdaptiveStream,n)&&(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:Re.HIGH})),e.quality=Re.HIGH)}this.emit(P.UpdateSettings,e)}},Qi=class i extends Ji{static fromParticipantInfo(e,t,n,r){return new i(e,t.sid,t.identity,t.name,t.metadata,t.attributes,n,t.kind,t.dataTracks.map(s=>{let a=Ii.from(s);return new qi(a,r,{publisherIdentity:t.identity})}),t.clientProtocol)}get logContext(){return Object.assign(Object.assign({},super.logContext),{remoteParticipantID:this.sid,remoteParticipant:this.identity})}constructor(e,t,n,r,s,a,o){let d=arguments.length>7&&arguments[7]!==void 0?arguments[7]:An.STANDARD,c=arguments.length>8&&arguments[8]!==void 0?arguments[8]:[],l=arguments.length>9&&arguments[9]!==void 0?arguments[9]:Fd;super(t,n||"",r,s,a,o,d),this.signalClient=e,this.trackPublications=new Map,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.dataTracks=new Gs(c.map(u=>[u.info.name,u])),this.volumeMap=new Map,this.clientProtocol=l}addTrackPublication(e){super.addTrackPublication(e),e.on(P.UpdateSettings,t=>{this.log.debug("send update settings",Object.assign(Object.assign(Object.assign({},this.logContext),j(e)),{settings:t})),this.signalClient.sendUpdateTrackSettings(t)}),e.on(P.UpdateSubscription,t=>{t.participantTracks.forEach(n=>{n.participantSid=this.sid}),this.signalClient.sendUpdateSubscription(t)}),e.on(P.SubscriptionPermissionChanged,t=>{this.emit(I.TrackSubscriptionPermissionChanged,e,t)}),e.on(P.SubscriptionStatusChanged,t=>{this.emit(I.TrackSubscriptionStatusChanged,e,t)}),e.on(P.Subscribed,t=>{this.emit(I.TrackSubscribed,t,e)}),e.on(P.Unsubscribed,t=>{this.emit(I.TrackUnsubscribed,t,e)}),e.on(P.SubscriptionFailed,t=>{this.emit(I.TrackSubscriptionFailed,e.trackSid,t)})}getTrackPublication(e){let t=super.getTrackPublication(e);if(t)return t}getTrackPublicationByName(e){let t=super.getTrackPublicationByName(e);if(t)return t}setVolume(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:_.Source.Microphone;this.volumeMap.set(t,e);let n=this.getTrackPublication(t);n&&n.track&&n.track.setVolume(e)}getVolume(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:_.Source.Microphone,t=this.getTrackPublication(e);return t&&t.track?t.track.getVolume():this.volumeMap.get(e)}addSubscribedMediaTrack(e,t,n,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(I.TrackSubscriptionFailed,t);return}a===void 0&&(a=20),setTimeout(()=>{this.addSubscribedMediaTrack(e,t,n,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),j(o))),this.emit(I.TrackSubscriptionFailed,t);return}let d=e.kind==="video",c;return d?c=new Bn(e,t,r,s):c=new Vs(e,t,r,this.audioContext,this.audioOutput),c.source=o.source,c.isMuted=o.isMuted,c.setMediaStream(n),c.start(),o.setTrack(c),this.volumeMap.has(o.source)&&ms(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;let t=new Map,n=new Map;return e.tracks.forEach(r=>{var s,a;let o=this.getTrackPublicationBySid(r.sid);if(o)o.updateInfo(r);else{let d=_.kindFromProto(r.type);if(!d)return;o=new Ks(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),n.set(r.sid,o);let c=Array.from(this.trackPublications.values()).find(l=>l.source===o?.source);c&&o.source!==_.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:j(c),newTrack:j(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),j(r))),this.unpublishTrack(r.trackSid,!0))}),n.forEach(r=>{this.emit(I.TrackPublished,r)}),!0}unpublishTrack(e,t){let n=this.trackPublications.get(e);if(!n)return;let r=n.track;switch(r&&(r.stop(),n.setTrack(void 0)),this.trackPublications.delete(e),n.kind){case _.Kind.Audio:this.audioTrackPublications.delete(e);break;case _.Kind.Video:this.videoTrackPublications.delete(e);break}t&&this.emit(I.TrackUnpublished,n)}setAudioOutput(e){return p(this,void 0,void 0,function*(){this.audioOutput=e;let t=[];this.audioTrackPublications.forEach(n=>{var r;et(n.track)&&ms(n.track)&&t.push(n.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(let n of this.dataTracks.entries()){var t=O(n,2);let r=t[0],s=t[1];e===s.info.sid&&this.dataTracks.delete(r)}}emit(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),r=1;r<t;r++)n[r-1]=arguments[r];return this.log.trace("participant event",Object.assign(Object.assign({},this.logContext),{event:e,args:n})),super.emit(e,...n)}},V;(function(i){i.Disconnected="disconnected",i.Connecting="connecting",i.Connected="connected",i.Reconnecting="reconnecting",i.SignalReconnecting="signalReconnecting"})(V||(V={}));var Dp=4*1e3,dn=class i extends Ee.EventEmitter{get hasE2EESetup(){return this.e2eeManager!==void 0}constructor(e){var t,n,r,s,a,o,d;if(super(),t=this,this.state=V.Disconnected,this.activeSpeakers=[],this.isE2EEEnabled=!1,this.audioEnabled=!0,this.e2eeStateMutex=new de,this.isVideoPlaybackBlocked=!1,this.log=F,this.bufferedEvents=[],this.isResuming=!1,this.connect=(c,l,u)=>p(this,void 0,void 0,function*(){var h;if(!sm())throw He()?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.");let m=yield this.disconnectLock.lock();if(this.state===V.Connected)return this.log.info("already connected to room ".concat(this.name)),m(),Promise.resolve();if(this.connectFuture)return m(),this.connectFuture.promise;this.setAndEmitConnectionState(V.Connecting),((h=this.regionUrlProvider)===null||h===void 0?void 0:h.getServerUrl().toString())!==Jd(c)&&(this.regionUrl=void 0,this.regionUrlProvider=void 0),sn(new URL(c))&&(this.regionUrlProvider===void 0?this.regionUrlProvider=new Ge(c,l):this.regionUrlProvider.updateToken(l),this.regionUrlProvider.fetchRegionSettings().then(T=>{var k;(k=this.regionUrlProvider)===null||k===void 0||k.setServerReportedRegions(T)}).catch(T=>{this.log.warn("could not fetch region settings",{error:T})}));let g=(T,k,S)=>p(this,void 0,void 0,function*(){var L,y;this.abortController&&this.abortController.abort();let b=new AbortController;this.abortController=b,m?.();try{if(yield Zt.getInstance().getBackOffPromise(c),b.signal.aborted)throw N.cancelled("Connection attempt aborted");yield this.attemptConnection(S??c,l,u,b),this.abortController=void 0,T()}catch(E){if(this.regionUrlProvider&&E instanceof N&&E.reason!==z.Cancelled&&E.reason!==z.NotAllowed){let M=null;try{this.log.debug("Fetching next region"),M=yield this.regionUrlProvider.getNextBestRegionUrl((L=this.abortController)===null||L===void 0?void 0:L.signal)}catch(D){if(D instanceof N&&(D.status===401||D.reason===z.Cancelled)){this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),k(D);return}}[z.InternalError,z.ServerUnreachable,z.Timeout].includes(E.reason)&&(this.log.debug("Adding failed connection attempt to back off"),Zt.getInstance().addFailedConnectionAttempt(c)),M&&!(!((y=this.abortController)===null||y===void 0)&&y.signal.aborted)?(this.log.info("Initial connection failed with ConnectionError: ".concat(E.message,". Retrying with another region: ").concat(M)),this.recreateEngine(!0),yield g(T,k,M)):(this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,Ao(E)),k(E))}else{let M=oe.UNKNOWN_REASON;E instanceof N&&(M=Ao(E)),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,M),k(E)}}}),f=this.regionUrl;return this.regionUrl=void 0,this.connectFuture=new ce((T,k)=>{g(T,k,f)},()=>{this.clearConnectionFutures()}),this.connectFuture.promise}),this.connectSignal=(c,l,u,h,m,g)=>p(this,void 0,void 0,function*(){var f;let T=yield u.join(c,l,{autoSubscribe:h.autoSubscribe,adaptiveStream:typeof m.adaptiveStream=="object"?!0:m.adaptiveStream,clientInfoCapabilities:Fn((f=m.frameMetadata)!==null&&f!==void 0?f:m.packetTrailer)||this.e2eeManager?[Vc.CAP_PACKET_TRAILER]:void 0,maxRetries:h.maxRetries,e2eeEnabled:!!this.e2eeManager,websocketTimeout:h.websocketTimeout},g.signal,!m.singlePeerConnection),k=T.joinResponse,S=T.serverInfo;if(this.serverInfo=S,!S.version)throw new is("unknown server version");return S.version==="0.15.1"&&this.options.dynacast&&(this.log.debug("disabling dynacast due to server version"),m.dynacast=!1),k}),this.applyJoinResponse=c=>{let 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)=>p(this,void 0,void 0,function*(){var m,g;this.state===V.Reconnecting||this.isResuming||!((m=this.engine)===null||m===void 0)&&m.pendingReconnect?(this.log.info("Reconnection attempt replaced by new connection attempt"),this.recreateEngine(!0)):this.maybeCreateEngine(),!((g=this.regionUrlProvider)===null||g===void 0)&&g.isCloud()&&this.engine.setRegionStrategy(this.createRegionStrategy()),this.acquireAudioContext(),this.connOptions=Object.assign(Object.assign({},Ba),u),this.connOptions.rtcConfig&&(this.engine.rtcConfig=this.connOptions.rtcConfig),this.connOptions.peerConnectionTimeout&&(this.engine.peerConnectionTimeout=this.connOptions.peerConnectionTimeout);try{let f=yield this.connectSignal(c,l,this.engine,this.connOptions,this.options,h);this.applyJoinResponse(f),this.setupLocalParticipantEvents(),this.emit(C.SignalConnected)}catch(f){yield this.engine.close(),this.recreateEngine();let T=h.signal.aborted?N.cancelled("Signal connection aborted"):N.serverUnreachable("could not establish signal connection");throw f instanceof Error&&(T.message="".concat(T.message,": ").concat(f.message)),f instanceof N&&(T.reason=f.reason,T.status=f.status),this.log.debug("error trying to establish signal connection",{error:f}),T}if(h.signal.aborted)throw yield this.engine.close(),this.recreateEngine(),N.cancelled("Connection attempt aborted");try{yield this.engine.waitForPCInitialConnection(this.connOptions.peerConnectionTimeout,h)}catch(f){throw yield this.engine.close(),this.recreateEngine(),f}Ce()&&this.options.disconnectOnPageLeave&&(window.addEventListener("pagehide",this.onPageLeave),window.addEventListener("beforeunload",this.onPageLeave)),Ce()&&window.addEventListener("freeze",this.onPageLeave),this.setAndEmitConnectionState(V.Connected),this.emit(C.Connected),Zt.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 p(t,[...l],void 0,function(){var h=this;let m=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return(function*(){var g,f,T;let k=yield h.disconnectLock.lock();try{if(h.state===V.Disconnected){h.log.debug("already disconnected");return}if(h.log.info("disconnect from room"),h.state===V.Connecting||h.state===V.Reconnecting||h.isResuming){let S="Abort connection attempt due to user initiated disconnect";h.log.warn(S),(g=h.abortController)===null||g===void 0||g.abort(S),(T=(f=h.connectFuture)===null||f===void 0?void 0:f.reject)===null||T===void 0||T.call(f,N.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(m,oe.CLIENT_INITIATED),h.engine=void 0}finally{k()}})()})},this.onPageLeave=()=>p(this,void 0,void 0,function*(){this.log.info("Page leave detected, disconnecting"),yield this.disconnect()}),this.startAudio=()=>p(this,void 0,void 0,function*(){let c=[],l=ke();if(l&&l.os==="iOS"){let u="livekit-dummy-audio-el",h=document.getElementById(u);if(!h){h=document.createElement("audio"),h.id=u,h.autoplay=!0,h.hidden=!0;let m=Rr();m.enabled=!0;let g=new MediaStream([m]);h.srcObject=g,document.addEventListener("visibilitychange",()=>{h&&(h.srcObject=document.hidden?null:g,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(C.Disconnected,()=>{h?.remove(),h=null})}c.push(h)}this.remoteParticipants.forEach(u=>{u.audioTrackPublications.forEach(h=>{h.track&&h.track.attachedElements.forEach(m=>{c.push(m)})})});try{yield Promise.all([this.acquireAudioContext(),...c.map(u=>(u.muted=!1,u.play()))]),this.handleAudioPlaybackStarted()}catch(u){throw this.handleAudioPlaybackFailed(u),u}}),this.startVideo=()=>p(this,void 0,void 0,function*(){let c=[];for(let l of this.remoteParticipants.values())l.videoTrackPublications.forEach(u=>{var h;(h=u.track)===null||h===void 0||h.attachedElements.forEach(m=>{c.includes(m)||c.push(m)})});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(let c of this.remoteParticipants.values())this.handleParticipantDisconnected(c.identity,c);this.setAndEmitConnectionState(V.Reconnecting)&&this.emit(C.Reconnecting)},this.handleRestarted=()=>{this.outgoingDataTrackManager.sfuWillRepublishTracks(),this.incomingDataTrackManager.resendSubscriptionUpdates()},this.handleSignalRestarted=c=>p(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(V.Connected),this.emit(C.Reconnected),this.registerConnectionReconcile(),this.emitBufferedEvents()}),this.handleParticipantUpdates=c=>{var l;for(let 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 m=this.remoteParticipants.get(h.identity);h.state===Jt.DISCONNECTED?this.handleParticipantDisconnected(h.identity,m):this.getOrCreateParticipant(h.identity,h)}let u=new Map(c.filter(h=>h.identity!==this.localParticipant.identity).map(h=>[h.identity,h.dataTracks.map(m=>Ii.from(m))]));this.incomingDataTrackManager.receiveSfuPublicationUpdates(u)},this.handleActiveSpeakersUpdate=c=>{let l=[],u={};c.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{let m=this.getRemoteParticipantBySid(h.sid);m&&(m.audioLevel=h.level,m.setIsSpeaking(!0),l.push(m))}}),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(C.ActiveSpeakersChanged,l)},this.handleSpeakersChanged=c=>{let l=new Map;this.activeSpeakers.forEach(h=>{let m=this.remoteParticipants.get(h.identity);m&&m.sid!==h.sid||l.set(h.sid,h)}),c.forEach(h=>{let m=this.getRemoteParticipantBySid(h.sid);h.sid===this.localParticipant.sid&&(m=this.localParticipant),m&&(m.audioLevel=h.level,m.setIsSpeaking(h.active),h.active?l.set(h.sid,m):l.delete(h.sid))});let u=Array.from(l.values());u.sort((h,m)=>m.audioLevel-h.audioLevel),this.activeSpeakers=u,this.emitWhenConnected(C.ActiveSpeakersChanged,u)},this.handleStreamStateUpdate=c=>{c.streamStates.forEach(l=>{let u=this.getRemoteParticipantBySid(l.participantSid);if(!u)return;let h=u.getTrackPublicationBySid(l.trackSid);if(!h||!h.track)return;let m=_.streamStateFromProto(l.state);h.track.setStreamState(m),m!==h.track.streamState&&(u.emit(I.TrackStreamStateChanged,h,h.track.streamState),this.emitWhenConnected(C.TrackStreamStateChanged,h,h.track.streamState,u))})},this.handleSubscriptionPermissionUpdate=c=>{let l=this.getRemoteParticipantBySid(c.participantSid);if(!l)return;let u=l.getTrackPublicationBySid(c.trackSid);u&&u.setAllowed(c.allowed)},this.handleSubscriptionError=c=>{let l=Array.from(this.remoteParticipants.values()).find(h=>h.trackPublications.has(c.trackSid));if(!l)return;let u=l.getTrackPublicationBySid(c.trackSid);u&&u.setSubscriptionError(c.err)},this.handleDataPacket=(c,l)=>{let 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"){let h=c.value.value;this.rpcServerManager.handleIncomingRpcRequest(c.participantIdentity,h)}else if(c.value.case==="rpcResponse"){let 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(C.DataReceived,l.payload,c,u,l.topic,h),c?.emit(I.DataReceived,l.payload,u,h)},this.handleSipDtmf=(c,l)=>{this.emit(C.SipDTMFReceived,l,c),c?.emit(I.SipDTMFReceived,l)},this.handleTranscription=(c,l)=>{let u=l.transcribedParticipantIdentity===this.localParticipant.identity?this.localParticipant:this.getParticipantByIdentity(l.transcribedParticipantIdentity),h=u?.trackPublications.get(l.trackId),m=fm(l,this.transcriptionReceivedTimes);h?.emit(P.TranscriptionReceived,m),u?.emit(I.TranscriptionReceived,m,h),this.emit(C.TranscriptionReceived,m,u,h)},this.handleChatMessage=(c,l)=>{let u=gm(l);this.emit(C.ChatMessage,u,c)},this.handleMetrics=(c,l)=>{this.emit(C.MetricsReceived,c,l)},this.handleDataStream=(c,l)=>{this.incomingDataStreamManager.handleDataStreamPacket(c,l)},this.bufferedSegments=new Map,this.handleAudioPlaybackStarted=()=>{this.canPlaybackAudio||(this.audioEnabled=!0,this.emit(C.AudioPlaybackStatusChanged,!0))},this.handleAudioPlaybackFailed=c=>{this.log.warn("could not playback audio",{error:c}),this.canPlaybackAudio&&(this.audioEnabled=!1,this.emit(C.AudioPlaybackStatusChanged,!1))},this.handleVideoPlaybackStarted=()=>{this.isVideoPlaybackBlocked&&(this.isVideoPlaybackBlocked=!1,this.emit(C.VideoPlaybackStatusChanged,!0))},this.handleVideoPlaybackFailed=()=>{this.isVideoPlaybackBlocked||(this.isVideoPlaybackBlocked=!0,this.emit(C.VideoPlaybackStatusChanged,!1))},this.handleDeviceChange=()=>p(this,void 0,void 0,function*(){var c;((c=ke())===null||c===void 0?void 0:c.os)!=="iOS"&&(yield this.selectDefaultDevices()),this.emit(C.MediaDevicesChanged)}),this.handleRoomUpdate=c=>{let l=this.roomInfo;this.roomInfo=c,l&&l.metadata!==c.metadata&&this.emitWhenConnected(C.RoomMetadataChanged,c.metadata),l?.activeRecording!==c.activeRecording&&this.emitWhenConnected(C.RecordingStatusChanged,c.activeRecording)},this.handleConnectionQualityUpdate=c=>{c.updates.forEach(l=>{if(l.participantSid===this.localParticipant.sid){this.localParticipant.setConnectionQuality(l.quality);return}let 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:Fd},this.onLocalParticipantMetadataChanged=c=>{this.emit(C.ParticipantMetadataChanged,c,this.localParticipant)},this.onLocalParticipantNameChanged=c=>{this.emit(C.ParticipantNameChanged,c,this.localParticipant)},this.onLocalAttributesChanged=c=>{this.emit(C.ParticipantAttributesChanged,c,this.localParticipant)},this.onLocalTrackMuted=c=>{this.emit(C.TrackMuted,c,this.localParticipant)},this.onLocalTrackUnmuted=c=>{this.emit(C.TrackUnmuted,c,this.localParticipant)},this.onTrackProcessorUpdate=c=>{var l;(l=c?.onPublish)===null||l===void 0||l.call(c,this)},this.onLocalTrackPublished=c=>p(this,void 0,void 0,function*(){var l,u,h,m,g,f;(l=c.track)===null||l===void 0||l.on(P.TrackProcessorUpdate,this.onTrackProcessorUpdate),(u=c.track)===null||u===void 0||u.on(P.Restarted,this.onLocalTrackRestarted),(g=(m=(h=c.track)===null||h===void 0?void 0:h.getProcessor())===null||m===void 0?void 0:m.onPublish)===null||g===void 0||g.call(m,this),this.emit(C.LocalTrackPublished,c,this.localParticipant),at(c.track)&&(yield c.track.checkForSilence())&&this.emit(C.LocalAudioSilenceDetected,c);let T=yield(f=c.track)===null||f===void 0?void 0:f.getDeviceId(!1),k=cs(c.source);k&&T&&T!==this.localParticipant.activeDeviceMap.get(k)&&(this.localParticipant.activeDeviceMap.set(k,T),this.emit(C.ActiveDeviceChanged,k,T))}),this.onLocalTrackUnpublished=c=>{var l,u;(l=c.track)===null||l===void 0||l.off(P.TrackProcessorUpdate,this.onTrackProcessorUpdate),(u=c.track)===null||u===void 0||u.off(P.Restarted,this.onLocalTrackRestarted),this.emit(C.LocalTrackUnpublished,c,this.localParticipant)},this.onLocalTrackRestarted=c=>p(this,void 0,void 0,function*(){let l=yield c.getDeviceId(!1),u=cs(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(C.ActiveDeviceChanged,u,l))}),this.onLocalConnectionQualityChanged=c=>{this.emit(C.ConnectionQualityChanged,c,this.localParticipant)},this.onMediaDevicesError=(c,l)=>{this.emit(C.MediaDevicesError,c,l)},this.onLocalParticipantPermissionsChanged=c=>{this.emit(C.ParticipantPermissionsChanged,c,this.localParticipant)},this.onLocalChatMessageSent=c=>{this.emit(C.ChatMessage,c,this.localParticipant)},this.setMaxListeners(100),this.remoteParticipants=new Map,this.sidToIdentity=new Map,this.options=Object.assign(Object.assign({},Qm),e),this.log=_e((n=this.options.loggerName)!==null&&n!==void 0?n:ue.Room,()=>this.logContext),this.transcriptionReceivedTimes=new Map,this.options.audioCaptureDefaults=Object.assign(Object.assign({},Qd),e?.audioCaptureDefaults),this.options.videoCaptureDefaults=Object.assign(Object.assign({},Yd),e?.videoCaptureDefaults),this.options.publishDefaults=Object.assign(Object.assign({},$m),e?.publishDefaults),this.maybeCreateEngine(),this.incomingDataStreamManager=new xs,this.outgoingDataStreamManager=new Ls(this.engine,this.log),this.incomingDataTrackManager=new Us({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(C.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(C.DataTrackUnpublished,c.sid),(l=this.remoteParticipants.get(c.publisherIdentity))===null||l===void 0||l.removeRemoteDataTrack(c.sid))}),this.outgoingDataTrackManager=new Bs({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(C.LocalDataTrackPublished,c.track)}).on("trackUnpublished",c=>{this.emit(C.LocalDataTrackUnpublished,c.sid)}).on("packetAvailable",c=>{let l=c.handle,u=c.bytes;this.engine.sendLossyBytes(u,U.DATA_TRACK_LOSSY,"wait").finally(()=>this.outgoingDataTrackManager.handlePacketSendComplete(l))}),this.registerRpcDataStreamHandler(),this.rpcClientManager=new qs(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,U.RELIABLE)}),this.rpcServerManager=new js(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,U.RELIABLE)}),this.disconnectLock=new de,this.localParticipant=new Hs("","",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",Lt(this.options.videoCaptureDefaults.deviceId)),this.options.audioCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("audioinput",Lt(this.options.audioCaptureDefaults.deviceId)),!((a=this.options.audioOutput)===null||a===void 0)&&a.deviceId&&this.switchActiveDevice("audiooutput",Lt(this.options.audioOutput.deviceId)).catch(c=>this.log.warn("Could not set audio output: ".concat(c.message))),Ce()){let c=new AbortController,l;if(i.cleanupRegistry){let u=new WeakRef(this);l=()=>{let h=u.deref();h&&h.handleDeviceChange()},i.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)}registerRpcMethod(e,t){this.rpcServerManager.registerRpcMethod(e,t)}unregisterRpcMethod(e){this.rpcServerManager.unregisterRpcMethod(e)}setE2EEEnabled(e){return p(this,void 0,void 0,function*(){let t=yield this.e2eeStateMutex.lock();try{if(this.e2eeManager)this.isE2EEEnabled!==e&&(yield this.localParticipant.setE2EEEnabled(e),this.localParticipant.identity!==""&&this.e2eeManager.setParticipantCryptorEnabled(e,this.localParticipant.identity));else throw Error("e2ee not configured, please set e2ee settings within the room options")}finally{t()}})}setupE2EE(){var e,t;let n=!!this.options.encryption,r=this.options.encryption||this.options.e2ee;r&&("e2eeManager"in r?(this.e2eeManager=r.e2eeManager,this.e2eeManager.isDataChannelEncryptionEnabled=n):this.e2eeManager=new gs(r,n),this.e2eeManager.on(bt.ParticipantEncryptionStatusChanged,(s,a)=>{ym(a)&&(this.isE2EEEnabled=s),this.emit(C.ParticipantEncryptionStatusChanged,s,a)}),this.e2eeManager.on(bt.EncryptionError,(s,a)=>{let o=a?this.getParticipantByIdentity(a):void 0;this.emit(C.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;let t=(e=this.options.frameMetadata)!==null&&e!==void 0?e:this.options.packetTrailer;this.frameMetadataManager=new ys(t),this.frameMetadataManager.setup(this)}get logContext(){var e,t,n;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:(n=this.localParticipant)===null||n===void 0?void 0:n.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===V.Disconnected?pe.resolve(""):this.roomInfo&&this.roomInfo.sid!==""?pe.resolve(this.roomInfo.sid):new pe((e,t)=>{let n=r=>{r.sid!==""&&(this.engine.off(R.RoomUpdate,n),e(r.sid))};this.engine.on(R.RoomUpdate,n),this.once(C.Disconnected,()=>{this.engine.off(R.RoomUpdate,n),t(new $("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 Ps(this.options),this.engine.e2eeManager=this.e2eeManager,this.engine.on(R.ParticipantUpdate,this.handleParticipantUpdates).on(R.RoomUpdate,this.handleRoomUpdate).on(R.SpeakersChanged,this.handleSpeakersChanged).on(R.StreamStateChanged,this.handleStreamStateUpdate).on(R.ConnectionQualityUpdate,this.handleConnectionQualityUpdate).on(R.SubscriptionError,this.handleSubscriptionError).on(R.SubscriptionPermissionUpdate,this.handleSubscriptionPermissionUpdate).on(R.MediaTrackAdded,(e,t,n)=>{this.onTrackAdded(e,t,n)}).on(R.Disconnected,e=>{this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e)}).on(R.ActiveSpeakersUpdate,this.handleActiveSpeakersUpdate).on(R.DataPacketReceived,this.handleDataPacket).on(R.Resuming,()=>{this.clearConnectionReconcile(),this.isResuming=!0,this.log.debug("Resuming signal connection"),this.setAndEmitConnectionState(V.SignalReconnecting)&&this.emit(C.SignalReconnecting)}).on(R.Resumed,()=>{this.registerConnectionReconcile(),this.isResuming=!1,this.log.debug("Resumed signal connection"),this.updateSubscriptions(),this.emitBufferedEvents(),this.setAndEmitConnectionState(V.Connected)&&this.emit(C.Reconnected)}).on(R.SignalResumed,()=>{this.bufferedEvents=[],(this.state===V.Reconnecting||this.isResuming)&&this.sendSyncState()}).on(R.Restarting,this.handleRestarting).on(R.Restarted,this.handleRestarted).on(R.SignalRestarted,this.handleSignalRestarted).on(R.Offline,()=>{this.setAndEmitConnectionState(V.Reconnecting)&&this.emit(C.Reconnecting)}).on(R.DCBufferStatusChanged,(e,t)=>{this.emit(C.DCBufferStatusChanged,e,t)}).on(R.LocalTrackSubscribed,e=>{this.handleLocalTrackSubscribed(e)}).on(R.RoomMoved,e=>{this.log.debug("room moved",e),e.room&&this.handleRoomUpdate(e.room),this.remoteParticipants.forEach((t,n)=>{this.handleParticipantDisconnected(n,t)}),this.emit(C.Moved,e.room.name),e.participant?this.handleParticipantUpdates([e.participant,...e.otherParticipants]):this.handleParticipantUpdates(e.otherParticipants)}).on(R.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!==J.NONE}})}).on(R.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(R.DataTrackSubscriberHandles,e=>{let t=new Map(Object.entries(e.subHandles).map(n=>{let r=O(n,2),s=r[0],a=r[1];return[parseInt(s,10),a.trackSid]}));this.incomingDataTrackManager.receivedSfuSubscriberHandles(t)}).on(R.DataTrackPacketReceived,e=>{try{this.incomingDataTrackManager.packetReceived(e)}catch(t){throw t}}).on(R.Joined,e=>{let t=new Map(e.otherParticipants.map(n=>[n.identity,n.dataTracks.map(r=>Ii.from(r))]));this.incomingDataTrackManager.receiveSfuPublicationUpdates(t)}).on(R.TokenRefreshed,e=>{var t;(t=this.regionUrlProvider)===null||t===void 0||t.updateToken(e)}).on(R.ServerRegionsReported,e=>{var t;(t=this.regionUrlProvider)===null||t===void 0||t.setServerReportedRegions({regionSettings:e,updatedAtInMs:Date.now(),maxAgeInMs:Is})}),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=>p(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 Pe.getInstance().getDevices(e,t)}prepareConnection(e,t){return p(this,void 0,void 0,function*(){if(this.state===V.Disconnected){this.log.debug("prepareConnection to ".concat(e));try{if(sn(new URL(e))&&t){this.regionUrlProvider=new Ge(e,t);let n=yield this.regionUrlProvider.getNextBestRegionUrl();n&&this.state===V.Disconnected&&(this.regionUrl=n,yield fetch(Nn(n),{method:"HEAD"}),this.log.debug("prepared connection to ".concat(n)))}else yield fetch(Nn(e),{method:"HEAD"})}catch(n){this.log.warn("could not prepare connection",{error:n})}}})}getParticipantByIdentity(e){return this.localParticipant.identity===e?this.localParticipant:this.remoteParticipants.get(e)}clearConnectionFutures(){this.connectFuture=void 0}simulateScenario(e,t){return p(this,void 0,void 0,function*(){let n=()=>p(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 Qe({scenario:{case:"speakerUpdate",value:3}});break;case"node-failure":r=new Qe({scenario:{case:"nodeFailure",value:!0}});break;case"server-leave":r=new Qe({scenario:{case:"serverLeave",value:!0}});break;case"migration":r=new Qe({scenario:{case:"migration",value:!0}});break;case"resume-reconnect":this.engine.failNext(),yield this.engine.client.handleOnClose("simulate resume-disconnect");break;case"disconnect-signal-on-resume":n=()=>p(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),r=new Qe({scenario:{case:"disconnectSignalOnResume",value:!0}});break;case"disconnect-signal-on-resume-no-messages":n=()=>p(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),r=new Qe({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 Qe({scenario:{case:"switchCandidateProtocol",value:e==="force-tls"?2:1}}),n=()=>p(this,void 0,void 0,function*(){let s=this.engine.client.onLeave;s&&s(new rr({reason:oe.CLIENT_INITIATED,action:$t.RECONNECT}))});break;case"subscriber-bandwidth":if(t===void 0||typeof t!="number")throw new Error("subscriber-bandwidth requires a number as argument");r=new Qe({scenario:{case:"subscriberBandwidth",value:Pt(t)}});break;case"leave-full-reconnect":r=new Qe({scenario:{case:"leaveRequestFullReconnect",value:!0}})}r&&(yield this.engine.client.sendSimulateScenario(r),yield n())})}get canPlaybackAudio(){return this.audioEnabled}get canPlaybackVideo(){return!this.isVideoPlaybackBlocked}getActiveDevice(e){return this.localParticipant.activeDeviceMap.get(e)}switchActiveDevice(e,t){return p(this,arguments,void 0,function(n,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,m;let g=!0,f=!1,T=a?{exact:r}:r;if(n==="audioinput"){f=s.localParticipant.audioTrackPublications.size===0;let k=(o=s.getActiveDevice(n))!==null&&o!==void 0?o:s.options.audioCaptureDefaults.deviceId;s.options.audioCaptureDefaults.deviceId=T;let S=Array.from(s.localParticipant.audioTrackPublications.values()).filter(y=>y.source===_.Source.Microphone);try{g=(yield Promise.all(S.map(y=>{var b;return(b=y.audioTrack)===null||b===void 0?void 0:b.setDeviceId(T)}))).every(y=>y===!0)}catch(y){throw s.options.audioCaptureDefaults.deviceId=k,y}let L=S.some(y=>{var b,E;return(E=(b=y.track)===null||b===void 0?void 0:b.isMuted)!==null&&E!==void 0?E:!1});g&&L&&(f=!0)}else if(n==="videoinput"){f=s.localParticipant.videoTrackPublications.size===0;let k=(d=s.getActiveDevice(n))!==null&&d!==void 0?d:s.options.videoCaptureDefaults.deviceId;s.options.videoCaptureDefaults.deviceId=T;let S=Array.from(s.localParticipant.videoTrackPublications.values()).filter(y=>y.source===_.Source.Camera);try{g=(yield Promise.all(S.map(y=>{var b;return(b=y.videoTrack)===null||b===void 0?void 0:b.setDeviceId(T)}))).every(y=>y===!0)}catch(y){throw s.options.videoCaptureDefaults.deviceId=k,y}let L=S.some(y=>{var b,E;return(E=(b=y.track)===null||b===void 0?void 0:b.isMuted)!==null&&E!==void 0?E:!1});g&&L&&(f=!0)}else if(n==="audiooutput"){if(f=!0,!us()&&!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 Pe.getInstance().normalizeDeviceId("audiooutput",r))!==null&&c!==void 0?c:""),(l=(m=s.options).audioOutput)!==null&&l!==void 0||(m.audioOutput={});let k=(u=s.getActiveDevice(n))!==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=k,S}}return f&&(s.localParticipant.activeDeviceMap.set(n,r),s.emit(C.ActiveDeviceChanged,n,r)),g})()})}setupLocalParticipantEvents(){this.localParticipant.on(I.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).on(I.ParticipantNameChanged,this.onLocalParticipantNameChanged).on(I.AttributesChanged,this.onLocalAttributesChanged).on(I.TrackMuted,this.onLocalTrackMuted).on(I.TrackUnmuted,this.onLocalTrackUnmuted).on(I.LocalTrackPublished,this.onLocalTrackPublished).on(I.LocalTrackUnpublished,this.onLocalTrackUnpublished).on(I.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).on(I.MediaDevicesError,this.onMediaDevicesError).on(I.AudioStreamAcquired,this.startAudio).on(I.ChatMessage,this.onLocalChatMessageSent).on(I.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged)}recreateEngine(e){let t=this.engine;e&&t&&!t.client.isDisconnected?t.client.sendLeave().finally(()=>t.close()):t?.close(),this.engine=void 0,this.isResuming=!1,this.remoteParticipants.clear(),this.sidToIdentity.clear(),this.bufferedEvents=[],this.maybeCreateEngine()}onTrackAdded(e,t,n){if(this.state===V.Connecting||this.state===V.Reconnecting){let u=()=>{this.log.debug("deferring on track for later",{mediaTrackId:e.id,mediaStreamId:t.id,tracksInStream:t.getTracks().map(m=>m.id)}),this.onTrackAdded(e,t,n),h()},h=()=>{this.off(C.Reconnected,u),this.off(C.Connected,u),this.off(C.Disconnected,h)};this.once(C.Reconnected,u),this.once(C.Connected,u),this.once(C.Disconnected,h);return}if(this.state===V.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}let r=nm(t.id),s=r[0],a=r[1],o=e.id;if(a&&a.startsWith("TR")&&(o=a),s===this.localParticipant.sid){this.log.warn("tried to create RemoteParticipant for local participant");return}let d=Array.from(this.remoteParticipants.values()).find(u=>u.sid===s);if(!d){s.startsWith("PA")&&this.log.error("Tried to add a track for a participant, that's not present. Sid: ".concat(s));return}if(!o.startsWith("TR")){let u=this.engine.getTrackIdForReceiver(n);if(!u){this.log.error("Tried to add a track whose 'sid' could not be found for a participant, that's not present. Sid: ".concat(s));return}o=u}o.startsWith("TR")||this.log.warn("Tried to add a track whose 'sid' could not be determined for a participant, that's not present. Sid: ".concat(s,", streamId: ").concat(a,", trackId: ").concat(o),{remoteParticipantID:s,streamId:a,trackId:o});let c;this.options.adaptiveStream&&(typeof this.options.adaptiveStream=="object"?c=this.options.adaptiveStream:c={});let l=d.addSubscribedMediaTrack(e,o,t,n,c);l?.isEncrypted&&!this.e2eeManager&&this.emit(C.EncryptionError,new Error("Encrypted ".concat(l.source," track received from participant ").concat(d.sid,", but room does not have encryption enabled!")))}handleLocalTrackSubscribed(e){let t=()=>this.localParticipant.getTrackPublications().find(d=>d.trackSid===e),n=t();if(n){this.emitLocalTrackSubscribed(n);return}this.log.debug("deferring LocalTrackSubscribed, publication not yet available",{subscribedSid:e});let r=1e4,s,a=d=>{d.trackSid===e&&(o(),this.emitLocalTrackSubscribed(d))},o=()=>{clearTimeout(s),this.localParticipant.off(I.LocalTrackPublished,a),this.off(C.Disconnected,o)};this.localParticipant.on(I.LocalTrackPublished,a),this.once(C.Disconnected,o),s=setTimeout(()=>{o();let 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(I.LocalTrackSubscribed,e),this.emitWhenConnected(C.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 n,r;if(this.clearConnectionReconcile(),this.isResuming=!1,this.bufferedEvents=[],this.transcriptionReceivedTimes.clear(),this.incomingDataStreamManager.clearControllers(),this.incomingDataTrackManager.reset(),this.outgoingDataTrackManager.reset(),this.state!==V.Disconnected){this.regionUrl=void 0,this.regionUrlProvider&&this.regionUrlProvider.notifyDisconnected();try{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(I.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).off(I.ParticipantNameChanged,this.onLocalParticipantNameChanged).off(I.AttributesChanged,this.onLocalAttributesChanged).off(I.TrackMuted,this.onLocalTrackMuted).off(I.TrackUnmuted,this.onLocalTrackUnmuted).off(I.LocalTrackPublished,this.onLocalTrackPublished).off(I.LocalTrackUnpublished,this.onLocalTrackUnpublished).off(I.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).off(I.MediaDevicesError,this.onMediaDevicesError).off(I.AudioStreamAcquired,this.startAudio).off(I.ChatMessage,this.onLocalChatMessageSent).off(I.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),Ce()&&(window.removeEventListener("beforeunload",this.onPageLeave),window.removeEventListener("pagehide",this.onPageLeave),window.removeEventListener("freeze",this.onPageLeave),(r=(n=navigator.mediaDevices)===null||n===void 0?void 0:n.removeEventListener)===null||r===void 0||r.call(n,"devicechange",this.handleDeviceChange))}finally{this.setAndEmitConnectionState(V.Disconnected),this.emit(C.Disconnected,t)}}}handleParticipantDisconnected(e,t){this.remoteParticipants.delete(e),t&&(this.incomingDataStreamManager.validateParticipantHasNoActiveDataStreams(e),this.incomingDataTrackManager.handleRemoteParticipantDisconnected(e),t.trackPublications.forEach(n=>{t.unpublishTrack(n.trackSid,!0)}),this.emit(C.ParticipantDisconnected,t),t.setDisconnected(),this.rpcClientManager.handleParticipantDisconnected(t.identity))}selectDefaultDevices(){return p(this,void 0,void 0,function*(){var e,t,n;let r=Pe.getInstance().previousDevices,s=yield Pe.getInstance().getDevices(void 0,!1),a=ke();if(a?.name==="Chrome"&&a.os!=="iOS")for(let d of s){let 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(C.ActiveDeviceChanged,d.kind,d.deviceId)}let o=["audiooutput","audioinput","videoinput"];for(let d of o){let c=zh(d),l=this.localParticipant.getTrackPublication(c);if(l&&(!((e=l.track)===null||e===void 0)&&e.isUserProvided))continue;let u=s.filter(m=>m.kind===d),h=this.getActiveDevice(d);if(h===((t=r.filter(m=>m.kind===d)[0])===null||t===void 0?void 0:t.deviceId)&&u.length>0&&((n=u[0])===null||n===void 0?void 0:n.deviceId)!==h){yield this.switchActiveDevice(d,u[0].deviceId);continue}d==="audioinput"&&!Ln()||d==="videoinput"||u.length>0&&!u.find(m=>m.deviceId===this.getActiveDevice(d))&&(d!=="audiooutput"||!Ln())&&(yield this.switchActiveDevice(d,u[0].deviceId))}})}acquireAudioContext(){return p(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=Vd())!==null&&e!==void 0?e:void 0),this.options.webAudioMix&&this.remoteParticipants.forEach(r=>r.setAudioContext(this.audioContext)),this.localParticipant.setAudioContext(this.audioContext),this.audioContext&&this.audioContext.state==="suspended")try{yield Promise.race([this.audioContext.resume(),ve(200)])}catch(r){this.log.warn("Could not resume audio context",{error:r})}let n=((t=this.audioContext)===null||t===void 0?void 0:t.state)==="running";n!==this.canPlaybackAudio&&(this.audioEnabled=n,this.emit(C.AudioPlaybackStatusChanged,n))})}createParticipant(e,t){var n;let r;return t?r=Qi.fromParticipantInfo(this.engine.client,t,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName},this.incomingDataTrackManager):r=new Qi(this.engine.client,"",e,void 0,void 0,void 0,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}),this.options.webAudioMix&&r.setAudioContext(this.audioContext),!((n=this.options.audioOutput)===null||n===void 0)&&n.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)){let r=this.remoteParticipants.get(e);return t&&r.updateInfo(t)&&this.sidToIdentity.set(t.sid,t.identity),r}let n=this.createParticipant(e,t);return this.remoteParticipants.set(e,n),this.sidToIdentity.set(t.sid,t.identity),this.emitWhenConnected(C.ParticipantConnected,n),n.on(I.TrackPublished,r=>{this.emitWhenConnected(C.TrackPublished,r,n)}).on(I.TrackSubscribed,(r,s)=>{r.kind===_.Kind.Audio?(r.on(P.AudioPlaybackStarted,this.handleAudioPlaybackStarted),r.on(P.AudioPlaybackFailed,this.handleAudioPlaybackFailed)):r.kind===_.Kind.Video&&(r.on(P.VideoPlaybackFailed,this.handleVideoPlaybackFailed),r.on(P.VideoPlaybackStarted,this.handleVideoPlaybackStarted)),this.emitWhenConnected(C.TrackSubscribed,r,s,n)}).on(I.TrackUnpublished,r=>{this.emit(C.TrackUnpublished,r,n)}).on(I.TrackUnsubscribed,(r,s)=>{this.emit(C.TrackUnsubscribed,r,s,n)}).on(I.TrackMuted,r=>{this.emitWhenConnected(C.TrackMuted,r,n)}).on(I.TrackUnmuted,r=>{this.emitWhenConnected(C.TrackUnmuted,r,n)}).on(I.ParticipantMetadataChanged,r=>{this.emitWhenConnected(C.ParticipantMetadataChanged,r,n)}).on(I.ParticipantNameChanged,r=>{this.emitWhenConnected(C.ParticipantNameChanged,r,n)}).on(I.AttributesChanged,r=>{this.emitWhenConnected(C.ParticipantAttributesChanged,r,n)}).on(I.ConnectionQualityChanged,r=>{this.emitWhenConnected(C.ConnectionQualityChanged,r,n)}).on(I.ParticipantPermissionsChanged,r=>{this.emitWhenConnected(C.ParticipantPermissionsChanged,r,n)}).on(I.TrackSubscriptionStatusChanged,(r,s)=>{this.emitWhenConnected(C.TrackSubscriptionStatusChanged,r,s,n)}).on(I.TrackSubscriptionFailed,(r,s)=>{this.emit(C.TrackSubscriptionFailed,r,n,s)}).on(I.TrackSubscriptionPermissionChanged,(r,s)=>{this.emitWhenConnected(C.TrackSubscriptionPermissionChanged,r,s,n)}).on(I.Active,()=>{this.emitWhenConnected(C.ParticipantActive,n),n.kind===An.AGENT&&this.localParticipant.setActiveAgent(n)}),t&&n.updateInfo(t),n}sendSyncState(){let e=Array.from(this.remoteParticipants.values()).reduce((r,s)=>(r.push(...s.getTrackPublications()),r),[]),t=this.localParticipant.getTrackPublications(),n=this.outgoingDataTrackManager.queryPublished();this.engine.sendSyncState(e,t,n)}updateSubscriptions(){for(let e of this.remoteParticipants.values())for(let t of e.videoTrackPublications.values())t.isSubscribed&&vm(t)&&t.emitTrackUpdate()}getRemoteParticipantBySid(e){let t=this.sidToIdentity.get(e);if(t)return this.remoteParticipants.get(t)}registerRpcDataStreamHandler(){this.incomingDataStreamManager.registerTextStreamHandler(al,(e,t)=>p(this,[e,t],void 0,function(n,r){var s=this;let a=r.identity;return(function*(){var o;let d=(o=n.info.attributes)!==null&&o!==void 0?o:{};yield s.rpcServerManager.handleIncomingDataStream(n,a,d)})()})),this.incomingDataStreamManager.registerTextStreamHandler(ol,(e,t)=>p(this,[e,t],void 0,function(n,r){var s=this;let a=r.identity;return(function*(){var o;let d=(o=n.info.attributes)!==null&&o!==void 0?o:{};yield s.rpcClientManager.handleIncomingDataStream(n,a,d)})()}))}registerConnectionReconcile(){this.clearConnectionReconcile();let e=0;this.connectionReconcileInterval=re.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.recreateEngine(),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,oe.STATE_MISMATCH))):e=0},Dp)}clearConnectionReconcile(){this.connectionReconcileInterval&&re.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===V.Connected),this.emit(C.ConnectionStateChanged,this.state),!0)}emitBufferedEvents(){this.bufferedEvents.forEach(e=>{let t=O(e,2),n=t[0],r=t[1];this.emit(n,...r)}),this.bufferedEvents=[]}emitWhenConnected(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),r=1;r<t;r++)n[r-1]=arguments[r];if(this.state===V.Reconnecting||this.isResuming||!this.engine||this.engine.pendingReconnect)this.bufferedEvents.push([e,n]);else if(this.state===V.Connected)return this.emit(e,...n);return!1}simulateParticipants(e){return p(this,void 0,void 0,function*(){var t,n,r,s;let 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 Xi({sid:"RM_SIMULATED",name:"simulated-room",emptyTimeout:0,maxParticipants:0,creationTime:Y.parse(new Date().getTime()),metadata:"",numParticipants:1,numPublishers:1,turnPassword:"",enabledCodecs:[],activeRecording:!1}),this.localParticipant.updateInfo(new Ut({identity:"simulated-local",name:"local-name"})),this.setupLocalParticipantEvents(),this.emit(C.SignalConnected),this.emit(C.Connected),this.setAndEmitConnectionState(V.Connected),a.video){let d=new Hn(_.Kind.Video,new Wt({source:ae.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:Ue.AUDIO,name:"video-dummy"}),new an(a.useRealTracks&&(!((t=window.navigator.mediaDevices)===null||t===void 0)&&t.getUserMedia)?(yield window.navigator.mediaDevices.getUserMedia({video:!0})).getVideoTracks()[0]:Mo(160*((n=o.aspectRatios[0])!==null&&n!==void 0?n: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(I.LocalTrackPublished,d)}if(a.audio){let d=new Hn(_.Kind.Audio,new Wt({source:ae.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:Ue.AUDIO}),new Et(a.useRealTracks&&(!((r=navigator.mediaDevices)===null||r===void 0)&&r.getUserMedia)?(yield navigator.mediaDevices.getUserMedia({audio:!0})).getAudioTracks()[0]:Rr(),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(I.LocalTrackPublished,d)}for(let d=0;d<o.count-1;d+=1){let c=new Ut({sid:Math.floor(Math.random()*1e4).toString(),identity:"simulated-".concat(d),state:Jt.ACTIVE,tracks:[],joinedAt:Y.parse(Date.now())}),l=this.getOrCreateParticipant(c.identity,c);if(o.video){let u=Mo(160*((s=o.aspectRatios[d%o.aspectRatios.length])!==null&&s!==void 0?s:1),160,!1,!0),h=new Wt({source:ae.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:Ue.AUDIO});l.addSubscribedMediaTrack(u,h.sid,new MediaStream([u]),new RTCRtpReceiver),c.tracks=[...c.tracks,h]}if(o.audio){let u=Rr(),h=new Wt({source:ae.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:Ue.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,n=new Array(t>1?t-1:0),r=1;r<t;r++)n[r-1]=arguments[r];if(e!==C.ActiveSpeakersChanged&&e!==C.TranscriptionReceived){let s=dl(n).filter(a=>a!==void 0);(e===C.TrackSubscribed||e===C.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,...n)}};dn.cleanupRegistry=typeof FinalizationRegistry<"u"&&typeof WeakRef<"u"&&new FinalizationRegistry(i=>{i()});function dl(i){return i.map(e=>{if(e)return Array.isArray(e)?dl(e):typeof e=="object"?"logContext"in e?e.logContext:void 0:e})}var Le;(function(i){i[i.IDLE=0]="IDLE",i[i.RUNNING=1]="RUNNING",i[i.SKIPPED=2]="SKIPPED",i[i.SUCCESS=3]="SUCCESS",i[i.FAILED=4]="FAILED"})(Le||(Le={}));var nt=class extends Ee.EventEmitter{constructor(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.status=Le.IDLE,this.logs=[],this.options={},this.url=e,this.token=t,this.name=this.constructor.name,this.room=new dn(n.roomOptions),this.connectOptions=n.connectOptions,this.options=n}run(e){return p(this,void 0,void 0,function*(){if(this.status!==Le.IDLE)throw Error("check is running already");this.setStatus(Le.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!==Le.SKIPPED&&this.setStatus(this.isSuccess()?Le.SUCCESS:Le.FAILED),e&&e(),this.getInfo()})}isSuccess(){return!this.logs.some(e=>e.level==="error")}connect(e){return p(this,void 0,void 0,function*(){return this.room.state===V.Connected?this.room:(e||(e=this.url),yield this.room.connect(e,this.token,this.connectOptions),this.room)})}disconnect(){return p(this,void 0,void 0,function*(){this.room&&this.room.state!==V.Disconnected&&(yield this.room.disconnect(),yield new Promise(e=>setTimeout(e,500)))})}skip(){this.setStatus(Le.SKIPPED)}switchProtocol(e){return p(this,void 0,void 0,function*(){let t=!1,n=!1;if(this.room.on(C.Reconnecting,()=>{t=!0}),this.room.once(C.Reconnected,()=>{n=!0}),this.room.simulateScenario("force-".concat(e)),yield new Promise(s=>setTimeout(s,1e3)),!t)return;let r=Date.now()+1e4;for(;Date.now()<r;){if(n)return;yield ve(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}}},Ws=class extends nt{get description(){return"Cloud regions"}perform(){return p(this,void 0,void 0,function*(){let e=new Ge(this.url,this.token);if(!e.isCloud()){this.skip();return}let t=[],n=new Set;for(let s=0;s<3;s++){let a=yield e.getNextBestRegionUrl();if(!a)break;if(n.has(a))continue;n.add(a);let 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);let r=t[0];this.bestStats=r,this.appendMessage("best Cloud region: ".concat(r.region))})}getInfo(){let e=super.getInfo();return e.data=this.bestStats,e}checkCloudRegion(e){return p(this,void 0,void 0,function*(){var t,n;yield this.connect(e),this.options.protocol==="tcp"&&(yield this.switchProtocol("tcp"));let r=(t=this.room.serverInfo)===null||t===void 0?void 0:t.region;if(!r)throw new Error("Region not found");let s=yield this.room.localParticipant.streamText({topic:"test"}),a=1e3,d=1e6/a,c="A".repeat(a),l=Date.now();for(let g=0;g<d;g++)yield s.write(c);yield s.close();let u=Date.now(),h=yield(n=this.room.engine.pcManager)===null||n===void 0?void 0:n.publisher.getStats(),m={region:r,rtt:1e4,duration:u-l};return h?.forEach(g=>{g.type==="candidate-pair"&&g.nominated&&(m.rtt=g.currentRoundTripTime*1e3)}),yield this.disconnect(),m})}},Fr=1e4,zs=class extends nt{get description(){return"Connection via UDP vs TCP"}perform(){return p(this,void 0,void 0,function*(){let 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");let n=this.bestStats;this.appendMessage("upstream bitrate: ".concat((n.bitrateTotal/n.count/1e3/1e3).toFixed(2)," mbps")),this.appendMessage("RTT: ".concat((n.rttTotal/n.count*1e3).toFixed(2)," ms")),this.appendMessage("jitter: ".concat((n.jitterTotal/n.count*1e3).toFixed(2)," ms")),n.packetsLost>0&&this.appendWarning("packets lost: ".concat((n.packetsLost/n.packetsSent*100).toFixed(2),"%")),n.qualityLimitationDurations.bandwidth>1&&this.appendWarning("bandwidth limited ".concat((n.qualityLimitationDurations.bandwidth/(Fr/1e3)*100).toFixed(2),"%")),n.qualityLimitationDurations.cpu>0&&this.appendWarning("cpu limited ".concat((n.qualityLimitationDurations.cpu/(Fr/1e3)*100).toFixed(2),"%"))})}getInfo(){let e=super.getInfo();return e.data=this.bestStats,e}checkConnectionProtocol(e){return p(this,void 0,void 0,function*(){yield this.connect(),e==="tcp"?yield this.switchProtocol("tcp"):yield this.switchProtocol("udp");let t=document.createElement("canvas");t.width=1280,t.height=720;let n=t.getContext("2d");if(!n)throw new Error("Could not get canvas context");let r=0,s=()=>{r=(r+1)%360,n.fillStyle="hsl(".concat(r,", 100%, 50%)"),n.fillRect(0,0,t.width,t.height),requestAnimationFrame(s)};s();let 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(()=>p(this,void 0,void 0,function*(){let h=yield c.getRTCStatsReport();h?.forEach(m=>{m.type==="outbound-rtp"?(l.packetsSent=m.packetsSent,l.qualityLimitationDurations=m.qualityLimitationDurations,l.bitrateTotal+=m.targetBitrate,l.count++):m.type==="remote-inbound-rtp"&&(l.packetsLost=m.packetsLost,l.rttTotal+=m.roundTripTime,l.jitterTotal+=m.jitter)})}),1e3);return yield new Promise(h=>setTimeout(h,Fr)),clearInterval(u),o.stop(),t.remove(),yield this.disconnect(),l})}},Js=class extends nt{get description(){return"Can publish audio"}perform(){return p(this,void 0,void 0,function*(){var e;let t=yield this.connect(),n=yield Mp();if(yield jd(n,1e3))throw new Error("unable to detect audio from microphone");this.appendMessage("detected audio from microphone"),t.localParticipant.publishTrack(n),yield new Promise(o=>setTimeout(o,3e3));let s=yield(e=n.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"))})}},$s=class extends nt{get description(){return"Can publish video"}perform(){return p(this,void 0,void 0,function*(){var e;let t=yield this.connect(),n=yield Ip();yield this.checkForVideo(n.mediaStreamTrack),t.localParticipant.publishTrack(n),yield new Promise(a=>setTimeout(a,5e3));let r=yield(e=n.sender)===null||e===void 0?void 0:e.getStats();if(!r)throw new Error("Could not get RTCStats");let s=0;if(r.forEach(a=>{a.type==="outbound-rtp"&&(a.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 p(this,void 0,void 0,function*(){let t=new MediaStream;t.addTrack(e.clone());let n=document.createElement("video");n.srcObject=t,n.muted=!0,n.autoplay=!0,n.playsInline=!0,n.setAttribute("playsinline","true"),document.body.appendChild(n),yield new Promise(r=>{n.onplay=()=>{setTimeout(()=>{var s,a,o,d;let c=document.createElement("canvas"),l=e.getSettings(),u=(a=(s=l.width)!==null&&s!==void 0?s:n.videoWidth)!==null&&a!==void 0?a:1280,h=(d=(o=l.height)!==null&&o!==void 0?o:n.videoHeight)!==null&&d!==void 0?d:720;c.width=u,c.height=h;let m=c.getContext("2d");m.drawImage(n,0,0);let f=m.getImageData(0,0,c.width,c.height).data,T=!0;for(let k=0;k<f.length;k+=4)if(f[k]!==0||f[k+1]!==0||f[k+2]!==0){T=!1;break}T?this.appendError("camera appears to be producing only black frames"):this.appendMessage("received video frames"),r()},1e3)},n.play()}),t.getTracks().forEach(r=>r.stop()),n.remove()})}},Qs=class extends nt{get description(){return"Resuming connection after interruption"}perform(){return p(this,void 0,void 0,function*(){var e;let t=yield this.connect(),n=!1,r=!1,s,a=new Promise(c=>{setTimeout(c,5e3),s=c}),o=()=>{n=!0};t.on(C.SignalReconnecting,o).on(C.Reconnecting,o).on(C.Reconnected,()=>{r=!0,s(!0)}),(e=t.engine.client.ws)===null||e===void 0||e.close();let d=t.engine.client.onClose;if(d&&d(""),yield a,n){if(!r||t.state!==V.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")})}},Ys=class extends nt{get description(){return"Can connect via TURN"}perform(){return p(this,void 0,void 0,function*(){var e,t,n;sn(new URL(this.url))&&(this.appendMessage("Using region specific url"),this.url=(e=yield new Ge(this.url,this.token).getNextBestRegionUrl())!==null&&e!==void 0?e:this.url);let r=new jn,s=yield r.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3},void 0,!0),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(),!((n=(t=this.connectOptions)===null||t===void 0?void 0:t.rtcConfig)===null||n===void 0)&&n.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)))})}},Xs=class extends nt{get description(){return"Establishing WebRTC connection"}perform(){return p(this,void 0,void 0,function*(){let e=!1,t=!1;this.room.on(C.SignalConnected,()=>{var n;let r=this.room.engine.client.onTrickle;this.room.engine.client.onTrickle=(s,a)=>{if(s.candidate){let o=new RTCIceCandidate(s),d="".concat(o.protocol," ").concat(o.address,":").concat(o.port," ").concat(o.type);o.address&&(Op(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)},!((n=this.room.engine.pcManager)===null||n===void 0)&&n.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(),F.info("now the room is connected")}catch(n){throw this.appendWarning("ports need to be open on firewall in order to connect."),n}e||this.appendWarning("Server is not configured for ICE/TCP"),t||this.appendWarning("No public IPv4 UDP candidates were found. Your server is likely not configured correctly")})}};function Op(i){let e=i.split(".");if(e.length===4){if(e[0]==="10")return!0;if(e[0]==="192"&&e[1]==="168")return!0;if(e[0]==="172"){let t=parseInt(e[1],10);if(t>=16&&t<=31)return!0}}return!1}var Zs=class extends nt{get description(){return"Connecting to signal connection via WebSocket"}perform(){return p(this,void 0,void 0,function*(){var e,t,n;(this.url.startsWith("ws:")||this.url.startsWith("http:"))&&this.appendWarning("Server is insecure, clients may block connections to it");let r=new jn,s;try{s=yield r.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3},void 0,!0)}catch(a){if(sn(new URL(this.url))){this.appendMessage("Initial connection failed with error ".concat(a.message,". Retrying with region fallback"));let d=yield new Ge(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)===Bc.Cloud&&(!((t=s.serverInfo)===null||t===void 0)&&t.region)&&this.appendMessage("LiveKit Cloud: ".concat((n=s.serverInfo)===null||n===void 0?void 0:n.region))):this.appendError("Websocket connection could not be established"),yield r.close()})}},uc=class extends Ee.EventEmitter{constructor(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.options={},this.checkResults=new Map,this.url=e,this.token=t,this.options=n}getNextCheckId(){let e=this.checkResults.size;return this.checkResults.set(e,{logs:[],status:Le.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!==Le.FAILED)}getResults(){return Array.from(this.checkResults.values())}createAndRunCheck(e){return p(this,void 0,void 0,function*(){let t=this.getNextCheckId(),n=new e(this.url,this.token,this.options),r=a=>{this.updateCheck(t,a)};n.on("update",r);let s=yield n.run();return n.off("update",r),s})}checkWebsocket(){return p(this,void 0,void 0,function*(){return this.createAndRunCheck(Zs)})}checkWebRTC(){return p(this,void 0,void 0,function*(){return this.createAndRunCheck(Xs)})}checkTURN(){return p(this,void 0,void 0,function*(){return this.createAndRunCheck(Ys)})}checkReconnect(){return p(this,void 0,void 0,function*(){return this.createAndRunCheck(Qs)})}checkPublishAudio(){return p(this,void 0,void 0,function*(){return this.createAndRunCheck(Js)})}checkPublishVideo(){return p(this,void 0,void 0,function*(){return this.createAndRunCheck($s)})}checkConnectionProtocol(){return p(this,void 0,void 0,function*(){let e=yield this.createAndRunCheck(zs);if(e.data&&"protocol"in e.data){let t=e.data;this.options.protocol=t.protocol}return e})}checkCloudRegion(){return p(this,void 0,void 0,function*(){return this.createAndRunCheck(Ws)})}};new TextEncoder;var uf=new TextDecoder;var fe=class extends Error{constructor(e,t){var n;super(e,t),H(this,"code","ERR_JOSE_GENERIC"),this.name=this.constructor.name,(n=Error.captureStackTrace)===null||n===void 0||n.call(Error,this,this.constructor)}};H(fe,"code","ERR_JOSE_GENERIC");var ea=class extends fe{constructor(e,t){let n=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:n,reason:r,payload:t}}),H(this,"code","ERR_JWT_CLAIM_VALIDATION_FAILED"),H(this,"claim",void 0),H(this,"reason",void 0),H(this,"payload",void 0),this.claim=n,this.reason=r,this.payload=t}};H(ea,"code","ERR_JWT_CLAIM_VALIDATION_FAILED");var ta=class extends fe{constructor(e,t){let n=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:n,reason:r,payload:t}}),H(this,"code","ERR_JWT_EXPIRED"),H(this,"claim",void 0),H(this,"reason",void 0),H(this,"payload",void 0),this.claim=n,this.reason=r,this.payload=t}};H(ta,"code","ERR_JWT_EXPIRED");var na=class extends fe{constructor(){super(...arguments),H(this,"code","ERR_JOSE_ALG_NOT_ALLOWED")}};H(na,"code","ERR_JOSE_ALG_NOT_ALLOWED");var ia=class extends fe{constructor(){super(...arguments),H(this,"code","ERR_JOSE_NOT_SUPPORTED")}};H(ia,"code","ERR_JOSE_NOT_SUPPORTED");var ra=class extends fe{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),H(this,"code","ERR_JWE_DECRYPTION_FAILED")}};H(ra,"code","ERR_JWE_DECRYPTION_FAILED");var sa=class extends fe{constructor(){super(...arguments),H(this,"code","ERR_JWE_INVALID")}};H(sa,"code","ERR_JWE_INVALID");var aa=class extends fe{constructor(){super(...arguments),H(this,"code","ERR_JWS_INVALID")}};H(aa,"code","ERR_JWS_INVALID");var oa=class extends fe{constructor(){super(...arguments),H(this,"code","ERR_JWT_INVALID")}};H(oa,"code","ERR_JWT_INVALID");var ca=class extends fe{constructor(){super(...arguments),H(this,"code","ERR_JWK_INVALID")}};H(ca,"code","ERR_JWK_INVALID");var da=class extends fe{constructor(){super(...arguments),H(this,"code","ERR_JWKS_INVALID")}};H(da,"code","ERR_JWKS_INVALID");var la=class extends fe{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),H(this,"code","ERR_JWKS_NO_MATCHING_KEY")}};H(la,"code","ERR_JWKS_NO_MATCHING_KEY");var ua=class extends fe{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),H(this,Symbol.asyncIterator,void 0),H(this,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS")}};H(ua,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS");var ha=class extends fe{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),H(this,"code","ERR_JWKS_TIMEOUT")}};H(ha,"code","ERR_JWKS_TIMEOUT");var ma=class extends fe{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),H(this,"code","ERR_JWS_SIGNATURE_VERIFICATION_FAILED")}};H(ma,"code","ERR_JWS_SIGNATURE_VERIFICATION_FAILED");var Lp=1e3,hf=60*Lp;var mf=Symbol.for("lk.serializer");var mt={AgentSnapshotPayload:{additionalProperties:!1,properties:{ack_message_id:{title:"Ack Message Id",type:"string"},capabilities:{additionalProperties:!0,title:"Capabilities",type:"object"},connection_id:{title:"Connection Id",type:"string"},last_client_seq:{minimum:1,title:"Last Client Seq",type:"integer"},profile_revision:{title:"Profile Revision",type:"string"},session_id:{title:"Session Id",type:"string"},status:{enum:["connecting","ready","ended"],title:"Status",type:"string"}},required:["session_id","profile_revision","capabilities","status","ack_message_id","connection_id","last_client_seq"],title:"AgentSnapshotPayload",type:"object"},ClientHelloPayload:{$defs:{ClientReconnectPayload:{additionalProperties:!1,properties:{duration_ms:{maximum:36e5,minimum:0,title:"Duration Ms",type:"integer"},recovered_at:{format:"date-time",title:"Recovered At",type:"string"},started_at:{format:"date-time",title:"Started At",type:"string"}},required:["started_at","recovered_at","duration_ms"],title:"ClientReconnectPayload",type:"object"}},additionalProperties:!1,properties:{last_server_seq:{default:0,minimum:0,title:"Last Server Seq",type:"integer"},reconnect:{anyOf:[{$ref:"#/$defs/ClientReconnectPayload"},{type:"null"}],default:null},sdk:{maxLength:80,minLength:1,title:"Sdk",type:"string"},tool_handlers:{items:{maxLength:80,pattern:"^[a-z][a-z0-9_]{0,79}$",type:"string"},maxItems:128,title:"Tool Handlers",type:"array"}},required:["sdk"],title:"ClientHelloPayload",type:"object"},ClientMessage:{additionalProperties:!1,properties:{client_seq:{minimum:1,title:"Client Seq",type:"integer"},connection_id:{maxLength:120,minLength:1,title:"Connection Id",type:"string"},message_id:{maxLength:120,minLength:1,title:"Message Id",type:"string"},payload:{additionalProperties:!0,title:"Payload",type:"object"},protocol_version:{const:1,default:1,title:"Protocol Version",type:"integer"},type:{maxLength:100,minLength:1,title:"Type",type:"string"}},required:["message_id","connection_id","client_seq","type","payload"],title:"ClientMessage",type:"object"},CommandAckPayload:{additionalProperties:!1,properties:{client_seq:{minimum:1,title:"Client Seq",type:"integer"},command_type:{maxLength:100,minLength:1,title:"Command Type",type:"string"},connection_id:{title:"Connection Id",type:"string"},message_id:{title:"Message Id",type:"string"}},required:["message_id","connection_id","client_seq","command_type"],title:"CommandAckPayload",type:"object"},CommandErrorPayload:{additionalProperties:!1,properties:{client_seq:{minimum:1,title:"Client Seq",type:"integer"},code:{maxLength:100,minLength:1,title:"Code",type:"string"},command_type:{maxLength:100,minLength:1,title:"Command Type",type:"string"},connection_id:{title:"Connection Id",type:"string"},message:{maxLength:500,minLength:1,title:"Message",type:"string"},message_id:{title:"Message Id",type:"string"},retryable:{title:"Retryable",type:"boolean"}},required:["message_id","connection_id","client_seq","command_type","code","message","retryable"],title:"CommandErrorPayload",type:"object"},ContextRejectedPayload:{additionalProperties:!1,properties:{client_seq:{minimum:1,title:"Client Seq",type:"integer"},code:{maxLength:100,minLength:1,title:"Code",type:"string"},command_type:{maxLength:100,minLength:1,title:"Command Type",type:"string"},connection_id:{title:"Connection Id",type:"string"},message:{maxLength:500,minLength:1,title:"Message",type:"string"},message_id:{title:"Message Id",type:"string"},retryable:{title:"Retryable",type:"boolean"}},required:["message_id","connection_id","client_seq","command_type","code","message","retryable"],title:"ContextRejectedPayload",type:"object"},ContextUpdatePayload:{$defs:{ContextImageReference:{additionalProperties:!1,properties:{bytes:{maximum:5242880,minimum:1,title:"Bytes",type:"integer"},detail:{default:"low",enum:["auto","low","high"],title:"Detail",type:"string"},height:{anyOf:[{maximum:8192,minimum:1,type:"integer"},{type:"null"}],default:null,title:"Height"},mime:{enum:["image/jpeg","image/png","image/webp"],title:"Mime",type:"string"},sha256:{pattern:"^[a-f0-9]{64}$",title:"Sha256",type:"string"},stream_id:{maxLength:120,minLength:1,title:"Stream Id",type:"string"},width:{anyOf:[{maximum:8192,minimum:1,type:"integer"},{type:"null"}],default:null,title:"Width"}},required:["stream_id","mime","bytes","sha256"],title:"ContextImageReference",type:"object"},ContextTextStreamReference:{additionalProperties:!1,properties:{bytes:{maximum:262144,minimum:1,title:"Bytes",type:"integer"},sha256:{pattern:"^[a-f0-9]{64}$",title:"Sha256",type:"string"},stream_id:{maxLength:120,minLength:1,title:"Stream Id",type:"string"}},required:["stream_id","bytes","sha256"],title:"ContextTextStreamReference",type:"object"}},additionalProperties:!1,oneOf:[{properties:{image:{type:"null"},text_stream:{type:"null"}},required:["text"],type:"object"},{properties:{image:{type:"null"},text:{type:"null"}},required:["text_stream"],type:"object"},{properties:{mode:{const:"replace"},text:{type:"null"},text_stream:{type:"null"}},required:["image"],type:"object"}],properties:{image:{anyOf:[{$ref:"#/$defs/ContextImageReference"},{type:"null"}],default:null},key:{maxLength:120,minLength:1,pattern:"^[A-Za-z0-9][A-Za-z0-9._:-]*$",title:"Key",type:"string"},label:{default:"",maxLength:200,title:"Label",type:"string"},mode:{enum:["append","replace"],title:"Mode",type:"string"},respond:{default:!1,title:"Respond",type:"boolean"},text:{anyOf:[{maxLength:32768,minLength:1,type:"string"},{type:"null"}],default:null,title:"Text"},text_stream:{anyOf:[{$ref:"#/$defs/ContextTextStreamReference"},{type:"null"}],default:null}},required:["key","mode"],title:"ContextUpdatePayload",type:"object"},ContextUpdatedPayload:{additionalProperties:!1,properties:{client_seq:{minimum:1,title:"Client Seq",type:"integer"},command_type:{maxLength:100,minLength:1,title:"Command Type",type:"string"},connection_id:{title:"Connection Id",type:"string"},context_sequence:{minimum:1,title:"Context Sequence",type:"integer"},key:{title:"Key",type:"string"},message_id:{title:"Message Id",type:"string"},mode:{enum:["append","replace"],title:"Mode",type:"string"},respond:{title:"Respond",type:"boolean"}},required:["message_id","connection_id","client_seq","command_type","key","mode","context_sequence","respond"],title:"ContextUpdatedPayload",type:"object"},RealtimeEvent:{additionalProperties:!1,properties:{event_id:{title:"Event Id",type:"string"},payload:{additionalProperties:!0,title:"Payload",type:"object"},protocol_version:{const:1,default:1,title:"Protocol Version",type:"integer"},server_seq:{anyOf:[{minimum:1,type:"integer"},{type:"null"}],default:null,title:"Server Seq"},stream_id:{title:"Stream Id",type:"string"},stream_seq:{minimum:1,title:"Stream Seq",type:"integer"},ts:{format:"date-time",title:"Ts",type:"string"},type:{maxLength:100,minLength:1,title:"Type",type:"string"}},required:["event_id","stream_id","stream_seq","ts","type","payload"],title:"RealtimeEvent",type:"object"}};function pt(i,e,t){let n=ln(i,e,t,i);if(n)throw new TypeError(n);return e}function ln(i,e,t,n){if(i.$ref){let r="#/$defs/";if(!i.$ref.startsWith(r))return`${t} uses an unsupported schema reference`;let s=n.$defs?.[i.$ref.slice(r.length)];return s?ln(s,e,t,n):`${t} uses a missing schema reference`}if(i.anyOf&&!i.anyOf.some(r=>ln(r,e,t,n)===null))return`${t} does not match any allowed schema`;if(i.oneOf&&i.oneOf.filter(s=>ln(s,e,t,n)===null).length!==1)return`${t} must match exactly one allowed schema`;if(i.allOf)for(let r of i.allOf){let s=ln(r,e,t,n);if(s)return s}if(Object.prototype.hasOwnProperty.call(i,"const")&&e!==i.const)return`${t} must equal ${String(i.const)}`;if(i.enum&&!i.enum.includes(e))return`${t} has an unsupported value`;if(i.type==="object"){if(!e||typeof e!="object"||Array.isArray(e))return`${t} must be an object`;let r=e;for(let s of i.required??[])if(!Object.prototype.hasOwnProperty.call(r,s))return`${t}.${s} is required`;for(let[s,a]of Object.entries(i.properties??{}))if(Object.prototype.hasOwnProperty.call(r,s)){let o=ln(a,r[s],`${t}.${s}`,n);if(o)return o}if(i.additionalProperties===!1){let s=new Set(Object.keys(i.properties??{})),a=Object.keys(r).find(o=>!s.has(o));if(a)return`${t}.${a} is not allowed`}}else if(i.type==="string"){if(typeof e!="string")return`${t} must be a string`;if(i.minLength!==void 0&&e.length<i.minLength)return`${t} is too short`;if(i.maxLength!==void 0&&e.length>i.maxLength)return`${t} is too long`;if(i.pattern!==void 0&&!new RegExp(i.pattern).test(e))return`${t} has an invalid format`;if(i.format==="date-time"&&Number.isNaN(Date.parse(e)))return`${t} must be a date-time`}else if(i.type==="integer"){if(!Number.isInteger(e))return`${t} must be an integer`}else if(i.type==="number"){if(typeof e!="number"||!Number.isFinite(e))return`${t} must be a number`}else{if(i.type==="boolean"&&typeof e!="boolean")return`${t} must be a boolean`;if(i.type==="null"&&e!==null)return`${t} must be null`}if(typeof e=="number"){if(i.minimum!==void 0&&e<i.minimum)return`${t} is below its minimum`;if(i.maximum!==void 0&&e>i.maximum)return`${t} exceeds its maximum`}return null}function ll(i){return pt(mt.RealtimeEvent,i,"RealtimeEvent")}function ul(i){try{return ll(i),!0}catch{return!1}}function Np(i){return pt(mt.ClientMessage,i,"ClientMessage")}function Up(i){return pt(mt.AgentSnapshotPayload,i,"AgentSnapshotPayload")}function Fp(i){return pt(mt.ClientHelloPayload,i,"ClientHelloPayload")}function hl(i){return pt(mt.CommandAckPayload,i,"CommandAckPayload")}function ml(i){try{return hl(i),!0}catch{return!1}}function pl(i){return pt(mt.CommandErrorPayload,i,"CommandErrorPayload")}function fl(i){try{return pl(i),!0}catch{return!1}}function gl(i){return pt(mt.ContextUpdatePayload,i,"ContextUpdatePayload")}function vl(i){try{return gl(i),!0}catch{return!1}}function yl(i){return pt(mt.ContextUpdatedPayload,i,"ContextUpdatedPayload")}function bl(i){try{return yl(i),!0}catch{return!1}}function kl(i){return pt(mt.ContextRejectedPayload,i,"ContextRejectedPayload")}function Tl(i){try{return kl(i),!0}catch{return!1}}var Gn=class extends Error{payload;constructor(e){super(e.message),this.name="CommandError",this.payload=e}};function Va(i){return ml(i)}function Ha(i){return fl(i)}function Ga(i){return bl(i)}function Ka(i){return vl(i)}function Wa(i){return Tl(i)}function za(i){return ul(i)}function Wn(i,e,t,n){return{protocol_version:1,message_id:`msg_${Bp()}`,connection_id:i,client_seq:e,type:t,payload:n}}var Kn=class{seen=new Set;seenOrder=[];seenLimit;streamSeq=0;streamId=null;serverSeq=0;constructor(e=2048){this.seenLimit=e}get lastStreamSeq(){return this.streamSeq}get currentStreamId(){return this.streamId}get lastServerSeq(){return this.serverSeq}accept(e){if(this.seen.has(e.event_id))return{deliver:!1,gap:null};if(e.stream_id.startsWith("control:"))return this.remember(e,!1),{deliver:!0,gap:null};e.stream_id!==this.streamId&&(this.streamId=e.stream_id,this.streamSeq=0);let t=e.stream_seq>this.streamSeq+1?{expected_stream_seq:this.streamSeq+1,received_stream_seq:e.stream_seq,after_server_seq:this.serverSeq}:null;return e.stream_seq<=this.streamSeq?{deliver:!1,gap:t}:(this.streamSeq=e.stream_seq,this.remember(e),{deliver:!0,gap:t})}acceptReplay(e){return this.seen.has(e.event_id)?!1:(this.remember(e),!0)}remember(e,t=!0){for(this.seen.add(e.event_id),this.seenOrder.push(e.event_id),t&&e.server_seq!==null&&(this.serverSeq=Math.max(this.serverSeq,e.server_seq));this.seenOrder.length>this.seenLimit;){let n=this.seenOrder.shift();n&&this.seen.delete(n)}}};function Bp(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`${Date.now().toString(36)}_${Math.random().toString(36).slice(2)}`}var it=class extends Error{retryAfter;constructor(e,t={}){super(e,t),this.retryAfter=t.retryAfter}};function Ja(i){let e=1e3*2**Math.min(Math.max(i-1,0),3);return Math.min(e*(1+Math.random()*.2),8e3)}var cr=class{constructor(e){this.send=e}paused=!1;generation=0;latest=new Map;pending=new Map;running=new Map;retryTimers=new Map;retryAttempts=new Map;blockedTransfers=new Map;submit(e,t){let n=new Set([...this.pending.keys(),...this.running.keys(),...this.blockedTransfers.keys()]);if(n.size>=64&&!n.has(e.key))return Promise.reject(new Error("Too many pending context keys"));this.latest.delete(e.key),this.latest.set(e.key,e);let r=0,s=0;for(let[o,d]of[...this.latest].reverse())r+="image"in d?d.image.size:new TextEncoder().encode(d.text).byteLength,s+=1,(r>16*1024*1024||s>64)&&this.latest.delete(o);let a=new Promise((o,d)=>{this.pending.get(e.key)?.reject(new Error("Context update superseded by a newer value")),this.pending.set(e.key,{update:e,retainedUpdate:e,timeoutMs:t,resolve:o,reject:d})});return this.start(e.key),a}pause(){this.generation+=1,this.paused=!0;for(let e of this.retryTimers.values())globalThis.clearTimeout(e);this.retryTimers.clear()}async resume(e=!1){let t=this.generation;if(await Promise.all(this.running.values()),t!==this.generation)throw new Error("Context restoration interrupted");if(e)for(let[n,r]of this.latest)this.pending.has(n)||this.pending.set(n,{update:{...r,respond:!1},retainedUpdate:r,timeoutMs:2e4,resolve:()=>{},reject:()=>{}});this.paused=!1;for(let n of this.pending.keys())this.start(n);if(await Promise.all(this.running.values()),t!==this.generation)throw new Error("Context restoration interrupted")}clear(e){this.pause(),this.latest.clear(),this.retryAttempts.clear();for(let t of this.pending.values())t.reject(e);this.pending.clear()}start(e){if(this.paused||this.running.has(e)||this.retryTimers.has(e)||this.blockedTransfers.has(e))return;let t=this.drain(e).finally(()=>{this.running.delete(e),this.pending.has(e)&&this.start(e)});this.running.set(e,t)}async drain(e){for(;!this.paused&&!this.blockedTransfers.has(e);){let t=this.pending.get(e);if(!t)return;this.pending.delete(e);try{t.resolve(await this.send(t.update,t.timeoutMs)),this.retryAttempts.delete(e)}catch(n){n instanceof it&&n.retryAfter&&this.blockUntilTransferSettles(e,n.retryAfter);let r=this.latest.get(e)===t.retainedUpdate;if(this.paused&&!t.update.respond&&!this.pending.has(e)&&r?this.pending.set(e,t):t.reject(n instanceof Error?n:new Error(String(n))),!this.paused){if(n instanceof it){r&&!t.update.respond&&!this.pending.has(e)&&this.pending.set(e,{...t,resolve:()=>{},reject:()=>{}}),this.pending.has(e)&&this.scheduleRetry(e);return}r&&this.latest.delete(e),this.retryAttempts.delete(e);return}}}}blockUntilTransferSettles(e,t){this.blockedTransfers.set(e,t),t.then(()=>{this.blockedTransfers.get(e)===t&&(this.blockedTransfers.delete(e),this.pending.has(e)&&this.start(e))})}scheduleRetry(e){let t=(this.retryAttempts.get(e)??0)+1;this.retryAttempts.set(e,t);let n=globalThis.setTimeout(()=>{this.retryTimers.delete(e),this.start(e)},Ja(t));this.retryTimers.set(e,n)}};var Gt=class extends Error{constructor(t,n=!0,r=0){super(t);this.retryable=n;this.retryAfterMs=r;this.name="DiagnosticDeliveryError"}};function Sl(){return globalThis.crypto?.randomUUID?.()??`diag_${Date.now().toString(36)}_${Math.random().toString(36).slice(2)}`}function Cl(i){return new TextEncoder().encode(JSON.stringify(i)).byteLength}var qp=new Set(["context_transfer","command_send","command_result","connection_recovery","tool_rpc"]),jp=new Set(["started","succeeded","failed","retrying","acknowledged","rejected","timed_out"]),Vp=new Set(["idle","connecting","connected_not_ready","connected","reconnecting","resuming","disconnected","failed"]),Hp=new Set(["client.hello","context.update","command.ack","command.error","context.updated","context.rejected"]),_l=/^[a-z0-9_.:-]+$/,Gp=/^[A-Za-z0-9][A-Za-z0-9._:-]*$/,Kp=["token_request","room_disconnect","room_connect","hello","agent_ready","remote_audio","complete"],Wp=["received","handler_started","response_ready","flush_requested",...Kp],dr=class{entries=[];sdkVersion;limit;throttleMs;now;schedule;startedAt;wallStartedAt=Date.now();instanceId=Sl();sequence=0;batchedThrough=0;droppedEntries=0;pending=null;sender=null;trigger="slow_operation";reporting=!1;scheduled=!1;nextAttemptAt=0;failures=0;constructor(e){this.sdkVersion=e.sdkVersion,this.limit=Math.max(1,Math.min(Math.trunc(e.limit??128),128)),this.throttleMs=Math.max(0,e.throttleMs??1e4),this.now=e.now??(()=>performance.now()),this.schedule=e.schedule??((t,n)=>{let r=globalThis.setTimeout(t,n);return r.unref?.(),r}),this.startedAt=this.now()}record(e){let t=zp(e,Math.max(this.now()-this.startedAt,0));t&&(t.entry_seq=++this.sequence,this.entries.push(t),this.prune())}snapshot(){return this.entries.map(e=>({...e}))}async flush(e,t){return!_l.test(e)||e.length>100?!1:(this.trigger=e,this.sender=t,e.startsWith("tool_rpc")&&!this.pending&&!this.reporting&&(this.prune(),this.makeBatch()),this.deliver())}prune(){let e=this.now()-this.startedAt-3e5;for(;this.entries.length&&(this.entries.length>this.limit||Cl(this.entries)>65536||this.entries[0].at_ms<=e);)this.entries.shift().entry_seq>this.batchedThrough&&(this.droppedEntries+=1);!this.reporting&&this.pending&&this.now()-this.pending.createdAt>=3e5&&(this.droppedEntries+=this.pending.report.entries.length,this.pending=null,this.failures=0)}makeBatch(){let e={source:"sdk",report_id:Sl(),sdk_instance_id:this.instanceId,started_at_ms:this.wallStartedAt,dropped_entries:this.droppedEntries,sdk_version:this.sdkVersion,trigger:this.trigger,entries:[]};for(let t of this.entries)if(!(t.entry_seq<=this.batchedThrough)&&(e.entries.push({...t}),Cl(e)>16384)){e.entries.pop();break}e.entries.length&&(this.batchedThrough=e.entries.at(-1).entry_seq,this.pending={report:e,createdAt:this.now()})}hasWork(){return this.pending!==null||this.entries.some(e=>e.entry_seq>this.batchedThrough)}async deliver(){if(this.reporting||!this.sender||(this.prune(),!this.hasWork()))return!1;if(this.now()<this.nextAttemptAt)return this.scheduleNext(),!1;if(this.pending||this.makeBatch(),!this.pending)return!1;let e=this.pending;this.reporting=!0;let t=this.throttleMs;try{return await this.sender(e.report),this.pending=null,this.failures=0,!0}catch(n){if(n instanceof Gt&&!n.retryable)this.droppedEntries+=e.report.entries.length,this.pending=null,this.failures=0;else{this.failures+=1;let r=Math.min(2e3*2**Math.min(this.failures-1,5),6e4);t=Math.max(this.throttleMs,r*(1+Math.random()*.2),n instanceof Gt?n.retryAfterMs:0)}return!1}finally{this.reporting=!1,this.nextAttemptAt=this.now()+t,this.scheduleNext()}}scheduleNext(){this.reporting||this.scheduled||!this.hasWork()||(this.scheduled=!0,this.schedule(()=>{this.scheduled=!1,this.deliver()},Math.min(Math.max(this.nextAttemptAt-this.now(),0),3e5)))}};function zp(i,e){if(!qp.has(i.operation)||!jp.has(i.status))return null;let t={entry_seq:0,at_ms:wl(e,0,864e5)??0,operation:i.operation,status:i.status},n=Ht(i.reason,100,_l),r=Ht(i.message_id,120),s=Ht(i.connection_id,120),a=Ht(i.context_key,120,Gp);n!==void 0&&(t.reason=n),r!==void 0&&(t.message_id=r),s!==void 0&&(t.connection_id=s),a!==void 0&&(t.context_key=a);let o=Ht(i.call_id,200),d=Ht(i.rpc_request_id,120),c=Ht(i.tool_name,80);return o!==void 0&&(t.call_id=o),d!==void 0&&(t.rpc_request_id=d),c!==void 0&&(t.tool_name=c),i.stage&&Wp.includes(i.stage)&&(t.stage=i.stage),(i.page_visibility==="visible"||i.page_visibility==="hidden")&&(t.page_visibility=i.page_visibility),Ke(t,"rpc_error_code",i.rpc_error_code,0,65535,!0),Ke(t,"http_status",i.http_status,100,599,!0),Ke(t,"event_loop_delay_ms",i.event_loop_delay_ms,0,864e5),Ke(t,"active_context_transfers",i.active_context_transfers,0,1e3,!0),Ke(t,"active_context_bytes",i.active_context_bytes,0,1073741824,!0),Ke(t,"client_seq",i.client_seq,1,Number.MAX_SAFE_INTEGER,!0),Ke(t,"payload_bytes",i.payload_bytes,0,5242880,!0),Ke(t,"duration_ms",i.duration_ms,0,36e5),Ke(t,"retry_count",i.retry_count,0,1e3,!0),Ke(t,"timeout_ms",i.timeout_ms,1,36e5,!0),Ke(t,"buffered_bytes",i.buffered_bytes,0,1073741824,!0),i.connection_state&&Vp.has(i.connection_state)&&(t.connection_state=i.connection_state),i.event_type&&Hp.has(i.event_type)&&(t.event_type=i.event_type),t}function Ht(i,e,t){if(!(typeof i!="string"||i.length===0||i.length>e)&&!(t&&!t.test(i)))return i}function wl(i,e,t,n=!1){if(!(typeof i!="number"||!Number.isFinite(i))&&!(i<e||i>t))return n?Math.trunc(i):Math.round(i*10)/10}function Ke(i,e,t,n,r,s=!1){let a=wl(t,n,r,s);a!==void 0&&(i[e]=a)}var zn=class{messages=new Map;get snapshot(){return[...this.messages.values()].sort((e,t)=>e.turnStartedAt-t.turnStartedAt||(e.role===t.role?e.messageSeq-t.messageSeq:e.role==="user"?-1:1))}accept(e){let t=/^transcript\.(user|agent)\.(interim|final)$/.exec(e.type);if(!t)return null;let n=e.payload;if(typeof n.message_id!="string"||!n.message_id||typeof n.turn_id!="string"||typeof n.text!="string"||!Number.isSafeInteger(n.revision)||Number(n.revision)<1||!Number.isSafeInteger(n.message_seq)||Number(n.message_seq)<1)return null;let r=this.messages.get(n.message_id),s=t[2]==="final",a=t[1];if(r&&(Number(n.revision)<=r.revision||r.final&&!s||r.role!==a||r.turnId!==n.turn_id))return null;let o=Object.freeze({messageId:n.message_id,turnId:n.turn_id,turnStartedAt:typeof n.turn_started_at=="number"?n.turn_started_at:Date.parse(e.ts)/1e3,revision:Number(n.revision),messageSeq:Number(n.message_seq),role:a,text:n.text,final:s,interrupted:n.interrupted===!0,playbackAlignment:n.playback_alignment==="estimated"?"estimated":"unknown",event:e});return this.messages.set(o.messageId,o),o}};var El="0.3.12",Jp=3e4,$p=5e3,Rl=500,Qp=5e3,Yp=[{delayBeforeMs:0,readyTimeoutMs:15e3},{delayBeforeMs:1e3,readyTimeoutMs:2e4},{delayBeforeMs:3e3,readyTimeoutMs:5e4}],Xp=9e4,Qn=class extends Error{constructor(){super("Recovery data channel stopped draining before the agent handshake completed"),this.name="RecoveryDataChannelStalledError"}},Yn=class extends Error{status;code;requestId;details;constructor(e,t){super(e),this.name="RealtimeSessionHttpError",this.status=t.status,this.code=t.code??null,this.requestId=t.requestId??null,this.details=t.details??[]}},rt=class extends TypeError{},lr=class extends Error{retryable;constructor(e){let t=e.payload,n=typeof t.message=="string"?t.message:"VoxEvolv reported a session error";super(n),this.name="SessionErrorEventError",this.retryable=t.retryable===!0}},Pl=class i{id;room;accessToken;credentials;stateValue="idle";listeners=new Set;stateListeners=new Set;gapListeners=new Set;connectionQualityListeners=new Set;recoveryListeners=new Set;startupAttemptListeners=new Set;remoteAudioTrackListeners=new Set;remoteAudioTrackUnsubscribedListeners=new Set;readyListeners=new Set;userTranscriptListeners=new Set;agentTranscriptListeners=new Set;transcriptListeners=new Set;transcriptStore=new zn;errorListeners=new Set;endedListeners=new Set;toolCallListeners=new Set;audioPlaybackBlockedListeners=new Set;remoteAudioStreams=new WeakMap;outputMediaStream=null;remoteAudioTrackResolve=null;cursor=new Kn;connectionId=`conn_${Math.random().toString(36).slice(2)}_${Date.now().toString(36)}`;clientSeq=0;lastHelloMessageId=null;reconnectStartedAt=null;pendingReconnect=null;agentReady=!1;agentStreamId=null;contextGeneration=0;replacementContext=new cr((e,t)=>this.sendContextUpdate(e,t));readyResolve=null;replayPromise=null;pendingCommands=new Map;commandPublishTail=Promise.resolve();toolHandlers=new Map;apiBase="/v1";hasConnectedValue=!1;sessionEnded=!1;pendingEndEvent=null;agentDisconnected=!1;terminalSessionError=null;endNotificationDelivered=!1;disconnectMode=null;activeRecovery=null;recoveryStartedAt=null;livekitResumeController=null;autoRejoinPromise=null;autoRejoinController=null;manualRejoinController=null;startupConnectController=null;startupAttemptController=null;useManagedMicrophone=!0;microphoneEnabled=!0;applicationAudioTrack=null;localApplicationAudioTrack=null;connectDefaults;recoveryReadiness;credentialRefreshGeneration=0;fetcher;endEndpoint;refreshCredentialsCallback;autoRejoinOptions;startupRetryOptions;lifecycleCredentials;diagnostics=new dr({sdkVersion:El});activeContextTransfers=0;activeContextBytes=0;diagnosticLoopTimer;diagnosticLoopExpectedAt=0;diagnosticLoopDelayMs;diagnosticReportTimeoutMs=Qp;onDiagnosticVisibilityChange=()=>{globalThis.document?.visibilityState==="hidden"&&this.flushDiagnostics("page_hidden")};constructor(e,t={}){Ol(e),this.id=e.id,this.accessToken=e.access_token,this.credentials=e.connection,this.connectDefaults=t.connect?.apiBase===void 0?t.connect??{}:{...t.connect,apiBase:hn(t.connect.apiBase)},this.apiBase=this.connectDefaults.apiBase??this.apiBase,this.recoveryReadiness={readyTimeoutMs:this.connectDefaults.readyTimeoutMs??15e3,waitForRemoteAudio:this.connectDefaults.waitForRemoteAudio??!0},this.fetcher=t.fetch??globalThis.fetch.bind(globalThis),this.endEndpoint=t.endEndpoint??null,this.refreshCredentialsCallback=t.refreshCredentials??null,this.autoRejoinOptions=Zp(t.autoRejoin),this.startupRetryOptions=ef(t.startupRetry),this.lifecycleCredentials=t.lifecycleCredentials??"same-origin",this.room=new dn({adaptiveStream:!0,dynacast:!0});for(let[n,r]of Object.entries(t.tools??{}))this.registerTool(n,r);this.room.registerRpcMethod("voxevolv.tool.invoke",n=>this.invokeBrowserTool(n)),this.room.registerRpcMethod("voxevolv.diagnostics.flush",async n=>{let r=JSON.parse(n.payload);if(typeof r?.call_id!="string"||r.call_id.length>200)throw new G(1500,"Invalid diagnostic request");return this.recordDiagnostic({operation:"tool_rpc",status:"started",stage:"flush_requested",call_id:r.call_id,rpc_request_id:n.requestId}),this.flushDiagnostics("tool_rpc_worker_request"),"{}"}),this.bindRoomEvents()}async invokeBrowserTool(e){let t=performance.now(),n,r,s,a=o=>this.recordDiagnostic({operation:"tool_rpc",status:"started",rpc_request_id:e.requestId,call_id:n,tool_name:r,duration_ms:performance.now()-t,...o});a({stage:"received"});try{let o;try{o=JSON.parse(e.payload)}catch(u){throw new G(1500,"Tool invocation payload was not valid JSON",void 0,{cause:u})}if(typeof o?.name!="string")throw new G(1500,"Tool invocation did not include a valid name");r=o.name,n=typeof o.call_id=="string"?o.call_id:e.requestId;let d=this.toolHandlers.get(r);if(!d)throw new G(1500,`No browser handler is registered for ${r}`);if(!o.arguments||typeof o.arguments!="object"||Array.isArray(o.arguments))throw new G(1500,"Tool invocation arguments must be an object");let c=o.arguments;this.notifyListeners(this.toolCallListeners,{name:r,callId:n,arguments:c}),a({stage:"handler_started"}),this.flushDiagnostics("tool_rpc_received"),s=globalThis.setTimeout(()=>{a({stage:"handler_started",reason:"handler_slow"}),this.flushDiagnostics("tool_rpc_slow")},2e3);let l;try{let u=await d(c,{callId:n});l=JSON.stringify(u??null)}catch(u){let h=u instanceof Error?u.message:"Browser tool handler failed";throw new G(1500,h,void 0,{cause:u})}return a({stage:"response_ready",status:"succeeded"}),l}catch(o){throw a({status:"failed",rpc_error_code:o instanceof G?o.code:void 0}),o}finally{globalThis.clearTimeout(s),this.flushDiagnostics("tool_rpc_finished")}}static async create(e){if("connect"in e)throw new TypeError("RealtimeSession.create() accepts apiBase and media options at the top level, not in connect");let{endpoint:t,request:n,microphone:r,audioTrack:s,readyTimeoutMs:a,waitForRemoteAudio:o,apiBase:d,...c}=e;if(!t)throw new TypeError("endpoint is required");if(!d)throw new TypeError("apiBase is required so rejoin, replay, and end use the intended VoxEvolv API or application proxy");let l=hn(d),u=c.fetch??globalThis.fetch.bind(globalThis),h=await u(t,{...n,method:"POST"});if(!h.ok)throw await $n(h,"Could not create realtime session");let m=await h.json();return new i(m,{...c,fetch:u,connect:{microphone:r,audioTrack:s,readyTimeoutMs:a,waitForRemoteAudio:o,apiBase:l}})}get state(){return this.stateValue}get hasConnectedBefore(){return this.hasConnectedValue}get outputStream(){return this.outputMediaStream??=new MediaStream,this.outputMediaStream}onEvent(e){return this.listeners.add(e),()=>this.listeners.delete(e)}onStateChange(e){return this.stateListeners.add(e),this.notifyListeners(new Set([e]),this.stateValue),()=>this.stateListeners.delete(e)}onProtocolGap(e){return this.gapListeners.add(e),()=>this.gapListeners.delete(e)}onConnectionQuality(e){return this.connectionQualityListeners.add(e),this.notifyListeners(new Set([e]),this.room.localParticipant.connectionQuality),()=>this.connectionQualityListeners.delete(e)}onRecovery(e){return this.recoveryListeners.add(e),()=>this.recoveryListeners.delete(e)}onStartupAttempt(e){return this.startupAttemptListeners.add(e),()=>this.startupAttemptListeners.delete(e)}waitForState(e,t,n={}){if(!e.length)throw new TypeError("states must contain at least one connection state");if(!Number.isFinite(t)||t<0)throw new TypeError("timeoutMs must be a non-negative finite number");let r=new Set(e);return r.has(this.stateValue)?Promise.resolve(this.stateValue):n.signal?.aborted?Promise.reject(n.signal.reason??new DOMException("Aborted","AbortError")):new Promise((s,a)=>{let o=!1,d=(h,m)=>{o||(o=!0,globalThis.clearTimeout(u),this.stateListeners.delete(c),n.signal?.removeEventListener("abort",l),m!==void 0?a(m):h!==null&&s(h))},c=h=>{r.has(h)&&d(h)},l=()=>{d(null,n.signal?.reason??new DOMException("Aborted","AbortError"))},u=globalThis.setTimeout(()=>{d(null,new Error(`Session did not reach ${e.join(" or ")} within ${t}ms`))},t);this.stateListeners.add(c),n.signal?.addEventListener("abort",l,{once:!0})})}onRemoteAudioTrack(e){return this.remoteAudioTrackListeners.add(e),()=>this.remoteAudioTrackListeners.delete(e)}onRemoteAudioTrackUnsubscribed(e){return this.remoteAudioTrackUnsubscribedListeners.add(e),()=>this.remoteAudioTrackUnsubscribedListeners.delete(e)}onReady(e){return this.readyListeners.add(e),()=>this.readyListeners.delete(e)}onUserTranscript(e){return this.userTranscriptListeners.add(e),()=>this.userTranscriptListeners.delete(e)}onAgentTranscript(e){return this.agentTranscriptListeners.add(e),()=>this.agentTranscriptListeners.delete(e)}get transcript(){return this.transcriptStore.snapshot}onTranscriptUpdated(e){return this.transcriptListeners.add(e),()=>this.transcriptListeners.delete(e)}onError(e){return this.errorListeners.add(e),()=>this.errorListeners.delete(e)}onEnded(e){return this.endedListeners.add(e),()=>this.endedListeners.delete(e)}onToolCall(e){return this.toolCallListeners.add(e),()=>this.toolCallListeners.delete(e)}onAudioPlaybackBlocked(e){return this.audioPlaybackBlockedListeners.add(e),()=>this.audioPlaybackBlockedListeners.delete(e)}registerTool(e,t){if(["connecting","connected_not_ready","connected","reconnecting","resuming"].includes(this.stateValue))throw new Error("Browser tools must be registered before connect()");if(!/^[a-z][a-z0-9_]{0,79}$/.test(e))throw new TypeError("Tool name must be lowercase letters, numbers, and underscores");if(this.toolHandlers.has(e))throw new TypeError(`Tool ${e} is already registered`);return this.toolHandlers.set(e,t),()=>{this.toolHandlers.get(e)===t&&this.toolHandlers.delete(e)}}async connect(e={}){if(this.startupConnectController||this.manualRejoinController)throw new Error("A session connection attempt is already in progress");if(["connecting","connected_not_ready","connected","reconnecting","resuming"].includes(this.stateValue))throw new Error(`Cannot connect while session is ${this.stateValue}`);this.cancelRecovery();let t=new AbortController;this.startupConnectController=t,this.credentialRefreshGeneration+=1;let n={...this.connectDefaults,...e};this.recoveryReadiness={readyTimeoutMs:n.readyTimeoutMs??15e3,waitForRemoteAudio:n.waitForRemoteAudio??!0},this.microphoneEnabled=n.audioTrack?n.audioTrack.enabled!==!1:n.microphone??!0,this.setState("connecting");try{this.startupRetryOptions?await this.connectWithStartupRetry(e,t):(this.startupAttemptController=t,await this.connectWithMode(e,!1,t.signal,!1))}catch(r){throw this.startupConnectController===t&&this.terminalSessionError?(this.sessionEnded=!0,this.setState("failed")):this.startupConnectController===t&&!this.sessionEnded&&this.setState("failed"),r}finally{this.startupAttemptController===t&&(this.startupAttemptController=null),this.startupConnectController===t&&(this.startupConnectController=null)}}async connectWithStartupRetry(e,t){let n=this.startupRetryOptions;if(!n)return;let r=performance.now(),s=globalThis.setTimeout(()=>{t.abort(new Error(`Session startup did not complete within ${n.timeoutMs}ms`))},n.timeoutMs),a=new Error("Session startup failed"),o=this.hasConnectedValue;this.apiBase=hn(e.apiBase??this.connectDefaults.apiBase??this.apiBase);try{for(let[d,c]of n.attempts.entries()){let l=d+1;c.delayBeforeMs>0&&(this.setState("connecting"),await Al(c.delayBeforeMs,t.signal)),X(t.signal);let u=Ml(t.signal);this.startupAttemptController=u,this.notifyStartupAttempt("started",l,c.readyTimeoutMs);try{if(!o){let h=n.timeoutMs-(performance.now()-r);await this.registerStartupRecovery(h,u.signal),o=!0}X(u.signal),d===0?await this.connectWithMode({...e,readyTimeoutMs:c.readyTimeoutMs},!1,u.signal,!1):await this.performRejoin(this.apiBase,{signal:u.signal,recovering:!1,connect:{...e,readyTimeoutMs:c.readyTimeoutMs},markFailureTerminal:!1}),X(t.signal),this.notifyStartupAttempt("succeeded",l,c.readyTimeoutMs);return}catch(h){if(a=un(h),this.notifyStartupAttempt("failed",l,c.readyTimeoutMs,a),t.signal.aborted)throw We(t.signal);if(rf(h)||l===n.attempts.length)throw h;this.setState("connecting")}finally{this.startupAttemptController===u&&(this.startupAttemptController=null)}}throw a}finally{globalThis.clearTimeout(s)}}async registerStartupRecovery(e,t){let n=Math.min(5e3,e/10),r=Ml(t),s=globalThis.setTimeout(()=>{r.abort(new Error("Startup registration timed out"))},Math.max(1,n));try{let a=()=>Te(this.fetcher(`${this.apiBase}/sessions/${this.id}/startup`,{method:"POST",headers:{Authorization:`Bearer ${this.accessToken}`,"Content-Type":"application/json"},credentials:this.lifecycleCredentials,body:JSON.stringify({timeout_ms:Math.max(1,Math.floor(Math.min(e-n,85e3)))}),signal:r.signal}),r.signal),o=await a();if(o.status===401&&this.refreshCredentialsCallback&&(await this.refreshCredentials(r.signal),o=await a()),!o.ok)throw await $n(o,"Could not register session startup");let d=await Te(o.json(),r.signal);if(typeof d.remaining_ms!="number"||d.remaining_ms<=0)throw new Error("Session startup window has expired")}finally{globalThis.clearTimeout(s)}}notifyStartupAttempt(e,t,n,r){let s=this.startupRetryOptions?.attempts.length??1;this.notifyListeners(this.startupAttemptListeners,{status:e,attempt:t,maxAttempts:s,readyTimeoutMs:n,...r?{error:r}:{}})}async connectWithMode(e,t,n,r=!0){X(n);let s=t?["connecting","connected_not_ready","connected","reconnecting"]:["connecting","connected_not_ready","connected","reconnecting","resuming"],a=!t&&!r&&this.stateValue==="connecting";if(s.includes(this.stateValue)&&!a)throw new Error(`Cannot connect while session is ${this.stateValue}`);let o=this.contextGeneration,d={...this.connectDefaults,...e},c=d.audioTrack??null,l=d.microphone??c===null,u=d.readyTimeoutMs??15e3,h=d.waitForRemoteAudio??!0,m=hn(d.apiBase??this.apiBase);this.validateAudioOptions(l,c),this.useManagedMicrophone=l,this.applicationAudioTrack=c,t?this.setState("resuming"):(this.sessionEnded=!1,this.agentStreamId=null,this.reconnectStartedAt=null,this.pendingEndEvent=null,this.agentDisconnected=!1,this.terminalSessionError=null,this.endNotificationDelivered=!1,this.setState("connecting")),this.apiBase=m,this.agentReady=!1;try{await this.measureRecoveryStage("room_connect",()=>this.connectRoom(n,t),t),X(n),c?await Te(this.publishApplicationAudioTrack(c),n):l&&await Te(this.room.localParticipant.setMicrophoneEnabled(this.microphoneEnabled),n),X(n),this.setState(t?"resuming":"connected_not_ready"),await this.measureRecoveryStage("hello",()=>t?this.sendRecoveryHello(n):Te(this.sendHello(),n),t);let g=Date.now()+u;if(await this.measureRecoveryStage("agent_ready",()=>this.waitForAgentReady(u,n),t),h&&await this.measureRecoveryStage("remote_audio",()=>this.waitForRemoteAudioTrack(g,n),t),X(n),this.sessionEnded||o!==this.contextGeneration)throw new Error("Connection restoration interrupted");if(this.resumeContextDelivery(t),X(n),this.sessionEnded||o!==this.contextGeneration)throw new Error("Connection restoration interrupted");this.hasConnectedValue=!0,this.setState("connected")}catch(g){n?.aborted&&this.rejectPendingCommands(un(We(n))),this.disconnectMode=t?"rejoin":"connect_failure";try{await this.room.disconnect()}catch{}finally{this.disconnectMode=null}throw!t&&r&&this.setState("failed"),g}}connectRoom(e,t){X(e);let n=this.room.connect(this.credentials.url,this.credentials.token);return e?new Promise((r,s)=>{let a=!1,o=()=>{a||(a=!0,e.removeEventListener("abort",c),r())},d=l=>{a||(a=!0,e.removeEventListener("abort",c),s(l))},c=()=>{this.disconnectMode=t?"rejoin":"connect_failure",this.room.disconnect().catch(()=>{}),d(We(e))};e.aborted?c():e.addEventListener("abort",c,{once:!0}),n.then(o,d)}):n}async rejoin(e=this.apiBase){if(this.startupConnectController||this.manualRejoinController)throw new Error("A session connection attempt is already in progress");if(this.sessionEnded)throw this.terminalSessionError??new Error("Cannot rejoin a session that has ended");if(["connecting","connected_not_ready","reconnecting","resuming"].includes(this.stateValue))throw new Error(`Cannot rejoin while session is ${this.stateValue}`);this.cancelRecovery();let t=hn(e),n=this.hasConnectedValue,r=new AbortController;this.manualRejoinController=r,n&&(this.beginRecovery("rejoin",1,{trigger:"manual_rejoin"}),this.setState("resuming"));try{if(await this.performRejoin(t,{recovering:n,signal:r.signal}),this.sessionEnded)return;n&&this.completeRecovery()}catch(s){if(r.signal.aborted&&!this.terminalSessionError)return;let a=un(s);throw n&&this.failRecovery(a),this.setState("failed"),s}finally{this.manualRejoinController===r&&(this.manualRejoinController=null)}}async performRejoin(e,t={}){let{signal:n,recovering:r=!0,connect:s,markFailureTerminal:a=!0}=t;this.contextGeneration+=1,this.replacementContext.pause(),this.rejectPendingCommands(new Error("Restoring the session"));let o=await this.fetchRoomToken(e,n,r);if(o.status===401&&this.refreshCredentialsCallback&&(await this.refreshCredentials(n),X(n),o=await this.fetchRoomToken(e,n,r)),this.sessionEnded){if(this.terminalSessionError)throw this.terminalSessionError;return}if(!o.ok){if(o.status===409&&await this.recoverSessionEnd(e,n))return;throw await Te($n(o,"Could not renew room token"),n)}let d=await Te(o.json(),n);if(X(n),this.credentials=d.connection,this.room.state!==V.Disconnected){this.disconnectMode="rejoin";try{await this.measureRecoveryStage("room_disconnect",()=>Te(this.room.disconnect(),n),r)}finally{this.disconnectMode=null}}X(n),r&&this.reconnectStartedAt!==null&&(this.pendingReconnect={started_at:new Date(this.reconnectStartedAt).toISOString(),recovered_at:new Date().toISOString(),duration_ms:Date.now()-this.reconnectStartedAt});let c=s??{...this.recoveryReadiness,microphone:this.useManagedMicrophone,...this.applicationAudioTrack?{audioTrack:this.applicationAudioTrack}:{}};await this.connectWithMode({...c,apiBase:e},r,n,a)}async setMicrophoneEnabled(e){if(this.microphoneEnabled=e,this.applicationAudioTrack){let t=this.localApplicationAudioTrack;e?await t?.unmute():await t?.mute();return}await this.room.localParticipant.setMicrophoneEnabled(e)}async sendCommand(e,t,n=1e4){let r=Wn(this.connectionId,++this.clientSeq,e,t);return this.sendTrackedCommand(r,n)}async updateContext(e,t=2e4){if(this.sessionEnded||["failed","disconnected"].includes(this.stateValue))throw new Error("Cannot update context while the session is inactive");if(e.mode==="replace")return this.replacementContext.submit(e,t);if(this.activeRecovery)throw new Error("Cannot append context during recovery");return this.sendContextUpdate(e,t)}async sendContextUpdate(e,t){let n=this.contextGeneration,r=af(e),s=Date.now(),a=!1;this.recordDiagnostic({operation:"context_transfer",status:"started",context_key:e.key,payload_bytes:r}),this.activeContextTransfers+=1,this.activeContextBytes+=r;let o=("image"in e?this.uploadImageContext(e):this.uploadTextContext(e)).finally(()=>{this.activeContextTransfers-=1,this.activeContextBytes-=r}),d=o.then(()=>{},()=>{}),c,l=new Promise((f,T)=>{c=globalThis.setTimeout(()=>{a=!0;let k=new it(`Context transfer timed out after ${t}ms`,{retryAfter:d});this.recordDiagnostic({operation:"context_transfer",status:"timed_out",reason:"context_transfer_timeout",context_key:e.key,payload_bytes:r,duration_ms:Date.now()-s,timeout_ms:t}),this.flushDiagnostics("context_transfer_timeout"),T(k)},t)}),u;try{u=await Promise.race([o,l])}catch(f){throw a||(this.recordDiagnostic({operation:"context_transfer",status:"failed",reason:"context_transfer_failed",context_key:e.key,payload_bytes:r,duration_ms:Date.now()-s}),this.flushDiagnostics("command_failed")),f instanceof TypeError||f instanceof it?f:new it(un(f).message,{cause:f})}finally{globalThis.clearTimeout(c)}let h=Date.now()-s;if(this.recordDiagnostic({operation:"context_transfer",status:"succeeded",context_key:e.key,payload_bytes:r,duration_ms:h}),h>2e3&&this.flushDiagnostics("slow_operation"),n!==this.contextGeneration)throw new Error("Context transfer interrupted by recovery");let{payload:m}=u;if(!Ka(m))throw new TypeError("Invalid context update payload");let g=Wn(this.connectionId,++this.clientSeq,"context.update",{...m});return this.sendTrackedCommand(g,t,u.resend)}resumeContextDelivery(e){this.replacementContext.resume(e).catch(()=>{})}async uploadTextContext(e){let t=new TextEncoder().encode(e.text);if(t.byteLength===0)throw new TypeError("Context text cannot be empty");if(t.byteLength>262144)throw new TypeError("Context text must be at most 262144 UTF-8 bytes");let n={key:e.key,mode:e.mode,label:e.label??"",respond:e.respond??!1};if(t.byteLength<=32768)return{payload:{...n,text:e.text}};let r=await xl(t),s=Dl(),a=async()=>{let o=await this.room.localParticipant.streamText({streamId:s,topic:"voxevolv.context.text",totalSize:t.byteLength,attributes:{sha256:r}});await o.write(e.text),await o.close()};return await a(),{payload:{...n,text_stream:{stream_id:s,bytes:t.byteLength,sha256:r}},resend:a}}async uploadImageContext(e){if(!new Set(["image/jpeg","image/png","image/webp"]).has(e.image.type))throw new TypeError("Image context must be JPEG, PNG, or WebP");let n=new Uint8Array(await e.image.arrayBuffer());if(n.byteLength===0||n.byteLength>5242880)throw new TypeError("Image context must be between 1 byte and 5 MiB");let r=await xl(n),s=Dl(),a=async()=>{let o=await this.room.localParticipant.streamBytes({streamId:s,topic:"voxevolv.context.image",name:"context-image",mimeType:e.image.type,totalSize:n.byteLength,attributes:{sha256:r}});await o.write(n),await o.close()};return await a(),{payload:{key:e.key,mode:"replace",label:e.label??"",image:{stream_id:s,mime:e.image.type,bytes:n.byteLength,sha256:r,...e.width===void 0?{}:{width:e.width},...e.height===void 0?{}:{height:e.height},detail:e.detail??"low"},respond:e.respond??!1},resend:a}}async disconnect(){if(this.abortStartupConnect(new Error("Session disconnected")),this.startupConnectController=null,this.failRecovery(new Error("Session disconnected during recovery")),this.cancelRecovery(),this.contextGeneration+=1,this.localApplicationAudioTrack=null,this.replacementContext.clear(new Error("Session disconnected")),this.stateValue!=="disconnected"){this.rejectPendingCommands(new Error("Session disconnected before command completion")),this.disconnectMode="intentional";try{await this.room.disconnect()}finally{this.disconnectMode=null,this.activeRecovery=null,this.setState("disconnected")}}}async end(e={}){this.credentialRefreshGeneration+=1,this.abortStartupConnect(new Error("Session ended")),this.startupConnectController=null,this.failRecovery(new Error("Session ended during recovery")),this.cancelRecovery(),this.sessionEnded=!0;let t=e.endpoint??this.endEndpoint??`${this.apiBase}/sessions/${this.id}`,n=e.request??{},r=new Headers(n.headers),s=!e.endpoint&&!this.endEndpoint;!r.has("Authorization")&&s&&r.set("Authorization",`Bearer ${this.accessToken}`);let a=await this.fetcher(t,{...n,method:n.method??"DELETE",headers:r,credentials:n.credentials??this.lifecycleCredentials});if(a.status===401&&s&&this.refreshCredentialsCallback&&(await this.refreshCredentials(n.signal??void 0),r.set("Authorization",`Bearer ${this.accessToken}`),a=await this.fetcher(t,{...n,method:n.method??"DELETE",headers:r,credentials:n.credentials??this.lifecycleCredentials})),!a.ok)throw await $n(a,"Could not end realtime session");(e.disconnect??!0)&&await this.disconnect()}async replay(e=this.apiBase,t=this.cursor.lastServerSeq){if(this.replayPromise)return this.replayPromise;let n=hn(e);return this.replayPromise=this.fetchReplay(n,t).finally(()=>{this.replayPromise=null}),this.replayPromise}setState(e){if(this.stateValue!==e){if(this.stateValue=e,(e==="connecting"||e==="resuming")&&(this.startDiagnosticLoopMonitor(),globalThis.document?.addEventListener?.("visibilitychange",this.onDiagnosticVisibilityChange)),e==="disconnected"||e==="failed"){globalThis.clearInterval(this.diagnosticLoopTimer),this.diagnosticLoopTimer=void 0,this.diagnosticLoopDelayMs=void 0,globalThis.document?.removeEventListener?.("visibilitychange",this.onDiagnosticVisibilityChange),this.flushDiagnostics("session_finished");let t=new Error(`Session ${e}`);this.contextGeneration+=1,this.replacementContext.clear(t),this.rejectPendingCommands(t)}this.notifyListeners(this.stateListeners,e)}}bindRoomEvents(){this.room.on(C.ParticipantDisconnected,e=>{e.isAgent&&!this.disconnectMode&&queueMicrotask(()=>{if(!(this.disconnectMode||this.terminalSessionError)){if(this.sessionEnded){this.agentDisconnected=!0,this.finishPendingEnd();return}this.room.state===V.Reconnecting||this.activeRecovery!==null||this.autoRejoinPromise!==null||this.manualRejoinController!==null||[...this.room.remoteParticipants.values()].some(t=>t.isAgent)||(this.agentDisconnected=!0,this.startAutoRejoin(new Error("Agent disconnected from the room"),{trigger:"agent_disconnected"}))}})}),this.room.on(C.SignalReconnecting,()=>this.handleLiveKitReconnecting()),this.room.on(C.Reconnecting,()=>this.handleLiveKitReconnecting()),this.room.on(C.Reconnected,()=>{this.handleLiveKitReconnected()}),this.room.on(C.Disconnected,e=>{this.handleLiveKitDisconnected(e)}),this.room.on(C.ConnectionStateChanged,e=>{if(!(this.sessionEnded||this.terminalSessionError)&&e===V.Connected){let t=this.activeRecovery!==null||this.stateValue==="resuming";this.setState(this.agentReady?"connected":t?"resuming":"connected_not_ready")}}),this.room.on(C.ConnectionQualityChanged,(e,t)=>{t.isLocal&&this.notifyListeners(this.connectionQualityListeners,e)}),this.room.on(C.TrackSubscribed,e=>{if(e.kind!==_.Kind.Audio)return;let t=e.attach();t.dataset.voxevolvRemoteAudio="true",t.style.display="none",document.body.appendChild(t);try{t.play().catch(s=>{this.notifyListeners(this.audioPlaybackBlockedListeners,{error:s,element:t,track:e.mediaStreamTrack})})}catch(r){this.notifyListeners(this.audioPlaybackBlockedListeners,{error:r,element:t,track:e.mediaStreamTrack})}let n=new MediaStream([e.mediaStreamTrack]);this.remoteAudioStreams.set(e,n),this.outputStream.addTrack(e.mediaStreamTrack),this.notifyRemoteAudioListeners(this.remoteAudioTrackListeners,e.mediaStreamTrack,n),this.remoteAudioTrackResolve?.()}),this.room.on(C.TrackUnsubscribed,e=>{if(e.kind!==_.Kind.Audio)return;let t=this.remoteAudioStreams.get(e)??new MediaStream([e.mediaStreamTrack]);this.notifyRemoteAudioListeners(this.remoteAudioTrackUnsubscribedListeners,e.mediaStreamTrack,t),this.remoteAudioStreams.delete(e),this.outputMediaStream?.removeTrack(e.mediaStreamTrack),e.detach().forEach(n=>n.remove())}),this.room.on(C.DataReceived,(e,t,n,r)=>{if(r!=="voxevolv.events"||n!==Ze.RELIABLE)return;let s;try{s=JSON.parse(new TextDecoder().decode(e))}catch{return}if(!za(s))return;let a=this.cursor.accept(s);a.gap&&(this.notifyListeners(this.gapListeners,a.gap),this.replay(this.apiBase,a.gap.after_server_seq)),a.deliver&&(this.observeReadiness(s),this.observeCommandResult(s),this.observeConvenienceEvents(s),this.notifyListeners(this.listeners,s))})}handleLiveKitReconnecting(){if(!(this.sessionEnded||this.disconnectMode==="intentional")){if(this.agentReady=!1,this.autoRejoinPromise!==null||this.activeRecovery?.strategy==="rejoin"||this.disconnectMode==="rejoin"){this.setState("resuming");return}this.contextGeneration+=1,this.livekitResumeController?.abort(new Error("LiveKit connection interrupted again")),this.livekitResumeController=null,this.replacementContext.pause(),this.reconnectStartedAt??=Date.now(),this.rejectPendingCommands(new Error("Connection interrupted before command completion"),!0),this.activeRecovery===null&&(this.beginRecovery("livekit",1,{trigger:"livekit_reconnecting"}),this.recordDiagnostic({operation:"connection_recovery",stage:"room_connect",status:"started"})),this.setState("reconnecting")}}async handleLiveKitReconnected(){if(this.sessionEnded||this.disconnectMode||this.autoRejoinPromise||this.livekitResumeController)return;let e=this.contextGeneration,t=new AbortController;this.livekitResumeController=t;let n=Date.now();this.reconnectStartedAt!==null&&(this.pendingReconnect={started_at:new Date(this.reconnectStartedAt).toISOString(),recovered_at:new Date(n).toISOString(),duration_ms:Math.max(n-this.reconnectStartedAt,0)},this.reconnectStartedAt=null),this.hasConnectedValue&&this.activeRecovery===null&&this.beginRecovery("livekit",1,{trigger:"livekit_reconnecting"}),this.recordDiagnostic({operation:"connection_recovery",stage:"room_connect",status:"succeeded",duration_ms:Math.max(Date.now()-(this.recoveryStartedAt??Date.now()),0)}),this.connectionId=`conn_${Math.random().toString(36).slice(2)}_${Date.now().toString(36)}`,this.clientSeq=0,this.setState(this.hasConnectedValue?"resuming":"connected_not_ready");try{await this.measureRecoveryStage("hello",()=>this.sendRecoveryHello(t.signal));let r=Date.now()+this.recoveryReadiness.readyTimeoutMs;if(await this.measureRecoveryStage("agent_ready",()=>this.waitForAgentReady(Math.max(r-Date.now(),0),t.signal)),this.recoveryReadiness.waitForRemoteAudio&&await this.measureRecoveryStage("remote_audio",()=>this.waitForRemoteAudioTrack(r,t.signal)),this.sessionEnded||e!==this.contextGeneration||(this.resumeContextDelivery(!0),this.sessionEnded||e!==this.contextGeneration))return;this.setState("connected"),this.completeRecovery()}catch(r){if(t.signal.aborted||this.sessionEnded||e!==this.contextGeneration)return;let s=un(r);this.shouldAutoRejoin()?this.startAutoRejoin(s,{trigger:"livekit_resume_failed"}):(this.failRecovery(s),this.setState("failed"))}finally{this.livekitResumeController===t&&(this.livekitResumeController=null)}}handleLiveKitDisconnected(e){if(this.agentReady=!1,this.disconnectMode!=="rejoin"&&(this.pendingReconnect=null),this.outputMediaStream?.getTracks().forEach(t=>{this.outputMediaStream?.removeTrack(t)}),this.rejectPendingCommands(new Error("Session disconnected before command completion")),this.disconnectMode!=="rejoin"&&this.disconnectMode!=="connect_failure"){if(this.disconnectMode==="intentional"){this.activeRecovery=null,this.deliverPendingEndEvent(),this.setState("disconnected");return}if(!this.terminalSessionError){if(this.shouldAutoRejoin(e)){this.startAutoRejoin(new Error(`LiveKit disconnected (${Il(e)})`),{trigger:"livekit_disconnected"});return}this.activeRecovery!==null&&this.failRecovery(new Error(`LiveKit disconnected (${Il(e)})`)),this.deliverPendingEndEvent(),this.setState("disconnected")}}}deliverPendingEndEvent(){let e=this.pendingEndEvent;e&&(this.pendingEndEvent=null,this.notifyEnded({...e,type:"session.ended"}))}finishPendingEnd(){this.deliverPendingEndEvent(),this.disconnect().catch(()=>{})}async recoverSessionEnd(e,t){let n=new AbortController,r=()=>n.abort(t?.reason);t?.addEventListener("abort",r,{once:!0}),t?.aborted&&r();let s=globalThis.setTimeout(()=>n.abort(),5e3);try{await this.fetchReplay(e,0,{signal:n.signal,terminalOnly:!0})}catch{}finally{globalThis.clearTimeout(s),t?.removeEventListener("abort",r)}return!this.sessionEnded||this.terminalSessionError?!1:(this.finishPendingEnd(),!0)}notifyEnded(e){this.endNotificationDelivered||(this.endNotificationDelivered=!0,this.notifyListeners(this.endedListeners,e))}beginRecovery(e,t,n){this.recoveryStartedAt??=Date.now(),this.activeRecovery={strategy:e,attempt:t,details:n},this.recordDiagnostic({operation:"connection_recovery",status:"started",reason:n.trigger,message_id:n.messageId,context_key:n.contextKey,timeout_ms:n.timeoutMs,retry_count:t-1}),this.flushDiagnostics("recovery_started"),this.notifyListeners(this.recoveryListeners,{status:"started",strategy:e,attempt:t,...n})}completeRecovery(){let e=this.activeRecovery;e&&(this.recordDiagnostic({operation:"connection_recovery",stage:"complete",status:"succeeded",duration_ms:Math.max(Date.now()-(this.recoveryStartedAt??Date.now()),0),retry_count:e.attempt-1,reason:e.details.trigger}),this.flushDiagnostics("recovery_completed"),this.recoveryStartedAt=null,this.activeRecovery=null,this.notifyListeners(this.recoveryListeners,{status:"succeeded",strategy:e.strategy,attempt:e.attempt,...e.details}))}failRecovery(e){let t=this.activeRecovery;t&&(this.recordDiagnostic({operation:"connection_recovery",stage:"complete",status:"failed",duration_ms:Math.max(Date.now()-(this.recoveryStartedAt??Date.now()),0),retry_count:t.attempt-1,reason:t.details.trigger}),this.flushDiagnostics("recovery_failed"),this.activeRecovery=null,this.notifyListeners(this.recoveryListeners,{status:"failed",strategy:t.strategy,attempt:t.attempt,...t.details,error:e}))}shouldAutoRejoin(e){return this.autoRejoinOptions!==null&&this.hasConnectedValue&&!this.sessionEnded&&!["disconnected","failed"].includes(this.stateValue)&&!tf(e)}startAutoRejoin(e,t){if(this.autoRejoinPromise||!this.shouldAutoRejoin())return;this.recoveryStartedAt??=Date.now(),this.agentReady=!1,this.contextGeneration+=1,this.livekitResumeController?.abort(e),this.replacementContext.pause(),this.rejectPendingCommands(e),this.reconnectStartedAt??=Date.now();let n=new AbortController;this.autoRejoinController=n;let r=globalThis.setTimeout(()=>{if(n.signal.aborted)return;let a=new Error("Session recovery timed out");n.abort(a),this.contextGeneration+=1,this.rejectPendingCommands(a),this.replacementContext.clear(a),this.failRecovery(a),this.setState("failed")},this.autoRejoinOptions.timeoutMs),s=this.runAutoRejoin(e,n.signal,t).finally(()=>{globalThis.clearTimeout(r),this.autoRejoinController===n&&(this.autoRejoinController=null,this.autoRejoinPromise=null)});this.autoRejoinPromise=s}async runAutoRejoin(e,t,n){let r=this.autoRejoinOptions;if(!r)return;let s=e;this.activeRecovery?.strategy==="livekit"&&this.failRecovery(e),this.setState("resuming");for(let a=1;a<=r.maxAttempts;a+=1)try{if(await sf(t),a>1){let o=r.baseDelayMs*2**(a-2),d=Math.min(o,r.maxDelayMs);await Al(d+Math.random()*Math.min(d,500),t)}if(X(t),this.beginRecovery("rejoin",a,n),await this.performRejoin(this.apiBase,{signal:t}),this.sessionEnded)return;X(t),this.reconnectStartedAt=null,this.completeRecovery();return}catch(o){if(t.aborted)return;if(s=un(o),nf(o))break}this.failRecovery(s),this.replacementContext.clear(s),this.setState("failed")}cancelRecovery(){this.livekitResumeController?.abort(),this.livekitResumeController=null,this.recoveryStartedAt=null,this.autoRejoinController?.abort(),this.autoRejoinController=null,this.manualRejoinController?.abort(),this.manualRejoinController=null,this.autoRejoinPromise=null,this.activeRecovery=null}notifyListeners(e,t){for(let n of e)try{n(t)}catch(r){console.error("VoxEvolv event listener failed",r)}}notifyRemoteAudioListeners(e,t,n){for(let r of e)try{r(t,n)}catch(s){console.error("VoxEvolv remote audio listener failed",s)}}validateAudioOptions(e,t){if(e&&t)throw new rt("microphone and audioTrack cannot both be enabled");if(t){if(t.kind!=="audio")throw new rt("audioTrack must be an audio MediaStreamTrack");if(t.readyState==="ended")throw new rt("audioTrack has already ended")}}async measureRecoveryStage(e,t,n=!0){if(!n)return t();let r=Date.now();this.recordDiagnostic({operation:"connection_recovery",stage:e,status:"started"});try{let s=await t();return this.recordDiagnostic({operation:"connection_recovery",stage:e,status:"succeeded",duration_ms:Date.now()-r}),s}catch(s){throw this.recordDiagnostic({operation:"connection_recovery",stage:e,status:"failed",duration_ms:Date.now()-r,reason:s instanceof Qn?"data_channel_stalled":"stage_failed"}),this.flushDiagnostics("recovery_stage_failed"),s}}async fetchRoomToken(e,t,n=!0){let r=new AbortController,s=()=>r.abort(t?.reason);t?.addEventListener("abort",s,{once:!0});let a=globalThis.setTimeout(()=>r.abort(),1e4),o=Date.now();n&&this.recordDiagnostic({operation:"connection_recovery",stage:"token_request",status:"started"});try{X(t);let d=await Te(this.fetcher(`${e}/sessions/${this.id}/room-tokens`,{method:"POST",headers:{Authorization:`Bearer ${this.accessToken}`},credentials:this.lifecycleCredentials,signal:r.signal}),r.signal);return n&&(this.recordDiagnostic({operation:"connection_recovery",stage:"token_request",status:d.ok?"succeeded":"failed",http_status:d.status,duration_ms:Date.now()-o}),d.ok||this.flushDiagnostics("recovery_stage_failed")),d}catch(d){throw n&&(this.recordDiagnostic({operation:"connection_recovery",stage:"token_request",status:"failed",duration_ms:Date.now()-o,reason:t?.aborted?"cancelled":r.signal.aborted?"request_timeout":"request_failed"}),this.flushDiagnostics("recovery_stage_failed")),d}finally{globalThis.clearTimeout(a),t?.removeEventListener("abort",s)}}async refreshCredentials(e){if(!this.refreshCredentialsCallback)return;X(e);let t=this.contextGeneration,n=++this.credentialRefreshGeneration,r=await Te(this.refreshCredentialsCallback(),e);if(X(e),t!==this.contextGeneration||n!==this.credentialRefreshGeneration)throw new Error("Credential refresh was superseded");if(Ol(r),r.id!==this.id)throw new Error("Refreshed credentials belong to a different session");this.accessToken=r.access_token,this.credentials=r.connection}async finishSessionFailure(e){this.sessionEnded=!0,this.contextGeneration+=1,this.rejectPendingCommands(e),this.replacementContext.clear(e),this.failRecovery(e),this.cancelRecovery(),this.disconnectMode="connect_failure";try{await this.room.disconnect()}finally{this.disconnectMode=null,this.setState("failed")}}observeConvenienceEvents(e){if(e.type==="session.error"){if(this.sessionEnded)return;let r=new lr(e);r.retryable&&this.startupAttemptController?this.startupAttemptController.abort(r):(this.terminalSessionError=r,this.abortStartupConnect(r),this.startupConnectController||this.finishSessionFailure(r).catch(()=>{}))}if(e.type==="session.ending"||e.type==="session.ended"){if(this.terminalSessionError)return;this.abortStartupConnect(new Error("Session ended during startup")),this.contextGeneration+=1,this.rejectPendingCommands(new Error("Session ended")),this.failRecovery(new Error("Session ended during recovery"))}if(e.type==="session.ending"&&(this.sessionEnded=!0,this.cancelRecovery(),this.replacementContext.clear(new Error("Session ended")),this.pendingEndEvent??=e,(!this.hasConnectedValue||this.agentDisconnected||this.room.state===V.Disconnected)&&this.finishPendingEnd()),e.type==="session.ended"){let r=this.pendingEndEvent;this.pendingEndEvent=null,this.sessionEnded=!0,this.replacementContext.clear(new Error("Session ended")),this.cancelRecovery(),this.notifyEnded(r?{...r,type:"session.ended"}:e),this.disconnect().catch(()=>{})}e.type.endsWith(".error")&&this.notifyListeners(this.errorListeners,e);let t=this.transcriptStore.accept(e);t&&this.notifyListeners(this.transcriptListeners,t);let n=df(e);n&&this.notifyListeners(n.role==="user"?this.userTranscriptListeners:this.agentTranscriptListeners,n)}abortStartupConnect(e){this.startupConnectController?.signal.aborted||this.startupConnectController?.abort(e)}async publishApplicationAudioTrack(e){let t=e.clone(),n=null;try{n=new Et(t,void 0,!0),this.localApplicationAudioTrack=n,this.microphoneEnabled||await n.mute(),await this.room.localParticipant.publishTrack(n,{source:_.Source.Microphone,name:"voxevolv-application-audio"})}catch(r){throw this.localApplicationAudioTrack===n&&(this.localApplicationAudioTrack=null),t.stop(),r}}async sendHello(){let e=this.pendingReconnect,t=Wn(this.connectionId,++this.clientSeq,"client.hello",{last_server_seq:this.cursor.lastServerSeq,sdk:`@voxevolv/client@${El}`,tool_handlers:[...this.toolHandlers.keys()].sort(),...e?{reconnect:e}:{}});this.lastHelloMessageId=t.message_id,await this.sendTrackedCommand(t,Jp),this.pendingReconnect===e&&(this.pendingReconnect=null)}async sendRecoveryHello(e){X(e);let t=this.reliableDataChannelBufferedBytes(),n=Date.now(),r,s=new Promise((a,o)=>{let d=()=>{let c=this.reliableDataChannelBufferedBytes();if(c===void 0||c===0||t===void 0||t===0||c<t)n=Date.now();else if(Date.now()-n>=$p){o(new Qn);return}t=c,r=globalThis.setTimeout(d,Rl)};r=globalThis.setTimeout(d,Rl)});try{await Te(Promise.race([this.sendHello(),s]),e)}catch(a){throw a instanceof Qn&&this.rejectPendingCommands(a),a}finally{r!==void 0&&globalThis.clearTimeout(r)}}async sendTrackedCommand(e,t,n){let r=cf(e),s=of(e.payload),a=Date.now();this.recordDiagnostic({operation:"command_send",status:"started",message_id:e.message_id,connection_id:e.connection_id,client_seq:e.client_seq,context_key:r,payload_bytes:s,retry_count:0,timeout_ms:t,event_type:Jn(e.type)});let o=()=>{},d=new Promise(l=>{o=l}),c=new Promise((l,u)=>{let h=globalThis.setTimeout(()=>{let m=this.pendingCommands.get(e.message_id);m&&globalThis.clearTimeout(m.retry),m?.markSettled(),this.pendingCommands.delete(e.message_id);let g=`Command ${e.type} timed out after ${t}ms`,f=e.type==="context.update"?new it(g,{retryAfter:m?.transferSettled}):new Error(g);this.recordDiagnostic({operation:"command_send",status:"timed_out",reason:e.type==="context.update"?"context_command_timeout":"command_timeout",message_id:e.message_id,connection_id:e.connection_id,client_seq:e.client_seq,context_key:r,payload_bytes:s,duration_ms:Date.now()-a,retry_count:m?.retryCount??0,timeout_ms:t,event_type:Jn(e.type)}),this.flushDiagnostics("command_timeout"),u(f)},t);this.pendingCommands.set(e.message_id,{commandType:e.type,message:e,startedAt:a,contextKey:r,payloadBytes:s,retryCount:0,publishQueued:!1,resolve:l,reject:u,timeout:h,settled:d,markSettled:o,retryTransfer:n,transferRetrying:!1,transferRetryRequested:!1}),this.scheduleCommandRetry(e)});return this.publishCommandAttempt(e,!1).catch(()=>{}),c}scheduleCommandRetry(e){let t=this.pendingCommands.get(e.message_id);if(!t)return;let n=e.type==="context.update"?Ja(t.retryCount+1):500;t.retry=globalThis.setTimeout(()=>{this.retryCommand(e).finally(()=>this.scheduleCommandRetry(e))},n)}async retryCommand(e){let t=this.pendingCommands.get(e.message_id);if(t&&!(e.type==="context.update"&&(this.sessionEnded||["reconnecting","resuming","disconnected","failed"].includes(this.stateValue))))try{if(t.transferRetryRequested&&t.retryTransfer){t.transferRetryRequested=!1,t.transferRetrying=!0;let n=t.retryTransfer();t.transferSettled=n.then(()=>{},()=>{}),t.contextKey&&this.replacementContext.blockUntilTransferSettles(t.contextKey,t.transferSettled),await Promise.race([n,t.settled])}await this.publishCommandAttempt(e,!0)}catch{}finally{t.transferRetrying=!1}}publishCommandAttempt(e,t){let n=this.pendingCommands.get(e.message_id);if(!n||n.publishQueued)return Promise.resolve();n.publishQueued=!0;let r=this.commandPublishTail.then(()=>this.publishCommandAttemptNow(e,t)).finally(()=>{let s=this.pendingCommands.get(e.message_id);s===n&&(s.publishQueued=!1)});return this.commandPublishTail=r.catch(()=>{}),r}async publishCommandAttemptNow(e,t){let n=this.pendingCommands.get(e.message_id);if(!n)return;t&&(n.retryCount+=1,this.recordDiagnostic({operation:"command_send",status:"retrying",message_id:e.message_id,connection_id:e.connection_id,client_seq:e.client_seq,context_key:n.contextKey,payload_bytes:n.payloadBytes,retry_count:n.retryCount,event_type:Jn(e.type)}));let r=Date.now();try{let a=!1,o=this.publishCommand(e).then(()=>{a=!0});if(await Promise.race([o,n.settled]),!a)return}catch(a){throw this.recordDiagnostic({operation:"command_send",status:"failed",reason:"command_publish_failed",message_id:e.message_id,connection_id:e.connection_id,client_seq:e.client_seq,context_key:n.contextKey,payload_bytes:n.payloadBytes,duration_ms:Date.now()-r,retry_count:n.retryCount,event_type:Jn(e.type)}),this.flushDiagnostics("command_failed"),a}let s=Date.now()-r;this.recordDiagnostic({operation:"command_send",status:"succeeded",message_id:e.message_id,connection_id:e.connection_id,client_seq:e.client_seq,context_key:n.contextKey,payload_bytes:n.payloadBytes,duration_ms:s,retry_count:n.retryCount,event_type:Jn(e.type)}),s>2e3&&this.flushDiagnostics("slow_operation")}async publishCommand(e){await this.room.localParticipant.publishData(new TextEncoder().encode(JSON.stringify(e)),{reliable:!0,topic:"voxevolv.commands"})}startDiagnosticLoopMonitor(){this.diagnosticLoopTimer===void 0&&(this.diagnosticLoopExpectedAt=performance.now()+1e3,this.diagnosticLoopTimer=globalThis.setInterval(()=>{let e=performance.now();this.diagnosticLoopDelayMs=Math.max(0,e-this.diagnosticLoopExpectedAt),this.diagnosticLoopExpectedAt=e+1e3},1e3),this.diagnosticLoopTimer.unref?.())}recordDiagnostic(e){let t={...e,connection_state:this.stateValue,buffered_bytes:this.reliableDataChannelBufferedBytes()};e.operation==="tool_rpc"&&(t.page_visibility=globalThis.document?.visibilityState,t.active_context_transfers=this.activeContextTransfers,t.active_context_bytes=this.activeContextBytes,this.diagnosticLoopTimer!==void 0&&(t.event_loop_delay_ms=Math.max(this.diagnosticLoopDelayMs??0,performance.now()-this.diagnosticLoopExpectedAt))),this.diagnostics.record(t)}reliableDataChannelBufferedBytes(){try{let e=this.room.engine.dataChannelForKind(0)?.bufferedAmount;return typeof e=="number"?e:void 0}catch{return}}flushDiagnostics(e){this.diagnostics.flush(e,t=>this.postDiagnostics(t))}async postDiagnostics(e){let t=new AbortController,n,r=new Promise((s,a)=>{n=globalThis.setTimeout(()=>{t.abort(),a(new Error(`Diagnostic report timed out after ${this.diagnosticReportTimeoutMs}ms`))},this.diagnosticReportTimeoutMs)});try{let s=async()=>{let a=await this.fetcher(`${this.apiBase}/sessions/${this.id}/diagnostics`,{method:"POST",headers:{Authorization:`Bearer ${this.accessToken}`,"Content-Type":"application/json"},credentials:this.lifecycleCredentials,body:JSON.stringify(e),signal:t.signal,keepalive:!0}),o=await a.json().catch(()=>null);if(!a.ok){let d=a.status===408||a.status===429||a.status>=500,c=Number(a.headers.get("Retry-After"))*1e3,l=typeof o?.retry_after_ms=="number"?o.retry_after_ms:c;throw new Gt(`Diagnostic report failed (${a.status})`,d,Number.isFinite(l)?Math.max(l,0):0)}if(o?.report_id!==e.report_id)throw new Gt("Diagnostic report was not acknowledged")};await Promise.race([s(),r])}finally{n!==void 0&&globalThis.clearTimeout(n)}}waitForRemoteAudioTrack(e,t){return(this.outputMediaStream?.getAudioTracks().length??0)>0?Promise.resolve():(X(t),new Promise((n,r)=>{let s=()=>{globalThis.clearTimeout(a),t?.removeEventListener("abort",o),this.remoteAudioTrackResolve=null},a=globalThis.setTimeout(()=>{s(),r(new Error("Agent audio track did not arrive within the ready timeout; pass waitForRemoteAudio: false to resolve connect() on signaling readiness alone"))},Math.max(e-Date.now(),0)),o=()=>{s(),r(We(t))};this.remoteAudioTrackResolve=()=>{s(),n()},t?.addEventListener("abort",o,{once:!0})}))}waitForAgentReady(e,t){return this.agentReady?Promise.resolve():(X(t),new Promise((n,r)=>{let s=()=>{globalThis.clearTimeout(a),t?.removeEventListener("abort",o),this.readyResolve=null},a=globalThis.setTimeout(()=>{s(),r(new Error(`Agent did not become ready within ${e}ms`))},e),o=()=>{s(),r(We(t))};this.readyResolve=()=>{s(),n()},t?.addEventListener("abort",o,{once:!0})}))}observeReadiness(e){if(e.stream_id==="durable-replay")return;let t=e.payload,n=e.type==="agent.snapshot"&&t.status==="ready"&&t.connection_id===this.connectionId&&t.ack_message_id===this.lastHelloMessageId;if(e.type!=="agent.ready"&&!n)return;if(this.agentStreamId&&this.agentStreamId!==e.stream_id&&!this.activeRecovery){this.startAutoRejoin(new Error("Agent worker was replaced"),{trigger:"worker_replaced"});return}this.agentStreamId=e.stream_id,this.agentDisconnected=!1;let r=this.agentReady;this.agentReady=!0,this.readyResolve?.(),r||this.notifyListeners(this.readyListeners,e)}observeCommandResult(e){if(e.type!=="command.ack"&&e.type!=="command.error"&&e.type!=="context.updated"&&e.type!=="context.rejected")return;let t=this.pendingCommands.get(String(e.payload.message_id??""));if(t){if(e.type==="command.ack"&&Va(e.payload)){this.recordCommandResult(t,e.type,"acknowledged"),globalThis.clearTimeout(t.timeout),globalThis.clearTimeout(t.retry),t.markSettled(),this.pendingCommands.delete(e.payload.message_id),t.resolve(e.payload);return}if(e.type==="context.updated"&&Ga(e.payload)){this.recordCommandResult(t,e.type,"acknowledged"),globalThis.clearTimeout(t.timeout),globalThis.clearTimeout(t.retry),t.markSettled(),this.pendingCommands.delete(e.payload.message_id),t.resolve(e.payload);return}if(e.type==="command.error"&&Ha(e.payload)||e.type==="context.rejected"&&Wa(e.payload)){if(this.recordCommandResult(t,e.type,"rejected",e.payload.code),this.flushDiagnostics("command_rejected"),e.type==="context.rejected"&&e.payload.retryable){e.payload.code==="stream_unavailable"&&t.retryTransfer&&!t.transferRetrying&&(t.transferRetryRequested=!0);return}globalThis.clearTimeout(t.timeout),globalThis.clearTimeout(t.retry),t.markSettled(),this.pendingCommands.delete(e.payload.message_id),t.reject(new Gn(e.payload))}}}rejectPendingCommands(e,t=!1){for(let[n,r]of this.pendingCommands)t&&r.commandType==="context.update"||(this.recordCommandResult(r,r.commandType==="context.update"?"context.rejected":"command.error","failed","pending_command_cancelled"),globalThis.clearTimeout(r.timeout),globalThis.clearTimeout(r.retry),r.markSettled(),r.reject(r.commandType==="context.update"?new it(e.message,{cause:e,retryAfter:r.transferSettled}):e),this.pendingCommands.delete(n))}recordCommandResult(e,t,n,r){let s=Date.now()-e.startedAt;this.recordDiagnostic({operation:"command_result",status:n,reason:r,message_id:e.message.message_id,connection_id:e.message.connection_id,client_seq:e.message.client_seq,context_key:e.contextKey,payload_bytes:e.payloadBytes,duration_ms:s,retry_count:e.retryCount,event_type:t}),s>2e3&&this.flushDiagnostics("slow_operation")}async fetchReplay(e,t,n={}){let{signal:r,terminalOnly:s=!1}=n,a=t;for(;;){X(r);let o=`${e}/sessions/${this.id}/events?after_seq=${a}&limit=200`+(s?"&terminal_only=true":""),d=await Te(this.fetcher(o,{headers:{Authorization:`Bearer ${this.accessToken}`},credentials:this.lifecycleCredentials,signal:r}),r);if(d.status===401&&this.refreshCredentialsCallback&&(await this.refreshCredentials(r),d=await Te(this.fetcher(o,{headers:{Authorization:`Bearer ${this.accessToken}`},credentials:this.lifecycleCredentials,signal:r}),r)),!d.ok)throw await Te($n(d,"Could not replay session events"),r);let c=await Te(d.json(),r);X(r);for(let l of c.items){a=Math.max(a,l.server_seq);let u={protocol_version:1,event_id:l.event_id,stream_id:"durable-replay",stream_seq:Math.max(this.cursor.lastStreamSeq,1),server_seq:l.server_seq,ts:l.created_at,type:l.type,payload:l.payload};this.cursor.acceptReplay(u)&&(this.observeReadiness(u),this.observeConvenienceEvents(u),this.notifyListeners(this.listeners,u))}if(a=Math.max(a,c.next_after_seq),!c.has_more)return}}};function Zp(i){if(!i)return null;let e=i===!0?{}:i,t={maxAttempts:e.maxAttempts??Number.MAX_SAFE_INTEGER,baseDelayMs:e.baseDelayMs??750,maxDelayMs:e.maxDelayMs??5e3,timeoutMs:e.timeoutMs??18e4};if(!Number.isFinite(t.timeoutMs)||t.timeoutMs<=0)throw new TypeError("autoRejoin.timeoutMs must be a positive finite number");if(!Number.isInteger(t.maxAttempts)||t.maxAttempts<1)throw new TypeError("autoRejoin.maxAttempts must be a positive integer");if(!Number.isFinite(t.baseDelayMs)||t.baseDelayMs<0)throw new TypeError("autoRejoin.baseDelayMs must be a non-negative finite number");if(!Number.isFinite(t.maxDelayMs)||t.maxDelayMs<0)throw new TypeError("autoRejoin.maxDelayMs must be a non-negative finite number");return t}function ef(i){if(i===!1)return null;let e=typeof i=="object"?i:{},t=(e.attempts??Yp).map(r=>({readyTimeoutMs:r.readyTimeoutMs,delayBeforeMs:r.delayBeforeMs??0})),n=e.timeoutMs??Xp;if(t.length===0)throw new TypeError("startupRetry.attempts must contain at least one attempt");for(let r of t){if(!Number.isFinite(r.readyTimeoutMs)||r.readyTimeoutMs<=0)throw new TypeError("startupRetry.attempts readyTimeoutMs must be a positive finite number");if(!Number.isFinite(r.delayBeforeMs)||r.delayBeforeMs<0)throw new TypeError("startupRetry.attempts delayBeforeMs must be a non-negative finite number")}if(!Number.isFinite(n)||n<=0)throw new TypeError("startupRetry.timeoutMs must be a positive finite number");return{attempts:t,timeoutMs:n}}function tf(i){return i!==void 0&&[oe.CLIENT_INITIATED,oe.DUPLICATE_IDENTITY,oe.PARTICIPANT_REMOVED,oe.ROOM_DELETED,oe.ROOM_CLOSED,oe.USER_UNAVAILABLE,oe.USER_REJECTED].includes(i)}function Il(i){return i===void 0?"unknown":oe[i]??String(i)}function nf(i){return i instanceof Yn&&[401,403,409].includes(i.status)}function rf(i){return i instanceof lr?!i.retryable:i instanceof Yn?i.status>=400&&i.status<500&&![408,425,429].includes(i.status):i instanceof rt?!0:i instanceof Error&&["ConstraintNotSatisfiedError","DevicesNotFoundError","InvalidStateError","NotAllowedError","NotFoundError","NotReadableError","NotSupportedError","OverconstrainedError","SecurityError","TrackStartError"].includes(i.name)}function un(i){return i instanceof Error?i:new Error(String(i))}function We(i){return i.reason??new DOMException("Aborted","AbortError")}function Ml(i){let e=new AbortController;return i.aborted?e.abort(We(i)):i.addEventListener("abort",()=>e.abort(We(i)),{once:!0}),e}function X(i){if(i?.aborted)throw We(i)}function Te(i,e){return e?new Promise((t,n)=>{let r=!1,s=d=>{r||(r=!0,e.removeEventListener("abort",o),t(d))},a=d=>{r||(r=!0,e.removeEventListener("abort",o),n(d))},o=()=>a(We(e));e.aborted?o():e.addEventListener("abort",o,{once:!0}),i.then(s,a)}):i}function Al(i,e){return X(e),i<=0?Promise.resolve():new Promise((t,n)=>{let r=globalThis.setTimeout(()=>{e.removeEventListener("abort",s),t()},i),s=()=>{globalThis.clearTimeout(r),n(We(e))};e.addEventListener("abort",s,{once:!0})})}function sf(i){return X(i),typeof navigator>"u"||navigator.onLine!==!1||typeof globalThis.addEventListener!="function"?Promise.resolve():new Promise((e,t)=>{let n=()=>{globalThis.removeEventListener("online",r),i.removeEventListener("abort",s)},r=()=>{n(),e()},s=()=>{n(),t(We(i))};globalThis.addEventListener("online",r,{once:!0}),i.addEventListener("abort",s,{once:!0})})}async function xl(i){if(!globalThis.crypto?.subtle)throw new Error("Web Crypto SHA-256 is unavailable");let e=await globalThis.crypto.subtle.digest("SHA-256",Uint8Array.from(i).buffer);return[...new Uint8Array(e)].map(t=>t.toString(16).padStart(2,"0")).join("")}function Dl(){return globalThis.crypto?.randomUUID?globalThis.crypto.randomUUID():`ctx_${Date.now().toString(36)}_${Math.random().toString(36).slice(2)}`}function af(i){return"image"in i?i.image.size:new TextEncoder().encode(i.text).byteLength}function of(i){let e=i.image;if(e&&typeof e=="object"&&"bytes"in e){let n=e.bytes;if(typeof n=="number")return n}let t=i.text_stream;if(t&&typeof t=="object"&&"bytes"in t){let n=t.bytes;if(typeof n=="number")return n}if(typeof i.text=="string")return new TextEncoder().encode(i.text).byteLength;try{return new TextEncoder().encode(JSON.stringify(i)).byteLength}catch{return}}function cf(i){if(i.type!=="context.update")return;let e=i.payload.key;return typeof e=="string"?e:void 0}function Jn(i){return i==="client.hello"||i==="context.update"?i:void 0}function Ol(i){if(!i||typeof i!="object")throw new rt("Session credentials must be an object");if(!i.id||!i.access_token||!i.access_token_expires_at)throw new rt("Session credentials are incomplete");if(!i.connection||!i.connection.url||!i.connection.token||!i.connection.room_name)throw new rt("Session connection credentials are incomplete")}function hn(i){let e=i.trim().replace(/\/+$/,"");if(!e)throw new rt("apiBase must be a non-root relative path or an absolute URL");return e}function df(i){let e=/^transcript\.(user|agent)\.(interim|final)$/.exec(i.type);if(!e)return null;let t=i.payload.text;return typeof t!="string"?null:{role:e[1],text:t,final:e[2]==="final",event:i}}async function $n(i,e){let t={};try{t=await i.json()}catch{}return new Yn(typeof t.message=="string"?t.message:`${e} (${i.status})`,{status:i.status,code:typeof t.error=="string"?t.error:null,requestId:typeof t.request_id=="string"?t.request_id:null,details:Array.isArray(t.details)?t.details:[]})}export{Gn as CommandError,Kn as EventCursor,Pl as RealtimeSession,Yn as RealtimeSessionHttpError,El as SDK_VERSION,zn as TranscriptStore,Wn as createClientMessage,Up as decodeAgentSnapshotPayload,Fp as decodeClientHelloPayload,Np as decodeClientMessage,hl as decodeCommandAckPayload,pl as decodeCommandErrorPayload,kl as decodeContextRejectedPayload,gl as decodeContextUpdatePayload,yl as decodeContextUpdatedPayload,ll as decodeRealtimeEvent,Va as isCommandAckPayload,Ha as isCommandErrorPayload,Wa as isContextRejectedPayload,Ka as isContextUpdatePayload,Ga as isContextUpdatedPayload,za as isRealtimeEvent};
39
+ `},Dr}var Ho;function Jm(){if(Ho)return xe;Ho=1;var i=Wm(),e=zm(),t=Ua();return xe.grammar=t,xe.write=e,xe.parse=i.parse,xe.parseParams=i.parseParams,xe.parseFmtpConfig=i.parseFmtpConfig,xe.parsePayloads=i.parsePayloads,xe.parseRemoteCandidates=i.parseRemoteCandidates,xe.parseImageAttributes=i.parseImageAttributes,xe.parseSimulcastStreamList=i.parseSimulcastStreamList,xe}var Ie=Jm(),$m=.7,Qm=20,kt={NegotiationStarted:"negotiationStarted",NegotiationComplete:"negotiationComplete",OfferAnswered:"offerAnswered",RTPVideoPayloadTypes:"rtpVideoPayloadTypes"},Ai=class extends Ee.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 n;super(),this.log=F,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=Da(r=>p(this,void 0,void 0,function*(){this.emit(kt.NegotiationStarted);try{yield this.createAndSendOffer()}catch(s){if(r)r(s);else throw s}}),Qm),this.close=()=>{this._pc&&(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.log=_e((n=t.loggerName)!==null&&n!==void 0?n:ue.PCTransport),this.loggerOptions=t,this.config=e,this._pc=this.createPC(),this.offerLock=new de}createPC(){let e=new RTCPeerConnection(this.config);return e.onicecandidate=t=>{var n;t.candidate&&((n=this.onIceCandidate)===null||n===void 0||n.call(this,t.candidate))},e.onicecandidateerror=t=>{var n;(n=this.onIceCandidateError)===null||n===void 0||n.call(this,t)},e.oniceconnectionstatechange=()=>{var t;(t=this.onIceConnectionStateChange)===null||t===void 0||t.call(this,e.iceConnectionState)},e.onsignalingstatechange=()=>{var t;(t=this.onSignalingStatechange)===null||t===void 0||t.call(this,e.signalingState)},e.onconnectionstatechange=()=>{var t;(t=this.onConnectionStateChange)===null||t===void 0||t.call(this,e.connectionState)},e.ondatachannel=t=>{var n;(n=this.onDataChannel)===null||n===void 0||n.call(this,t)},e.ontrack=t=>{var n;(n=this.onTrack)===null||n===void 0||n.call(this,t)},e}get 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 p(this,void 0,void 0,function*(){if(this.pc.remoteDescription&&!this.restartingIce)return this.pc.addIceCandidate(e);this.pendingCandidates.push(e)})}setRemoteDescription(e,t){return p(this,void 0,void 0,function*(){var n,r;if(e.type==="answer"&&this.latestOfferId>0&&t>0&&t!==this.latestOfferId)return this.log.warn("ignoring answer for old offer",Object.assign(Object.assign({},this.logContext),{offerId:t,latestOfferId:this.latestOfferId})),!1;let s;if(e.type==="offer"){let a=Ym(e),o=a.stereoMids,d=a.nackMids;this.remoteStereoMids=o,this.remoteNackMids=d}else if(e.type==="answer"){if(this.pendingInitialOffer&&this._pc){let o=this.pendingInitialOffer;this.pendingInitialOffer=void 0;let d=Ie.parse((n=o.sdp)!==null&&n!==void 0?n:"");d.media.forEach(c=>{ei(c)}),this.log.debug("setting pending initial offer before processing answer",this.logContext),yield this.setMungedSDP(o,Ie.write(d))}let a=Ie.parse((r=e.sdp)!==null&&r!==void 0?r:"");a.media.forEach(o=>{let d=Fa(o.mid);o.type==="audio"&&this.trackBitrates.some(c=>{if(!c.transceiver||d!=c.transceiver.mid)return!1;let l=0;if(o.rtp.some(h=>h.codec.toUpperCase()===c.codec.toUpperCase()?(l=h.payload,!0):!1),l===0)return!0;let u=!1;for(let h of o.fmtp)if(h.payload===l){h.config=h.config.split(";").filter(m=>!m.includes("maxaveragebitrate")).join(";"),c.maxbr>0&&(h.config+=";maxaveragebitrate=".concat(c.maxbr*1e3)),u=!0;break}return u||c.maxbr>0&&o.fmtp.push({payload:l,config:"maxaveragebitrate=".concat(c.maxbr*1e3)}),!0})}),s=Ie.write(a)}return yield this.setMungedSDP(e,s,!0),this.pendingCandidates.forEach(a=>{this.pc.addIceCandidate(a)}),this.pendingCandidates=[],this.restartingIce=!1,e.type==="answer"&&(this.latestAcknowledgedOfferId=t,this.emit(kt.OfferAnswered,t)),this.renegotiate?(this.renegotiate=!1,yield this.createAndSendOffer()):e.type==="answer"&&(this.emit(kt.NegotiationComplete),e.sdp&&Ie.parse(e.sdp).media.forEach(o=>{o.type==="video"&&this.emit(kt.RTPVideoPayloadTypes,o.rtp)})),!0})}createInitialOffer(){return p(this,void 0,void 0,function*(){var e;let t=yield this.offerLock.lock();try{if(this.pc.signalingState!=="stable"){this.log.warn("signaling state is not stable, cannot create initial offer",this.logContext);return}let n=this.latestOfferId+1;this.latestOfferId=n;let r=yield this.pc.createOffer();this.pendingInitialOffer={sdp:r.sdp,type:r.type};let s=Ie.parse((e=r.sdp)!==null&&e!==void 0?e:"");return s.media.forEach(a=>{ei(a)}),r.sdp=Ie.write(s),{offer:r,offerId:n}}finally{t()}})}createAndSendOffer(e){return p(this,void 0,void 0,function*(){var t;let n=yield this.offerLock.lock();try{if(this.onOffer===void 0)return;if(e?.iceRestart&&(this.log.debug("restarting ICE",this.logContext),this.restartingIce=!0),this._pc&&(this._pc.signalingState==="have-local-offer"||this.pendingInitialOffer)){let o=this._pc.remoteDescription;if(e?.iceRestart&&o)yield this._pc.setRemoteDescription(o);else{this.renegotiate=!0,this.log.debug("requesting renegotiation",Object.assign({},this.logContext));return}}else if(!this._pc||this._pc.signalingState==="closed"){this.log.warn("could not createOffer with closed peer connection",this.logContext);return}this.log.debug("starting to negotiate",this.logContext);let r=this.latestOfferId+1;this.latestOfferId=r;let s=yield this.pc.createOffer(e);this.log.debug("original offer",Object.assign({sdp:s.sdp},this.logContext));let a=Ie.parse((t=s.sdp)!==null&&t!==void 0?t:"");if(a.media.forEach(o=>{ei(o),o.type==="audio"?Go(o,["all"],[]):o.type==="video"&&this.trackBitrates.some(d=>{if(!o.msid||!d.cid||!o.msid.includes(d.cid))return!1;let c=0;if(o.rtp.some(u=>u.codec.toUpperCase()===d.codec.toUpperCase()?(c=u.payload,!0):!1),c===0||(je(d.codec)&&!Bt()&&this.ensureVideoDDExtensionForSVC(o,a),!je(d.codec)))return!0;let l=Math.round(d.maxbr*$m);for(let u of o.fmtp)if(u.payload===c){u.config.includes("x-google-start-bitrate")||(u.config+=";x-google-start-bitrate=".concat(l));break}return!0})}),this.latestOfferId>r){this.log.warn("latestOfferId mismatch",Object.assign(Object.assign({},this.logContext),{latestOfferId:this.latestOfferId,offerId:r}));return}yield this.setMungedSDP(s,Ie.write(a)),this.onOffer(s,this.latestOfferId)}finally{n()}})}createAndSetAnswer(){return p(this,void 0,void 0,function*(){var e;let t=yield this.pc.createAnswer(),n=Ie.parse((e=t.sdp)!==null&&e!==void 0?e:"");return n.media.forEach(r=>{ei(r),r.type==="audio"&&Go(r,this.remoteStereoMids,this.remoteNackMids)}),yield this.setMungedSDP(t,Ie.write(n)),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 W("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 W("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 p(this,void 0,void 0,function*(){var e;if(!this._pc)return;let t="",n=new Map,r=new Map;if((yield this._pc.getStats()).forEach(o=>{switch(o.type){case"transport":t=o.selectedCandidatePairId;break;case"candidate-pair":t===""&&o.selected&&(t=o.id),n.set(o.id,o);break;case"remote-candidate":r.set(o.id,"".concat(o.address,":").concat(o.port));break}}),t==="")return;let a=(e=n.get(t))===null||e===void 0?void 0:e.remoteCandidateId;if(a!==void 0)return r.get(a)})}setMungedSDP(e,t,n){return p(this,void 0,void 0,function*(){var r,s;let a=e.sdp;if(t){e.sdp=t;try{this.log.debug("setting munged ".concat(n?"remote":"local"," description"),this.logContext),n?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"),Object.assign(Object.assign({},this.logContext),{error:o,mungedSdp:t,originalSdp:a})),e.sdp=a}}try{n?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);let c={error:d,sdp:e.sdp};throw t&&t!==a&&(c.mungedSdp=t),!n&&this.pc.remoteDescription&&(c.remoteSdp=this.pc.remoteDescription),this.log.error("unable to set ".concat(e.type),Object.assign(Object.assign({},this.logContext),{fields:c})),new lt(d)}})}ensureVideoDDExtensionForSVC(e,t){var n,r;if(!((n=e.ext)===null||n===void 0?void 0:n.some(a=>a.uri===Po))){if(this.ddExtID===0){let a=0;t.media.forEach(o=>{var d;(d=o.ext)===null||d===void 0||d.forEach(c=>{c.value>a&&(a=c.value)})}),this.ddExtID=a+1}(r=e.ext)===null||r===void 0||r.push({value:this.ddExtID,uri:Po})}}};function Go(i,e,t){let n=Fa(i.mid),r=0;i.rtp.some(s=>s.codec==="opus"?(r=s.payload,!0):!1),r>0&&(i.rtcpFb||(i.rtcpFb=[]),t.includes(n)&&!i.rtcpFb.some(s=>s.payload===r&&s.type==="nack")&&i.rtcpFb.push({payload:r,type:"nack"}),(e.includes(n)||e.length===1&&e[0]==="all")&&i.fmtp.some(s=>s.payload===r?(s.config.includes("stereo=1")||(s.config+=";stereo=1"),!0):!1))}function Ym(i){var e;let t=[],n=[],r=Ie.parse((e=i.sdp)!==null&&e!==void 0?e:""),s=0;return r.media.forEach(a=>{var o;let d=Fa(a.mid);a.type==="audio"&&(a.rtp.some(c=>c.codec==="opus"?(s=c.payload,!0):!1),!((o=a.rtcpFb)===null||o===void 0)&&o.some(c=>c.payload===s&&c.type==="nack")&&n.push(d),a.fmtp.some(c=>c.payload===s?(c.config.includes("sprop-stereo=1")&&t.push(d),!0):!1))}),{stereoMids:t,nackMids:n}}function ei(i){if(i.connection){let e=i.connection.ip.indexOf(":")>=0;(i.connection.version===4&&e||i.connection.version===6&&!e)&&(i.connection.ip="0.0.0.0",i.connection.version=4)}}function Fa(i){return typeof i=="number"?i.toFixed(0):i}var _s="vp8",Xm={audioPreset:ss.music,dtx:!0,red:!0,forceStereo:!1,simulcast:!0,screenShareEncoding:Ia.h1080fps15.encoding,stopMicTrackOnMute:!1,videoCodec:_s,backupCodec:!0,preConnectBuffer:!1},Xd={deviceId:{ideal:"default"},autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0,voiceIsolation:!0},Zd={deviceId:{ideal:"default"},resolution:On.h720.resolution},Zm={adaptiveStream:!1,dynacast:!1,stopLocalTrackOnUnpublish:!0,reconnectPolicy:new $r,disconnectOnPageLeave:!0,webAudioMix:!1,singlePeerConnection:!0},Ba={autoSubscribe:!0,maxRetries:1,peerConnectionTimeout:15e3,websocketTimeout:15e3},te;(function(i){i[i.NEW=0]="NEW",i[i.CONNECTING=1]="CONNECTING",i[i.CONNECTED=2]="CONNECTED",i[i.FAILED=3]="FAILED",i[i.CLOSING=4]="CLOSING",i[i.CLOSED=5]="CLOSED"})(te||(te={}));var xi=class{get needsPublisher(){return this.isPublisherConnectionRequired}get needsSubscriber(){return this.isSubscriberConnectionRequired}get currentState(){return this.state}get mode(){return this._mode}constructor(e,t,n){var r;this.peerConnectionTimeout=Ba.peerConnectionTimeout,this.log=F,this.updateState=()=>{var s,a;let o=this.state,d=this.requiredTransports.map(c=>c.getConnectionState());d.every(c=>c==="connected")?this.state=te.CONNECTED:d.some(c=>c==="failed")?this.state=te.FAILED:d.some(c=>c==="connecting")?this.state=te.CONNECTING:d.every(c=>c==="closed")?this.state=te.CLOSED:d.some(c=>c==="closed")?this.state=te.CLOSING:d.every(c=>c==="new")&&(this.state=te.NEW),o!==this.state&&(this.log.debug("pc state change: from ".concat(te[o]," to ").concat(te[this.state]),this.logContext),(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.log=_e((r=t.loggerName)!==null&&r!==void 0?r:ue.PCManager),this.loggerOptions=t,this.isPublisherConnectionRequired=e!=="subscriber-primary",this.isSubscriberConnectionRequired=e==="subscriber-primary",this.publisher=new Ai(n,t),this._mode=e,e!=="publisher-only"&&(this.subscriber=new Ai(n,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,Fe.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,Fe.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=te.NEW,this.connectionLock=new de,this.remoteOfferLock=new de}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 p(this,void 0,void 0,function*(){var e;if(this.publisher&&this.publisher.getSignallingState()!=="closed"){let t=this.publisher;for(let n of t.getSenders())try{t.canRemoveTrack()&&t.removeTrack(n)}catch(r){this.log.warn("could not removeTrack",Object.assign(Object.assign({},this.logContext),{error:r}))}}yield Promise.all([this.publisher.close(),(e=this.subscriber)===null||e===void 0?void 0:e.close()]),this.updateState()})}triggerIceRestart(){return p(this,void 0,void 0,function*(){this.subscriber&&(this.subscriber.restartingIce=!0),this.needsPublisher&&(yield this.createAndSendPublisherOffer({iceRestart:!0}))})}addIceCandidate(e,t){return p(this,void 0,void 0,function*(){var n;t===Fe.PUBLISHER?yield this.publisher.addIceCandidate(e):yield(n=this.subscriber)===null||n===void 0?void 0:n.addIceCandidate(e)})}createSubscriberAnswerFromOffer(e,t){return p(this,void 0,void 0,function*(){var n,r,s;this.log.debug("received server offer",Object.assign(Object.assign({},this.logContext),{RTCSdpType:e.type,sdp:e.sdp,signalingState:(n=this.subscriber)===null||n===void 0?void 0:n.getSignallingState().toString()}));let 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 n;this.publisher.setConfiguration(e),(n=this.subscriber)===null||n===void 0||n.setConfiguration(e),t&&this.triggerIceRestart()}ensurePCTransportConnection(e,t){return p(this,void 0,void 0,function*(){var n;let r=yield this.connectionLock.lock();try{this.isPublisherConnectionRequired&&this.publisher.getConnectionState()!=="connected"&&this.publisher.getConnectionState()!=="connecting"&&(this.log.debug("negotiation required, start negotiating",this.logContext),this.publisher.negotiate()),yield Promise.all((n=this.requiredTransports)===null||n===void 0?void 0:n.map(s=>this.ensureTransportConnected(s,e,t)))}finally{r()}})}negotiate(e){return p(this,void 0,void 0,function*(){return new pe((t,n)=>{let 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,a=()=>{s||(s=!0,clearTimeout(c),this.publisher.off(kt.OfferAnswered,o),e.signal.removeEventListener("abort",d))},o=l=>{l>r&&(a(),t())},d=()=>{a(),n(new lt("negotiation aborted"))},c=setTimeout(()=>{a(),n(new lt("negotiation timed out"))},this.peerConnectionTimeout);e.signal.addEventListener("abort",d),this.publisher.on(kt.OfferAnswered,o),this.publisher.negotiate(l=>{a(),l instanceof Error?n(l):n(new Error(String(l)))})})})}addPublisherTransceiver(e,t){return this.publisher.addTransceiver(e,t)}addPublisherTransceiverOfKind(e,t){return this.publisher.addTransceiverOfKind(e,t)}getMidForReceiver(e){let n=(this.subscriber?this.subscriber.getTransceivers():this.publisher.getTransceivers()).find(r=>r.receiver===e);return n?.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===Fe.PUBLISHER?this.publisher.getConnectedAddress():e===Fe.SUBSCRIBER?this.publisher.getConnectedAddress():this.requiredTransports[0].getConnectedAddress()}get requiredTransports(){let e=[];return this.isPublisherConnectionRequired&&e.push(this.publisher),this.isSubscriberConnectionRequired&&this.subscriber&&e.push(this.subscriber),e}ensureTransportConnected(e,t){return p(this,arguments,void 0,function(n,r){var s=this;let a=arguments.length>2&&arguments[2]!==void 0?arguments[2]:this.peerConnectionTimeout;return(function*(){if(n.getConnectionState()!=="connected")return new Promise((d,c)=>p(s,void 0,void 0,function*(){let l=()=>{this.log.warn("abort transport connection",this.logContext),se.clearTimeout(u),c(N.cancelled("room connection has been cancelled"))};r?.signal.aborted&&l(),r?.signal.addEventListener("abort",l);let u=se.setTimeout(()=>{r?.signal.removeEventListener("abort",l),c(N.internal("could not establish pc connection"))},a);for(;this.state!==te.CONNECTED;)if(yield ve(50),r?.signal.aborted){c(N.cancelled("room connection has been cancelled"));return}se.clearTimeout(u),r?.signal.removeEventListener("abort",l),d()}))})()})}},qa=typeof MediaRecorder<"u",ws=class{constructor(){throw new Error("MediaRecorder is not available in this environment")}},ep=qa?MediaRecorder:ws,Es=class extends ep{constructor(e,t){if(!qa)throw new Error("MediaRecorder is not available in this environment");super(new MediaStream([e.mediaStreamTrack]),t);let n,r,s=()=>r===void 0,a=()=>{this.removeEventListener("dataavailable",n),this.removeEventListener("stop",a),this.removeEventListener("error",o),r?.close(),r=void 0},o=d=>{r?.error(d),this.removeEventListener("dataavailable",n),this.removeEventListener("stop",a),this.removeEventListener("error",o),r=void 0};this.byteStream=new ReadableStream({start:d=>{r=d,n=c=>p(this,void 0,void 0,function*(){let l;if(c.data.arrayBuffer){let 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",n)},cancel:()=>{a()}}),this.addEventListener("stop",a),this.addEventListener("error",o)}};function tp(){return qa}var np=1e3,ip=1e4,Di=class extends _{get sender(){return this._sender}set sender(e){this._sender=e}get constraints(){return this._constraints}get hasPreConnectBuffer(){return!!this.localTrackRecorder}constructor(e,t,n){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=Da(()=>p(this,void 0,void 0,function*(){yield this.pauseUpstream()}),5e3),this.handleTrackUnmuteEvent=()=>p(this,void 0,void 0,function*(){this.debouncedTrackMuteHandler.cancel("unmute"),yield this.resumeUpstream()}),this.handleEnded=()=>{this.isInBackground&&(this.reacquireTrack=!0),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent),this.emit(P.Ended,this)},this.reacquireTrack=!1,this.providedByUser=r,this.muteLock=new de,this.pauseUpstreamLock=new de,this.trackChangeLock=new de,this.trackChangeLock.lock().then(a=>p(this,void 0,void 0,function*(){try{yield this.setMediaStreamTrack(e,!0)}finally{a()}})),this._constraints=e.getConstraints(),n&&(this._constraints=n)}get id(){return this._mediaStreamTrack.id}get dimensions(){if(this.kind!==_.Kind.Video)return;let e=this._mediaStreamTrack.getSettings(),t=e.width,n=e.height;if(t&&n)return{width:t,height:n}}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,n){return p(this,void 0,void 0,function*(){var r;if(e===this._mediaStreamTrack&&!t)return;this._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&&(zt(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=n?!0:!this.isMuted,yield this.resumeUpstream(),this.attachedElements.forEach(a=>{zt(s??e,a)}))})}waitForDimensions(){return p(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:np;return(function*(){var n;if(e.kind===_.Kind.Audio)throw new Error("cannot get dimensions for audio tracks");((n=ke())===null||n===void 0?void 0:n.os)==="iOS"&&(yield ve(10));let r=Date.now();for(;Date.now()-r<t;){let s=e.dimensions;if(s)return s;yield ve(50)}throw new qe("unable to get track dimensions after timeout")})()})}setDeviceId(e){return p(this,void 0,void 0,function*(){return this._constraints.deviceId===e&&this._mediaStreamTrack.getSettings().deviceId===Lt(e)?!0:(this._constraints.deviceId=e,this.isMuted?(this.pendingDeviceChange=!0,!0):(yield this.restartTrack(),Lt(e)===this._mediaStreamTrack.getSettings().deviceId))})}getDeviceId(){return p(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===_.Source.ScreenShare)return;let n=e._mediaStreamTrack.getSettings(),r=n.deviceId,s=n.groupId,a=e.kind===_.Kind.Audio?"audioinput":"videoinput";return t?Pe.getInstance().normalizeDeviceId(a,r,s):r})()})}mute(){return p(this,void 0,void 0,function*(){return this.setTrackMuted(!0),this})}unmute(){return p(this,void 0,void 0,function*(){return this.setTrackMuted(!1),this})}replaceTrack(e,t){return p(this,void 0,void 0,function*(){let n=yield this.trackChangeLock.lock();try{if(!this.sender)throw new qe("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{n()}return yield this.onSenderTrackSwapped(),this})}onSenderTrackSwapped(){return p(this,void 0,void 0,function*(){})}restart(e,t){return p(this,void 0,void 0,function*(){this.manuallyStopped=!1;let n=yield this.trackChangeLock.lock();try{e||(e=this._constraints);let r=e,s=r.deviceId,a=r.facingMode,o=Ph(e,["deviceId","facingMode"]);this.log.debug("restarting track with constraints",Object.assign(Object.assign({},this.logContext),{constraints:e}));let d={audio:!1,video:!1};this.kind===_.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();let l=(yield navigator.mediaDevices.getUserMedia(d)).getTracks()[0];return this.kind===_.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(P.Restarted,this),this.manuallyStopped&&(this.log.warn("track was stopped during a restart, stopping restarted track",this.logContext),this.stop()),this}finally{n()}})}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?P.Muted:P.Unmuted,this))}get needsReAcquisition(){return this._mediaStreamTrack.readyState!=="live"||this._mediaStreamTrack.muted||!this._mediaStreamTrack.enabled||this.reacquireTrack}handleAppVisibilityChanged(){let e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return p(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),Wd()&&(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 p(this,void 0,void 0,function*(){var e;let 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(P.UpstreamPaused,this);let n=ke();if(n?.name==="Safari"&&tt(n.version,"12.0")<0)throw new Dn("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 p(this,void 0,void 0,function*(){var e;let 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(P.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 p(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 p(this,arguments,void 0,function(t){var n=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return(function*(){var s;let a=yield n.trackChangeLock.lock();try{n.log.debug("setting up processor",n.logContext);let o=document.createElement(n.kind),d={kind:n.kind,track:n._mediaStreamTrack,element:o,audioContext:n.audioContext,localTrack:n};if(yield t.init(d),n.log.debug("processor initialized",n.logContext),n.processor&&(yield n.internalStopProcessor()),n.kind==="unknown")throw TypeError("cannot set processor on track of unknown kind");if(zt(n._mediaStreamTrack,o),o.muted=!0,o.play().catch(c=>{c instanceof DOMException&&c.name==="AbortError"?(n.log.warn("failed to play processor element, retrying",Object.assign(Object.assign({},n.logContext),{error:c})),setTimeout(()=>{o.play().catch(l=>{n.log.error("failed to play processor element",Object.assign(Object.assign({},n.logContext),{err:l}))})},100)):n.log.error("failed to play processor element",Object.assign(Object.assign({},n.logContext),{error:c}))}),n.processor=t,n.processorElement=o,n.processor.processedTrack){for(let c of n.attachedElements)c!==n.processorElement&&r&&(Yt(n._mediaStreamTrack,c),zt(n.processor.processedTrack,c));yield(s=n.sender)===null||s===void 0?void 0:s.replaceTrack(n.processor.processedTrack)}n.emit(P.TrackProcessorUpdate,n.processor)}finally{a()}yield n.onSenderTrackSwapped()})()})}getProcessor(){return this.processor}stopProcessor(){return p(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return(function*(){let n=yield e.trackChangeLock.lock();try{yield e.internalStopProcessor(t)}finally{n()}yield e.onSenderTrackSwapped()})()})}internalStopProcessor(){return p(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return(function*(){var n,r;e.processor&&(e.log.debug("stopping processor",e.logContext),(n=e.processor.processedTrack)===null||n===void 0||n.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(P.TrackProcessorUpdate))})()})}startPreConnectBuffer(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:100;if(!tp()){this.log.warn("MediaRecorder is not available, cannot start preconnect 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 Es(this,{mimeType:t})}this.localTrackRecorder.start(e),this.autoStopPreConnectBuffer=setTimeout(()=>{this.log.warn("preconnect buffer timed out, stopping recording automatically",this.logContext),this.stopPreConnectBuffer()},ip)}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}},Et=class extends Di{get enhancedNoiseCancellation(){return this.isKrispNoiseFilterEnabled}constructor(e,t){let n=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,_.Kind.Audio,t,n,s),this.stopOnMute=!1,this.isKrispNoiseFilterEnabled=!1,this.monitorSender=()=>p(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=ar(a,this.prevStats)),this.prevStats=a}),this.handleKrispNoiseFilterEnable=()=>{this.isKrispNoiseFilterEnabled=!0,this.log.debug("Krisp noise filter enabled",this.logContext),this.emit(P.AudioTrackFeatureUpdate,this,le.TF_ENHANCED_NOISE_CANCELLATION,!0)},this.handleKrispNoiseFilterDisable=()=>{this.isKrispNoiseFilterEnabled=!1,this.log.debug("Krisp noise filter disabled",this.logContext),this.emit(P.AudioTrackFeatureUpdate,this,le.TF_ENHANCED_NOISE_CANCELLATION,!1)},this.audioContext=r,this.checkForSilence()}mute(){let e=Object.create(null,{mute:{get:()=>super.mute}});return p(this,void 0,void 0,function*(){let t=yield this.muteLock.lock();try{return this.isMuted?(this.log.debug("Track already muted",this.logContext),this):(this.source===_.Source.Microphone&&this.stopOnMute&&!this.isUserProvided&&(this.log.debug("stopping mic track",this.logContext),this._mediaStreamTrack.stop()),yield e.mute.call(this),this)}finally{t()}})}unmute(){let e=Object.create(null,{unmute:{get:()=>super.unmute}});return p(this,void 0,void 0,function*(){let t=yield this.muteLock.lock();try{return this.isMuted?(this.source===_.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 p(this,void 0,void 0,function*(){let t;if(e){let n=Ma({audio:e});typeof n.audio!="boolean"&&(t=n.audio)}yield this.restart(t)})}restart(e,t){let n=Object.create(null,{restart:{get:()=>super.restart}});return p(this,void 0,void 0,function*(){let r=yield n.restart.call(this,e,t);return this.checkForSilence(),r})}startMonitor(){Ce()&&(this.monitorInterval||(this.monitorInterval=setInterval(()=>{this.monitorSender()},Oa)))}setProcessor(e){return p(this,void 0,void 0,function*(){var t;let n=yield this.trackChangeLock.lock();try{if(!He()&&!this.audioContext)throw Error("Audio context needs to be set on LocalAudioTrack in order to enable processors");this.processor&&(yield this.internalStopProcessor());let 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(P.TrackProcessorUpdate,this.processor)}finally{n()}})}setAudioContext(e){this.audioContext=e}getSenderStats(){return p(this,void 0,void 0,function*(){var e;if(!(!((e=this.sender)===null||e===void 0)&&e.getStats))return;let t=yield this.sender.getStats(),n;return t.forEach(r=>{r.type==="outbound-rtp"&&(n={type:"audio",streamId:r.id,packetsSent:r.packetsSent,packetsLost:r.packetsLost,bytesSent:r.bytesSent,timestamp:r.timestamp,roundTripTime:r.roundTripTime,jitter:r.jitter})}),n})}checkForSilence(){return p(this,void 0,void 0,function*(){let e=yield Hd(this);return e&&(this.isMuted||this.log.debug("silence detected on local audio track",this.logContext),this.emit(P.AudioSilenceDetected)),e})}};function rp(i,e,t){switch(i.kind){case"audio":return new Et(i,e,!1,void 0,t);case"video":return new an(i,e,!1,t);default:throw new qe("unsupported track type: ".concat(i.kind))}}var sp=Object.values(On),ap=Object.values(as),op=Object.values(Ia),cp=[On.h180,On.h360],dp=[as.h180,as.h360],lp=i=>[{scaleResolutionDownBy:2,fps:i.encoding.maxFramerate}].map(t=>{var n,r;return new K(Math.floor(i.width/t.scaleResolutionDownBy),Math.floor(i.height/t.scaleResolutionDownBy),Math.max(15e4,Math.floor(i.encoding.maxBitrate/(Math.pow(t.scaleResolutionDownBy,2)*(((n=i.encoding.maxFramerate)!==null&&n!==void 0?n:30)/((r=t.fps)!==null&&r!==void 0?r:30))))),t.fps,i.encoding.priority)}),Rs=["q","h","f"];function Oi(i,e,t,n){var r,s;let a=n?.videoEncoding;i&&(a=n?.screenShareEncoding);let o=n?.simulcast,d=n?.scalabilityMode,c=n?.videoCodec;if(!a&&!o&&!d||!e||!t)return[{}];a||(a=up(i,e,t,c),F.debug("using video encoding",a));let l=a.maxFramerate,u=new K(e,t,a.maxBitrate,a.maxFramerate,a.priority);if(d&&je(c)){let k=new Li(d),T=[];if(k.spatial>3)throw new Error("unsupported scalabilityMode: ".concat(d));let S=ke();if(Ln()||He()||S?.name==="Chrome"&&tt(S?.version,"113")<0){let L=k.suffix=="h"?2:3,y=um(S);for(let b=0;b<k.spatial;b+=1)T.push({rid:Rs[2-b],maxBitrate:a.maxBitrate/Math.pow(L,b),maxFramerate:u.encoding.maxFramerate,scaleResolutionDownBy:y?Math.pow(2,b):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),F.debug("using svc encoding",{encodings:T}),T}if(!o)return[a];let h;i?h=(r=Wo(n?.screenShareSimulcastLayers))!==null&&r!==void 0?r:Ko(i,u):h=(s=Wo(n?.videoSimulcastLayers))!==null&&s!==void 0?s:Ko(i,u);let m;if(h.length>0){let k=h[0];if(h.length>1){var f=h,g=O(f,2);m=g[1]}let T=Math.max(e,t);if(T>=960&&m)return Or(e,t,[k,m,u],l);if(T>=480)return Or(e,t,[k,u],l)}return Or(e,t,[u])}function el(i,e,t){var n,r,s,a;if(!t.backupCodec||t.backupCodec===!0||t.backupCodec.codec===t.videoCodec)return;e!==t.backupCodec.codec&&F.warn("requested a different codec than specified as backup",{serverRequested:e,backup:t.backupCodec.codec}),t.videoCodec=e,t.videoEncoding=t.backupCodec.encoding;let o=i.mediaStreamTrack.getSettings(),d=(n=o.width)!==null&&n!==void 0?n:(r=i.dimensions)===null||r===void 0?void 0:r.width,c=(s=o.height)!==null&&s!==void 0?s:(a=i.dimensions)===null||a===void 0?void 0:a.height;return i.source===_.Source.ScreenShare&&t.simulcast&&(t.simulcast=!1),Oi(i.source===_.Source.ScreenShare,d,c,t)}function up(i,e,t,n){let r=hp(i,e,t),s=r[0].encoding,a=Math.max(e,t);for(let o=0;o<r.length;o+=1){let d=r[o];if(s=d.encoding,d.width>=a)break}if(n)switch(n){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 hp(i,e,t){if(i)return op;let n=e>t?e/t:t/e;return Math.abs(n-16/9)<Math.abs(n-4/3)?sp:ap}function Ko(i,e){if(i)return lp(e);let t=e.width,n=e.height,r=t>n?t/n:n/t;return Math.abs(r-16/9)<Math.abs(r-4/3)?cp:dp}function Or(i,e,t,n){let r=[];if(t.forEach((s,a)=>{if(a>=Rs.length)return;let o=Math.min(i,e),c={rid:Rs[a],scaleResolutionDownBy:Math.max(1,o/Math.min(s.width,s.height)),maxBitrate:s.encoding.maxBitrate},l=n&&s.encoding.maxFramerate?Math.min(n,s.encoding.maxFramerate):s.encoding.maxFramerate;l&&(c.maxFramerate=l);let u=ke(),h=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)}),He()&&Jd()==="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,F.info("Simulcast on iOS React-Native requires all encodings to share the same framerate.")),F.info('Setting framerate of encoding "'.concat((d=o.rid)!==null&&d!==void 0?d:"",'" to ').concat(s)),o.maxFramerate=s)})}return r}function Wo(i){if(i)return i.slice().sort((e,t)=>{let n=e.encoding,r=t.encoding;return n.maxBitrate>r.maxBitrate?1:n.maxBitrate<r.maxBitrate?-1:n.maxBitrate===r.maxBitrate&&n.maxFramerate&&r.maxFramerate?n.maxFramerate>r.maxFramerate?1:-1:0})}var Li=class{constructor(e){let 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(i){return i.source===_.Source.ScreenShare||i.constraints.height&&Lt(i.constraints.height)>=1080?"maintain-resolution":"balanced"}var pp=5e3,an=class extends Di{get sender(){return this._sender}set sender(e){this._sender=e,this.degradationPreference&&this.setDegradationPreference(this.degradationPreference)}constructor(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,r=arguments.length>3?arguments[3]:void 0;super(e,_.Kind.Video,t,n,r),this.simulcastCodecs=new Map,this.degradationPreference="balanced",this.isCpuConstrained=!1,this.optimizeForPerformance=!1,this.monitorSender=()=>p(this,void 0,void 0,function*(){if(!this.sender){this._currentBitrate=0;return}let s;try{s=yield this.getSenderStats()}catch(d){this.log.error("could not get video sender stats",Object.assign(Object.assign({},this.logContext),{error:d}));return}let 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(P.CpuConstrained)),this.prevStats){let d=0;a.forEach((c,l)=>{var u;let h=(u=this.prevStats)===null||u===void 0?void 0:u.get(l);d+=ar(c,h)}),this._currentBitrate=d}this.prevStats=a}),this.senderLock=new de}get isSimulcast(){return!!(this.sender&&this.sender.getParameters().encodings.length>1)}startMonitor(e){var t;if(this.signalClient=e,!Ce())return;let n=(t=this.sender)===null||t===void 0?void 0:t.getParameters();n&&(this.encodings=n.encodings),!this.monitorInterval&&(this.monitorInterval=setInterval(()=>{this.monitorSender()},Oa))}stop(){this._mediaStreamTrack.getConstraints(),this.simulcastCodecs.forEach(e=>{e.mediaStreamTrack.stop()}),super.stop()}pauseUpstream(){let e=Object.create(null,{pauseUpstream:{get:()=>super.pauseUpstream}});return p(this,void 0,void 0,function*(){var t,n,r,s,a;yield e.pauseUpstream.call(this);try{for(var o=!0,d=Be(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){n={error:l}}finally{try{!o&&!t&&(r=d.return)&&(yield r.call(d))}finally{if(n)throw n.error}}})}resumeUpstream(){let e=Object.create(null,{resumeUpstream:{get:()=>super.resumeUpstream}});return p(this,void 0,void 0,function*(){var t,n,r,s,a;yield e.resumeUpstream.call(this);try{for(var o=!0,d=Be(this.simulcastCodecs.values()),c;c=yield d.next(),t=c.done,!t;o=!0){s=c.value,o=!1;let l=s;yield(a=l.sender)===null||a===void 0?void 0:a.replaceTrack(l.mediaStreamTrack)}}catch(l){n={error:l}}finally{try{!o&&!t&&(r=d.return)&&(yield r.call(d))}finally{if(n)throw n.error}}})}mute(){let e=Object.create(null,{mute:{get:()=>super.mute}});return p(this,void 0,void 0,function*(){let t=yield this.muteLock.lock();try{return this.isMuted?(this.log.debug("Track already muted",this.logContext),this):(this.source===_.Source.Camera&&!this.isUserProvided&&(this.log.debug("stopping camera track",this.logContext),this._mediaStreamTrack.stop()),yield e.mute.call(this),this)}finally{t()}})}unmute(){let e=Object.create(null,{unmute:{get:()=>super.unmute}});return p(this,void 0,void 0,function*(){let t=yield this.muteLock.lock();try{return this.isMuted?(this.source===_.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(let t of this.simulcastCodecs.values())t.mediaStreamTrack.enabled=!e}getSenderStats(){return p(this,void 0,void 0,function*(){var e;if(!(!((e=this.sender)===null||e===void 0)&&e.getStats))return[];let t=[],n=yield this.sender.getStats();return n.forEach(r=>{var s;if(r.type==="outbound-rtp"){let 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=n.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){let t=[];for(let n=Re.LOW;n<=Re.HIGH;n+=1)t.push(new wa({quality:n,enabled:n<=e}));this.log.debug("setting publishing quality. max quality ".concat(e),this.logContext),this.setPublishingLayers(je(this.codec),t)}restartTrack(e){return p(this,void 0,void 0,function*(){var t,n,r,s,a;let o;if(e){let u=Ma({video:e});typeof u.video!="boolean"&&(o=u.video)}yield this.restart(o),this.isCpuConstrained=!1;try{for(var d=!0,c=Be(this.simulcastCodecs.values()),l;l=yield c.next(),t=l.done,!t;d=!0){s=l.value,d=!1;let 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){n={error:u}}finally{try{!d&&!t&&(r=c.return)&&(yield r.call(c))}finally{if(n)throw n.error}}yield this.onSenderTrackSwapped()})}onSenderTrackSwapped(){return p(this,void 0,void 0,function*(){yield this.refreshSenderEncodings()})}refreshSenderEncodings(){return p(this,void 0,void 0,function*(){var e;if(!this.sender||!this.publishOptions||this.optimizeForPerformance)return;let 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;let s=this.source===_.Source.ScreenShare,a=Oi(s,r.width,r.height,Object.assign({},this.publishOptions));yield this.applyEncodingsToSender(this.sender,a),this.encodings=a,this.lastEncodedDimensions=r;for(let o of this.simulcastCodecs){var n=O(o,2);let d=n[0],c=n[1];if(!c.sender||((e=c.sender.transport)===null||e===void 0?void 0:e.state)==="closed"||!jd(d))continue;let l=Object.assign({},this.publishOptions),u=el(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 p(this,void 0,void 0,function*(){let n=e.getParameters();!n.encodings||n.encodings.length!==t.length||(n.encodings.forEach((r,s)=>{if(r.active===!1)return;let 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:n.encodings})),yield e.setParameters(n))})}setProcessor(e){let t=Object.create(null,{setProcessor:{get:()=>super.setProcessor}});return p(this,arguments,void 0,function(n){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,n,s),!((l=r.processor)===null||l===void 0)&&l.processedTrack)try{for(var h=!0,m=Be(r.simulcastCodecs.values()),f;f=yield m.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=m.return)&&(yield d.call(m))}finally{if(o)throw o.error}}})()})}setDegradationPreference(e){return p(this,void 0,void 0,function*(){if(this.degradationPreference=e,this.sender)try{this.log.debug("setting degradationPreference to ".concat(e),this.logContext);let t=this.sender.getParameters();t.degradationPreference=e,this.sender.setParameters(t)}catch(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}let n={codec:e,mediaStreamTrack:this.mediaStreamTrack.clone(),sender:void 0,encodings:t};return this.simulcastCodecs.set(e,n),n}setSimulcastTrackSender(e,t){let n=this.simulcastCodecs.get(e);n&&(n.sender=t,setTimeout(()=>{this.subscribedCodecs&&this.setPublishingCodecs(this.subscribedCodecs)},pp))}setPublishingCodecs(e){return p(this,void 0,void 0,function*(){var t,n,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(je(e[0].codec),e[0].qualities),[];this.subscribedCodecs=e;let c=[];try{for(t=!0,n=Be(e);r=yield n.next(),s=r.done,!s;t=!0){d=r.value,t=!1;let l=d;if(!this.codec||this.codec===l.codec)yield this.setPublishingLayers(je(l.codec),l.qualities);else{let 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(let 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 zo(u.sender,u.encodings,l.qualities,this.senderLock,je(l.codec),this.log,this.logContext))}}}catch(l){a={error:l}}finally{try{!t&&!s&&(o=n.return)&&(yield o.call(n))}finally{if(a)throw a.error}}return c})}setPublishingLayers(e,t){return p(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 zo(this.sender,this.encodings,t,this.senderLock,e,this.log,this.logContext))})}prioritizePerformance(){return p(this,void 0,void 0,function*(){if(!this.sender)throw new Error("sender not found");let e=yield this.senderLock.lock();try{this.optimizeForPerformance=!0;let t=this.sender.getParameters();t.encodings=t.encodings.map((n,r)=>{var s;return Object.assign(Object.assign({},n),{active:r===0,scaleResolutionDownBy:Math.max(1,Math.ceil(((s=this.mediaStreamTrack.getSettings().height)!==null&&s!==void 0?s:360)/360)),scalabilityMode:r===0&&je(this.codec)?"L1T3":void 0,maxFramerate:r===0?15:0,maxBitrate:r===0?n.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(){let e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return p(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),Wd()&&this.isInBackground&&this.source===_.Source.Camera&&(this._mediaStreamTrack.enabled=!1)})}};function zo(i,e,t,n,r,s,a){return p(this,void 0,void 0,function*(){let o=yield n.lock();s.debug("setPublishingLayersForSender",Object.assign(Object.assign({},a),{sender:i,qualities:t,senderEncodings:e}));try{let d=i.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(m=>m.enabled)&&t.forEach(m=>m.enabled=!0),c.forEach((h,m)=>{var f;let g=(f=h.rid)!==null&&f!==void 0?f:"";g===""&&(g="q");let k=tl(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),Ft()&&(T.enabled?(h.scaleResolutionDownBy=e[m].scaleResolutionDownBy,h.maxBitrate=e[m].maxBitrate,h.maxFrameRate=e[m].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 i.setParameters(d))}finally{o()}})}function tl(i){switch(i){case"f":return Re.HIGH;case"h":return Re.MEDIUM;case"q":return Re.LOW;default:return Re.HIGH}}function Jo(i,e,t,n){if(!t)return[new Tt({quality:Re.HIGH,width:i,height:e,bitrate:0,ssrc:0})];if(n){let r=t[0].scalabilityMode,s=new Li(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 Tt({quality:Math.min(Re.HIGH,s.spatial-1)-c,width:Math.ceil(i/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;let d=(s=r.scaleResolutionDownBy)!==null&&s!==void 0?s:1,c=tl((a=r.rid)!==null&&a!==void 0?a:"");return new Tt({quality:c,width:Math.ceil(i/d),height:Math.ceil(e/d),bitrate:(o=r.maxBitrate)!==null&&o!==void 0?o:0,ssrc:0})})}var $o="_lossy",Qo="_reliable",Yo="_data_track",fp=2*1e3,Lr="leave-reconnect",gp=3e4,vp=8*1024,yp=256*1024,bp=3,kp=3,Me;(function(i){i[i.New=0]="New",i[i.Connected=1]="Connected",i[i.Disconnected=2]="Disconnected",i[i.Reconnecting=3]="Reconnecting",i[i.Closed=4]="Closed"})(Me||(Me={}));var U;(function(i){i[i.RELIABLE=0]="RELIABLE",i[i.LOSSY=1]="LOSSY",i[i.DATA_TRACK_LOSSY=2]="DATA_TRACK_LOSSY"})(U||(U={}));var Xo=64e3,Ps=class extends Ee.EventEmitter{get isClosed(){return this._isClosed}get isNewlyCreated(){return this._isNewlyCreated}get pendingReconnect(){return!!this.reconnectTimeout}constructor(e){var t;super(),this.options=e,this.rtcConfig={},this.peerConnectionTimeout=Ba.peerConnectionTimeout,this.fullReconnectOnNext=!1,this.latestRemoteOfferId=0,this.subscriberPrimary=!1,this.pcState=Me.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=F,this.reliableDataSequence=1,this.reliableMessageBuffer=new Mi,this.reliableReceivedState=new Cs(gp),this.lossyDataStatCurrentBytes=0,this.lossyDataStatByterate=0,this.lossyDataDropCount=0,this.midToTrackId={},this.isWaitingForNetworkReconnect=!1,this.bufferStatusLowClosingFuture=new ce,this.handleDataChannel=n=>p(this,[n],void 0,function(r){var s=this;let a=r.channel;return(function*(){if(!a)return;let o;if(a.label===Qo)s.reliableDCSub=a,o=s.handleDataMessage;else if(a.label===$o)s.lossyDCSub=a,o=s.handleDataMessage;else if(a.label===Yo)s.dataTrackDCSub=a,o=s.handleDataTrackMessage;else return;s.log.debug("on data channel ".concat(a.id,", ").concat(a.label)),a.onmessage=o})()}),this.handleDataMessage=n=>p(this,void 0,void 0,function*(){var r,s,a,o,d;let c=yield this.dataProcessLock.lock();try{let l;if(n.data instanceof ArrayBuffer)l=n.data;else if(n.data instanceof Blob)l=yield n.data.arrayBuffer();else{this.log.error("unsupported data type",{data:n.data});return}let u=ge.fromBinary(new Uint8Array(l));if(u.sequence>0&&u.participantSid!==""){let 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(R.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}let 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),m=Lc.fromBinary(h.payload),f=new ge({value:m.value,participantIdentity:u.participantIdentity,participantSid:u.participantSid});((o=f.value)===null||o===void 0?void 0:o.case)==="user"&&Zo(f,f.value.value),this.emit(R.DataPacketReceived,f,u.value.value.encryptionType)}else((d=u.value)===null||d===void 0?void 0:d.case)==="user"&&Zo(u,u.value.value),this.emit(R.DataPacketReceived,u,$.NONE)}finally{c()}}),this.handleDataTrackMessage=n=>p(this,void 0,void 0,function*(){let r;if(n.data instanceof ArrayBuffer)r=n.data;else if(n.data instanceof Blob)r=yield n.data.arrayBuffer();else{this.log.error("unsupported data type",{data:n.data});return}this.emit("dataTrackPacketReceived",new Uint8Array(r))}),this.handleDataError=n=>{if(this._isClosed)return;let s=n.currentTarget.maxRetransmits===0?"lossy":"reliable";if(typeof RTCErrorEvent<"u"&&n instanceof RTCErrorEvent&&n.error){let a=n.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:n})},this.handleDataChannelClose=n=>()=>{var r;!this._isClosed&&((r=this.pcManager)===null||r===void 0?void 0:r.publisher.getConnectionState())==="connected"&&this.log.error("publisher data channel '".concat(U[n],"' closed unexpectedly"),this.logContext)},this.handleBufferedAmountLow=n=>{this.updateAndEmitDCBufferStatus(n)},this.handleDisconnect=(n,r)=>{if(this._isClosed)return;this.log.warn("".concat(n," disconnected")),this.reconnectAttempts===0&&(this.reconnectStart=Date.now());let s=d=>{this.log.warn("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(d,"ms. giving up")),this.emit(R.Disconnected),this.close()},a=Date.now()-this.reconnectStart,o=this.getNextRetryDelay({elapsedMs:a,retryCount:this.reconnectAttempts});if(o===null){s(a);return}n===Lr&&(o=0),this.log.debug("reconnecting in ".concat(o,"ms")),this.clearReconnectTimeout(),this.token&&this.emit(R.TokenRefreshed,this.token),this.reconnectTimeout=se.setTimeout(()=>this.attemptReconnect(r).finally(()=>this.reconnectTimeout=void 0),o)},this.waitForRestarted=()=>new Promise((n,r)=>{this.pcState===Me.Connected&&n();let s=()=>{this.off(R.Disconnected,a),n()},a=()=>{this.off(R.Restarted,s),r()};this.once(R.Restarted,s),this.once(R.Disconnected,a)}),this.updateAndEmitDCBufferStatus=n=>{if(n===U.RELIABLE){let s=this.dataChannelForKind(n);s&&this.reliableMessageBuffer.alignBufferedAmount(s.bufferedAmount)}let r=this.isBufferStatusLow(n);typeof r<"u"&&r!==this.dcBufferStatus.get(n)&&(this.dcBufferStatus.set(n,r),this.emit(R.DCBufferStatusChanged,r,n))},this.isBufferStatusLow=n=>{let r=this.dataChannelForKind(n);if(r)return r.bufferedAmount<=r.bufferedAmountLowThreshold},this.onRtpMapAvailable=n=>{let r=new Map;n.forEach(s=>{let a=s.codec.toLowerCase();gm(a)&&r.set(s.payload,a)}),this.emit(R.RTPVideoMapUpdate,r)},this.handleBrowserOnLine=()=>p(this,void 0,void 0,function*(){!this.url||!(yield fetch(Nn(this.url),{method:"HEAD"}).then(r=>r.ok).catch(()=>!1))||(this.log.info("detected network reconnected"),(this.client.currentState===z.RECONNECTING||this.isWaitingForNetworkReconnect&&this.client.currentState===z.CONNECTED)&&(this.clearReconnectTimeout(),this.attemptReconnect(Rt.RR_SIGNAL_DISCONNECTED),this.isWaitingForNetworkReconnect=!1))}),this.handleBrowserOffline=()=>p(this,void 0,void 0,function*(){if(this.url)try{yield Promise.race([fetch(Nn(this.url),{method:"HEAD"}),ve(4e3).then(()=>Promise.reject())])}catch{window.navigator.onLine===!1&&(this.log.info("detected network interruption"),this.isWaitingForNetworkReconnect=!0)}}),this.log=_e((t=e.loggerName)!==null&&t!==void 0?t:ue.Engine,()=>this.logContext),this.loggerOptions={loggerName:e.loggerName,loggerContextCb:()=>this.logContext},this.client=new jn(void 0,this.loggerOptions),this.client.signalLatency=this.options.expSignalLatency,this.reconnectPolicy=this.options.reconnectPolicy,this.closingLock=new de,this.dataProcessLock=new de,this.dcBufferStatus=new Map([[U.RELIABLE,!0],[U.LOSSY,!0],[U.DATA_TRACK_LOSSY,!0]]),this.client.onParticipantUpdate=n=>this.emit(R.ParticipantUpdate,n),this.client.onConnectionQuality=n=>this.emit(R.ConnectionQualityUpdate,n),this.client.onRoomUpdate=n=>this.emit(R.RoomUpdate,n),this.client.onSubscriptionError=n=>this.emit(R.SubscriptionError,n),this.client.onSubscriptionPermissionUpdate=n=>this.emit(R.SubscriptionPermissionUpdate,n),this.client.onSpeakersChanged=n=>this.emit(R.SpeakersChanged,n),this.client.onStreamStateUpdate=n=>this.emit(R.StreamStateChanged,n),this.client.onRequestResponse=n=>this.emit(R.SignalRequestResponse,n),this.client.onParticipantUpdate=n=>this.emit(R.ParticipantUpdate,n),this.client.onJoined=n=>this.emit(R.Joined,n),this.on(R.Closing,()=>{var n,r;(r=(n=this.bufferStatusLowClosingFuture).reject)===null||r===void 0||r.call(n,new W("engine closed"))}),this.bufferStatusLowClosingFuture.promise.catch(()=>{})}get logContext(){var e,t,n,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=(n=this.latestJoinResponse)===null||n===void 0?void 0:n.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,n,r){return p(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,m;c._isNewlyCreated=!1,c.url=s,c.token=a,c.signalOpts=o,c.maxJoinAttempts=o.maxRetries;try{c.joinAttempts+=1,c.setupSignalClientCallbacks();let f=!l&&_m(),g;if(f){c.pcManager||(yield c.configure(),c.applyInitialPublisherLayout());let S=yield(u=c.pcManager)===null||u===void 0?void 0:u.publisher.createInitialOffer();S&&(g=Mt(S.offer,S.offerId))}if(d?.aborted)throw N.cancelled("Connection aborted");if(!l&&c.shouldFailOnV1Path)throw c.shouldFailOnV1Path=!1,N.serviceNotFound("Simulated v1 path failure","v0-rtc");let 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?(m=c.pcManager)===null||m===void 0||m.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(R.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=O(S,2),y=L[0],b=L[1];return"".concat(y,": ").concat(b)}).join(", "))),{joinResponse:k,serverInfo:T}}catch(f){if(f instanceof N){if(f.reason===J.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===J.ServiceNotFound)return c.log.warn("Initial connection failed: ".concat(f.message," \u2013 Retrying")),c.pcManager&&(c.pcManager.onStateChange=void 0,yield c.cleanupPeerConnections()),c.join(s,a,o,d,!0)}throw f}})()})}close(){return p(this,void 0,void 0,function*(){let e=yield this.closingLock.lock();if(this.isClosed){e();return}try{this._isClosed=!0,this.joinAttempts=0,this.emit(R.Closing),this.removeAllListeners(),this.deregisterOnLineListener(),this.clearPendingReconnect(),this.cleanupLossyDataStats(),yield this.cleanupPeerConnections(),yield this.cleanupClient()}finally{e()}})}cleanupPeerConnections(){return p(this,void 0,void 0,function*(){var e;let t=n=>{n&&(n.onbufferedamountlow=null,n.onclose=null,n.onclosing=null,n.onerror=null,n.onmessage=null,n.onopen=null,n.close())};t(this.lossyDC),t(this.lossyDCSub),t(this.reliableDC),t(this.reliableDCSub),t(this.dataTrackDC),t(this.dataTrackDCSub),yield(e=this.pcManager)===null||e===void 0?void 0:e.close(),this.pcManager=void 0,this.lossyDC=void 0,this.lossyDCSub=void 0,this.reliableDC=void 0,this.reliableDCSub=void 0,this.dataTrackDC=void 0,this.dataTrackDCSub=void 0,this.reliableMessageBuffer=new Mi,this.reliableDataSequence=1,this.reliableReceivedState.clear()})}cleanupLossyDataStats(){this.lossyDataStatByterate=0,this.lossyDataStatCurrentBytes=0,this.lossyDataStatInterval&&(clearInterval(this.lossyDataStatInterval),this.lossyDataStatInterval=void 0),this.lossyDataDropCount=0}cleanupClient(){return p(this,void 0,void 0,function*(){yield this.client.close(),this.client.resetCallbacks();for(let e of Object.keys(this.pendingTrackResolvers))this.pendingTrackResolvers[e].reject();this.pendingTrackResolvers={}})}addTrack(e){if(this.pendingTrackResolvers[e.cid])throw new qe("a track with the same ID has already been published");return new Promise((t,n)=>{let r=setTimeout(()=>{delete this.pendingTrackResolvers[e.cid],n(N.timeout("publication of local track timed out, no response from server"))},1e4);this.pendingTrackResolvers[e.cid]={resolve:s=>{clearTimeout(r),t(s)},reject:()=>{clearTimeout(r),n(new Error("Cancelled publication by calling unpublish"))}},this.client.sendAddTrack(e)})}removeTrack(e){if(e.track&&this.pendingTrackResolvers[e.track.id]){let 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.reliableDCSub)===null||e===void 0?void 0:e.readyState}getConnectedServerAddress(){return p(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 p(this,void 0,void 0,function*(){var n;if(!(this.pcManager&&this.pcManager.currentState!==te.NEW)){if(e){this.participantSid=(n=e.participant)===null||n===void 0?void 0:n.sid;let r=this.makeRTCConfiguration(e);this.pcManager=new xi(t?"publisher-only":e.subscriberPrimary?"subscriber-primary":"publisher-primary",this.loggerOptions,r)}else{let r=this.makeRTCConfiguration();this.pcManager=new xi("publisher-only",this.loggerOptions,r)}this.emit(R.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)=>p(this,void 0,void 0,function*(){if(this.log.debug("primary PC state changed ".concat(r)),["closed","disconnected","failed"].includes(s)&&(this.publisherConnectionPromise=void 0),r===te.CONNECTED){let c=this.pcState===Me.New;this.pcState=Me.Connected,c&&this.emit(R.Connected,this.latestJoinResponse)}else r===te.FAILED&&(this.pcState===Me.Connected||this.pcState===Me.Reconnecting)&&(this.pcState=Me.Disconnected,this.handleDisconnect("peerconnection failed",a==="failed"?Rt.RR_SUBSCRIBER_FAILED:Rt.RR_PUBLISHER_FAILED));let o=this.client.isDisconnected||this.client.currentState===z.RECONNECTING,d=[te.FAILED,te.CLOSING,te.CLOSED].includes(r);o&&d&&!this._isClosed&&this.emit(R.Offline)}),this.pcManager.onTrack=r=>{r.streams.length!==0&&this.emit(R.MediaTrackAdded,r.track,r.streams[0],r.receiver)}}})}setupSignalClientCallbacks(){this.client.onAnswer=(e,t,n)=>p(this,void 0,void 0,function*(){this.pcManager&&(this.log.debug("received server answer",{RTCSdpType:e.type,sdp:e.sdp,midToTrackId:n}),this.midToTrackId=n,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,n)=>p(this,void 0,void 0,function*(){if(this.latestRemoteOfferId=t,!this.pcManager)return;this.midToTrackId=n;let 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}let n=this.pendingTrackResolvers[e.cid].resolve;delete this.pendingTrackResolvers[e.cid],n(e.track)},this.client.onLocalTrackUnpublished=e=>{this.emit(R.LocalTrackUnpublished,e)},this.client.onLocalTrackSubscribed=e=>{this.emit(R.LocalTrackSubscribed,e)},this.client.onTokenRefresh=e=>{this.token=e,this.emit(R.TokenRefreshed,e)},this.client.onRemoteMuteChanged=(e,t)=>{this.emit(R.RemoteMute,e,t)},this.client.onSubscribedQualityUpdate=e=>{this.emit(R.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(R.RoomMoved,e)},this.client.onMediaSectionsRequirement=e=>{this.addMediaSections(e.numAudios,e.numVideos),this.negotiate()},this.client.onPublishDataTrackResponse=e=>{this.emit(R.PublishDataTrackResponse,e)},this.client.onUnPublishDataTrackResponse=e=>{this.emit(R.UnPublishDataTrackResponse,e)},this.client.onDataTrackSubscriberHandles=e=>{this.emit(R.DataTrackSubscriberHandles,e)},this.client.onClose=()=>{this.handleDisconnect("signal",Rt.RR_SIGNAL_DISCONNECTED)},this.client.onLeave=e=>{switch(this.log.info("client leave request received (action=".concat(e?.action,")"),{reason:e?.reason}),e.regions&&(this.log.debug("updating regions"),this.emit(R.ServerRegionsReported,e.regions)),e.action){case $t.DISCONNECT:this.emit(R.Disconnected,e?.reason),this.close();break;case $t.RECONNECT:this.fullReconnectOnNext=!0,this.handleDisconnect(Lr);break;case $t.RESUME:this.handleDisconnect(Lr)}}}makeRTCConfiguration(e){var t;let n=Object.assign({},this.rtcConfig);if((((t=this.signalOpts)===null||t===void 0?void 0:t.e2eeEnabled)||this.frameMetadataWorker&&!Un())&&xa()&&(this.log.debug("E2EE - setting up transports with insertable streams"),n.encodedInsertableStreams=!0),n.sdpSemantics="unified-plan",n.continualGatheringPolicy="gather_continually",!e)return n;if(e.iceServers&&!n.iceServers){let s=[];e.iceServers.forEach(a=>{let o={urls:a.urls};a.username&&(o.username=a.username),a.credential&&(o.credential=a.credential),s.push(o)}),n.iceServers=s}return e.clientConfiguration&&e.clientConfiguration.forceRelay===Mn.ENABLED&&(n.iceTransportPolicy="relay"),n}applyInitialPublisherLayout(){this.createDataChannels(),He()||this.addMediaSections(bp,kp)}addMediaSections(e,t){var n,r;let s={direction:"recvonly"};for(let a=0;a<e;a++)(n=this.pcManager)===null||n===void 0||n.addPublisherTransceiverOfKind("audio",s);for(let a=0;a<t;a++)(r=this.pcManager)===null||r===void 0||r.addPublisherTransceiverOfKind("video",s)}createDataChannels(){this.pcManager&&(this.lossyDC&&(this.lossyDC.onmessage=null,this.lossyDC.onerror=null,this.lossyDC.onclose=null),this.reliableDC&&(this.reliableDC.onmessage=null,this.reliableDC.onerror=null,this.reliableDC.onclose=null),this.dataTrackDC&&(this.dataTrackDC.onmessage=null,this.dataTrackDC.onerror=null,this.dataTrackDC.onclose=null),this.lossyDC=this.pcManager.createPublisherDataChannel($o,{ordered:!1,maxRetransmits:0}),this.reliableDC=this.pcManager.createPublisherDataChannel(Qo,{ordered:!0}),this.dataTrackDC=this.pcManager.createPublisherDataChannel(Yo,{ordered:!1,maxRetransmits:0}),this.lossyDC.onmessage=this.handleDataMessage,this.reliableDC.onmessage=this.handleDataMessage,this.dataTrackDC.onmessage=this.handleDataTrackMessage,this.lossyDC.onerror=this.handleDataError,this.reliableDC.onerror=this.handleDataError,this.dataTrackDC.onerror=this.handleDataError,this.lossyDC.onclose=this.handleDataChannelClose(U.LOSSY),this.reliableDC.onclose=this.handleDataChannelClose(U.RELIABLE),this.dataTrackDC.onclose=this.handleDataChannelClose(U.DATA_TRACK_LOSSY),this.lossyDC.bufferedAmountLowThreshold=65535,this.reliableDC.bufferedAmountLowThreshold=65535,this.dataTrackDC.bufferedAmountLowThreshold=65535,this.lossyDC.onbufferedamountlow=()=>this.handleBufferedAmountLow(U.LOSSY),this.reliableDC.onbufferedamountlow=()=>this.handleBufferedAmountLow(U.RELIABLE),this.dataTrackDC.onbufferedamountlow=()=>this.handleBufferedAmountLow(U.DATA_TRACK_LOSSY),this.cleanupLossyDataStats(),this.lossyDataStatInterval=setInterval(()=>{this.lossyDataStatByterate=this.lossyDataStatCurrentBytes,this.lossyDataStatCurrentBytes=0;let e=this.dataChannelForKind(U.LOSSY);if(e){let t=this.lossyDataStatByterate/10;e.bufferedAmountLowThreshold=Math.min(Math.max(t,vp),yp)}},1e3))}createSender(e,t,n){return p(this,void 0,void 0,function*(){let r;if(ds())r=yield this.createTransceiverRTCRtpSender(e,t,n);else if(ls())this.log.warn("using add-track fallback"),r=yield this.createRTCRtpSender(e.mediaStreamTrack);else throw new W("Required webRTC APIs not supported on this device");return this.setupFrameMetadataSender(r,t),r})}createSimulcastSender(e,t,n,r){return p(this,void 0,void 0,function*(){let s;if(ds())s=yield this.createSimulcastTransceiverSender(e,t,n,r);else if(ls())this.log.debug("using add-track fallback"),s=yield this.createRTCRtpSender(e.mediaStreamTrack);else throw new W("Cannot stream on this device");return s&&this.setupFrameMetadataSender(s,n),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 n,r,s;let a=this.frameMetadataWorker;if(!a||!((n=this.signalOpts)===null||n===void 0)&&n.e2eeEnabled)return;let o=(r=t.frameMetadata)!==null&&r!==void 0?r:t.packetTrailer,d=Ei(o);if(Un()){d&&(e.transform=new RTCRtpScriptTransform(a,{kind:"encode",packetTrailer:o}));return}if(!Fn((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}let 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,n){return p(this,void 0,void 0,function*(){if(!this.pcManager)throw new W("publisher is closed");let r=[];e.mediaStream&&r.push(e.mediaStream),ht(e)&&(e.codec=t.videoCodec);let s={direction:"sendonly",streams:r};return n&&(s.sendEncodings=n),(yield this.pcManager.addPublisherTransceiver(e.mediaStreamTrack,s)).sender})}createSimulcastTransceiverSender(e,t,n,r){return p(this,void 0,void 0,function*(){if(!this.pcManager)throw new W("publisher is closed");let s={direction:"sendonly"};r&&(s.sendEncodings=r);let a=yield this.pcManager.addPublisherTransceiver(t.mediaStreamTrack,s);if(n.videoCodec)return e.setSimulcastTrackSender(n.videoCodec,a.sender),a.sender})}createRTCRtpSender(e){return p(this,void 0,void 0,function*(){if(!this.pcManager)throw new W("publisher is closed");return this.pcManager.addPublisherTrack(e)})}attemptReconnect(e){return p(this,void 0,void 0,function*(){var t,n,r;if(!this._isClosed){if(this.attemptingReconnect){this.log.warn("already attempting reconnect, returning early");return}(((t=this.clientConfiguration)===null||t===void 0?void 0:t.resumeConnection)===Mn.DISABLED||((r=(n=this.pcManager)===null||n===void 0?void 0:n.currentState)!==null&&r!==void 0?r:te.NEW)===te.NEW)&&(this.fullReconnectOnNext=!0);try{this.attemptingReconnect=!0,this.fullReconnectOnNext?yield this.restartConnection():yield this.resumeConnection(e),this.clearPendingReconnect(),this.fullReconnectOnNext=!1}catch(s){this.reconnectAttempts+=1;let a=!0;s instanceof W?(this.log.debug("received unrecoverable error",{error:s}),a=!1):s instanceof vt||(this.fullReconnectOnNext=!0),a?this.handleDisconnect("reconnect",Rt.RR_UNKNOWN):(this.log.info("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(Date.now()-this.reconnectStart,"ms. giving up")),this.emit(R.Disconnected),yield this.close())}finally{this.attemptingReconnect=!1}}})}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 p(this,void 0,void 0,function*(){var t,n,r;try{if(!this.url||!this.token)throw new W("could not reconnect, url or token not saved");this.log.info("reconnecting, attempt: ".concat(this.reconnectAttempts)),this.emit(R.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 vt;s=(yield this.join(e??this.url,this.token,this.signalOpts,void 0,!this.options.singlePeerConnection)).joinResponse}catch(a){throw a instanceof N&&a.reason===J.NotAllowed?new W("could not reconnect, token might be expired"):new vt}if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(this.client.setReconnected(),this.emit(R.SignalRestarted,s),yield this.waitForPCReconnected(),this.client.currentState!==z.CONNECTED)throw new vt("Signal connection got severed during reconnect");(t=this.regionStrategy)===null||t===void 0||t.resetAttempts(),this.emit(R.Restarted)}catch(s){let a=yield(n=this.regionStrategy)===null||n===void 0?void 0:n.getNextUrl();if(a){yield this.restartConnection(a);return}else throw(r=this.regionStrategy)===null||r===void 0||r.resetAttempts(),s}})}resumeConnection(e){return p(this,void 0,void 0,function*(){var t;if(!this.url||!this.token)throw new W("could not reconnect, url or token not saved");if(!this.pcManager)throw new W("publisher and subscriber connections unset");this.log.info("resuming signal connection, attempt ".concat(this.reconnectAttempts)),this.emit(R.Resuming);let n;try{this.setupSignalClientCallbacks(),n=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 N&&r.reason===J.NotAllowed?new W("could not reconnect, token might be expired"):r instanceof N&&r.reason===J.LeaveRequest?r:new vt(s)}if(this.emit(R.SignalResumed),n){let r=this.makeRTCConfiguration(n);this.pcManager.updateConfiguration(r),this.latestJoinResponse&&(this.latestJoinResponse.serverInfo=n.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!==z.CONNECTED)throw new vt("Signal connection got severed during reconnect");this.client.setReconnected(),((t=this.reliableDC)===null||t===void 0?void 0:t.readyState)==="open"&&this.reliableDC.id===null&&this.createDataChannels(),n?.lastMessageSeq&&this.resendReliableMessagesForResume(n.lastMessageSeq),this.emit(R.Resumed)})}waitForPCInitialConnection(e,t){return p(this,void 0,void 0,function*(){if(!this.pcManager)throw new W("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(t,e)})}waitForPCReconnected(){return p(this,void 0,void 0,function*(){this.pcState=Me.Reconnecting,this.log.debug("waiting for peer connection to reconnect");try{if(yield ve(fp),!this.pcManager)throw new W("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(void 0,this.peerConnectionTimeout),this.pcState=Me.Connected}catch(e){throw this.pcState=Me.Disconnected,N.internal("could not establish PC connection, ".concat(e.message))}})}publishRpcAck(e,t){return p(this,void 0,void 0,function*(){let n=new ge({destinationIdentities:[e],kind:Ze.RELIABLE,value:{case:"rpcAck",value:new er({requestId:t})}});yield this.sendDataPacket(n,U.RELIABLE)})}sendDataPacket(e,t,n){return p(this,void 0,void 0,function*(){var r,s;if(n?.throwIfAborted(),yield this.ensurePublisherConnected(t),n?.throwIfAborted(),this.e2eeManager&&this.e2eeManager.isDataChannelEncryptionEnabled){let c=Om(e);if(c){let l=yield this.e2eeManager.encryptData(c.toBinary());e.value={case:"encryptedPacket",value:new Oc({encryptedValue:l.payload,iv:l.iv,keyIndex:l.keyIndex})}}}let a=t===U.RELIABLE?this.dataChannelForKind(t):void 0;a&&(yield this.waitForBufferStatusLow(t,n)),n?.throwIfAborted(),t===U.RELIABLE&&(e.sequence=this.reliableDataSequence,this.reliableDataSequence+=1);let o=e.toBinary(),d=Math.min((s=(r=this.pcManager)===null||r===void 0?void 0:r.getMaxPublisherMessageSize())!==null&&s!==void 0?s:Xo,Xo);if(typeof d<"u"&&d!==0&&o.byteLength>d)throw new rs("cannot publish data packet larger than ".concat(d," bytes (got ").concat(o.byteLength,")"));switch(t){case U.LOSSY:case U.DATA_TRACK_LOSSY:return this.sendLossyBytes(o,t);case U.RELIABLE:let c=a;if(c){if(this.reliableMessageBuffer.push({data:o,sequence:e.sequence}),this.attemptingReconnect)return;c.send(o)}this.updateAndEmitDCBufferStatus(t);break}})}sendLossyBytes(e,t){return p(this,arguments,void 0,function(n,r){var s=this;let a=arguments.length>2&&arguments[2]!==void 0?arguments[2]:"drop";return(function*(){yield s.ensurePublisherConnected(r);let o=s.dataChannelForKind(r);if(o){if(!s.isBufferStatusLow(r))switch(a){case"wait":yield s.waitForBufferStatusLow(r);break;case"drop":s.lossyDataDropCount+=1,s.lossyDataDropCount%100===0&&s.log.warn("dropping lossy data channel messages, total dropped: ".concat(s.lossyDataDropCount));return}if(s.lossyDataStatCurrentBytes+=n.byteLength,s.attemptingReconnect)return;o.send(n)}s.updateAndEmitDCBufferStatus(r)})()})}resendReliableMessagesForResume(e){return p(this,void 0,void 0,function*(){yield this.ensurePublisherConnected(U.RELIABLE);let t=this.dataChannelForKind(U.RELIABLE);t&&(this.reliableMessageBuffer.popToSequence(e),this.reliableMessageBuffer.getAll().forEach(n=>{t.send(n.data)})),this.updateAndEmitDCBufferStatus(U.RELIABLE)})}waitForBufferStatusLow(e,t){return t?new Promise((n,r)=>{if(t.aborted){r(t.reason);return}if(this.isClosed){r(new W("engine closed"));return}let s=this.dataChannelForKind(e);if(!s){r(new W("DataChannel not found"));return}if(this.isBufferStatusLow(e)){n();return}let a=()=>{s.removeEventListener("bufferedamountlow",o),t.removeEventListener("abort",d)},o=()=>{a(),n()},d=()=>{a(),r(t.reason)};s.addEventListener("bufferedamountlow",o,{once:!0}),t.addEventListener("abort",d,{once:!0}),this.bufferStatusLowClosingFuture.promise.catch(c=>{a(),r(c)})}):p(this,void 0,void 0,function*(){return new pe((n,r)=>p(this,void 0,void 0,function*(){if(this.isClosed&&r(new W("engine closed")),this.isBufferStatusLow(e))n();else{let s=this.dataChannelForKind(e);if(!s){r(new W("DataChannel not found, kind: ".concat(e)));return}this.bufferStatusLowClosingFuture.promise.catch(a=>r(a)),s.addEventListener("bufferedamountlow",()=>n(),{once:!0})}}))})}ensureDataTransportConnected(e){return p(this,arguments,void 0,function(t){var n=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.subscriberPrimary;return(function*(){var s;if(!n.pcManager)throw new W("PC manager is closed");let a=r?n.pcManager.subscriber:n.pcManager.publisher,o=r?"Subscriber":"Publisher";if(!a)throw N.internal("".concat(o," connection not set"));let d=!1;!r&&!n.dataChannelForKind(t,r)&&(n.createDataChannels(),d=!0),!d&&!r&&!n.pcManager.publisher.isICEConnected&&n.pcManager.publisher.getICEConnectionState()!=="checking"&&(d=!0),d&&n.negotiate().catch(u=>{n.log.error(u)});let c=n.dataChannelForKind(t,r);if(c?.readyState==="open")return;let l=new Date().getTime()+n.peerConnectionTimeout;for(;new Date().getTime()<l;){if(a.isICEConnected&&((s=n.dataChannelForKind(t,r))===null||s===void 0?void 0:s.readyState)==="open")return;yield ve(50)}throw N.internal("could not establish ".concat(o," connection, state: ").concat(a.getICEConnectionState()))})()})}ensurePublisherConnected(e){return p(this,void 0,void 0,function*(){this.publisherConnectionPromise||(this.publisherConnectionPromise=this.ensureDataTransportConnected(e,!1)),yield this.publisherConnectionPromise})}verifyTransport(){return!(!this.pcManager||![te.CONNECTING,te.CONNECTED].includes(this.pcManager.currentState)||!this.client.ws||this.client.ws.readyState===WebSocket.CLOSED)}negotiate(){return p(this,void 0,void 0,function*(){return new pe((e,t)=>p(this,void 0,void 0,function*(){if(!this.pcManager){t(new lt("PC manager is closed"));return}this.pcManager.requirePublisher(),this.pcManager.publisher.getTransceivers().length==0&&!this.lossyDC&&!this.reliableDC&&!this.dataTrackDC&&this.createDataChannels();let n=new AbortController,r=()=>{n.abort(),this.log.debug("engine disconnected while negotiation was ongoing"),e()};this.isClosed&&t(new lt("cannot negotiate on closed engine")),this.on(R.Closing,r),this.on(R.Restarting,r),this.pcManager.publisher.off(kt.RTPVideoPayloadTypes,this.onRtpMapAvailable),this.pcManager.publisher.once(kt.RTPVideoPayloadTypes,this.onRtpMapAvailable);try{yield this.pcManager.negotiate(n),e()}catch(s){if(n.signal.aborted){e();return}s instanceof lt&&(this.fullReconnectOnNext=!0),this.handleDisconnect("negotiation",Rt.RR_UNKNOWN),s instanceof Error?t(s):t(new Error(String(s)))}finally{this.off(R.Closing,r),this.off(R.Restarting,r)}}))})}dataChannelForKind(e,t){switch(e){case U.RELIABLE:return t?this.reliableDCSub:this.reliableDC;case U.LOSSY:return t?this.lossyDCSub:this.lossyDC;case U.DATA_TRACK_LOSSY:return t?this.dataTrackDCSub:this.dataTrackDC}}sendSyncState(e,t,n){var r,s,a,o;if(!this.pcManager){this.log.warn("sync state cannot be sent without peer connection setup");return}let 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,m=new Array,f=new Array;e.forEach(g=>{g.isDesired!==h&&m.push(g.trackSid),g.isEnabled||f.push(g.trackSid)}),this.client.sendSyncState(new Ea({answer:this.pcManager.mode==="publisher-only"?c?Mt({sdp:c.sdp,type:c.type}):void 0:u?Mt({sdp:u.sdp,type:u.type}):void 0,offer:this.pcManager.mode==="publisher-only"?d?Mt({sdp:d.sdp,type:d.type}):void 0:l?Mt({sdp:l.sdp,type:l.type}):void 0,subscription:new ir({trackSids:m,subscribe:!h,participantTracks:[]}),publishTracks:Xh(t),dataChannels:this.dataChannelsInfo(),trackSidsDisabled:f,datachannelReceiveStates:this.reliableReceivedState.map((g,k)=>new id({publisherSid:k,lastSeq:g})),publishDataTracks:n.map(g=>new ka({info:Ii.toProtobuf(g)}))}))}failNext(){this.shouldFailNext=!0}failNextV1Path(){this.shouldFailOnV1Path=!0}dataChannelsInfo(){let e=[],t=(n,r)=>{n?.id!==void 0&&n.id!==null&&e.push(new rd({label:n.label,id:n.id,target:r}))};return t(this.dataChannelForKind(U.LOSSY),Fe.PUBLISHER),t(this.dataChannelForKind(U.RELIABLE),Fe.PUBLISHER),t(this.dataChannelForKind(U.LOSSY,!0),Fe.SUBSCRIBER),t(this.dataChannelForKind(U.RELIABLE,!0),Fe.SUBSCRIBER),e}clearReconnectTimeout(){this.reconnectTimeout&&se.clearTimeout(this.reconnectTimeout)}clearPendingReconnect(){this.clearReconnectTimeout(),this.reconnectAttempts=0}registerOnLineListener(){Ce()&&(window.addEventListener("online",this.handleBrowserOnLine),window.addEventListener("offline",this.handleBrowserOffline))}deregisterOnLineListener(){Ce()&&(window.removeEventListener("online",this.handleBrowserOnLine),window.removeEventListener("offline",this.handleBrowserOffline))}getTrackIdForReceiver(e){var t;let n=(t=this.pcManager)===null||t===void 0?void 0:t.getMidForReceiver(e);if(n){let r=Object.entries(this.midToTrackId).find(s=>O(s,1)[0]===n);if(r)return r[1]}}};function Zo(i,e){let t=i.participantIdentity?i.participantIdentity:e.participantIdentity;i.participantIdentity=t,e.participantIdentity=t;let n=i.destinationIdentities.length!==0?i.destinationIdentities:e.destinationIdentities;i.destinationIdentities=n,e.destinationIdentities=n}var Is=5e3,Tp=3e4,Ge=class i{static fetchRegionSettings(e,t,n){return p(this,void 0,void 0,function*(){let r=yield i.fetchLock.lock();try{let s=yield fetch("".concat(Sp(e),"/regions"),{headers:{authorization:"Bearer ".concat(t)},signal:n});if(s.ok){let a=Cm(s.headers),o=a?a*1e3:Is;return{regionSettings:yield s.json(),updatedAtInMs:Date.now(),maxAgeInMs:o}}else throw s.status===401?N.notAllowed("Could not fetch region settings: ".concat(s.statusText),s.status):N.internal("Could not fetch region settings: ".concat(s.statusText))}catch(s){throw s instanceof N?s:n?.aborted?N.cancelled("Region fetching was aborted"):N.serverUnreachable("Could not fetch region settings, ".concat(s instanceof Error?"".concat(s.name,": ").concat(s.message):s))}finally{r()}})}static scheduleRefetch(e,t,n){return p(this,void 0,void 0,function*(){let r=i.settingsTimeouts.get(e.hostname);clearTimeout(r),i.settingsTimeouts.set(e.hostname,setTimeout(()=>p(this,void 0,void 0,function*(){try{let s=yield i.fetchRegionSettings(e,t);i.updateCachedRegionSettings(e,t,s)}catch(s){if(s instanceof N&&s.reason===J.NotAllowed){F.debug("token is not valid, cancelling auto region refresh");return}F.debug("auto refetching of region settings failed",{error:s}),i.scheduleRefetch(e,t,n)}}),n))})}static updateCachedRegionSettings(e,t,n){i.cache.set(e.hostname,n),i.scheduleRefetch(e,t,n.maxAgeInMs)}static stopRefetch(e){let t=i.settingsTimeouts.get(e);t&&(clearTimeout(t),i.settingsTimeouts.delete(e))}static scheduleCleanup(e){let t=i.connectionTrackers.get(e);t&&(t.cleanupTimeout&&clearTimeout(t.cleanupTimeout),t.cleanupTimeout=setTimeout(()=>{let n=i.connectionTrackers.get(e);n&&n.connectionCount===0&&(F.debug("stopping region refetch after disconnect delay",{hostname:e}),i.stopRefetch(e)),n&&(n.cleanupTimeout=void 0)},Tp))}static cancelCleanup(e){let t=i.connectionTrackers.get(e);t?.cleanupTimeout&&(clearTimeout(t.cleanupTimeout),t.cleanupTimeout=void 0)}notifyConnected(){let e=this.serverUrl.hostname,t=i.connectionTrackers.get(e);t||(t={connectionCount:0},i.connectionTrackers.set(e,t)),t.connectionCount++,i.cancelCleanup(e)}notifyDisconnected(){let e=this.serverUrl.hostname,t=i.connectionTrackers.get(e);t&&(t.connectionCount=Math.max(0,t.connectionCount-1),t.connectionCount===0&&i.scheduleCleanup(e))}constructor(e,t){this.attemptedRegions=[],this.serverUrl=new URL(e),this.token=t}updateToken(e){var t;this.token=e;let n=this.getServerUrl(),r=i.cache.get(n.hostname);i.scheduleRefetch(this.serverUrl,this.token,(t=r?.maxAgeInMs)!==null&&t!==void 0?t:Is)}isCloud(){return sn(this.serverUrl)}getServerUrl(){return this.serverUrl}fetchRegionSettings(e){return p(this,void 0,void 0,function*(){return i.fetchRegionSettings(this.serverUrl,this.token,e)})}getNextBestRegionUrl(e){return p(this,void 0,void 0,function*(){if(!this.isCloud())throw Error("region availability is only supported for LiveKit Cloud domains");let t=i.cache.get(this.serverUrl.hostname);(!t||Date.now()-t.updatedAtInMs>t.maxAgeInMs)&&(t=yield this.fetchRegionSettings(e),i.updateCachedRegionSettings(this.serverUrl,this.token,t));let n=t.regionSettings.regions.filter(r=>!this.attemptedRegions.find(s=>s.url===r.url));if(n.length>0){let r=n[0];return this.attemptedRegions.push(r),F.debug("next region: ".concat(r.region)),r.url}else return null})}resetAttempts(){this.attemptedRegions=[]}setServerReportedRegions(e){i.updateCachedRegionSettings(this.serverUrl,this.token,e)}};Ge.cache=new Map;Ge.settingsTimeouts=new Map;Ge.connectionTrackers=new Map;Ge.fetchLock=new de;function Sp(i){return"".concat(i.protocol.replace("ws","http"),"//").concat(i.host,"/settings")}var Ni=class{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 Se("Not enough chunk(s) received - expected ".concat(this.totalByteSize," bytes of data total, only received ").concat(this.bytesReceived," bytes"),be.Incomplete);if(this.bytesReceived>this.totalByteSize)throw new Se("Extra chunk(s) received - expected ".concat(this.totalByteSize," bytes of data total, received ").concat(this.bytesReceived," bytes"),be.LengthExceeded)}}constructor(e,t,n){this.reader=t,this.totalByteSize=n,this._info=e,this.bytesReceived=0}},Ms=class extends Ni{handleChunkReceived(e){var t;this.bytesReceived+=e.content.byteLength,this.validateBytesReceived();let n=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;(t=this.onProgress)===null||t===void 0||t.call(this,n)}[Symbol.asyncIterator](){let e=this.reader.getReader();e.closed.catch(()=>{});let t=()=>{e.releaseLock(),this.signal=void 0};return{next:()=>p(this,void 0,void 0,function*(){try{let n=this.signal;if(n?.aborted)throw n.reason;let r=yield new Promise((s,a)=>{if(n){let o=()=>a(n.reason);n.addEventListener("abort",o,{once:!0}),e.read().then(s,a).finally(()=>{n.removeEventListener("abort",o)})}else e.read().then(s,a)});return r.done?(this.validateBytesReceived(!0),{done:!0,value:void 0}):(this.handleChunkReceived(r.value),{done:!1,value:r.value.content})}catch(n){throw t(),n}}),return(){return p(this,void 0,void 0,function*(){return t(),{done:!0,value:void 0}})}}}withAbortSignal(e){return this.signal=e,this}readAll(){return p(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return(function*(){var n,r,s,a;let o=new Set,d=t.signal?e.withAbortSignal(t.signal):e;try{for(var c=!0,l=Be(d),u;u=yield l.next(),n=u.done,!n;c=!0){a=u.value,c=!1;let h=a;o.add(h)}}catch(h){r={error:h}}finally{try{!c&&!n&&(s=l.return)&&(yield s.call(l))}finally{if(r)throw r.error}}return Array.from(o)})()})}},As=class extends Ni{constructor(e,t,n){super(e,t,n),this.receivedChunks=new Map}handleChunkReceived(e){var t;let n=pi(e.chunkIndex),r=this.receivedChunks.get(n);if(r&&r.version>e.version)return;this.receivedChunks.set(n,e),this.bytesReceived+=e.content.byteLength,this.validateBytesReceived();let s=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;(t=this.onProgress)===null||t===void 0||t.call(this,s)}[Symbol.asyncIterator](){let e=this.reader.getReader();e.closed.catch(()=>{});let t=new TextDecoder("utf-8",{fatal:!0}),n=this.signal,r=()=>{e.releaseLock(),this.signal=void 0};return{next:()=>p(this,void 0,void 0,function*(){try{if(n?.aborted)throw n.reason;let s=yield new Promise((a,o)=>{if(n){let d=()=>o(n.reason);n.addEventListener("abort",d,{once:!0}),e.read().then(a,o).finally(()=>{n.removeEventListener("abort",d)})}else e.read().then(a,o)});if(s.done)return this.validateBytesReceived(!0),{done:!0,value:void 0};{this.handleChunkReceived(s.value);let a;try{a=t.decode(s.value.content)}catch(o){throw new Se("Cannot decode datastream chunk ".concat(s.value.chunkIndex," as text: ").concat(o),be.DecodeFailed)}return{done:!1,value:a}}}catch(s){throw r(),s}}),return(){return p(this,void 0,void 0,function*(){return r(),{done:!0,value:void 0}})}}}withAbortSignal(e){return this.signal=e,this}readAll(){return p(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return(function*(){var n,r,s,a;let o="",d=t.signal?e.withAbortSignal(t.signal):e;try{for(var c=!0,l=Be(d),u;u=yield l.next(),n=u.done,!n;c=!0)a=u.value,c=!1,o+=a}catch(h){r={error:h}}finally{try{!c&&!n&&(s=l.return)&&(yield s.call(l))}finally{if(r)throw r.error}}return o})()})}},xs=class{constructor(){this.log=F,this.byteStreamControllers=new Map,this.textStreamControllers=new Map,this.byteStreamHandlers=new Map,this.textStreamHandlers=new Map,this.isConnected=!1,this.bufferedPackets=[]}setConnected(e){this.isConnected=e,e&&this.flushBufferedPackets()}flushBufferedPackets(){let e=this.bufferedPackets;this.bufferedPackets=[];for(let t of e){let n=t.packet,r=t.encryptionType;this.handleDataStreamPacket(n,r)}}registerTextStreamHandler(e,t){if(this.textStreamHandlers.has(e))throw new Se('A text stream handler for topic "'.concat(e,'" has already been set.'),be.HandlerAlreadyRegistered);this.textStreamHandlers.set(e,t)}unregisterTextStreamHandler(e){this.textStreamHandlers.delete(e)}registerByteStreamHandler(e,t){if(this.byteStreamHandlers.has(e))throw new Se('A byte stream handler for topic "'.concat(e,'" has already been set.'),be.HandlerAlreadyRegistered);this.byteStreamHandlers.set(e,t)}unregisterByteStreamHandler(e){this.byteStreamHandlers.delete(e)}clearControllers(){this.byteStreamControllers.clear(),this.textStreamControllers.clear(),this.bufferedPackets=[]}validateParticipantHasNoActiveDataStreams(e){let t=Array.from(this.textStreamControllers.entries()).filter(a=>a[1].sendingParticipantIdentity===e),n=Array.from(this.byteStreamControllers.entries()).filter(a=>a[1].sendingParticipantIdentity===e);if(t.length>0||n.length>0){let a=new Se("Participant ".concat(e," unexpectedly disconnected in the middle of sending data"),be.AbnormalEnd);for(let o of n){var r=O(o,2);let d=r[0];r[1].controller.error(a),this.byteStreamControllers.delete(d)}for(let o of t){var s=O(o,2);let 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,n){var r;if(e.contentHeader.case==="byteHeader"){let 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,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:pi(e.timestamp),attributes:e.attributes,encryptionType:n},d=new ReadableStream({start:c=>{if(a=c,this.textStreamControllers.has(e.streamId))throw new Se("A data stream read is already in progress for a stream with id ".concat(e.streamId,"."),be.AlreadyOpened);this.byteStreamControllers.set(e.streamId,{info:o,controller:a,startTime:Date.now(),sendingParticipantIdentity:t})}});s(new Ms(o,d,pi(e.totalLength)),{identity:t})}else if(e.contentHeader.case==="textHeader"){let 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,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:n,attachedStreamIds:e.contentHeader.value.attachedStreamIds},d=new ReadableStream({start:c=>{if(a=c,this.textStreamControllers.has(e.streamId))throw new Se("A data stream read is already in progress for a stream with id ".concat(e.streamId,"."),be.AlreadyOpened);this.textStreamControllers.set(e.streamId,{info:o,controller:a,startTime:Date.now(),sendingParticipantIdentity:t})}});s(new As(o,d,pi(e.totalLength)),{identity:t})}}handleStreamChunk(e,t){let n=this.byteStreamControllers.get(e.streamId);n&&(n.info.encryptionType!==t?(n.controller.error(new Se("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(n.info.encryptionType),be.EncryptionTypeMismatch)),this.byteStreamControllers.delete(e.streamId)):e.content.length>0&&n.controller.enqueue(e));let r=this.textStreamControllers.get(e.streamId);r&&(r.info.encryptionType!==t?(r.controller.error(new Se("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(r.info.encryptionType),be.EncryptionTypeMismatch)),this.textStreamControllers.delete(e.streamId)):e.content.length>0&&r.controller.enqueue(e))}handleStreamTrailer(e,t){let n=this.textStreamControllers.get(e.streamId);n&&(n.info.encryptionType!==t?n.controller.error(new Se("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(n.info.encryptionType),be.EncryptionTypeMismatch)):(n.info.attributes=Object.assign(Object.assign({},n.info.attributes),e.attributes),n.controller.close(),this.textStreamControllers.delete(e.streamId)));let r=this.byteStreamControllers.get(e.streamId);r&&(r.info.encryptionType!==t?r.controller.error(new Se("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(r.info.encryptionType),be.EncryptionTypeMismatch)):(r.info.attributes=Object.assign(Object.assign({},r.info.attributes),e.attributes),r.controller.close()),this.byteStreamControllers.delete(e.streamId))}},Ui=class{constructor(e,t,n){this.writableStream=e,this.defaultWriter=e.getWriter(),this.onClose=n,this.info=t}write(e){return this.defaultWriter.write(e)}close(){return p(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)})}},Ds=class extends Ui{},Os=class extends Ui{},ec=15e3,Ls=class{constructor(e,t){this.engine=e,this.log=t}setupEngine(e){this.engine=e}sendText(e,t){return p(this,void 0,void 0,function*(){var n;let r=crypto.randomUUID(),a=new TextEncoder().encode(e).byteLength,o=(n=t?.attachments)===null||n===void 0?void 0:n.map(()=>crypto.randomUUID()),d=new Array(o?o.length+1:1).fill(0),c=(u,h)=>{var m;d[h]=u;let f=d.reduce((g,k)=>g+k,0);(m=t?.onProgress)===null||m===void 0||m.call(t,f)},l=yield this.streamText({streamId:r,totalSize:a,destinationIdentities:t?.destinationIdentities,topic:t?.topic,attachedStreamIds:o,attributes:t?.attributes});return yield l.write(e),c(1,0),yield l.close(),t?.attachments&&o&&(yield Promise.all(t.attachments.map((u,h)=>p(this,void 0,void 0,function*(){return this._sendFile(o[h],u,{topic:t.topic,mimeType:u.type,onProgress:m=>{c(m,h+1)}})})))),l.info})}streamText(e){return p(this,void 0,void 0,function*(){var t,n,r;let s=(t=e?.streamId)!==null&&t!==void 0?t:crypto.randomUUID(),a={id:s,mimeType:"text/plain",timestamp:Date.now(),topic:(n=e?.topic)!==null&&n!==void 0?n:"",size:e?.totalSize,attributes:e?.attributes,encryptionType:!((r=this.engine.e2eeManager)===null||r===void 0)&&r.isDataChannelEncryptionEnabled?$.GCM:$.NONE,attachedStreamIds:e?.attachedStreamIds},o=new bi({streamId:s,mimeType:a.mimeType,topic:a.topic,timestamp:Pt(a.timestamp),totalLength:Pt(a.size),attributes:a.attributes,contentHeader:{case:"textHeader",value:new zc({version:e?.version,attachedStreamIds:a.attachedStreamIds,replyToStreamId:e?.replyToStreamId,operationType:e?.type==="update"?Gr.UPDATE:Gr.CREATE})}}),d=e?.destinationIdentities,c=new ge({destinationIdentities:d,value:{case:"streamHeader",value:o}});yield this.engine.sendDataPacket(c,U.RELIABLE,e?.signal);let l=0,u=this.engine,h=new WritableStream({write(k){return p(this,void 0,void 0,function*(){for(let T of Sm(k,ec)){let S=new ki({content:T,streamId:s,chunkIndex:Pt(l)}),L=new ge({destinationIdentities:d,value:{case:"streamChunk",value:S}});yield u.sendDataPacket(L,U.RELIABLE,e?.signal),l+=1}})},close(){return p(this,void 0,void 0,function*(){let k=new Ti({streamId:s}),T=new ge({destinationIdentities:d,value:{case:"streamTrailer",value:k}});yield u.sendDataPacket(T,U.RELIABLE,e?.signal)})},abort(k){console.log("Sink error:",k)}}),m=()=>p(this,void 0,void 0,function*(){try{yield g.close()}catch(k){if(!e?.signal?.aborted)throw k}}),f=()=>{u.off(R.Closing,m),e?.signal?.removeEventListener("abort",f)};u.once(R.Closing,m);let g=new Ds(h,a,f);return e?.signal?.addEventListener("abort",f,{once:!0}),e?.signal?.aborted&&f(),g})}sendFile(e,t){return p(this,void 0,void 0,function*(){let n=crypto.randomUUID();return yield this._sendFile(n,e,t),{id:n}})}_sendFile(e,t,n){return p(this,void 0,void 0,function*(){var r;let s=yield this.streamBytes({streamId:e,totalSize:t.size,name:t.name,mimeType:(r=n?.mimeType)!==null&&r!==void 0?r:t.type,topic:n?.topic,destinationIdentities:n?.destinationIdentities}),a=t.stream().getReader();for(;;){let o=yield a.read(),d=o.done,c=o.value;if(d)break;yield s.write(c)}return yield s.close(),s.info})}streamBytes(e){return p(this,void 0,void 0,function*(){var t,n,r,s,a;let o=(t=e?.streamId)!==null&&t!==void 0?t:crypto.randomUUID(),d=e?.destinationIdentities,c={id:o,mimeType:(n=e?.mimeType)!==null&&n!==void 0?n:"application/octet-stream",topic:(r=e?.topic)!==null&&r!==void 0?r:"",timestamp:Date.now(),attributes:e?.attributes,size:e?.totalSize,name:(s=e?.name)!==null&&s!==void 0?s:"unknown",encryptionType:!((a=this.engine.e2eeManager)===null||a===void 0)&&a.isDataChannelEncryptionEnabled?$.GCM:$.NONE},l=new bi({totalLength:Pt(c.size),mimeType:c.mimeType,streamId:o,topic:c.topic,timestamp:Pt(Date.now()),attributes:c.attributes,contentHeader:{case:"byteHeader",value:new Jc({name:c.name})}}),u=new ge({destinationIdentities:d,value:{case:"streamHeader",value:l}});yield this.engine.sendDataPacket(u,U.RELIABLE,e?.signal);let h=0,m=new de,f=this.engine,g=this.log,k=new WritableStream({write(S){return p(this,void 0,void 0,function*(){let L=yield m.lock(),y=0;try{for(;y<S.byteLength;){let b=S.slice(y,y+ec),E=new ge({destinationIdentities:d,value:{case:"streamChunk",value:new ki({content:b,streamId:o,chunkIndex:Pt(h)})}});yield f.sendDataPacket(E,U.RELIABLE,e?.signal),h+=1,y+=b.byteLength}}finally{L()}})},close(){return p(this,void 0,void 0,function*(){let S=new Ti({streamId:o}),L=new ge({destinationIdentities:d,value:{case:"streamTrailer",value:S}});yield f.sendDataPacket(L,U.RELIABLE,e?.signal)})},abort(S){g.error("Sink error:",S)}});return new Os(k,c)})}};function nl(i){if(i.length===0)return new AbortController().signal;if(i.length===1)return i[0];for(let r of i)if(r.aborted)return r;let e=new AbortController,t=Array(i.length),n=()=>{for(let r of t)r()};return i.forEach((r,s)=>{let a=()=>{e.abort(r.reason),n()};r.addEventListener("abort",a),t[s]=()=>r.removeEventListener("abort",a)}),e.signal}function il(i){let e=new AbortController;return setTimeout(()=>{e.abort(new DOMException("signal timed out after ".concat(i," ms"),"TimeoutError"))},i),e.signal}var ie=1,st=2,tc=4,Cp=8,nc=0,ic=12,rc=5,_p=7,sc=3,wp=3,ac=2,oc=1,cc=0,dc=3,ti=2,lc=2,Ep=1,Rp=0,ot;(function(i){i[i.TooShort=0]="TooShort",i[i.HeaderOverrun=1]="HeaderOverrun",i[i.MissingExtWords=2]="MissingExtWords",i[i.UnsupportedVersion=3]="UnsupportedVersion",i[i.InvalidHandle=4]="InvalidHandle",i[i.MalformedExt=5]="MalformedExt"})(ot||(ot={}));var Xe=class i extends we{constructor(e,t,n){super(19,e,n),this.name="DataTrackDeserializeError",this.reason=t,this.reasonName=ot[t]}static tooShort(){return new i("Too short to contain a valid header",ot.TooShort)}static headerOverrun(){return new i("Header exceeds total packet length",ot.HeaderOverrun)}static missingExtWords(){return new i("Extension word indicator is missing",ot.MissingExtWords)}static unsupportedVersion(e){return new i("Unsupported version ".concat(e),ot.UnsupportedVersion)}static invalidHandle(e){return new i("invalid track handle: ".concat(e.message),ot.InvalidHandle,{cause:e})}static malformedExt(e){return new i("Extension with tag ".concat(e," is malformed"),ot.MalformedExt)}},En;(function(i){i[i.TooSmallForHeader=0]="TooSmallForHeader",i[i.TooSmallForPayload=1]="TooSmallForPayload"})(En||(En={}));var Fi=class i extends we{constructor(e,t,n){super(19,e,n),this.name="DataTrackSerializeError",this.reason=t,this.reasonName=En[t]}static tooSmallForHeader(){return new i("Buffer cannot fit header",En.TooSmallForHeader)}static tooSmallForPayload(){return new i("Buffer cannot fit payload",En.TooSmallForPayload)}},on=class{toBinary(){let e=this.toBinaryLengthBytes(),t=new ArrayBuffer(e),n=new DataView(t),r=this.toBinaryInto(n);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)}},cn;(function(i){i[i.UserTimestamp=2]="UserTimestamp",i[i.E2ee=1]="E2ee"})(cn||(cn={}));var Bi=class extends on{},qt=class i extends Bi{constructor(e){super(),this.timestamp=e}toBinaryLengthBytes(){return ie+ie+i.lengthBytes}toBinaryInto(e){let t=0;e.setUint8(t,i.tag),t+=ie,e.setUint8(t,i.lengthBytes),t+=ie,e.setBigUint64(t,this.timestamp),t+=Cp;let n=this.toBinaryLengthBytes();if(t!==n)throw new Error("DataTrackUserTimestampExtension.toBinaryInto: Wrote ".concat(t," bytes but expected length was ").concat(n," bytes"));return t}toJSON(){return{tag:i.tag,lengthBytes:i.lengthBytes,timestamp:this.timestamp}}};qt.tag=cn.UserTimestamp;qt.lengthBytes=8;var jt=class i extends Bi{constructor(e,t){super(),this.keyIndex=e,this.iv=t}toBinaryLengthBytes(){return ie+ie+i.lengthBytes}toBinaryInto(e){let t=0;e.setUint8(t,i.tag),t+=ie,e.setUint8(t,i.lengthBytes),t+=ie,e.setUint8(t,this.keyIndex),t+=ie;for(let r=0;r<this.iv.length;r+=1)e.setUint8(t,this.iv[r]),t+=ie;let n=this.toBinaryLengthBytes();if(t!==n)throw new Error("DataTrackE2eeExtension.toBinaryInto: Wrote ".concat(t," bytes but expected length was ").concat(n," bytes"));return t}toJSON(){return{tag:i.tag,lengthBytes:i.lengthBytes,keyIndex:this.keyIndex,iv:this.iv}}};jt.tag=cn.E2ee;jt.lengthBytes=13;var en=class i extends on{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){let r=this.e2ee.toBinaryInto(e);t+=r}if(this.userTimestamp){let r=this.userTimestamp.toBinaryInto(new DataView(e.buffer,e.byteOffset+t));t+=r}let n=this.toBinaryLengthBytes();if(t!==n)throw new Error("DataTrackExtensions.toBinaryInto: Wrote ".concat(t," bytes but expected length was ").concat(n," bytes"));return t}static fromBinary(e){let t=Na(e),n,r,s=0;for(;t.byteLength-s>=ie+ie;){let a=t.getUint8(s);s+=ie;let o=t.getUint8(s);if(s+=ie,a!==Rp)switch(a){case cn.UserTimestamp:if(t.byteLength-s<qt.lengthBytes)throw Xe.malformedExt(a);n=new qt(t.getBigUint64(s)),s+=o;break;case cn.E2ee:if(t.byteLength-s<jt.lengthBytes)throw Xe.malformedExt(a);let d=t.getUint8(s),c=new Uint8Array(12);for(let l=0;l<c.length;l+=1){let u=s;u+=ie,u+=l*ie,c[l]=t.getUint8(u)}r=new jt(d,c),s+=o;break;default:if(t.byteLength-s<o)throw Xe.malformedExt(a);s+=o;break}}return[new i({userTimestamp:n,e2ee:r}),t.byteLength]}toJSON(){var e,t,n,r;return{userTimestamp:(t=(e=this.userTimestamp)===null||e===void 0?void 0:e.toJSON())!==null&&t!==void 0?t:null,e2ee:(r=(n=this.e2ee)===null||n===void 0?void 0:n.toJSON())!==null&&r!==void 0?r:null}}},rl={from(i){return{payload:i.payload,extensions:new en({userTimestamp:i.userTimestamp?new qt(i.userTimestamp):void 0})}},lossyIntoFrame(i){var e;return{payload:i.payload,userTimestamp:(e=i.extensions.userTimestamp)===null||e===void 0?void 0:e.timestamp}}},sl=Symbol.for("lk.track"),al=Symbol.for("lk.data-track"),qi=class{constructor(e,t,n){this.trackSymbol=sl,this.isLocal=!1,this.typeSymbol=al,this.info=e,this.manager=t,this.publisherIdentity=n.publisherIdentity}subscribe(e){try{let t=this.manager.openSubscriptionStream(this.info.sid,e?.signal,e?.bufferSize),n=O(t,2),r=n[0];return n[1].catch(()=>{}),r}catch(t){throw t}}setPipelineOptions(e){this.manager.setPipelineOptions(this.info.sid,e)}},Vn=class i extends on{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 en}extensionsMetrics(){let e=this.extensions.toBinaryLengthBytes(),t=Math.ceil((ti+e)/4),n=t*4-ti-e;return{lengthBytes:e,lengthWords:t,paddingLengthBytes:n}}toBinaryLengthBytes(){let e=this.extensionsMetrics(),t=e.lengthBytes,n=e.paddingLengthBytes,r=ic;return t>0&&(r+=ti+t+n),r}toBinaryInto(e){if(e.byteLength<this.toBinaryLengthBytes())throw Fi.tooSmallForHeader();let t=nc<<rc,n;switch(this.marker){case Q.Inter:n=cc;break;case Q.Final:n=oc;break;case Q.Start:n=ac;break;case Q.Single:n=dc;break}t|=n<<sc;let r=this.extensionsMetrics(),s=r.lengthBytes,a=r.lengthWords,o=r.paddingLengthBytes;s>0&&(t|=1<<lc);let d=0;if(e.setUint8(d,t),d+=ie,e.setUint8(d,0),d+=ie,e.setUint16(d,this.trackHandle),d+=st,e.setUint16(d,this.sequence.value),d+=st,e.setUint16(d,this.frameNumber.value),d+=st,e.setUint32(d,this.timestamp.asTicks()),d+=tc,s>0){let l=a-1;e.setUint16(d,l),d+=st;let 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+=ie}let c=this.toBinaryLengthBytes();if(d!==c)throw new Error("DataTrackPacketHeader.toBinaryInto: Wrote ".concat(d," bytes but expected length was ").concat(c," bytes"));return c}static fromBinary(e){let t=Na(e);if(t.byteLength<ic)throw Xe.tooShort();let n=0,r=t.getUint8(n);n+=ie;let s=r>>rc&_p;if(s>nc)throw Xe.unsupportedVersion(s);let a;switch(r>>sc&wp){case ac:a=Q.Start;break;case oc:a=Q.Final;break;case dc:a=Q.Single;break;case cc:default:a=Q.Inter;break}let o=(r>>lc&Ep)>0;n+=ie;let d;try{d=qm.fromNumber(t.getUint16(n))}catch(m){throw m instanceof qn&&(m.isReason(Nt.Reserved)||m.isReason(Nt.TooLarge))?Xe.invalidHandle(m):m}n+=st;let c=Ct.u16(t.getUint16(n));n+=st;let l=Ct.u16(t.getUint16(n));n+=st;let u=Pi.fromRtpTicks(t.getUint32(n));n+=tc;let h=new en;if(o){if(t.byteLength-n<st)throw Xe.missingExtWords();let m=t.getUint16(n);n+=st;let g=4*(m+1)-ti;if(n+g>t.byteLength)throw Xe.headerOverrun();let k=new DataView(t.buffer,t.byteOffset+n,g),T=en.fromBinary(k),S=O(T,2),L=S[0],y=S[1];h=L,n+=y}return[new i({marker:a,trackHandle:d,sequence:c,frameNumber:l,timestamp:u,extensions:h}),n]}toJSON(){return{marker:this.marker,trackHandle:this.trackHandle,sequence:this.sequence.value,frameNumber:this.frameNumber.value,timestamp:this.timestamp.asTicks(),extensions:this.extensions.toJSON()}}},Q;(function(i){i[i.Start=0]="Start",i[i.Inter=1]="Inter",i[i.Final=2]="Final",i[i.Single=3]="Single"})(Q||(Q={}));var ji=class i extends on{constructor(e,t){super(),this.header=e,this.payload=t}toBinaryLengthBytes(){return this.header.toBinaryLengthBytes()+this.payload.byteLength}toBinaryInto(e){let t=0,n=this.header.toBinaryInto(e);if(t+=n,e.byteLength-t<this.payload.byteLength)throw Fi.tooSmallForPayload();for(let s=0;s<this.payload.length;s+=1)e.setUint8(t,this.payload[s]),t+=ie;let 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){let t=Na(e),n=Vn.fromBinary(t),r=O(n,2),s=r[0],a=r[1],o=t.buffer.slice(t.byteOffset+a,t.byteOffset+t.byteLength);return[new i(s,new Uint8Array(o)),t.byteLength]}toJSON(){return{header:this.header.toJSON(),payload:this.payload}}},Nr=_e(ue.DataTracks),At=class i extends we{constructor(e,t,n,r){super(19,"Frame ".concat(n," dropped: ").concat(e),r),this.name="DataTrackDepacketizerDropError",this.reason=t,this.reasonName=xt[t],this.frameNumber=n}static interrupted(e,t){return new i("Interrupted by the start of a new frame ".concat(t),xt.Interrupted,e)}static unknownFrame(e){return new i("Initial packet was never received.",xt.UnknownFrame,e)}static bufferFull(e){return new i("Reorder buffer is full.",xt.BufferFull,e)}static incomplete(e,t,n){return new i("Not all packets received before final packet. Received ".concat(t," packets, expected ").concat(n," packets."),xt.Incomplete,e)}},xt;(function(i){i[i.Interrupted=0]="Interrupted",i[i.UnknownFrame=1]="UnknownFrame",i[i.BufferFull=2]="BufferFull",i[i.Incomplete=3]="Incomplete"})(xt||(xt={}));var Vi=class i{constructor(){this.partials=new Map}push(e,t){switch(e.header.marker){case Q.Single:return this.frameFromSingle(e,t);case Q.Start:return this.beginPartial(e,t);case Q.Inter:case Q.Final:return this.pushToPartial(e)}}reset(){this.partials.clear()}peekOldestPartialFrameNumber(){let e=this.partials.keys().next();return e.done?null:e.value}frameFromSingle(e,t){var n;if(e.header.marker!==Q.Single)throw new Error("Depacketizer.frameFromSingle: packet.header.marker was not FrameMarker.Single, found ".concat(e.header.marker,"."));let r=(n=t?.maxPartialFrames)!==null&&n!==void 0?n:1;if(this.partials.size>=r){let s=this.peekOldestPartialFrameNumber();if(typeof s!="number")throw new Error("Depacketizer.frameFromSingle: no oldest frame number found, but partials.size is ".concat(this.partials.size,"."));if(this.partials.delete(s),t?.throwOnInterruption)throw At.interrupted(s,e.header.frameNumber.value);Nr.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 n;if(e.header.marker!==Q.Start)throw new Error("Depacketizer.beginPartial: packet.header.marker was not FrameMarker.Start, found ".concat(e.header.marker,"."));let r=e.header.sequence,s=e.header.frameNumber.value,a={startSequence:r,extensions:e.header.extensions,payloads:new Map([[r.value,e.payload]])},o=(n=t?.maxPartialFrames)!==null&&n!==void 0?n:1;for(;this.partials.size>=o;){let d=this.peekOldestPartialFrameNumber();if(typeof d!="number")break;if(this.partials.delete(d),t?.throwOnInterruption)throw At.interrupted(d,s);Nr.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!==Q.Inter&&e.header.marker!==Q.Final)throw new Error("Depacketizer.pushToPartial: packet.header.marker was not FrameMarker.Inter or FrameMarker.Final, found ".concat(e.header.marker,"."));let t=e.header.frameNumber.value,n=this.partials.get(t);if(!n)throw this.partials.delete(t),At.unknownFrame(t);if(n.payloads.size>=i.MAX_BUFFER_PACKETS)throw this.partials.delete(t),At.bufferFull(t);return n.payloads.has(e.header.sequence.value)&&Nr.warn("Data track frame ".concat(t," received duplicate packet for sequence ").concat(e.header.sequence.value,", so replacing with newly received packet.")),n.payloads.set(e.header.sequence.value,e.payload),e.header.marker===Q.Final?this.finalize(t,n,e.header.sequence.value):null}finalize(e,t,n){let r=t.payloads.size,s=0;for(let c of t.payloads.values())s+=c.length;let a=new Uint8Array(s),o=t.startSequence.clone(),d=0;for(;;){let c=t.payloads.get(o.value);if(!c)break;t.payloads.delete(o.value);let 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!=n){o.increment();continue}return this.partials.delete(e),{payload:a,extensions:t.extensions}}throw this.partials.delete(e),At.incomplete(e,r,n-t.startSequence.value+1)}};Vi.MAX_BUFFER_PACKETS=128;var Dt;(function(i){i[i.Unpublished=0]="Unpublished",i[i.Timeout=1]="Timeout",i[i.Disconnected=2]="Disconnected",i[i.Cancelled=4]="Cancelled"})(Dt||(Dt={}));var De=class i extends we{constructor(e,t,n){super(22,e,n),this.name="DataTrackSubscribeError",this.reason=t,this.reasonName=Dt[t]}static unpublished(){return new i("The track has been unpublished and is no longer available",Dt.Unpublished)}static timeout(){return new i("Request to subscribe to data track timed-out",Dt.Timeout)}static disconnected(){return new i("Cannot subscribe to data track when disconnected",Dt.Disconnected)}static cancelled(){return new i("Subscription to data track cancelled by caller",Dt.Cancelled)}},Ur=_e(ue.DataTracks),Ns=class{constructor(e){var t,n;let r=e.e2eeManager!==null;if(e.info.usesE2ee!==r)throw new Error("IncomingDataTrackPipeline: DataTrackInfo.usesE2ee must match presence of decryptionProvider");let s=new Vi;this.publisherIdentity=e.publisherIdentity,this.e2eeManager=(t=e.e2eeManager)!==null&&t!==void 0?t:null,this.depacketizer=s,this.options=(n=e.pipelineOptions)!==null&&n!==void 0?n:{}}updateE2eeManager(e){this.e2eeManager=e}setOptions(e){this.options=e}processPacket(e){return p(this,void 0,void 0,function*(){let t=this.depacketize(e);if(!t)return null;let n=yield this.decryptIfNeeded(t);return n||null})}depacketize(e){let t;try{t=this.depacketizer.push(e,{throwOnInterruption:!1,maxPartialFrames:this.options.maxPartialFrames})}catch(n){return Ur.warn("Data frame depacketize error: ".concat(n)),null}return t}decryptIfNeeded(e){return p(this,void 0,void 0,function*(){var t,n;let r=this.e2eeManager;if(!r)return e;let s=(n=(t=e.extensions)===null||t===void 0?void 0:t.e2ee)!==null&&n!==void 0?n:null;if(!s)return Ur.error("Missing E2EE meta"),null;let a;try{a=yield r.handleEncryptedData(e.payload,s.iv,this.publisherIdentity,s.keyIndex)}catch(o){return Ur.error("Error decrypting packet: ".concat(o)),null}return e.payload=a.payload,e})}},he=_e(ue.DataTracks),Pp=1e4,Ip=16,Us=class extends Ee.EventEmitter{constructor(e){var t;super(),this.descriptors=new Map,this.subscriptionHandles=new Map,this.e2eeManager=(t=e?.e2eeManager)!==null&&t!==void 0?t:null}updateE2eeManager(e){this.e2eeManager=e;for(let t of this.descriptors.values())t.subscription.type==="active"&&t.subscription.pipeline.updateE2eeManager(e)}setPipelineOptions(e,t){let n=this.descriptors.get(e);if(!n){he.warn("Unknown track ".concat(e,", cannot set pipeline options."));return}n.pipelineOptions=t,n.subscription.type==="active"&&n.subscription.pipeline.setOptions(t)}openSubscriptionStream(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:Ip,r=null,s=new ce,a=()=>{t?.removeEventListener("abort",d)},o=()=>{if(a(),!r){he.warn("ReadableStream subscribed to ".concat(e," was not started."));return}let l=this.descriptors.get(e);if(!l){he.warn("Unknown track ".concat(e,", skipping cancel..."));return}if(l.subscription.type!=="active"){he.warn("Subscription for track ".concat(e," is not active, skipping cancel..."));return}l.subscription.streamControllers.delete(r),l.subscription.streamControllers.size===0&&this.unSubscribeRequest(l.info.sid)},d=()=>{var l;if(!r)return;let u=this.descriptors.get(e);u?.subscription.type==="active"&&u.subscription.streamControllers.delete(r),r.error(De.cancelled()),(l=s.reject)===null||l===void 0||l.call(s,De.cancelled()),o()};return[new ReadableStream({start:l=>{r=l,this.subscribeRequest(e,t).then(()=>p(this,void 0,void 0,function*(){var u,h,m;let f=this.descriptors.get(e);if(!f){he.error("Unknown track ".concat(e));let g=De.disconnected();l.error(g),(u=s.reject)===null||u===void 0||u.call(s,g);return}if(f.subscription.type!=="active"){he.error("Subscription for track ".concat(e," is not active"));let g=De.disconnected();l.error(g),(h=s.reject)===null||h===void 0||h.call(s,g);return}if(t?.aborted){d();return}t?.addEventListener("abort",d),f.subscription.streamControllers.set(l,a),(m=s.resolve)===null||m===void 0||m.call(s)})).catch(u=>{var h;l.error(u),(h=s.reject)===null||h===void 0||h.call(s,u)})},cancel:()=>{o()}},new CountQueuingStrategy({highWaterMark:n})),s.promise]}subscribeRequest(e,t){return p(this,void 0,void 0,function*(){let n=this.descriptors.get(e);if(!n)throw new Error("Cannot subscribe to unknown track");let r=(s,a,o)=>p(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));let d=nl([a,o].filter(u=>typeof u<"u")),c=new ce;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)});let l=()=>{var u;if(s.subscription.type==="pending"){if(s.subscription.pendingRequestCount-=1,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,De.cancelled())}};d.aborted&&l(),d.addEventListener("abort",l),yield c.promise,d.removeEventListener("abort",l)});switch(n.subscription.type){case"none":{n.subscription={type:"pending",completionFuture:new ce,pendingRequestCount:1,cancel:()=>{var a,o;let d=n.subscription;n.subscription={type:"none"},this.emit("sfuUpdateSubscription",{sid:e,subscribe:!1}),d.type==="pending"&&((o=(a=d.completionFuture).reject)===null||o===void 0||o.call(a,s.aborted?De.timeout():De.cancelled()))}},this.emit("sfuUpdateSubscription",{sid:e,subscribe:!0});let s=il(Pp);yield r(n,t,s);return}case"pending":{n.subscription.pendingRequestCount+=1,yield r(n,t);return}case"active":return}})}querySubscribed(){return p(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;let n=this.descriptors.get(e);if(!n)throw new Error("Cannot subscribe to unknown track");if(n.subscription.type!=="active"){he.warn("Unexpected descriptor state in unSubscribeRequest, expected active, found ".concat((t=n.subscription)===null||t===void 0?void 0:t.type));return}this.closeStreamControllers(n.subscription.streamControllers,e);let r=n.subscription;n.subscription={type:"none"},this.subscriptionHandles.delete(r.subcriptionHandle),this.emit("sfuUpdateSubscription",{sid:e,subscribe:!1})}closeStreamControllers(e,t){for(let r of e){var n=O(r,2);let s=n[0],a=n[1];a();try{s.close()}catch(o){he.warn("Failed to close readable stream for track ".concat(t,": ").concat(o))}}}receiveSfuPublicationUpdates(e){return p(this,void 0,void 0,function*(){if(e.size===0)return;let t=new Map;for(let s of e.entries()){var n=O(s,2);let a=n[0],o=n[1],d=new Set;for(let c of o)d.add(c.sid),!this.descriptors.has(c.sid)&&(yield this.handleTrackPublished(a,c));t.set(a,d)}for(let s of t.entries()){var r=O(s,2);let a=r[0],o=r[1],c=Array.from(this.descriptors.entries()).filter(l=>{let u=O(l,2);return u[0],u[1].publisherIdentity===a}).map(l=>O(l,1)[0]).filter(l=>!o.has(l));for(let l of c)this.handleTrackUnpublished(l)}})}queryPublications(){return p(this,void 0,void 0,function*(){return Array.from(this.descriptors.values()).map(e=>e.info)})}handleTrackPublished(e,t){return p(this,void 0,void 0,function*(){if(this.descriptors.has(t.sid)){he.error("Existing descriptor for track ".concat(t.sid));return}let n={info:t,publisherIdentity:e,subscription:{type:"none"},pipelineOptions:{}};this.descriptors.set(n.info.sid,n);let r=new qi(n.info,this,{publisherIdentity:e});this.emit("trackPublished",{track:r})})}handleTrackUnpublished(e){let t=this.descriptors.get(e);if(!t){he.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(let n of e.entries()){var t=O(n,2);let r=t[0],s=t[1];this.registerSubscriberHandle(r,s)}}registerSubscriberHandle(e,t){var n,r;let s=this.descriptors.get(t);if(!s){he.error("Unknown track ".concat(t));return}switch(s.subscription.type){case"none":{he.warn("No subscription for ".concat(t));return}case"active":{s.subscription.subcriptionHandle=e,this.subscriptionHandles.set(e,t);return}case"pending":{let a=new Ns({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=(n=o.completionFuture).resolve)===null||r===void 0||r.call(n)}}}packetReceived(e){return p(this,void 0,void 0,function*(){let t;try{var n=ji.fromBinary(e),r=O(n,1);t=r[0]}catch(d){he.error("Failed to deserialize packet: ".concat(d));return}let s=this.subscriptionHandles.get(t.header.trackHandle);if(!s){he.warn("Unknown subscriber handle ".concat(t.header.trackHandle));return}let a=this.descriptors.get(s);if(!a){he.error("Missing descriptor for track ".concat(s));return}if(a.subscription.type!=="active"){he.warn("Received packet for track ".concat(s," without active subscription"));return}let o=yield a.subscription.pipeline.processPacket(t);if(o)for(let d of a.subscription.streamControllers.keys()){if(d.desiredSize!==null&&d.desiredSize<=0){he.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}let c=rl.lossyIntoFrame(o);d.enqueue(c)}})}resendSubscriptionUpdates(){for(let t of this.descriptors){var e=O(t,2);let n=e[0];e[1].subscription.type!=="none"&&this.emit("sfuUpdateSubscription",{sid:n,subscribe:!0})}}handleRemoteParticipantDisconnected(e){var t,n;for(let r of this.descriptors.values())if(r.publisherIdentity===e)switch(r.subscription.type){case"none":break;case"pending":(n=(t=r.subscription.completionFuture).reject)===null||n===void 0||n.call(t,De.disconnected());break;case"active":this.unSubscribeRequest(r.info.sid);break}}reset(){var e,t;for(let n of this.descriptors.values())this.emit("trackUnpublished",{sid:n.info.sid,publisherIdentity:n.publisherIdentity}),n.subscription.type==="pending"&&((t=(e=n.subscription.completionFuture).reject)===null||t===void 0||t.call(e,De.disconnected())),n.subscription.type==="active"&&this.closeStreamControllers(n.subscription.streamControllers,n.info.sid);this.descriptors.clear(),this.subscriptionHandles.clear()}},Hi=class i extends we{constructor(e,t,n){super(19,e,n),this.name="DataTrackPacketizerError",this.reason=t,this.reasonName=Gi[t]}static mtuTooShort(){return new i("MTU is too short to send frame",Gi.MtuTooShort)}},Gi;(function(i){i[i.MtuTooShort=0]="MtuTooShort"})(Gi||(Gi={}));var Fs=class i{constructor(e,t){this.sequence=Ct.u16(0),this.frameNumber=Ct.u16(0),this.clock=bs.rtpStartingNow(Pi.rtpRandom()),this.handle=e,this.mtuSizeBytes=t}static computeFrameMarker(e,t){return t<=1?Q.Single:e===0?Q.Start:e===t-1?Q.Final:Q.Inter}*packetize(e,t){var n;let r=this.frameNumber.getThenIncrement(),s={marker:Q.Inter,trackHandle:this.handle,sequence:Ct.u16(0),frameNumber:r,timestamp:(n=t?.now)!==null&&n!==void 0?n:this.clock.now(),extensions:e.extensions},a=new Vn(s).toBinaryLengthBytes();if(a>=this.mtuSizeBytes)throw Hi.mtuTooShort();let 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;let h=this.sequence.getThenIncrement(),m=new Vn(Object.assign(Object.assign({},s),{marker:i.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 ji(m,g)}}},Oe;(function(i){i[i.NotAllowed=0]="NotAllowed",i[i.DuplicateName=1]="DuplicateName",i[i.Timeout=2]="Timeout",i[i.LimitReached=3]="LimitReached",i[i.Disconnected=4]="Disconnected",i[i.Cancelled=5]="Cancelled",i[i.InvalidName=6]="InvalidName",i[i.Unknown=7]="Unknown"})(Oe||(Oe={}));var Ae=class i extends we{constructor(e,t,n){super(21,e,n),this.name="DataTrackPublishError",this.reason=t,this.reasonName=Oe[t],this.rawMessage=n?.rawMessage}static notAllowed(e){return new i("Data track publishing unauthorized",Oe.NotAllowed,{rawMessage:e})}static duplicateName(e){return new i("Track name already taken",Oe.DuplicateName,{rawMessage:e})}static invalidName(e){return new i("Track name is invalid",Oe.InvalidName,{rawMessage:e})}static timeout(){return new i("Publish data track timed-out. Does the LiveKit server support data tracks?",Oe.Timeout)}static limitReached(e){return new i("Data track publication limit reached",Oe.LimitReached,{rawMessage:e})}static unknown(e,t){return new i("Received RequestResponse for publishDataTrack, but reason was unrecognised (".concat(e,", ").concat(t,")"),Oe.Unknown)}static disconnected(){return new i("Room disconnected",Oe.Disconnected)}static cancelled(){return new i("Publish data track cancelled by caller",Oe.Cancelled)}},Rn;(function(i){i[i.TrackUnpublished=0]="TrackUnpublished",i[i.Dropped=1]="Dropped"})(Rn||(Rn={}));var Ot=class i extends we{constructor(e,t,n){super(22,e,n),this.name="DataTrackPushFrameError",this.reason=t,this.reasonName=Rn[t]}static trackUnpublished(){return new i("Track is no longer published",Rn.TrackUnpublished)}static dropped(e){return new i("Frame was dropped",Rn.Dropped,{cause:e})}},Pn;(function(i){i[i.Packetizer=0]="Packetizer",i[i.Encryption=1]="Encryption"})(Pn||(Pn={}));var Ki=class i extends we{constructor(e,t,n){super(21,e,n),this.name="DataTrackOutgoingPipelineError",this.reason=t,this.reasonName=Pn[t]}static packetizer(e){return new i("Error packetizing frame",Pn.Packetizer,{cause:e})}static encryption(e){return new i("Error encrypting frame",Pn.Encryption,{cause:e})}},Wi=class i{constructor(e,t){this.trackSymbol=sl,this.isLocal=!0,this.typeSymbol=al,this.handle=null,this.log=F,this.flushedFuture=new ce,this.isFlushed=!0,this.handleManagerReset=()=>{var n,r;(r=(n=this.flushedFuture).resolve)===null||r===void 0||r.call(n),this.manager.off("packetsFlushedChange",this.handleManagerPacketsFlushedChange),this.manager.off("reset",this.handleManagerReset)},this.handleManagerPacketsFlushedChange=n=>{var r,s;this.isFlushed=n.isFlushed,n.isFlushed&&((s=(r=this.flushedFuture).resolve)===null||s===void 0||s.call(r),this.flushedFuture=new ce)},this.options=e,this.manager=t,this.log=_e(ue.DataTracks),this.manager.on("packetsFlushedChange",this.handleManagerPacketsFlushedChange),this.manager.on("reset",this.handleManagerReset)}static withExplicitHandle(e,t,n){let r=new i(e,t);return r.handle=n,r}get info(){let e=this.descriptor;if(e?.type==="active")return e.info}get descriptor(){return this.handle?this.manager.getDescriptor(this.handle):null}publish(e){return p(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 Ot.trackUnpublished();let t=rl.from(e);try{return this.manager.tryProcessAndSend(this.handle,t)}catch(n){throw n}}flush(){return p(this,void 0,void 0,function*(){if(!this.isFlushed)return this.flushedFuture.promise})}unpublish(){return p(this,void 0,void 0,function*(){if(!this.handle){F.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}})}},zi=class i{constructor(e){this.e2eeManager=e.e2eeManager,this.packetizer=new Fs(e.info.pubHandle,i.TRANSPORT_MTU_BYTES)}updateE2eeManager(e){this.e2eeManager=e}processFrame(e){return Ih(this,arguments,function*(){let n=yield rn(this.encryptIfNeeded(e));try{yield rn(yield*Mh(Be(this.packetizer.packetize(n))))}catch(r){throw r instanceof Hi?Ki.packetizer(r):r}})}encryptIfNeeded(e){return p(this,void 0,void 0,function*(){if(!this.e2eeManager)return e;let t;try{t=yield this.e2eeManager.encryptData(e.payload)}catch(n){throw Ki.encryption(n)}return e.payload=t.payload,e.extensions.e2ee=new jt(t.keyIndex,t.iv),e})}};zi.TRANSPORT_MTU_BYTES=16e3;var $e=_e(ue.DataTracks),uc={pending(){return{type:"pending",completionFuture:new ce}},active(i,e){return{type:"active",info:i,publishState:"published",pipeline:new zi({info:i,e2eeManager:e}),unpublishingFuture:new ce}}},Mp=1e4,Bs=class i extends Ee.EventEmitter{constructor(e){var t;super(),this.handleAllocator=new ks,this.descriptors=new Map,this.inFlightPacketCounter=new Map,this.e2eeManager=(t=e?.e2eeManager)!==null&&t!==void 0?t:null}static withDescriptors(e){let t=new i;return t.descriptors=e,t}updateE2eeManager(e){this.e2eeManager=e;for(let t of this.descriptors.values())t.type==="active"&&t.pipeline.updateE2eeManager(e)}getDescriptor(e){var t;return(t=this.descriptors.get(e))!==null&&t!==void 0?t:null}tryProcessAndSend(e,t){return p(this,void 0,void 0,function*(){var n,r,s,a,o;let d=this.getDescriptor(e);if(d?.type!=="active"||d.publishState==="unpublished")throw Ot.trackUnpublished();if(d.publishState==="republishing")throw Ot.dropped("Data track republishing");try{try{for(var c=!0,l=Be(d.pipeline.processFrame(t)),u;u=yield l.next(),n=u.done,!n;c=!0){a=u.value,c=!1;let h=a,m=(o=this.inFlightPacketCounter.get(e))!==null&&o!==void 0?o:0;this.inFlightPacketCounter.set(e,m+1),m===0&&this.emit("packetsFlushedChange",{handle:e,isFlushed:!1}),this.emit("packetAvailable",{handle:e,bytes:h.toBinary()})}}catch(h){r={error:h}}finally{try{!c&&!n&&(s=l.return)&&(yield s.call(l))}finally{if(r)throw r.error}}}catch(h){throw Ot.dropped(h)}})}handlePacketSendComplete(e){var t;let r=((t=this.inFlightPacketCounter.get(e))!==null&&t!==void 0?t:0)-1;r<0&&($e.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 p(this,void 0,void 0,function*(){let n=this.handleAllocator.get();if(!n)throw Ae.limitReached();let r=il(Mp),s=t?nl([t,r]):r;if(this.descriptors.has(n))throw new Error("Descriptor for handle already exists");let a=uc.pending();this.descriptors.set(n,a);let o=()=>{var d,c;let l=this.descriptors.get(n);if(!l){$e.warn("No descriptor for ".concat(n));return}this.descriptors.delete(n),this.emit("sfuUnpublishRequest",{handle:n}),l.type==="pending"&&((c=(d=l.completionFuture).reject)===null||c===void 0||c.call(d,r.aborted?Ae.timeout():Ae.cancelled()))};return s.aborted?(o(),a.completionFuture.promise.then(()=>n)):(s.addEventListener("abort",o),this.emit("sfuPublishRequest",{handle:n,name:e.name,usesE2ee:this.e2eeManager!==null}),yield a.completionFuture.promise,s.removeEventListener("abort",o),this.emit("trackPublished",{track:Wi.withExplicitHandle(e,this,n)}),n)})}queryPublished(){return Array.from(this.descriptors.values()).filter(t=>t.type==="active").map(t=>t.info)}unpublishRequest(e){return p(this,void 0,void 0,function*(){let t=this.descriptors.get(e);if(!t){$e.warn("No descriptor for ".concat(e));return}if(t.type!=="active"){$e.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 n,r,s,a;let o=this.descriptors.get(e);if(!o){$e.warn("No descriptor for ".concat(e));return}switch(this.descriptors.delete(e),o.type){case"pending":{if(t.type==="ok"){let d=t.data,c=d.usesE2ee?this.e2eeManager:null;this.descriptors.set(d.pubHandle,uc.active(d,c)),(r=(n=o.completionFuture).resolve)===null||r===void 0||r.call(n)}else(a=(s=o.completionFuture).reject)===null||a===void 0||a.call(s,t.error);return}case"active":{if(o.publishState!=="republishing"){$e.warn("Track ".concat(e," already active"));return}if(t.type==="error"){$e.warn("Republish failed for track ".concat(e));return}$e.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,n;let r=this.descriptors.get(e);if(!r){$e.warn("No descriptor for ".concat(e));return}if(this.descriptors.delete(e),r.type!=="active"){$e.warn("Track ".concat(e," not active"));return}r.publishState="unpublished",(n=(t=r.unpublishingFuture).resolve)===null||n===void 0||n.call(t)}sfuWillRepublishTracks(){var e,t;for(let r of this.descriptors.entries()){var n=O(r,2);let s=n[0],a=n[1];switch(a.type){case"pending":this.descriptors.delete(s),(t=(e=a.completionFuture).reject)===null||t===void 0||t.call(e,Ae.disconnected());break;case"active":a.publishState="republishing",this.emit("sfuPublishRequest",{handle:a.info.pubHandle,name:a.info.name,usesE2ee:a.info.usesE2ee})}}}reset(){return p(this,void 0,void 0,function*(){var e,t,n,r;this.handleAllocator.reset();for(let s of this.descriptors.values())switch(s.type){case"pending":(t=(e=s.completionFuture).reject)===null||t===void 0||t.call(e,Ae.disconnected());break;case"active":(r=(n=s.unpublishingFuture).resolve)===null||r===void 0||r.call(n),yield this.unpublishRequest(s.info.pubHandle);break}this.descriptors.clear(),this.inFlightPacketCounter.clear(),this.emit("reset")})}},G=class i extends Error{constructor(e,t,n,r){super(t),this.code=e,this.message=hc(t,i.MAX_MESSAGE_BYTES),this.data=n?hc(n,i.MAX_DATA_BYTES):void 0,typeof r?.cause<"u"&&(this.cause=r?.cause)}static fromProto(e){return new i(e.code,e.message,e.data)}toProto(){return new Fc({code:this.code,message:this.message,data:this.data})}static builtIn(e,t,n){return new i(i.ErrorCode[e],i.ErrorMessage[e],t,n)}};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"};var ol=15360,cl="lk.rpc_request",dl="lk.rpc_response",me;(function(i){i.RPC_REQUEST_ID="lk.rpc_request_id",i.RPC_REQUEST_METHOD="lk.rpc_request_method",i.RPC_REQUEST_RESPONSE_TIMEOUT_MS="lk.rpc_request_response_timeout_ms",i.RPC_REQUEST_VERSION="lk.rpc_request_version"})(me||(me={}));var Ap=1,ll=2;function ja(i){return new TextEncoder().encode(i).length}function hc(i,e){if(ja(i)<=e)return i;let t=0,n=i.length,r=new TextEncoder;for(;t<n;){let s=Math.floor((t+n+1)/2);r.encode(i.slice(0,s)).length<=e?t=s:n=s-1}return i.slice(0,t)}var qs=class extends Ee.EventEmitter{constructor(e,t,n,r){super(),this.pendingAcks=new Map,this.pendingResponses=new Map,this.log=e,this.outgoingDataStreamManager=t,this.getRemoteParticipantClientProtocol=n,this.getServerVersion=r}performRpc(e){return p(this,arguments,void 0,function(t){var n=this;let r=t.destinationIdentity,s=t.method,a=t.payload,o=t.responseTimeout,d=o===void 0?15e3:o;return(function*(){let u=n.getRemoteParticipantClientProtocol(r);if(ja(a)>ol&&u<Si)throw G.builtIn("REQUEST_PAYLOAD_TOO_LARGE");let m=n.getServerVersion();if(m&&tt(m,"1.8.0")<0)throw G.builtIn("UNSUPPORTED_SERVER");let f=Math.max(d,8e3),g=crypto.randomUUID(),k=new ce,T=null,S=setTimeout(()=>{var y;n.pendingAcks.delete(g),(y=k.reject)===null||y===void 0||y.call(k,G.builtIn("CONNECTION_TIMEOUT")),n.pendingResponses.delete(g),T!==null&&clearTimeout(T)},7e3);n.pendingAcks.set(g,{resolve:()=>{clearTimeout(S)},participantIdentity:r}),n.pendingResponses.set(g,{completionFuture:k,participantIdentity:r}),yield n.publishRpcRequest(r,g,s,a,f,u),T=setTimeout(()=>{var y;n.pendingResponses.delete(g),(y=k.reject)===null||y===void 0||y.call(k,G.builtIn("RESPONSE_TIMEOUT"))},d);let L=k.promise.finally(()=>{clearTimeout(T),n.pendingAcks.has(g)&&(n.log.warn("RPC response received before ack",g),n.pendingAcks.delete(g),clearTimeout(S))});return[g,L]})()})}publishRpcRequest(e,t,n,r,s,a){return p(this,void 0,void 0,function*(){if(a>=Si){let o=yield this.outgoingDataStreamManager.streamText({topic:cl,destinationIdentities:[e],attributes:{[me.RPC_REQUEST_ID]:t,[me.RPC_REQUEST_METHOD]:n,[me.RPC_REQUEST_RESPONSE_TIMEOUT_MS]:"".concat(s),[me.RPC_REQUEST_VERSION]:"".concat(ll)}});yield o.write(r),yield o.close();return}this.emit("sendDataPacket",{packet:new ge({destinationIdentities:[e],kind:Ze.RELIABLE,value:{case:"rpcRequest",value:new va({id:t,method:n,payload:r,responseTimeoutMs:s,version:Ap})}})})})}handleIncomingDataStream(e,t,n){return p(this,void 0,void 0,function*(){let r=n[me.RPC_REQUEST_ID];if(!r){this.log.warn("RPC data stream malformed: ".concat(me.RPC_REQUEST_ID," not set."));return}let 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 n,r;let s=this.pendingResponses.get(e);s?((r=(n=s.completionFuture).resolve)===null||r===void 0||r.call(n,t),this.pendingResponses.delete(e)):this.log.error("Response received for unexpected RPC request",e)}handleIncomingRpcResponseFailure(e,t){var n,r;let s=this.pendingResponses.get(e);s?((r=(n=s.completionFuture).reject)===null||r===void 0||r.call(n,t),this.pendingResponses.delete(e)):this.log.error("Response received for unexpected RPC request",e)}handleIncomingRpcAck(e){let t=this.pendingAcks.get(e);t?(t.resolve(),this.pendingAcks.delete(e)):this.log.error("Ack received for unexpected RPC request: ".concat(e))}handleParticipantDisconnected(e){var t;for(let a of this.pendingAcks){var n=O(a,2);let o=n[0];n[1].participantIdentity===e&&this.pendingAcks.delete(o)}for(let a of this.pendingResponses){var r=O(a,2);let o=r[0];var s=r[1];let 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))}}},js=class extends Ee.EventEmitter{constructor(e,t,n){super(),this.rpcHandlers=new Map,this.log=e,this.outgoingDataStreamManager=t,this.getRemoteParticipantClientProtocol=n}registerRpcMethod(e,t){if(this.rpcHandlers.has(e))throw Error("RPC handler already registered for method ".concat(e,", unregisterRpcMethod before trying to register again"));this.rpcHandlers.set(e,t)}unregisterRpcMethod(e){this.rpcHandlers.delete(e)}handleIncomingRpcRequest(e,t){return p(this,void 0,void 0,function*(){var n;if(this.publishRpcAck(e,t.id),t.version!==1){this.publishRpcResponsePacket(e,t.id,null,G.builtIn("UNSUPPORTED_VERSION"));return}let 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((n=a?.message)!==null&&n!==void 0?n:a),{cause:a})),this.publishRpcResponsePacket(e,t.id,null,o);return}yield this.publishRpcResponse(e,t.id,s??"")})}handleIncomingDataStream(e,t,n){return p(this,void 0,void 0,function*(){let r=n[me.RPC_REQUEST_ID],s=n[me.RPC_REQUEST_METHOD],a=parseInt(n[me.RPC_REQUEST_RESPONSE_TIMEOUT_MS],10),o=parseInt(n[me.RPC_REQUEST_VERSION],10);if(!r||!s||Number.isNaN(a)||Number.isNaN(o)){this.log.warn("RPC data stream malformed: ".concat(me.RPC_REQUEST_ID," / ").concat(me.RPC_REQUEST_METHOD," / ").concat(me.RPC_REQUEST_RESPONSE_TIMEOUT_MS," / ").concat(me.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!==ll){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}let 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 ge({destinationIdentities:[e],kind:Ze.RELIABLE,value:{case:"rpcAck",value:new er({requestId:t})}})})}publishRpcResponsePacket(e,t,n,r){this.emit("sendDataPacket",{packet:new ge({destinationIdentities:[e],kind:Ze.RELIABLE,value:{case:"rpcResponse",value:new ya({requestId:t,value:r?{case:"error",value:r.toProto()}:{case:"payload",value:n??""}})}})})}publishRpcResponse(e,t,n){return p(this,void 0,void 0,function*(){if(this.getRemoteParticipantClientProtocol(e)>=Si){let a=yield this.outgoingDataStreamManager.streamText({topic:dl,destinationIdentities:[e],attributes:{[me.RPC_REQUEST_ID]:t}});yield a.write(n),yield a.close();return}if(ja(n)>ol){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,n,null)})}},Vs=class extends Ri{constructor(e,t,n,r,s,a){super(e,t,_.Kind.Audio,n,a),this.monitorReceiver=()=>p(this,void 0,void 0,function*(){if(!this.receiver){this._currentBitrate=0;return}let o=yield this.getReceiverStats();o&&this.prevStats&&this.receiver&&(this._currentBitrate=ar(o,this.prevStats)),this.prevStats=o}),this.audioContext=r,this.webAudioPluginNodes=[],s&&(this.sinkId=s.deviceId)}setVolume(e){var t;for(let n of this.attachedElements)this.audioContext?(t=this.gainNode)===null||t===void 0||t.gain.setTargetAtTime(e,0,.1):n.volume=e;He()&&this._mediaStreamTrack._setVolume(e),this.elementVolume=e}getVolume(){if(this.elementVolume)return this.elementVolume;if(He())return 1;let e=0;return this.attachedElements.forEach(t=>{t.volume>e&&(e=t.volume)}),e}setSinkId(e){return p(this,void 0,void 0,function*(){this.sinkId=e,yield Promise.all(this.attachedElements.map(t=>{if(us(t))return t.setSinkId(e)}))})}attach(e){let t=this.attachedElements.length===0;return e?super.attach(e):e=super.attach(),this.sinkId&&us(e)&&e.setSinkId(this.sinkId).catch(n=>{this.log.error("Failed to set sink id on remote audio track",n,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 n=this.sourceNode;this.webAudioPluginNodes.forEach(r=>{n.connect(r),n=r}),this.gainNode=e.createGain(),n.connect(this.gainNode),this.gainNode.connect(e.destination),this.elementVolume&&this.gainNode.gain.setTargetAtTime(this.elementVolume,0,.1),e.state!=="running"&&e.resume().then(()=>{e.state!=="running"&&this.emit(P.AudioPlaybackFailed,new Error("Audio Context couldn't be started automatically"))}).catch(r=>{this.emit(P.AudioPlaybackFailed,r)})}disconnectWebAudio(){var e,t;(e=this.gainNode)===null||e===void 0||e.disconnect(),(t=this.sourceNode)===null||t===void 0||t.disconnect(),this.gainNode=void 0,this.sourceNode=void 0}getReceiverStats(){return p(this,void 0,void 0,function*(){if(!this.receiver||!this.receiver.getStats)return;let e=yield this.receiver.getStats(),t;return e.forEach(n=>{n.type==="inbound-rtp"&&(t={type:"audio",streamId:n.id,timestamp:n.timestamp,jitter:n.jitter,bytesReceived:n.bytesReceived,concealedSamples:n.concealedSamples,concealmentEvents:n.concealmentEvents,silentConcealedSamples:n.silentConcealedSamples,silentConcealmentEvents:n.silentConcealmentEvents,totalAudioEnergy:n.totalAudioEnergy,totalSamplesDuration:n.totalSamplesDuration})}),t})}},Ne=class extends Ee.EventEmitter{constructor(e,t,n,r){var s;super(),this.metadataMuted=!1,this.encryption=$.NONE,this.log=F,this.handleMuted=()=>{this.emit(P.Muted)},this.handleUnmuted=()=>{this.emit(P.Unmuted)},this.log=_e((s=r?.loggerName)!==null&&s!==void 0?s:ue.Publication),this.loggerContextCb=this.loggerContextCb,this.setMaxListeners(100),this.kind=e,this.trackSid=t,this.trackName=n,this.source=_.Source.Unknown}setTrack(e){this.track&&(this.track.off(P.Muted,this.handleMuted),this.track.off(P.Unmuted,this.handleUnmuted)),this.track=e,e&&(e.on(P.Muted,this.handleMuted),e.on(P.Unmuted,this.handleUnmuted))}get logContext(){var e;return Object.assign(Object.assign({},(e=this.loggerContextCb)===null||e===void 0?void 0:e.call(this)),j(this))}get isMuted(){return this.metadataMuted}get isEnabled(){return!0}get isSubscribed(){return this.track!==void 0}get isEncrypted(){return this.encryption!==$.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=_.sourceFromProto(e.source),this.mimeType=e.mimeType,this.kind===_.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(i){(function(e){e.Desired="desired",e.Subscribed="subscribed",e.Unsubscribed="unsubscribed"})(i.SubscriptionStatus||(i.SubscriptionStatus={})),(function(e){e.Allowed="allowed",e.NotAllowed="not_allowed"})(i.PermissionStatus||(i.PermissionStatus={}))})(Ne||(Ne={}));var Hn=class extends Ne{get isUpstreamPaused(){var e;return(e=this.track)===null||e===void 0?void 0:e.isUpstreamPaused}constructor(e,t,n,r){super(e,t.sid,t.name,r),this.track=void 0,this.handleTrackEnded=()=>{this.emit(P.Ended)},this.handleCpuConstrained=()=>{this.track&&ht(this.track)&&this.emit(P.CpuConstrained,this.track)},this.updateInfo(t),this.setTrack(n)}setTrack(e){this.track&&(this.track.off(P.Ended,this.handleTrackEnded),this.track.off(P.CpuConstrained,this.handleCpuConstrained)),super.setTrack(e),e&&(e.on(P.Ended,this.handleTrackEnded),e.on(P.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 p(this,void 0,void 0,function*(){var e;return(e=this.track)===null||e===void 0?void 0:e.mute()})}unmute(){return p(this,void 0,void 0,function*(){var e;return(e=this.track)===null||e===void 0?void 0:e.unmute()})}pauseUpstream(){return p(this,void 0,void 0,function*(){var e;yield(e=this.track)===null||e===void 0?void 0:e.pauseUpstream()})}resumeUpstream(){return p(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)){let t=this.track.getSourceTrackSettings(),n=new Set;return t.autoGainControl&&n.add(le.TF_AUTO_GAIN_CONTROL),t.echoCancellation&&n.add(le.TF_ECHO_CANCELLATION),t.noiseSuppression&&n.add(le.TF_NOISE_SUPPRESSION),t.channelCount&&t.channelCount>1&&n.add(le.TF_STEREO),!((e=this.options)===null||e===void 0)&&e.dtx||n.add(le.TF_NO_DTX),this.track.enhancedNoiseCancellation&&n.add(le.TF_ENHANCED_NOISE_CANCELLATION),Array.from(n.values())}else return[]}};function or(i,e){return p(this,void 0,void 0,function*(){i??(i={});let t=!1,n=Kd(i),r=n.audioProcessor,s=n.videoProcessor,a=n.optionsWithoutProcessor,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),i.audio&&typeof a.audio=="object"&&typeof a.audio.deviceId=="string"){let 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"){let 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");let c=Vd(a,Xd,Zd),l=Ma(c),u=navigator.mediaDevices.getUserMedia(l);a.audio&&(Pe.userMediaPromiseMap.set("audioinput",u),u.catch(()=>Pe.userMediaPromiseMap.delete("audioinput"))),a.video&&(Pe.userMediaPromiseMap.set("videoinput",u),u.catch(()=>Pe.userMediaPromiseMap.delete("videoinput")));try{let h=yield u;return yield Promise.all(h.getTracks().map(m=>p(this,void 0,void 0,function*(){let f=m.kind==="audio",g,k=f?l.audio:l.video;typeof k!="boolean"&&(g=k);let T=m.getSettings().deviceId;g?.deviceId&&Lt(g.deviceId)!==T?g.deviceId=T:g||(g={deviceId:T});let S=rp(m,g,e);return S.kind===_.Kind.Video?S.source=_.Source.Camera:S.kind===_.Kind.Audio&&(S.source=_.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 or(Object.assign(Object.assign({},i),{audio:o,video:d}),e)}})}function xp(i){return p(this,void 0,void 0,function*(){return(yield or({audio:!1,video:i??!0}))[0]})}function Dp(i){return p(this,void 0,void 0,function*(){return(yield or({audio:i??!0,video:!1}))[0]})}var yt;(function(i){i.Excellent="excellent",i.Good="good",i.Poor="poor",i.Lost="lost",i.Unknown="unknown"})(yt||(yt={}));function Op(i){switch(i){case kn.EXCELLENT:return yt.Excellent;case kn.GOOD:return yt.Good;case kn.POOR:return yt.Poor;case kn.LOST:return yt.Lost;default:return yt.Unknown}}var Ji=class extends Ee.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===An.AGENT}get isActive(){var e;return((e=this.participantInfo)===null||e===void 0?void 0:e.state)===Jt.ACTIVE}get kind(){return this._kind}get attributes(){return Object.freeze(Object.assign({},this._attributes))}constructor(e,t,n,r,s,a){let o=arguments.length>6&&arguments[6]!==void 0?arguments[6]:An.STANDARD;var d;super(),this.audioLevel=0,this.isSpeaking=!1,this._connectionQuality=yt.Unknown,this.log=F,this.loggerOptions=a,this.log=_e((d=a?.loggerName)!==null&&d!==void 0?d:ue.Participant,()=>this.logContext),this.setMaxListeners(100),this.sid=e,this.identity=t,this.name=n,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(let n of this.trackPublications){var t=O(n,2);let r=t[1];if(r.source===e)return r}}getTrackPublicationByName(e){for(let n of this.trackPublications){var t=O(n,2);let r=t[1];if(r.trackName===e)return r}}waitUntilActive(){return this.isActive?Promise.resolve():this.activeFuture?this.activeFuture.promise:(this.activeFuture=new ce,this.once(I.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;let t=this.getTrackPublication(_.Source.Camera);return!(!((e=t?.isMuted)!==null&&e!==void 0)||e)}get isMicrophoneEnabled(){var e;let t=this.getTrackPublication(_.Source.Microphone);return!(!((e=t?.isMuted)!==null&&e!==void 0)||e)}get isScreenShareEnabled(){return!!this.getTrackPublication(_.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===Jt.ACTIVE&&((t=this.participantInfo)===null||t===void 0?void 0:t.state)!==Jt.ACTIVE&&this.emit(I.Active),e.permission&&this.setPermissions(e.permission),this.participantInfo=e,!0)}_setMetadata(e){let t=this.metadata!==e,n=this.metadata;this.metadata=e,t&&this.emit(I.ParticipantMetadataChanged,n)}_setName(e){let t=this.name!==e;this.name=e,t&&this.emit(I.ParticipantNameChanged,e)}_setAttributes(e){let t=em(this.attributes,e);this._attributes=e,Object.keys(t).length>0&&this.emit(I.AttributesChanged,t)}setPermissions(e){var t,n,r,s,a,o;let d=this.permissions,c=e.canPublish!==((t=this.permissions)===null||t===void 0?void 0:t.canPublish)||e.canSubscribe!==((n=this.permissions)===null||n===void 0?void 0:n.canSubscribe)||e.canPublishData!==((r=this.permissions)===null||r===void 0?void 0:r.canPublishData)||e.hidden!==((s=this.permissions)===null||s===void 0?void 0:s.hidden)||e.recorder!==((a=this.permissions)===null||a===void 0?void 0:a.recorder)||e.canPublishSources.length!==this.permissions.canPublishSources.length||e.canPublishSources.some((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);return this.permissions=e,c&&this.emit(I.ParticipantPermissionsChanged,d),c}setIsSpeaking(e){e!==this.isSpeaking&&(this.isSpeaking=e,e&&(this.lastSpokeAt=new Date),this.emit(I.IsSpeakingChanged,e))}setConnectionQuality(e){let t=this._connectionQuality;this._connectionQuality=Op(e),t!==this._connectionQuality&&this.emit(I.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){e.on(P.Muted,()=>{this.emit(I.TrackMuted,e)}),e.on(P.Unmuted,()=>{this.emit(I.TrackUnmuted,e)});let t=e;switch(t.track&&(t.track.sid=e.trackSid),this.trackPublications.set(e.trackSid,e),e.kind){case _.Kind.Audio:this.audioTrackPublications.set(e.trackSid,e);break;case _.Kind.Video:this.videoTrackPublications.set(e.trackSid,e);break}}};function Lp(i){var e,t,n;if(!i.participantSid&&!i.participantIdentity)throw new Error("Invalid track permission, must provide at least one of participantIdentity and participantSid");return new td({participantIdentity:(e=i.participantIdentity)!==null&&e!==void 0?e:"",participantSid:(t=i.participantSid)!==null&&t!==void 0?t:"",allTracks:(n=i.allowAll)!==null&&n!==void 0?n:!1,trackSids:i.allowedTrackSids||[]})}var Hs=class extends Ji{constructor(e,t,n,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=$.NONE,this.e2eeStateMutex=new de,this.enabledPublishVideoCodecs=[],this.handleReconnecting=()=>{this.reconnectFuture||(this.reconnectFuture=new ce)},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,m,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=(m=this.activeAgentFuture)===null||m===void 0?void 0:m.reject)===null||f===void 0||f.call(m,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 ce),(u=(l=this.signalConnectedFuture).resolve)===null||u===void 0||u.call(l)},this.handleSignalRequestResponse=c=>{let l=c.requestId,u=c.reason,h=c.message,m=this.pendingSignalRequests.get(l);switch(m&&(u!==It.OK&&m.reject(new _i(h,u)),this.pendingSignalRequests.delete(l)),c.request.case){case"publishDataTrack":{let f;switch(c.reason){case It.NOT_ALLOWED:f=Ae.notAllowed(c.message);break;case It.DUPLICATE_NAME:f=Ae.duplicateName(c.message);break;case It.INVALID_NAME:f=Ae.invalidName(c.message);break;case It.LIMIT_EXCEEDED:f=Ae.limitReached(c.message);break;default:f=Ae.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=>Lp(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",j(c));return}this.engine.updateMuteStatus(c.sid,l)},this.onTrackUpstreamPaused=c=>{this.log.debug("upstream paused",j(c)),this.onTrackMuted(c,!0)},this.onTrackUpstreamResumed=c=>{this.log.debug("upstream resumed",j(c)),this.onTrackMuted(c,c.isMuted)},this.onTrackFeatureUpdate=c=>{let 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)=>{this.log.debug("track cpu constrained",j(l)),this.emit(I.LocalTrackCpuConstrained,c,l)},this.handleSubscribedQualityUpdate=c=>p(this,void 0,void 0,function*(){var l,u,h,m,f;if(!(!((f=this.roomOptions)===null||f===void 0)&&f.dynacast))return;let 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;let k=yield g.videoTrack.setPublishingCodecs(c.subscribedCodecs);try{for(var T=!0,S=Be(k),L;L=yield S.next(),l=L.done,!l;T=!0){m=L.value,T=!1;let y=m;$h(y)&&(this.log.debug("publish ".concat(y," for ").concat(g.videoTrack.sid),j(g)),yield this.publishAdditionalCodecForTrack(g.videoTrack,y,g.options))}}catch(y){u={error:y}}finally{try{!T&&!l&&(h=S.return)&&(yield h.call(S))}finally{if(u)throw u.error}}}),this.handleLocalTrackUnpublished=c=>{let 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=>p(this,void 0,void 0,function*(){if(c.source===_.Source.ScreenShare||c.source===_.Source.ScreenShareAudio)this.log.debug("unpublishing local track due to TrackEnded",j(c)),this.unpublishTrack(c);else if(c.isUserProvided)yield c.mute();else if(at(c)||Je(c))try{if(Ce())try{let l=yield navigator?.permissions.query({name:c.source===_.Source.Camera?"camera":"microphone"});if(l&&l.state==="denied")throw this.log.warn("user has revoked access to ".concat(c.source),j(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",j(c)),at(c)?yield c.restartTrack({deviceId:"default"}):yield c.restartTrack())}catch{this.log.warn("could not restart track, muting instead",j(c)),yield c.mute()}}),this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this.engine=n,this.roomOptions=r,this.setupEngine(n),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!==$.NONE}getTrackPublication(e){let t=super.getTrackPublication(e);if(t)return t}getTrackPublicationByName(e){let t=super.getTrackPublicationByName(e);if(t)return t}setupEngine(e){var t;this.engine=e,this.engine.on(R.RemoteMute,(n,r)=>{let s=this.trackPublications.get(n);!s||!s.track||(r?s.mute():s.unmute())}),!((t=this.signalConnectedFuture)===null||t===void 0)&&t.isResolved&&(this.signalConnectedFuture=void 0),this.engine.on(R.Connected,this.handleReconnected).on(R.SignalConnected,this.handleSignalConnected).on(R.SignalRestarted,this.handleReconnected).on(R.SignalResumed,this.handleReconnected).on(R.Restarting,this.handleReconnecting).on(R.Resuming,this.handleReconnecting).on(R.LocalTrackUnpublished,this.handleLocalTrackUnpublished).on(R.SubscribedQualityUpdate,this.handleSubscribedQualityUpdate).on(R.Closing,this.handleClosing).on(R.SignalRequestResponse,this.handleSignalRequestResponse)}setMetadata(e){return p(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({metadata:e})})}setName(e){return p(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({name:e})})}setAttributes(e){return p(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({attributes:e})})}requestMetadataUpdate(e){return p(this,arguments,void 0,function(t){var n=this;let r=t.metadata,s=t.name,a=t.attributes;return(function*(){return new pe((o,d)=>p(n,void 0,void 0,function*(){var c,l;try{let u=!1,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),m=performance.now();for(this.pendingSignalRequests.set(h,{resolve:o,reject:f=>{d(f),u=!0},values:{name:s,metadata:r,attributes:a}});performance.now()-m<5e3&&!u;){if((!s||this.name===s)&&(!r||this.metadata===r)&&(!a||Object.entries(a).every(f=>{let g=O(f,2),k=g[0],T=g[1];return this.attributes[k]===T||T===""&&!this.attributes[k]}))){this.pendingSignalRequests.delete(h),o();return}yield ve(50)}d(new _i("Request to update local metadata timed out","TimeoutError"))}catch(u){u instanceof Error?d(u):d(new Error(String(u)))}}))})()})}setCameraEnabled(e,t,n){return this.setTrackEnabled(_.Source.Camera,e,t,n)}setMicrophoneEnabled(e,t,n){return this.setTrackEnabled(_.Source.Microphone,e,t,n)}setScreenShareEnabled(e,t,n){return this.setTrackEnabled(_.Source.ScreenShare,e,t,n)}setE2EEEnabled(e){return p(this,void 0,void 0,function*(){let t=yield this.e2eeStateMutex.lock();try{if(this.encryptionType=e?$.GCM:$.NONE,yield Promise.all(this.pendingPublishPromises.values()),this.trackPublications.size===0||Array.from(this.trackPublications.values()).every(n=>n.isEncrypted===e))return;yield this.republishAllTracks(void 0,!1)}finally{t()}})}setTrackEnabled(e,t,n,r){return p(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)){let h=yield this.waitForPendingPublicationOfSource(e);return h||this.log.info("waiting for pending publication promise timed out",{source:e}),yield h?.unmute(),h}this.pendingPublishing.add(e);try{switch(e){case _.Source.Camera:u=yield this.createTracks({video:(s=n)!==null&&s!==void 0?s:!0});break;case _.Source.Microphone:u=yield this.createTracks({audio:(a=n)!==null&&a!==void 0?a:!0});break;case _.Source.ScreenShare:u=yield this.createScreenTracks(Object.assign({},n));break;default:throw new qe(e)}}catch(h){throw u?.forEach(m=>{m.stop()}),h instanceof Error&&this.emit(I.MediaDevicesError,h,cs(e)),this.pendingPublishing.delete(e),h}for(let h of u){let m=Object.assign(Object.assign({},this.roomOptions.publishDefaults),n);e===_.Source.Microphone&&et(h)&&m.preConnectBuffer&&(this.log.info("starting preconnect buffer for microphone"),h.startPreConnectBuffer())}try{let h=[];for(let f of u)this.log.info("publishing track",j(f)),h.push(this.publishTrack(f,r));let m=yield Promise.all(h);var d=O(m,1);o=d[0]}catch(h){throw u?.forEach(m=>{m.stop()}),h}finally{this.pendingPublishing.delete(e)}}else if(!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===_.Source.ScreenShare){let u=[this.unpublishTrack(o.track)],h=this.getTrackPublication(_.Source.ScreenShareAudio);h&&h.track&&u.push(this.unpublishTrack(h.track));var c=yield Promise.all(u),l=O(c,1);o=l[0]}else yield o.mute();return o})}enableCameraAndMicrophone(){return p(this,void 0,void 0,function*(){if(!(this.pendingPublishing.has(_.Source.Camera)||this.pendingPublishing.has(_.Source.Microphone))){this.pendingPublishing.add(_.Source.Camera),this.pendingPublishing.add(_.Source.Microphone);try{let e=yield this.createTracks({audio:!0,video:!0});yield Promise.all(e.map(t=>this.publishTrack(t)))}finally{this.pendingPublishing.delete(_.Source.Camera),this.pendingPublishing.delete(_.Source.Microphone)}}})}createTracks(e){return p(this,void 0,void 0,function*(){var t,n;e??(e={});let r=Vd(e,(t=this.roomOptions)===null||t===void 0?void 0:t.audioCaptureDefaults,(n=this.roomOptions)===null||n===void 0?void 0:n.videoCaptureDefaults);try{return(yield or(r,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext})).map(o=>(et(o)&&(this.microphoneError=void 0,o.setAudioContext(this.audioContext),o.source=_.Source.Microphone,this.emit(I.AudioStreamAcquired)),ht(o)&&(this.cameraError=void 0,o.source=_.Source.Camera),o))}catch(s){throw s instanceof Error&&(e.audio&&(this.microphoneError=s),e.video&&(this.cameraError=s)),s}})}createScreenTracks(e){return p(this,void 0,void 0,function*(){if(e===void 0&&(e={}),navigator.mediaDevices.getDisplayMedia===void 0)throw new Dn("getDisplayMedia not supported");e.resolution===void 0&&!lm()&&(e.resolution=Ia.h1080fps30.resolution);let t=Yh(e),n=yield navigator.mediaDevices.getDisplayMedia(t),r=n.getVideoTracks();if(r.length===0)throw new qe("no video track found");let s=new an(r[0],void 0,!1,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});s.source=_.Source.ScreenShare,e.contentHint&&(s.mediaStreamTrack.contentHint=e.contentHint);let a=[s];if(n.getAudioTracks().length>0){this.emit(I.AudioStreamAcquired);let o=new Et(n.getAudioTracks()[0],void 0,!1,this.audioContext,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});o.source=_.Source.ScreenShareAudio,a.push(o)}return a})}publishTrack(e,t){return p(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,n)=>{let r=()=>{clearTimeout(o),this.engine.off(R.Restarted,s),this.engine.off(R.Closing,a)},s=()=>{r(),t()},a=()=>{r(),n(new Error("engine closed before restart completed"))},o=setTimeout(()=>{r(),n(new Error("timed out waiting for engine restart"))},e);this.engine.once(R.Restarted,s),this.engine.once(R.Closing,a)})}publishOrRepublishTrack(e,t){return p(this,arguments,void 0,function(n,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;at(n)&&n.setAudioContext(s.audioContext),yield(d=s.reconnectFuture)===null||d===void 0?void 0:d.promise,s.republishPromise&&!a&&(yield s.republishPromise),Xt(n)&&s.pendingPublishPromises.has(n)&&(yield s.pendingPublishPromises.get(n));let h;if(n instanceof MediaStreamTrack)h=n.getConstraints();else{h=n.constraints;let S;switch(n.source){case _.Source.Microphone:S="audioinput";break;case _.Source.Camera:S="videoinput"}S&&s.activeDeviceMap.has(S)&&(h=Object.assign(Object.assign({},h),{deviceId:s.activeDeviceMap.get(S)}))}if(n instanceof MediaStreamTrack)switch(n.kind){case"audio":n=new Et(n,h,!0,s.audioContext,{loggerName:s.roomOptions.loggerName,loggerContextCb:()=>s.logContext});break;case"video":n=new an(n,h,!0,{loggerName:s.roomOptions.loggerName,loggerContextCb:()=>s.logContext});break;default:throw new qe("unsupported MediaStreamTrack kind ".concat(n.kind))}else n.updateLoggerOptions({loggerName:s.roomOptions.loggerName,loggerContextCb:()=>s.logContext});let m;if(s.trackPublications.forEach(S=>{S.track&&S.track===n&&(m=S)}),m)return s.log.warn("track has already been published, skipping",j(m)),m;let f=Object.assign(Object.assign({},s.roomOptions.publishDefaults),r),g="channelCount"in n.mediaStreamTrack.getSettings()&&n.mediaStreamTrack.getSettings().channelCount===2||n.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.",j(n)),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)),!hm()&&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&&(n.source=f.source);let T=new Promise((S,L)=>p(s,void 0,void 0,function*(){try{if(this.engine.client.currentState!==z.CONNECTED){this.log.debug("deferring track publication until signal is connected",{track:j(n)});let y=!1,b=setTimeout(()=>{y=!0,n.stop(),L(new Ci("publishing rejected as engine not connected within timeout",408))},15e3);if(yield this.waitUntilEngineConnected(),clearTimeout(b),y)return;let E=yield this.publish(n,f,k);S(E)}else try{let y=yield this.publish(n,f,k);S(y)}catch(y){L(y)}}catch(y){L(y)}}));s.pendingPublishPromises.set(n,T);try{return yield T}catch(S){if(!o&&S instanceof lt)return s.log.warn("negotiation due to track publish failed, retrying after reconnect",{error:S}),s.pendingPublishPromises.delete(n),yield s.waitForNextEngineRestart(),yield s.publishOrRepublishTrack(n,r,a,!0);throw S}finally{s.pendingPublishPromises.delete(n)}})()})}waitUntilEngineConnected(){return this.signalConnectedFuture||(this.signalConnectedFuture=new ce),this.signalConnectedFuture.promise}hasPermissionsToPublish(e){if(!this.permissions)return this.log.warn("no permissions present for publishing track",j(e)),!1;let t=this.permissions,n=t.canPublish,r=t.canPublishSources;return n&&(r.length===0||r.map(s=>tm(s)).includes(e.source))?!0:(this.log.warn("insufficient permissions to publish",j(e)),!1)}publish(e,t,n){return p(this,void 0,void 0,function*(){var r,s,a,o,d,c,l,u,h,m;if(!this.hasPermissionsToPublish(e))throw new Ci("failed to publish track, insufficient permissions",403);Array.from(this.trackPublications.values()).find(A=>Xt(e)&&A.source===e.source)&&e.source!==_.Source.Unknown&&this.log.info("publishing a second track with the same source: ".concat(e.source),j(e)),t.stopMicTrackOnMute&&et(e)&&(e.stopOnMute=!0),e.source===_.Source.ScreenShare&&Ft()&&(t.simulcast=!1),t.videoCodec==="av1"&&!am()&&(t.videoCodec=void 0),t.videoCodec==="vp9"&&!om()&&(t.videoCodec=void 0),t.videoCodec===void 0&&(t.videoCodec=_s),this.enabledPublishVideoCodecs.length>0&&(this.enabledPublishVideoCodecs.some(A=>t.videoCodec===_n(A.mime))||(t.videoCodec=_n(this.enabledPublishVideoCodecs[0].mime)));let g=t.videoCodec;e.on(P.Muted,this.onTrackMuted),e.on(P.Unmuted,this.onTrackUnmuted),e.on(P.Ended,this.handleTrackEnded),e.on(P.UpstreamPaused,this.onTrackUpstreamPaused),e.on(P.UpstreamResumed,this.onTrackUpstreamResumed),e.on(P.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate);let k=[],T=!(!((r=t.dtx)!==null&&r!==void 0)||r),S=e.getSourceTrackSettings();S.autoGainControl&&k.push(le.TF_AUTO_GAIN_CONTROL),S.echoCancellation&&k.push(le.TF_ECHO_CANCELLATION),S.noiseSuppression&&k.push(le.TF_NOISE_SUPPRESSION),S.channelCount&&S.channelCount>1&&k.push(le.TF_STEREO),T&&k.push(le.TF_NO_DTX),at(e)&&e.hasPreConnectBuffer&&k.push(le.TF_PRECONNECT_BUFFER);let L=this.normalizeRequestedFrameMetadataOptions(e,t),y=new xn({cid:e.mediaStreamTrack.id,name:t.name,type:_.kindToProto(e.kind),muted:e.isMuted,source:_.sourceToProto(e.source),disableDtx:T,encryption:this.encryptionType,stereo:n,disableRed:this.isE2EEEnabled||!(!((s=t.red)!==null&&s!==void 0)||s),stream:t?.stream,backupCodecPolicy:t?.backupCodecPolicy,audioFeatures:k,packetTrailerFeatures:L}),b;if(e.kind===_.Kind.Video){let A;try{A=yield e.waitForDimensions()}catch{let B=(o=(a=this.roomOptions.videoCaptureDefaults)===null||a===void 0?void 0:a.resolution)!==null&&o!==void 0?o:On.h720.resolution;A={width:B.width,height:B.height},this.log.error("could not determine track dimensions, using defaults",Object.assign(Object.assign({},j(e)),{dims:A}))}y.width=A.width,y.height=A.height,Je(e)&&(je(g)&&(e.source===_.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",j(e)))),t.scalabilityMode=(d=t.scalabilityMode)!==null&&d!==void 0?d:"L3T3_KEY"),y.simulcastCodecs=[new Wr({codec:g,cid:e.mediaStreamTrack.id})],t.backupCodec===!0&&(t.backupCodec={codec:_s}),t.backupCodec&&g!==t.backupCodec.codec&&y.encryption===$.NONE&&(this.roomOptions.dynacast||(this.roomOptions.dynacast=!0),y.simulcastCodecs.push(new Wr({codec:t.backupCodec.codec,cid:""})))),b=Oi(e.source===_.Source.ScreenShare,y.width,y.height,t),y.layers=Jo(y.width,y.height,b,je(t.videoCodec))}else e.kind===_.Kind.Audio&&(b=[{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:(m=(h=t.audioPreset)===null||h===void 0?void 0:h.priority)!==null&&m!==void 0?m:"high"}]);if(!this.engine||this.engine.isClosed)throw new W("cannot publish track when not connected");let E=()=>p(this,void 0,void 0,function*(){var A,x,B;if(!this.engine.pcManager)throw new W("pcManager is not ready");if(e.sender=yield this.engine.createSender(e,t,b),Je(e)&&(e.publishOptions=t),this.emit(I.LocalSenderCreated,e.sender,e),Je(e)&&((A=t.degradationPreference)!==null&&A!==void 0||(t.degradationPreference=mp(e)),e.setDegradationPreference(t.degradationPreference)),b)if(Ft()&&e.kind===_.Kind.Audio){let Z;for(let ee of this.engine.pcManager.publisher.getTransceivers())if(ee.sender===e.sender){Z=ee;break}Z&&this.engine.pcManager.publisher.setTrackCodecBitrate({transceiver:Z,codec:"opus",maxbr:!((x=b[0])===null||x===void 0)&&x.maxBitrate?b[0].maxBitrate/1e3:0})}else e.codec&&je(e.codec)&&(!((B=b[0])===null||B===void 0)&&B.maxBitrate)&&this.engine.pcManager.publisher.setTrackCodecBitrate({cid:y.cid,codec:e.codec,maxbr:b[0].maxBitrate/1e3});yield this.engine.negotiate()}),M,D=new Promise((A,x)=>p(this,void 0,void 0,function*(){var B;try{M=yield this.engine.addTrack(y),A(M)}catch(Z){if(e.sender&&(!((B=this.engine.pcManager)===null||B===void 0)&&B.publisher)){try{this.engine.pcManager.publisher.removeTrack(e.sender)}catch(ee){this.log.error(ee)}yield this.engine.negotiate().catch(ee=>{this.log.error("failed to negotiate after removing track due to failed add track request",Object.assign(Object.assign({},j(e)),{error:ee}))})}x(Z)}}));if(this.enabledPublishVideoCodecs.length>0&&L.length===0)M=(yield Promise.all([D,E()]))[0];else{M=yield D;let A;if(M.codecs.forEach(x=>{A===void 0&&(A=x.mimeType)}),A&&e.kind===_.Kind.Video){let x=_n(A);x!==g&&(this.log.debug("falling back to server selected codec",Object.assign(Object.assign({},j(e)),{codec:x})),t.videoCodec=x,b=Oi(e.source===_.Source.ScreenShare,y.width,y.height,t))}yield E()}let q=new Hn(e.kind,M,e,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});if(q.on(P.CpuConstrained,A=>this.onTrackCpuConstrained(A,q)),q.options=t,e.sid=M.sid,Je(e)&&(e.publishOptions=t,y.width&&y.height&&(e.lastEncodedDimensions={width:y.width,height:y.height})),this.log.debug("publishing ".concat(e.kind," with encodings"),{encodings:b,trackInfo:M}),Je(e)?e.startMonitor(this.engine.client):at(e)&&e.startMonitor(),this.addTrackPublication(q),this.emit(I.LocalTrackPublished,q),at(e)&&M.audioFeatures.includes(le.TF_PRECONNECT_BUFFER)){let A=e.getPreConnectBuffer(),x=e.getPreConnectBufferMimeType();this.on(I.LocalTrackSubscribed,B=>{if(B.trackSid===M.sid){if(!e.hasPreConnectBuffer){this.log.warn("subscribe event came to late, buffer already closed");return}this.log.debug("finished recording preconnect buffer",j(e)),e.stopPreConnectBuffer()}}),A&&new Promise((Z,ee)=>p(this,void 0,void 0,function*(){var ze,mn,ye,ft,ur,hr;try{this.log.debug("waiting for agent",j(e));let gr=setTimeout(()=>{ee(new Error("agent not active within 10 seconds"))},1e4),Fl=yield this.waitUntilActiveAgentPresent();clearTimeout(gr),this.log.debug("sending preconnect buffer",j(e));let Ya=yield this.streamBytes({name:"preconnect-buffer",mimeType:x,topic:"lk.agent.pre-connect-audio-buffer",destinationIdentities:[Fl.identity],attributes:{trackId:q.trackSid,sampleRate:String((ur=S.sampleRate)!==null&&ur!==void 0?ur:"48000"),channels:String((hr=S.channelCount)!==null&&hr!==void 0?hr:"1")}});try{for(var mr=!0,pr=Be(A),fr;fr=yield pr.next(),ze=fr.done,!ze;mr=!0){ft=fr.value,mr=!1;let vr=ft;yield Ya.write(vr)}}catch(vr){mn={error:vr}}finally{try{!mr&&!ze&&(ye=pr.return)&&(yield ye.call(pr))}finally{if(mn)throw mn.error}}yield Ya.close(),Z()}catch(gr){ee(gr)}})).then(()=>{this.log.debug("preconnect buffer sent successfully",j(e))}).catch(Z=>{this.log.error("error sending preconnect buffer",Object.assign(Object.assign({},j(e)),{error:Z}))})}return q})}canPublishFrameMetadata(){var e;return!!(this.roomOptions.e2ee||this.roomOptions.encryption||Fn((e=this.roomOptions.frameMetadata)!==null&&e!==void 0?e:this.roomOptions.packetTrailer))}normalizeRequestedFrameMetadataOptions(e,t){var n;let r=(n=t.frameMetadata)!==null&&n!==void 0?n:t.packetTrailer;if(e.kind!==_.Kind.Video||!Ei(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),j(e))),t.frameMetadata=void 0,t.packetTrailer=void 0,[];let s=Lm(r),a=Nm(s);return t.frameMetadata=a,t.packetTrailer=a,s}get isLocal(){return!0}publishAdditionalCodecForTrack(e,t,n){return p(this,void 0,void 0,function*(){var r;if(this.encryptionType!==$.NONE)return;let s;if(this.trackPublications.forEach(f=>{f.track&&f.track===e&&(s=f)}),!s)throw new qe("track is not published");if(!Je(e))throw new qe("track is not a video track");let a=Object.assign(Object.assign({},(r=this.roomOptions)===null||r===void 0?void 0:r.publishDefaults),n),o=el(e,t,a);if(!o){this.log.info("backup codec has been disabled, ignoring request to add additional codec for track",j(e));return}let d=e.addSimulcastTrack(t,o);if(!d)return;let c=this.normalizeRequestedFrameMetadataOptions(e,a),l=new xn({cid:d.mediaStreamTrack.id,type:_.kindToProto(e.kind),muted:e.isMuted,source:_.sourceToProto(e.source),sid:e.sid,packetTrailerFeatures:c,simulcastCodecs:[{codec:a.videoCodec,cid:d.mediaStreamTrack.id}]});if(l.layers=Jo(l.width,l.height,o),!this.engine||this.engine.isClosed)throw new W("cannot publish track when not connected");let u=()=>p(this,void 0,void 0,function*(){yield this.engine.createSimulcastSender(e,d,a,o),yield this.engine.negotiate()}),m=(yield Promise.all([this.engine.addTrack(l),u()]))[0];this.log.debug("published ".concat(t," for track ").concat(e.sid),{encodings:o,trackInfo:m})})}unpublishTrack(e,t){return p(this,void 0,void 0,function*(){var n,r;if(Xt(e)){let l=this.pendingPublishPromises.get(e);l&&(this.log.debug("awaiting publish promise before attempting to unpublish",j(e)),yield l)}let s=this.getPublicationForTrack(e),a=s?j(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(P.Muted,this.onTrackMuted),e.off(P.Unmuted,this.onTrackUnmuted),e.off(P.Ended,this.handleTrackEnded),e.off(P.UpstreamPaused,this.onTrackUpstreamPaused),e.off(P.UpstreamResumed,this.onTrackUpstreamResumed),e.off(P.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate),t===void 0&&(t=(r=(n=this.roomOptions)===null||n===void 0?void 0:n.stopLocalTrackOnUnpublish)!==null&&r!==void 0?r:!0),t?e.stop():e.stopMonitor();let o=!1,d=e.sender;if(e.sender=void 0,this.engine.pcManager&&this.engine.pcManager.currentState<te.FAILED&&d)try{for(let 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}if(Je(e)){for(let l of e.simulcastCodecs){var c=O(l,2);let 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 _.Kind.Audio:this.audioTrackPublications.delete(s.trackSid);break;case _.Kind.Video:this.videoTrackPublications.delete(s.trackSid);break}return this.emit(I.LocalTrackUnpublished,s),s.setTrack(void 0),o&&(yield this.engine.negotiate()),s})}unpublishTracks(e){return p(this,void 0,void 0,function*(){return(yield Promise.all(e.map(n=>this.unpublishTrack(n)))).filter(n=>!!n)})}republishAllTracks(e){return p(this,arguments,void 0,function(t){var n=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return(function*(){n.republishPromise&&(yield n.republishPromise),n.republishPromise=new pe((s,a)=>p(n,void 0,void 0,function*(){try{let 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=>p(this,void 0,void 0,function*(){let c=d.track;yield this.unpublishTrack(c,!1),r&&!c.isMuted&&c.source!==_.Source.ScreenShare&&c.source!==_.Source.ScreenShareAudio&&(at(c)||Je(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 n.republishPromise})()})}publishData(e){return p(this,arguments,void 0,function(t){var n=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return(function*(){let s=r.reliable?U.RELIABLE:U.LOSSY,a=r.reliable?Ze.RELIABLE:Ze.LOSSY,o=r.destinationIdentities,d=r.topic,c=new ga({participantIdentity:n.identity,payload:t,destinationIdentities:o,topic:d}),l=new ge({kind:a,value:{case:"user",value:c}});yield n.engine.sendDataPacket(l,s,r.signal)})()})}publishDtmf(e,t){return p(this,void 0,void 0,function*(){let n=new ge({kind:Ze.RELIABLE,value:{case:"sipDtmf",value:new Uc({code:e,digit:t})}});yield this.engine.sendDataPacket(n,U.RELIABLE)})}sendChatMessage(e,t){return p(this,void 0,void 0,function*(){let n={id:crypto.randomUUID(),message:e,timestamp:Date.now(),attachedFiles:t?.attachments},r=new ge({value:{case:"chatMessage",value:new yi(Object.assign(Object.assign({},n),{timestamp:Y.parse(n.timestamp)}))}});return yield this.engine.sendDataPacket(r,U.RELIABLE),this.emit(I.ChatMessage,n),n})}editChatMessage(e,t){return p(this,void 0,void 0,function*(){let n=Object.assign(Object.assign({},t),{message:e,editTimestamp:Date.now()}),r=new ge({value:{case:"chatMessage",value:new yi(Object.assign(Object.assign({},n),{timestamp:Y.parse(n.timestamp),editTimestamp:Y.parse(n.editTimestamp)}))}});return yield this.engine.sendDataPacket(r,U.RELIABLE),this.emit(I.ChatMessage,n),n})}sendText(e,t){return p(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.sendText(e,t)})}streamText(e){return p(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.streamText(e)})}sendFile(e,t){return p(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.sendFile(e,t)})}streamBytes(e){return p(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.streamBytes(e)})}performRpc(e){return this.rpcClientManager.performRpc(e).then(t=>{let n=O(t,2);return n[0],n[1]})}registerRpcMethod(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 n,r;let s=this.trackPublications.get(t.sid);if(s){let a=s.isMuted||((r=(n=s.track)===null||n===void 0?void 0:n.isUpstreamPaused)!==null&&r!==void 0?r:!1);a!==t.muted&&(this.log.debug("updating server mute state after reconcile",Object.assign(Object.assign({},j(s)),{mutedOnServer:a})),this.engine.client.sendMuteTrack(t.sid,a))}}),!0):!1}setActiveAgent(e){var t,n,r,s;this.firstActiveAgent=e,e&&!this.firstActiveAgent&&(this.firstActiveAgent=e),e?(n=(t=this.activeAgentFuture)===null||t===void 0?void 0:t.resolve)===null||n===void 0||n.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 ce),this.activeAgentFuture.promise)}getPublicationForTrack(e){let t;return this.trackPublications.forEach(n=>{let r=n.track;r&&(e instanceof MediaStreamTrack?(at(r)||Je(r))&&r.mediaStreamTrack===e&&(t=n):e===r&&(t=n))}),t}waitForPendingPublicationOfSource(e){return p(this,void 0,void 0,function*(){let n=Date.now();for(;Date.now()<n+1e4;){let r=Array.from(this.pendingPublishPromises.entries()).find(s=>O(s,1)[0].source===e);if(r)return r[1];yield ve(20)}})}publishDataTrack(e){return p(this,void 0,void 0,function*(){let t=new Wi(e,this.roomOutgoingDataTrackManager);return yield t.publish(),t})}},$i=class extends DOMException{constructor(e,t){super(e,"AbortError"),this.reason=t}},Gs=class extends Map{constructor(){super(...arguments),this.pending=new Map}set(e,t){var n,r;super.set(e,t);let s=(n=this.pending)===null||n===void 0?void 0:n.get(e);if(s){for(let 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 p(this,void 0,void 0,function*(){let n=this.get(e);if(typeof n<"u")return n;if(t?.aborted)throw new $i("The operation was aborted.",t.reason);let r=new ce(void 0,()=>{let a=this.pending.get(e);if(!a)return;let 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){let a=()=>{var o;r.isResolved||(o=r.reject)===null||o===void 0||o.call(r,new $i("The operation was aborted.",t.reason))};t.addEventListener("abort",a,{once:!0}),r.promise.finally(()=>{t.removeEventListener("abort",a)})}return r.promise})}},Ks=class extends Ne{constructor(e,t,n,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(P.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=n,this.updateInfo(t)}setSubscribed(e){let t=this.subscriptionStatus,n=this.permissionStatus;this.subscribed=e,e&&(this.allowed=!0);let r=new ir({trackSids:[this.trackSid],subscribe:this.subscribed,participantTracks:[new Bc({participantSid:"",trackSids:[this.trackSid]})]});this.emit(P.UpdateSubscription,r),this.emitSubscriptionUpdateIfChanged(t),this.emitPermissionUpdateIfChanged(n)}get subscriptionStatus(){return this.subscribed===!1?Ne.SubscriptionStatus.Unsubscribed:super.isSubscribed?Ne.SubscriptionStatus.Subscribed:Ne.SubscriptionStatus.Desired}get permissionStatus(){return this.allowed?Ne.PermissionStatus.Allowed:Ne.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,n;this.isManualOperationAllowed()&&(((t=this.requestedVideoDimensions)===null||t===void 0?void 0:t.width)===e.width&&((n=this.requestedVideoDimensions)===null||n===void 0?void 0:n.height)===e.height||(Pr(this.track)&&(this.requestedVideoDimensions=e),this.requestedMaxQuality=void 0,this.emitTrackUpdate()))}setVideoFPS(e){this.isManualOperationAllowed()&&Pr(this.track)&&this.fps!==e&&(this.fps=e,this.emitTrackUpdate())}get videoQuality(){var e;return(e=this.requestedMaxQuality)!==null&&e!==void 0?e:Re.HIGH}setTrack(e){let t=this.subscriptionStatus,n=this.permissionStatus,r=this.track;r!==e&&(r&&(r.off(P.VideoDimensionsChanged,this.handleVideoDimensionsChange),r.off(P.VisibilityChanged,this.handleVisibilityChange),r.off(P.Ended,this.handleEnded),r.detach(),r.stopMonitor(),this.emit(P.Unsubscribed,r)),super.setTrack(e),e&&(e.sid=this.trackSid,e.on(P.VideoDimensionsChanged,this.handleVideoDimensionsChange),e.on(P.VisibilityChanged,this.handleVisibilityChange),e.on(P.Ended,this.handleEnded),this.emit(P.Subscribed,e)),this.emitPermissionUpdateIfChanged(n),this.emitSubscriptionUpdateIfChanged(t))}setAllowed(e){let t=this.subscriptionStatus,n=this.permissionStatus;this.allowed=e,this.emitPermissionUpdateIfChanged(n),this.emitSubscriptionUpdateIfChanged(t)}setSubscriptionError(e){this.emit(P.SubscriptionFailed,e)}updateInfo(e){super.updateInfo(e);let t=this.metadataMuted;this.metadataMuted=e.muted,this.track?this.track.setMuted(e.muted):t!==e.muted&&this.emit(e.muted?P.Muted:P.Unmuted)}emitSubscriptionUpdateIfChanged(e){let t=this.subscriptionStatus;e!==t&&this.emit(P.SubscriptionStatusChanged,t,e)}emitPermissionUpdateIfChanged(e){this.permissionStatus!==e&&this.emit(P.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 Pr(this.track)&&this.track.isAdaptiveStream}emitTrackUpdate(){let e=new Yc({trackSids:[this.trackSid],disabled:!this.isEnabled,fps:this.fps});if(this.kind===_.Kind.Video){let t=this.requestedVideoDimensions;if(this.videoDimensionsAdaptiveStream!==void 0)if(t)Ro(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){let n=nm(this.trackInfo,this.requestedMaxQuality);n&&Ro(this.videoDimensionsAdaptiveStream,n)&&(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:Re.HIGH})),e.quality=Re.HIGH)}this.emit(P.UpdateSettings,e)}},Qi=class i extends Ji{static fromParticipantInfo(e,t,n,r){return new i(e,t.sid,t.identity,t.name,t.metadata,t.attributes,n,t.kind,t.dataTracks.map(s=>{let a=Ii.from(s);return new qi(a,r,{publisherIdentity:t.identity})}),t.clientProtocol)}get logContext(){return Object.assign(Object.assign({},super.logContext),{remoteParticipantID:this.sid,remoteParticipant:this.identity})}constructor(e,t,n,r,s,a,o){let d=arguments.length>7&&arguments[7]!==void 0?arguments[7]:An.STANDARD,c=arguments.length>8&&arguments[8]!==void 0?arguments[8]:[],l=arguments.length>9&&arguments[9]!==void 0?arguments[9]:qd;super(t,n||"",r,s,a,o,d),this.signalClient=e,this.trackPublications=new Map,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.dataTracks=new Gs(c.map(u=>[u.info.name,u])),this.volumeMap=new Map,this.clientProtocol=l}addTrackPublication(e){super.addTrackPublication(e),e.on(P.UpdateSettings,t=>{this.log.debug("send update settings",Object.assign(Object.assign(Object.assign({},this.logContext),j(e)),{settings:t})),this.signalClient.sendUpdateTrackSettings(t)}),e.on(P.UpdateSubscription,t=>{t.participantTracks.forEach(n=>{n.participantSid=this.sid}),this.signalClient.sendUpdateSubscription(t)}),e.on(P.SubscriptionPermissionChanged,t=>{this.emit(I.TrackSubscriptionPermissionChanged,e,t)}),e.on(P.SubscriptionStatusChanged,t=>{this.emit(I.TrackSubscriptionStatusChanged,e,t)}),e.on(P.Subscribed,t=>{this.emit(I.TrackSubscribed,t,e)}),e.on(P.Unsubscribed,t=>{this.emit(I.TrackUnsubscribed,t,e)}),e.on(P.SubscriptionFailed,t=>{this.emit(I.TrackSubscriptionFailed,e.trackSid,t)})}getTrackPublication(e){let t=super.getTrackPublication(e);if(t)return t}getTrackPublicationByName(e){let t=super.getTrackPublicationByName(e);if(t)return t}setVolume(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:_.Source.Microphone;this.volumeMap.set(t,e);let n=this.getTrackPublication(t);n&&n.track&&n.track.setVolume(e)}getVolume(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:_.Source.Microphone,t=this.getTrackPublication(e);return t&&t.track?t.track.getVolume():this.volumeMap.get(e)}addSubscribedMediaTrack(e,t,n,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(I.TrackSubscriptionFailed,t);return}a===void 0&&(a=20),setTimeout(()=>{this.addSubscribedMediaTrack(e,t,n,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),j(o))),this.emit(I.TrackSubscriptionFailed,t);return}let d=e.kind==="video",c;return d?c=new Bn(e,t,r,s):c=new Vs(e,t,r,this.audioContext,this.audioOutput),c.source=o.source,c.isMuted=o.isMuted,c.setMediaStream(n),c.start(),o.setTrack(c),this.volumeMap.has(o.source)&&ms(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;let t=new Map,n=new Map;return e.tracks.forEach(r=>{var s,a;let o=this.getTrackPublicationBySid(r.sid);if(o)o.updateInfo(r);else{let d=_.kindFromProto(r.type);if(!d)return;o=new Ks(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),n.set(r.sid,o);let c=Array.from(this.trackPublications.values()).find(l=>l.source===o?.source);c&&o.source!==_.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:j(c),newTrack:j(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),j(r))),this.unpublishTrack(r.trackSid,!0))}),n.forEach(r=>{this.emit(I.TrackPublished,r)}),!0}unpublishTrack(e,t){let n=this.trackPublications.get(e);if(!n)return;let r=n.track;switch(r&&(r.stop(),n.setTrack(void 0)),this.trackPublications.delete(e),n.kind){case _.Kind.Audio:this.audioTrackPublications.delete(e);break;case _.Kind.Video:this.videoTrackPublications.delete(e);break}t&&this.emit(I.TrackUnpublished,n)}setAudioOutput(e){return p(this,void 0,void 0,function*(){this.audioOutput=e;let t=[];this.audioTrackPublications.forEach(n=>{var r;et(n.track)&&ms(n.track)&&t.push(n.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(let n of this.dataTracks.entries()){var t=O(n,2);let r=t[0],s=t[1];e===s.info.sid&&this.dataTracks.delete(r)}}emit(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),r=1;r<t;r++)n[r-1]=arguments[r];return this.log.trace("participant event",Object.assign(Object.assign({},this.logContext),{event:e,args:n})),super.emit(e,...n)}},V;(function(i){i.Disconnected="disconnected",i.Connecting="connecting",i.Connected="connected",i.Reconnecting="reconnecting",i.SignalReconnecting="signalReconnecting"})(V||(V={}));var Np=4*1e3,dn=class i extends Ee.EventEmitter{get hasE2EESetup(){return this.e2eeManager!==void 0}constructor(e){var t,n,r,s,a,o,d;if(super(),t=this,this.state=V.Disconnected,this.activeSpeakers=[],this.isE2EEEnabled=!1,this.audioEnabled=!0,this.e2eeStateMutex=new de,this.isVideoPlaybackBlocked=!1,this.log=F,this.bufferedEvents=[],this.isResuming=!1,this.connect=(c,l,u)=>p(this,void 0,void 0,function*(){var h;if(!cm())throw He()?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.");let m=yield this.disconnectLock.lock();if(this.state===V.Connected)return this.log.info("already connected to room ".concat(this.name)),m(),Promise.resolve();if(this.connectFuture)return m(),this.connectFuture.promise;this.setAndEmitConnectionState(V.Connecting),((h=this.regionUrlProvider)===null||h===void 0?void 0:h.getServerUrl().toString())!==Qd(c)&&(this.regionUrl=void 0,this.regionUrlProvider=void 0),sn(new URL(c))&&(this.regionUrlProvider===void 0?this.regionUrlProvider=new Ge(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})}));let f=(k,T,S)=>p(this,void 0,void 0,function*(){var L,y;this.abortController&&this.abortController.abort();let b=new AbortController;this.abortController=b,m?.();try{if(yield Zt.getInstance().getBackOffPromise(c),b.signal.aborted)throw N.cancelled("Connection attempt aborted");yield this.attemptConnection(S??c,l,u,b),this.abortController=void 0,k()}catch(E){if(this.regionUrlProvider&&E instanceof N&&E.reason!==J.Cancelled&&E.reason!==J.NotAllowed){let M=null;try{this.log.debug("Fetching next region"),M=yield this.regionUrlProvider.getNextBestRegionUrl((L=this.abortController)===null||L===void 0?void 0:L.signal)}catch(D){if(D instanceof N&&(D.status===401||D.reason===J.Cancelled)){this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),T(D);return}}[J.InternalError,J.ServerUnreachable,J.Timeout].includes(E.reason)&&(this.log.debug("Adding failed connection attempt to back off"),Zt.getInstance().addFailedConnectionAttempt(c)),M&&!(!((y=this.abortController)===null||y===void 0)&&y.signal.aborted)?(this.log.info("Initial connection failed with ConnectionError: ".concat(E.message,". Retrying with another region: ").concat(M)),this.recreateEngine(!0),yield f(k,T,M)):(this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,Do(E)),T(E))}else{let M=re.UNKNOWN_REASON;E instanceof N&&(M=Do(E)),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,M),T(E)}}}),g=this.regionUrl;return this.regionUrl=void 0,this.connectFuture=new ce((k,T)=>{f(k,T,g)},()=>{this.clearConnectionFutures()}),this.connectFuture.promise}),this.connectSignal=(c,l,u,h,m,f)=>p(this,void 0,void 0,function*(){var g;let k=yield u.join(c,l,{autoSubscribe:h.autoSubscribe,adaptiveStream:typeof m.adaptiveStream=="object"?!0:m.adaptiveStream,clientInfoCapabilities:Fn((g=m.frameMetadata)!==null&&g!==void 0?g:m.packetTrailer)||this.e2eeManager?[Gc.CAP_PACKET_TRAILER]:void 0,maxRetries:h.maxRetries,e2eeEnabled:!!this.e2eeManager,websocketTimeout:h.websocketTimeout},f.signal,!m.singlePeerConnection),T=k.joinResponse,S=k.serverInfo;if(this.serverInfo=S,!S.version)throw new is("unknown server version");return S.version==="0.15.1"&&this.options.dynacast&&(this.log.debug("disabling dynacast due to server version"),m.dynacast=!1),T}),this.applyJoinResponse=c=>{let 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)=>p(this,void 0,void 0,function*(){var m,f;this.state===V.Reconnecting||this.isResuming||!((m=this.engine)===null||m===void 0)&&m.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({},Ba),u),this.connOptions.rtcConfig&&(this.engine.rtcConfig=this.connOptions.rtcConfig),this.connOptions.peerConnectionTimeout&&(this.engine.peerConnectionTimeout=this.connOptions.peerConnectionTimeout);try{let g=yield this.connectSignal(c,l,this.engine,this.connOptions,this.options,h);this.applyJoinResponse(g),this.setupLocalParticipantEvents(),this.emit(C.SignalConnected)}catch(g){yield this.engine.close(),this.recreateEngine();let k=h.signal.aborted?N.cancelled("Signal connection aborted"):N.serverUnreachable("could not establish signal connection");throw g instanceof Error&&(k.message="".concat(k.message,": ").concat(g.message)),g instanceof N&&(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(),N.cancelled("Connection attempt aborted");try{yield this.engine.waitForPCInitialConnection(this.connOptions.peerConnectionTimeout,h)}catch(g){throw yield this.engine.close(),this.recreateEngine(),g}Ce()&&this.options.disconnectOnPageLeave&&(window.addEventListener("pagehide",this.onPageLeave),window.addEventListener("beforeunload",this.onPageLeave)),Ce()&&window.addEventListener("freeze",this.onPageLeave),this.setAndEmitConnectionState(V.Connected),this.emit(C.Connected),Zt.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 p(t,[...l],void 0,function(){var h=this;let m=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return(function*(){var f,g,k;let T=yield h.disconnectLock.lock();try{if(h.state===V.Disconnected){h.log.debug("already disconnected");return}if(h.log.info("disconnect from room"),h.state===V.Connecting||h.state===V.Reconnecting||h.isResuming){let 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,N.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(m,re.CLIENT_INITIATED),h.engine=void 0}finally{T()}})()})},this.onPageLeave=()=>p(this,void 0,void 0,function*(){this.log.info("Page leave detected, disconnecting"),yield this.disconnect()}),this.startAudio=()=>p(this,void 0,void 0,function*(){let c=[],l=ke();if(l&&l.os==="iOS"){let u="livekit-dummy-audio-el",h=document.getElementById(u);if(!h){h=document.createElement("audio"),h.id=u,h.autoplay=!0,h.hidden=!0;let m=Rr();m.enabled=!0;let f=new MediaStream([m]);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(C.Disconnected,()=>{h?.remove(),h=null})}c.push(h)}this.remoteParticipants.forEach(u=>{u.audioTrackPublications.forEach(h=>{h.track&&h.track.attachedElements.forEach(m=>{c.push(m)})})});try{yield Promise.all([this.acquireAudioContext(),...c.map(u=>(u.muted=!1,u.play()))]),this.handleAudioPlaybackStarted()}catch(u){throw this.handleAudioPlaybackFailed(u),u}}),this.startVideo=()=>p(this,void 0,void 0,function*(){let c=[];for(let l of this.remoteParticipants.values())l.videoTrackPublications.forEach(u=>{var h;(h=u.track)===null||h===void 0||h.attachedElements.forEach(m=>{c.includes(m)||c.push(m)})});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(let c of this.remoteParticipants.values())this.handleParticipantDisconnected(c.identity,c);this.setAndEmitConnectionState(V.Reconnecting)&&this.emit(C.Reconnecting)},this.handleRestarted=()=>{this.outgoingDataTrackManager.sfuWillRepublishTracks(),this.incomingDataTrackManager.resendSubscriptionUpdates()},this.handleSignalRestarted=c=>p(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(V.Connected),this.emit(C.Reconnected),this.registerConnectionReconcile(),this.emitBufferedEvents()}),this.handleParticipantUpdates=c=>{var l;for(let 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 m=this.remoteParticipants.get(h.identity);h.state===Jt.DISCONNECTED?this.handleParticipantDisconnected(h.identity,m):this.getOrCreateParticipant(h.identity,h)}let u=new Map(c.filter(h=>h.identity!==this.localParticipant.identity).map(h=>[h.identity,h.dataTracks.map(m=>Ii.from(m))]));this.incomingDataTrackManager.receiveSfuPublicationUpdates(u)},this.handleActiveSpeakersUpdate=c=>{let l=[],u={};c.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{let m=this.getRemoteParticipantBySid(h.sid);m&&(m.audioLevel=h.level,m.setIsSpeaking(!0),l.push(m))}}),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(C.ActiveSpeakersChanged,l)},this.handleSpeakersChanged=c=>{let l=new Map;this.activeSpeakers.forEach(h=>{let m=this.remoteParticipants.get(h.identity);m&&m.sid!==h.sid||l.set(h.sid,h)}),c.forEach(h=>{let m=this.getRemoteParticipantBySid(h.sid);h.sid===this.localParticipant.sid&&(m=this.localParticipant),m&&(m.audioLevel=h.level,m.setIsSpeaking(h.active),h.active?l.set(h.sid,m):l.delete(h.sid))});let u=Array.from(l.values());u.sort((h,m)=>m.audioLevel-h.audioLevel),this.activeSpeakers=u,this.emitWhenConnected(C.ActiveSpeakersChanged,u)},this.handleStreamStateUpdate=c=>{c.streamStates.forEach(l=>{let u=this.getRemoteParticipantBySid(l.participantSid);if(!u)return;let h=u.getTrackPublicationBySid(l.trackSid);if(!h||!h.track)return;let m=_.streamStateFromProto(l.state);h.track.setStreamState(m),m!==h.track.streamState&&(u.emit(I.TrackStreamStateChanged,h,h.track.streamState),this.emitWhenConnected(C.TrackStreamStateChanged,h,h.track.streamState,u))})},this.handleSubscriptionPermissionUpdate=c=>{let l=this.getRemoteParticipantBySid(c.participantSid);if(!l)return;let u=l.getTrackPublicationBySid(c.trackSid);u&&u.setAllowed(c.allowed)},this.handleSubscriptionError=c=>{let l=Array.from(this.remoteParticipants.values()).find(h=>h.trackPublications.has(c.trackSid));if(!l)return;let u=l.getTrackPublicationBySid(c.trackSid);u&&u.setSubscriptionError(c.err)},this.handleDataPacket=(c,l)=>{let 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"){let h=c.value.value;this.rpcServerManager.handleIncomingRpcRequest(c.participantIdentity,h)}else if(c.value.case==="rpcResponse"){let 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(C.DataReceived,l.payload,c,u,l.topic,h),c?.emit(I.DataReceived,l.payload,u,h)},this.handleSipDtmf=(c,l)=>{this.emit(C.SipDTMFReceived,l,c),c?.emit(I.SipDTMFReceived,l)},this.handleTranscription=(c,l)=>{let u=l.transcribedParticipantIdentity===this.localParticipant.identity?this.localParticipant:this.getParticipantByIdentity(l.transcribedParticipantIdentity),h=u?.trackPublications.get(l.trackId),m=ym(l,this.transcriptionReceivedTimes);h?.emit(P.TranscriptionReceived,m),u?.emit(I.TranscriptionReceived,m,h),this.emit(C.TranscriptionReceived,m,u,h)},this.handleChatMessage=(c,l)=>{let u=bm(l);this.emit(C.ChatMessage,u,c)},this.handleMetrics=(c,l)=>{this.emit(C.MetricsReceived,c,l)},this.handleDataStream=(c,l)=>{this.incomingDataStreamManager.handleDataStreamPacket(c,l)},this.bufferedSegments=new Map,this.handleAudioPlaybackStarted=()=>{this.canPlaybackAudio||(this.audioEnabled=!0,this.emit(C.AudioPlaybackStatusChanged,!0))},this.handleAudioPlaybackFailed=c=>{this.log.warn("could not playback audio",{error:c}),this.canPlaybackAudio&&(this.audioEnabled=!1,this.emit(C.AudioPlaybackStatusChanged,!1))},this.handleVideoPlaybackStarted=()=>{this.isVideoPlaybackBlocked&&(this.isVideoPlaybackBlocked=!1,this.emit(C.VideoPlaybackStatusChanged,!0))},this.handleVideoPlaybackFailed=()=>{this.isVideoPlaybackBlocked||(this.isVideoPlaybackBlocked=!0,this.emit(C.VideoPlaybackStatusChanged,!1))},this.handleDeviceChange=()=>p(this,void 0,void 0,function*(){var c;((c=ke())===null||c===void 0?void 0:c.os)!=="iOS"&&(yield this.selectDefaultDevices()),this.emit(C.MediaDevicesChanged)}),this.handleRoomUpdate=c=>{let l=this.roomInfo;this.roomInfo=c,l&&l.metadata!==c.metadata&&this.emitWhenConnected(C.RoomMetadataChanged,c.metadata),l?.activeRecording!==c.activeRecording&&this.emitWhenConnected(C.RecordingStatusChanged,c.activeRecording)},this.handleConnectionQualityUpdate=c=>{c.updates.forEach(l=>{if(l.participantSid===this.localParticipant.sid){this.localParticipant.setConnectionQuality(l.quality);return}let 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:qd},this.onLocalParticipantMetadataChanged=c=>{this.emit(C.ParticipantMetadataChanged,c,this.localParticipant)},this.onLocalParticipantNameChanged=c=>{this.emit(C.ParticipantNameChanged,c,this.localParticipant)},this.onLocalAttributesChanged=c=>{this.emit(C.ParticipantAttributesChanged,c,this.localParticipant)},this.onLocalTrackMuted=c=>{this.emit(C.TrackMuted,c,this.localParticipant)},this.onLocalTrackUnmuted=c=>{this.emit(C.TrackUnmuted,c,this.localParticipant)},this.onTrackProcessorUpdate=c=>{var l;(l=c?.onPublish)===null||l===void 0||l.call(c,this)},this.onLocalTrackPublished=c=>p(this,void 0,void 0,function*(){var l,u,h,m,f,g;(l=c.track)===null||l===void 0||l.on(P.TrackProcessorUpdate,this.onTrackProcessorUpdate),(u=c.track)===null||u===void 0||u.on(P.Restarted,this.onLocalTrackRestarted),(f=(m=(h=c.track)===null||h===void 0?void 0:h.getProcessor())===null||m===void 0?void 0:m.onPublish)===null||f===void 0||f.call(m,this),this.emit(C.LocalTrackPublished,c,this.localParticipant),at(c.track)&&(yield c.track.checkForSilence())&&this.emit(C.LocalAudioSilenceDetected,c);let k=yield(g=c.track)===null||g===void 0?void 0:g.getDeviceId(!1),T=cs(c.source);T&&k&&k!==this.localParticipant.activeDeviceMap.get(T)&&(this.localParticipant.activeDeviceMap.set(T,k),this.emit(C.ActiveDeviceChanged,T,k))}),this.onLocalTrackUnpublished=c=>{var l,u;(l=c.track)===null||l===void 0||l.off(P.TrackProcessorUpdate,this.onTrackProcessorUpdate),(u=c.track)===null||u===void 0||u.off(P.Restarted,this.onLocalTrackRestarted),this.emit(C.LocalTrackUnpublished,c,this.localParticipant)},this.onLocalTrackRestarted=c=>p(this,void 0,void 0,function*(){let l=yield c.getDeviceId(!1),u=cs(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(C.ActiveDeviceChanged,u,l))}),this.onLocalConnectionQualityChanged=c=>{this.emit(C.ConnectionQualityChanged,c,this.localParticipant)},this.onMediaDevicesError=(c,l)=>{this.emit(C.MediaDevicesError,c,l)},this.onLocalParticipantPermissionsChanged=c=>{this.emit(C.ParticipantPermissionsChanged,c,this.localParticipant)},this.onLocalChatMessageSent=c=>{this.emit(C.ChatMessage,c,this.localParticipant)},this.setMaxListeners(100),this.remoteParticipants=new Map,this.sidToIdentity=new Map,this.options=Object.assign(Object.assign({},Zm),e),this.log=_e((n=this.options.loggerName)!==null&&n!==void 0?n:ue.Room,()=>this.logContext),this.transcriptionReceivedTimes=new Map,this.options.audioCaptureDefaults=Object.assign(Object.assign({},Xd),e?.audioCaptureDefaults),this.options.videoCaptureDefaults=Object.assign(Object.assign({},Zd),e?.videoCaptureDefaults),this.options.publishDefaults=Object.assign(Object.assign({},Xm),e?.publishDefaults),this.maybeCreateEngine(),this.incomingDataStreamManager=new xs,this.outgoingDataStreamManager=new Ls(this.engine,this.log),this.incomingDataTrackManager=new Us({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(C.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(C.DataTrackUnpublished,c.sid),(l=this.remoteParticipants.get(c.publisherIdentity))===null||l===void 0||l.removeRemoteDataTrack(c.sid))}),this.outgoingDataTrackManager=new Bs({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(C.LocalDataTrackPublished,c.track)}).on("trackUnpublished",c=>{this.emit(C.LocalDataTrackUnpublished,c.sid)}).on("packetAvailable",c=>{let l=c.handle,u=c.bytes;this.engine.sendLossyBytes(u,U.DATA_TRACK_LOSSY,"wait").finally(()=>this.outgoingDataTrackManager.handlePacketSendComplete(l))}),this.registerRpcDataStreamHandler(),this.rpcClientManager=new qs(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,U.RELIABLE)}),this.rpcServerManager=new js(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,U.RELIABLE)}),this.disconnectLock=new de,this.localParticipant=new Hs("","",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",Lt(this.options.videoCaptureDefaults.deviceId)),this.options.audioCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("audioinput",Lt(this.options.audioCaptureDefaults.deviceId)),!((a=this.options.audioOutput)===null||a===void 0)&&a.deviceId&&this.switchActiveDevice("audiooutput",Lt(this.options.audioOutput.deviceId)).catch(c=>this.log.warn("Could not set audio output: ".concat(c.message))),Ce()){let c=new AbortController,l;if(i.cleanupRegistry){let u=new WeakRef(this);l=()=>{let h=u.deref();h&&h.handleDeviceChange()},i.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)}registerRpcMethod(e,t){this.rpcServerManager.registerRpcMethod(e,t)}unregisterRpcMethod(e){this.rpcServerManager.unregisterRpcMethod(e)}setE2EEEnabled(e){return p(this,void 0,void 0,function*(){let t=yield this.e2eeStateMutex.lock();try{if(this.e2eeManager)this.isE2EEEnabled!==e&&(yield this.localParticipant.setE2EEEnabled(e),this.localParticipant.identity!==""&&this.e2eeManager.setParticipantCryptorEnabled(e,this.localParticipant.identity));else throw Error("e2ee not configured, please set e2ee settings within the room options")}finally{t()}})}setupE2EE(){var e,t;let n=!!this.options.encryption,r=this.options.encryption||this.options.e2ee;r&&("e2eeManager"in r?(this.e2eeManager=r.e2eeManager,this.e2eeManager.isDataChannelEncryptionEnabled=n):this.e2eeManager=new gs(r,n),this.e2eeManager.on(bt.ParticipantEncryptionStatusChanged,(s,a)=>{Tm(a)&&(this.isE2EEEnabled=s),this.emit(C.ParticipantEncryptionStatusChanged,s,a)}),this.e2eeManager.on(bt.EncryptionError,(s,a)=>{let o=a?this.getParticipantByIdentity(a):void 0;this.emit(C.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;let t=(e=this.options.frameMetadata)!==null&&e!==void 0?e:this.options.packetTrailer;this.frameMetadataManager=new ys(t),this.frameMetadataManager.setup(this)}get logContext(){var e,t,n;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:(n=this.localParticipant)===null||n===void 0?void 0:n.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===V.Disconnected?pe.resolve(""):this.roomInfo&&this.roomInfo.sid!==""?pe.resolve(this.roomInfo.sid):new pe((e,t)=>{let n=r=>{r.sid!==""&&(this.engine.off(R.RoomUpdate,n),e(r.sid))};this.engine.on(R.RoomUpdate,n),this.once(C.Disconnected,()=>{this.engine.off(R.RoomUpdate,n),t(new W("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 Ps(this.options),this.engine.e2eeManager=this.e2eeManager,this.engine.on(R.ParticipantUpdate,this.handleParticipantUpdates).on(R.RoomUpdate,this.handleRoomUpdate).on(R.SpeakersChanged,this.handleSpeakersChanged).on(R.StreamStateChanged,this.handleStreamStateUpdate).on(R.ConnectionQualityUpdate,this.handleConnectionQualityUpdate).on(R.SubscriptionError,this.handleSubscriptionError).on(R.SubscriptionPermissionUpdate,this.handleSubscriptionPermissionUpdate).on(R.MediaTrackAdded,(e,t,n)=>{this.onTrackAdded(e,t,n)}).on(R.Disconnected,e=>{this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e)}).on(R.ActiveSpeakersUpdate,this.handleActiveSpeakersUpdate).on(R.DataPacketReceived,this.handleDataPacket).on(R.Resuming,()=>{this.clearConnectionReconcile(),this.isResuming=!0,this.log.debug("Resuming signal connection"),this.setAndEmitConnectionState(V.SignalReconnecting)&&this.emit(C.SignalReconnecting)}).on(R.Resumed,()=>{this.registerConnectionReconcile(),this.isResuming=!1,this.log.debug("Resumed signal connection"),this.updateSubscriptions(),this.emitBufferedEvents(),this.setAndEmitConnectionState(V.Connected)&&this.emit(C.Reconnected)}).on(R.SignalResumed,()=>{this.bufferedEvents=[],(this.state===V.Reconnecting||this.isResuming)&&this.sendSyncState()}).on(R.Restarting,this.handleRestarting).on(R.Restarted,this.handleRestarted).on(R.SignalRestarted,this.handleSignalRestarted).on(R.Offline,()=>{this.setAndEmitConnectionState(V.Reconnecting)&&this.emit(C.Reconnecting)}).on(R.DCBufferStatusChanged,(e,t)=>{this.emit(C.DCBufferStatusChanged,e,t)}).on(R.LocalTrackSubscribed,e=>{this.handleLocalTrackSubscribed(e)}).on(R.RoomMoved,e=>{this.log.debug("room moved",e),e.room&&this.handleRoomUpdate(e.room),this.remoteParticipants.forEach((t,n)=>{this.handleParticipantDisconnected(n,t)}),this.emit(C.Moved,e.room.name),e.participant?this.handleParticipantUpdates([e.participant,...e.otherParticipants]):this.handleParticipantUpdates(e.otherParticipants)}).on(R.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!==$.NONE}})}).on(R.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(R.DataTrackSubscriberHandles,e=>{let t=new Map(Object.entries(e.subHandles).map(n=>{let r=O(n,2),s=r[0],a=r[1];return[parseInt(s,10),a.trackSid]}));this.incomingDataTrackManager.receivedSfuSubscriberHandles(t)}).on(R.DataTrackPacketReceived,e=>{try{this.incomingDataTrackManager.packetReceived(e)}catch(t){throw t}}).on(R.Joined,e=>{let t=new Map(e.otherParticipants.map(n=>[n.identity,n.dataTracks.map(r=>Ii.from(r))]));this.incomingDataTrackManager.receiveSfuPublicationUpdates(t)}).on(R.TokenRefreshed,e=>{var t;(t=this.regionUrlProvider)===null||t===void 0||t.updateToken(e)}).on(R.ServerRegionsReported,e=>{var t;(t=this.regionUrlProvider)===null||t===void 0||t.setServerReportedRegions({regionSettings:e,updatedAtInMs:Date.now(),maxAgeInMs:Is})}),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=>p(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 Pe.getInstance().getDevices(e,t)}prepareConnection(e,t){return p(this,void 0,void 0,function*(){if(this.state===V.Disconnected){this.log.debug("prepareConnection to ".concat(e));try{if(sn(new URL(e))&&t){this.regionUrlProvider=new Ge(e,t);let n=yield this.regionUrlProvider.getNextBestRegionUrl();n&&this.state===V.Disconnected&&(this.regionUrl=n,yield fetch(Nn(n),{method:"HEAD"}),this.log.debug("prepared connection to ".concat(n)))}else yield fetch(Nn(e),{method:"HEAD"})}catch(n){this.log.warn("could not prepare connection",{error:n})}}})}getParticipantByIdentity(e){return this.localParticipant.identity===e?this.localParticipant:this.remoteParticipants.get(e)}clearConnectionFutures(){this.connectFuture=void 0}simulateScenario(e,t){return p(this,void 0,void 0,function*(){let n=()=>p(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 Qe({scenario:{case:"speakerUpdate",value:3}});break;case"node-failure":r=new Qe({scenario:{case:"nodeFailure",value:!0}});break;case"server-leave":r=new Qe({scenario:{case:"serverLeave",value:!0}});break;case"migration":r=new Qe({scenario:{case:"migration",value:!0}});break;case"resume-reconnect":this.engine.failNext(),yield this.engine.client.handleOnClose("simulate resume-disconnect");break;case"disconnect-signal-on-resume":n=()=>p(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),r=new Qe({scenario:{case:"disconnectSignalOnResume",value:!0}});break;case"disconnect-signal-on-resume-no-messages":n=()=>p(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),r=new Qe({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 Qe({scenario:{case:"switchCandidateProtocol",value:e==="force-tls"?2:1}}),n=()=>p(this,void 0,void 0,function*(){let s=this.engine.client.onLeave;s&&s(new rr({reason:re.CLIENT_INITIATED,action:$t.RECONNECT}))});break;case"subscriber-bandwidth":if(t===void 0||typeof t!="number")throw new Error("subscriber-bandwidth requires a number as argument");r=new Qe({scenario:{case:"subscriberBandwidth",value:Pt(t)}});break;case"leave-full-reconnect":r=new Qe({scenario:{case:"leaveRequestFullReconnect",value:!0}})}r&&(yield this.engine.client.sendSimulateScenario(r),yield n())})}get canPlaybackAudio(){return this.audioEnabled}get canPlaybackVideo(){return!this.isVideoPlaybackBlocked}getActiveDevice(e){return this.localParticipant.activeDeviceMap.get(e)}switchActiveDevice(e,t){return p(this,arguments,void 0,function(n,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,m;let f=!0,g=!1,k=a?{exact:r}:r;if(n==="audioinput"){g=s.localParticipant.audioTrackPublications.size===0;let T=(o=s.getActiveDevice(n))!==null&&o!==void 0?o:s.options.audioCaptureDefaults.deviceId;s.options.audioCaptureDefaults.deviceId=k;let S=Array.from(s.localParticipant.audioTrackPublications.values()).filter(y=>y.source===_.Source.Microphone);try{f=(yield Promise.all(S.map(y=>{var b;return(b=y.audioTrack)===null||b===void 0?void 0:b.setDeviceId(k)}))).every(y=>y===!0)}catch(y){throw s.options.audioCaptureDefaults.deviceId=T,y}let L=S.some(y=>{var b,E;return(E=(b=y.track)===null||b===void 0?void 0:b.isMuted)!==null&&E!==void 0?E:!1});f&&L&&(g=!0)}else if(n==="videoinput"){g=s.localParticipant.videoTrackPublications.size===0;let T=(d=s.getActiveDevice(n))!==null&&d!==void 0?d:s.options.videoCaptureDefaults.deviceId;s.options.videoCaptureDefaults.deviceId=k;let S=Array.from(s.localParticipant.videoTrackPublications.values()).filter(y=>y.source===_.Source.Camera);try{f=(yield Promise.all(S.map(y=>{var b;return(b=y.videoTrack)===null||b===void 0?void 0:b.setDeviceId(k)}))).every(y=>y===!0)}catch(y){throw s.options.videoCaptureDefaults.deviceId=T,y}let L=S.some(y=>{var b,E;return(E=(b=y.track)===null||b===void 0?void 0:b.isMuted)!==null&&E!==void 0?E:!1});f&&L&&(g=!0)}else if(n==="audiooutput"){if(g=!0,!us()&&!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 Pe.getInstance().normalizeDeviceId("audiooutput",r))!==null&&c!==void 0?c:""),(l=(m=s.options).audioOutput)!==null&&l!==void 0||(m.audioOutput={});let T=(u=s.getActiveDevice(n))!==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(n,r),s.emit(C.ActiveDeviceChanged,n,r)),f})()})}setupLocalParticipantEvents(){this.localParticipant.on(I.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).on(I.ParticipantNameChanged,this.onLocalParticipantNameChanged).on(I.AttributesChanged,this.onLocalAttributesChanged).on(I.TrackMuted,this.onLocalTrackMuted).on(I.TrackUnmuted,this.onLocalTrackUnmuted).on(I.LocalTrackPublished,this.onLocalTrackPublished).on(I.LocalTrackUnpublished,this.onLocalTrackUnpublished).on(I.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).on(I.MediaDevicesError,this.onMediaDevicesError).on(I.AudioStreamAcquired,this.startAudio).on(I.ChatMessage,this.onLocalChatMessageSent).on(I.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged)}recreateEngine(e){let t=this.engine;e&&t&&!t.client.isDisconnected?t.client.sendLeave().finally(()=>t.close()):t?.close(),this.engine=void 0,this.isResuming=!1,this.remoteParticipants.clear(),this.sidToIdentity.clear(),this.bufferedEvents=[],this.maybeCreateEngine()}onTrackAdded(e,t,n){if(this.state===V.Connecting||this.state===V.Reconnecting){let u=()=>{this.log.debug("deferring on track for later",{mediaTrackId:e.id,mediaStreamId:t.id,tracksInStream:t.getTracks().map(m=>m.id)}),this.onTrackAdded(e,t,n),h()},h=()=>{this.off(C.Reconnected,u),this.off(C.Connected,u),this.off(C.Disconnected,h)};this.once(C.Reconnected,u),this.once(C.Connected,u),this.once(C.Disconnected,h);return}if(this.state===V.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}let r=sm(t.id),s=r[0],a=r[1],o=e.id;if(a&&a.startsWith("TR")&&(o=a),s===this.localParticipant.sid){this.log.warn("tried to create RemoteParticipant for local participant");return}let d=Array.from(this.remoteParticipants.values()).find(u=>u.sid===s);if(!d){s.startsWith("PA")&&this.log.error("Tried to add a track for a participant, that's not present. Sid: ".concat(s));return}if(!o.startsWith("TR")){let u=this.engine.getTrackIdForReceiver(n);if(!u){this.log.error("Tried to add a track whose 'sid' could not be found for a participant, that's not present. Sid: ".concat(s));return}o=u}o.startsWith("TR")||this.log.warn("Tried to add a track whose 'sid' could not be determined for a participant, that's not present. Sid: ".concat(s,", streamId: ").concat(a,", trackId: ").concat(o),{remoteParticipantID:s,streamId:a,trackId:o});let c;this.options.adaptiveStream&&(typeof this.options.adaptiveStream=="object"?c=this.options.adaptiveStream:c={});let l=d.addSubscribedMediaTrack(e,o,t,n,c);l?.isEncrypted&&!this.e2eeManager&&this.emit(C.EncryptionError,new Error("Encrypted ".concat(l.source," track received from participant ").concat(d.sid,", but room does not have encryption enabled!")))}handleLocalTrackSubscribed(e){let t=()=>this.localParticipant.getTrackPublications().find(d=>d.trackSid===e),n=t();if(n){this.emitLocalTrackSubscribed(n);return}this.log.debug("deferring LocalTrackSubscribed, publication not yet available",{subscribedSid:e});let r=1e4,s,a=d=>{d.trackSid===e&&(o(),this.emitLocalTrackSubscribed(d))},o=()=>{clearTimeout(s),this.localParticipant.off(I.LocalTrackPublished,a),this.off(C.Disconnected,o)};this.localParticipant.on(I.LocalTrackPublished,a),this.once(C.Disconnected,o),s=setTimeout(()=>{o();let 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(I.LocalTrackSubscribed,e),this.emitWhenConnected(C.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 n,r;if(this.clearConnectionReconcile(),this.isResuming=!1,this.bufferedEvents=[],this.transcriptionReceivedTimes.clear(),this.incomingDataStreamManager.clearControllers(),this.incomingDataTrackManager.reset(),this.outgoingDataTrackManager.reset(),this.state!==V.Disconnected){this.regionUrl=void 0,this.regionUrlProvider&&this.regionUrlProvider.notifyDisconnected();try{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(I.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).off(I.ParticipantNameChanged,this.onLocalParticipantNameChanged).off(I.AttributesChanged,this.onLocalAttributesChanged).off(I.TrackMuted,this.onLocalTrackMuted).off(I.TrackUnmuted,this.onLocalTrackUnmuted).off(I.LocalTrackPublished,this.onLocalTrackPublished).off(I.LocalTrackUnpublished,this.onLocalTrackUnpublished).off(I.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).off(I.MediaDevicesError,this.onMediaDevicesError).off(I.AudioStreamAcquired,this.startAudio).off(I.ChatMessage,this.onLocalChatMessageSent).off(I.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),Ce()&&(window.removeEventListener("beforeunload",this.onPageLeave),window.removeEventListener("pagehide",this.onPageLeave),window.removeEventListener("freeze",this.onPageLeave),(r=(n=navigator.mediaDevices)===null||n===void 0?void 0:n.removeEventListener)===null||r===void 0||r.call(n,"devicechange",this.handleDeviceChange))}finally{this.setAndEmitConnectionState(V.Disconnected),this.emit(C.Disconnected,t)}}}handleParticipantDisconnected(e,t){this.remoteParticipants.delete(e),t&&(this.incomingDataStreamManager.validateParticipantHasNoActiveDataStreams(e),this.incomingDataTrackManager.handleRemoteParticipantDisconnected(e),t.trackPublications.forEach(n=>{t.unpublishTrack(n.trackSid,!0)}),this.emit(C.ParticipantDisconnected,t),t.setDisconnected(),this.rpcClientManager.handleParticipantDisconnected(t.identity))}selectDefaultDevices(){return p(this,void 0,void 0,function*(){var e,t,n;let r=Pe.getInstance().previousDevices,s=yield Pe.getInstance().getDevices(void 0,!1),a=ke();if(a?.name==="Chrome"&&a.os!=="iOS")for(let d of s){let 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(C.ActiveDeviceChanged,d.kind,d.deviceId)}let o=["audiooutput","audioinput","videoinput"];for(let d of o){let c=Qh(d),l=this.localParticipant.getTrackPublication(c);if(l&&(!((e=l.track)===null||e===void 0)&&e.isUserProvided))continue;let u=s.filter(m=>m.kind===d),h=this.getActiveDevice(d);if(h===((t=r.filter(m=>m.kind===d)[0])===null||t===void 0?void 0:t.deviceId)&&u.length>0&&((n=u[0])===null||n===void 0?void 0:n.deviceId)!==h){yield this.switchActiveDevice(d,u[0].deviceId);continue}d==="audioinput"&&!Ln()||d==="videoinput"||u.length>0&&!u.find(m=>m.deviceId===this.getActiveDevice(d))&&(d!=="audiooutput"||!Ln())&&(yield this.switchActiveDevice(d,u[0].deviceId))}})}acquireAudioContext(){return p(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=Gd())!==null&&e!==void 0?e:void 0),this.options.webAudioMix&&this.remoteParticipants.forEach(r=>r.setAudioContext(this.audioContext)),this.localParticipant.setAudioContext(this.audioContext),this.audioContext&&this.audioContext.state==="suspended")try{yield Promise.race([this.audioContext.resume(),ve(200)])}catch(r){this.log.warn("Could not resume audio context",{error:r})}let n=((t=this.audioContext)===null||t===void 0?void 0:t.state)==="running";n!==this.canPlaybackAudio&&(this.audioEnabled=n,this.emit(C.AudioPlaybackStatusChanged,n))})}createParticipant(e,t){var n;let r;return t?r=Qi.fromParticipantInfo(this.engine.client,t,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName},this.incomingDataTrackManager):r=new Qi(this.engine.client,"",e,void 0,void 0,void 0,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}),this.options.webAudioMix&&r.setAudioContext(this.audioContext),!((n=this.options.audioOutput)===null||n===void 0)&&n.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)){let r=this.remoteParticipants.get(e);return t&&r.updateInfo(t)&&this.sidToIdentity.set(t.sid,t.identity),r}let n=this.createParticipant(e,t);return this.remoteParticipants.set(e,n),this.sidToIdentity.set(t.sid,t.identity),this.emitWhenConnected(C.ParticipantConnected,n),n.on(I.TrackPublished,r=>{this.emitWhenConnected(C.TrackPublished,r,n)}).on(I.TrackSubscribed,(r,s)=>{r.kind===_.Kind.Audio?(r.on(P.AudioPlaybackStarted,this.handleAudioPlaybackStarted),r.on(P.AudioPlaybackFailed,this.handleAudioPlaybackFailed)):r.kind===_.Kind.Video&&(r.on(P.VideoPlaybackFailed,this.handleVideoPlaybackFailed),r.on(P.VideoPlaybackStarted,this.handleVideoPlaybackStarted)),this.emitWhenConnected(C.TrackSubscribed,r,s,n)}).on(I.TrackUnpublished,r=>{this.emit(C.TrackUnpublished,r,n)}).on(I.TrackUnsubscribed,(r,s)=>{this.emit(C.TrackUnsubscribed,r,s,n)}).on(I.TrackMuted,r=>{this.emitWhenConnected(C.TrackMuted,r,n)}).on(I.TrackUnmuted,r=>{this.emitWhenConnected(C.TrackUnmuted,r,n)}).on(I.ParticipantMetadataChanged,r=>{this.emitWhenConnected(C.ParticipantMetadataChanged,r,n)}).on(I.ParticipantNameChanged,r=>{this.emitWhenConnected(C.ParticipantNameChanged,r,n)}).on(I.AttributesChanged,r=>{this.emitWhenConnected(C.ParticipantAttributesChanged,r,n)}).on(I.ConnectionQualityChanged,r=>{this.emitWhenConnected(C.ConnectionQualityChanged,r,n)}).on(I.ParticipantPermissionsChanged,r=>{this.emitWhenConnected(C.ParticipantPermissionsChanged,r,n)}).on(I.TrackSubscriptionStatusChanged,(r,s)=>{this.emitWhenConnected(C.TrackSubscriptionStatusChanged,r,s,n)}).on(I.TrackSubscriptionFailed,(r,s)=>{this.emit(C.TrackSubscriptionFailed,r,n,s)}).on(I.TrackSubscriptionPermissionChanged,(r,s)=>{this.emitWhenConnected(C.TrackSubscriptionPermissionChanged,r,s,n)}).on(I.Active,()=>{this.emitWhenConnected(C.ParticipantActive,n),n.kind===An.AGENT&&this.localParticipant.setActiveAgent(n)}),t&&n.updateInfo(t),n}sendSyncState(){let e=Array.from(this.remoteParticipants.values()).reduce((r,s)=>(r.push(...s.getTrackPublications()),r),[]),t=this.localParticipant.getTrackPublications(),n=this.outgoingDataTrackManager.queryPublished();this.engine.sendSyncState(e,t,n)}updateSubscriptions(){for(let e of this.remoteParticipants.values())for(let t of e.videoTrackPublications.values())t.isSubscribed&&km(t)&&t.emitTrackUpdate()}getRemoteParticipantBySid(e){let t=this.sidToIdentity.get(e);if(t)return this.remoteParticipants.get(t)}registerRpcDataStreamHandler(){this.incomingDataStreamManager.registerTextStreamHandler(cl,(e,t)=>p(this,[e,t],void 0,function(n,r){var s=this;let a=r.identity;return(function*(){var o;let d=(o=n.info.attributes)!==null&&o!==void 0?o:{};yield s.rpcServerManager.handleIncomingDataStream(n,a,d)})()})),this.incomingDataStreamManager.registerTextStreamHandler(dl,(e,t)=>p(this,[e,t],void 0,function(n,r){var s=this;let a=r.identity;return(function*(){var o;let d=(o=n.info.attributes)!==null&&o!==void 0?o:{};yield s.rpcClientManager.handleIncomingDataStream(n,a,d)})()}))}registerConnectionReconcile(){this.clearConnectionReconcile();let e=0;this.connectionReconcileInterval=se.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.recreateEngine(),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,re.STATE_MISMATCH))):e=0},Np)}clearConnectionReconcile(){this.connectionReconcileInterval&&se.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===V.Connected),this.emit(C.ConnectionStateChanged,this.state),!0)}emitBufferedEvents(){this.bufferedEvents.forEach(e=>{let t=O(e,2),n=t[0],r=t[1];this.emit(n,...r)}),this.bufferedEvents=[]}emitWhenConnected(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),r=1;r<t;r++)n[r-1]=arguments[r];if(this.state===V.Reconnecting||this.isResuming||!this.engine||this.engine.pendingReconnect)this.bufferedEvents.push([e,n]);else if(this.state===V.Connected)return this.emit(e,...n);return!1}simulateParticipants(e){return p(this,void 0,void 0,function*(){var t,n,r,s;let 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 Xi({sid:"RM_SIMULATED",name:"simulated-room",emptyTimeout:0,maxParticipants:0,creationTime:Y.parse(new Date().getTime()),metadata:"",numParticipants:1,numPublishers:1,turnPassword:"",enabledCodecs:[],activeRecording:!1}),this.localParticipant.updateInfo(new Ut({identity:"simulated-local",name:"local-name"})),this.setupLocalParticipantEvents(),this.emit(C.SignalConnected),this.emit(C.Connected),this.setAndEmitConnectionState(V.Connected),a.video){let d=new Hn(_.Kind.Video,new Wt({source:oe.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:Ue.AUDIO,name:"video-dummy"}),new an(a.useRealTracks&&(!((t=window.navigator.mediaDevices)===null||t===void 0)&&t.getUserMedia)?(yield window.navigator.mediaDevices.getUserMedia({video:!0})).getVideoTracks()[0]:xo(160*((n=o.aspectRatios[0])!==null&&n!==void 0?n: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(I.LocalTrackPublished,d)}if(a.audio){let d=new Hn(_.Kind.Audio,new Wt({source:oe.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:Ue.AUDIO}),new Et(a.useRealTracks&&(!((r=navigator.mediaDevices)===null||r===void 0)&&r.getUserMedia)?(yield navigator.mediaDevices.getUserMedia({audio:!0})).getAudioTracks()[0]:Rr(),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(I.LocalTrackPublished,d)}for(let d=0;d<o.count-1;d+=1){let c=new Ut({sid:Math.floor(Math.random()*1e4).toString(),identity:"simulated-".concat(d),state:Jt.ACTIVE,tracks:[],joinedAt:Y.parse(Date.now())}),l=this.getOrCreateParticipant(c.identity,c);if(o.video){let u=xo(160*((s=o.aspectRatios[d%o.aspectRatios.length])!==null&&s!==void 0?s:1),160,!1,!0),h=new Wt({source:oe.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:Ue.AUDIO});l.addSubscribedMediaTrack(u,h.sid,new MediaStream([u]),new RTCRtpReceiver),c.tracks=[...c.tracks,h]}if(o.audio){let u=Rr(),h=new Wt({source:oe.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:Ue.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,n=new Array(t>1?t-1:0),r=1;r<t;r++)n[r-1]=arguments[r];if(e!==C.ActiveSpeakersChanged&&e!==C.TranscriptionReceived){let s=ul(n).filter(a=>a!==void 0);(e===C.TrackSubscribed||e===C.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,...n)}};dn.cleanupRegistry=typeof FinalizationRegistry<"u"&&typeof WeakRef<"u"&&new FinalizationRegistry(i=>{i()});function ul(i){return i.map(e=>{if(e)return Array.isArray(e)?ul(e):typeof e=="object"?"logContext"in e?e.logContext:void 0:e})}var Le;(function(i){i[i.IDLE=0]="IDLE",i[i.RUNNING=1]="RUNNING",i[i.SKIPPED=2]="SKIPPED",i[i.SUCCESS=3]="SUCCESS",i[i.FAILED=4]="FAILED"})(Le||(Le={}));var nt=class extends Ee.EventEmitter{constructor(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.status=Le.IDLE,this.logs=[],this.options={},this.url=e,this.token=t,this.name=this.constructor.name,this.room=new dn(n.roomOptions),this.connectOptions=n.connectOptions,this.options=n}run(e){return p(this,void 0,void 0,function*(){if(this.status!==Le.IDLE)throw Error("check is running already");this.setStatus(Le.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!==Le.SKIPPED&&this.setStatus(this.isSuccess()?Le.SUCCESS:Le.FAILED),e&&e(),this.getInfo()})}isSuccess(){return!this.logs.some(e=>e.level==="error")}connect(e){return p(this,void 0,void 0,function*(){return this.room.state===V.Connected?this.room:(e||(e=this.url),yield this.room.connect(e,this.token,this.connectOptions),this.room)})}disconnect(){return p(this,void 0,void 0,function*(){this.room&&this.room.state!==V.Disconnected&&(yield this.room.disconnect(),yield new Promise(e=>setTimeout(e,500)))})}skip(){this.setStatus(Le.SKIPPED)}switchProtocol(e){return p(this,void 0,void 0,function*(){let t=!1,n=!1;if(this.room.on(C.Reconnecting,()=>{t=!0}),this.room.once(C.Reconnected,()=>{n=!0}),this.room.simulateScenario("force-".concat(e)),yield new Promise(s=>setTimeout(s,1e3)),!t)return;let r=Date.now()+1e4;for(;Date.now()<r;){if(n)return;yield ve(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}}},Ws=class extends nt{get description(){return"Cloud regions"}perform(){return p(this,void 0,void 0,function*(){let e=new Ge(this.url,this.token);if(!e.isCloud()){this.skip();return}let t=[],n=new Set;for(let s=0;s<3;s++){let a=yield e.getNextBestRegionUrl();if(!a)break;if(n.has(a))continue;n.add(a);let 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);let r=t[0];this.bestStats=r,this.appendMessage("best Cloud region: ".concat(r.region))})}getInfo(){let e=super.getInfo();return e.data=this.bestStats,e}checkCloudRegion(e){return p(this,void 0,void 0,function*(){var t,n;yield this.connect(e),this.options.protocol==="tcp"&&(yield this.switchProtocol("tcp"));let r=(t=this.room.serverInfo)===null||t===void 0?void 0:t.region;if(!r)throw new Error("Region not found");let 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();let u=Date.now(),h=yield(n=this.room.engine.pcManager)===null||n===void 0?void 0:n.publisher.getStats(),m={region:r,rtt:1e4,duration:u-l};return h?.forEach(f=>{f.type==="candidate-pair"&&f.nominated&&(m.rtt=f.currentRoundTripTime*1e3)}),yield this.disconnect(),m})}},Fr=1e4,zs=class extends nt{get description(){return"Connection via UDP vs TCP"}perform(){return p(this,void 0,void 0,function*(){let 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");let n=this.bestStats;this.appendMessage("upstream bitrate: ".concat((n.bitrateTotal/n.count/1e3/1e3).toFixed(2)," mbps")),this.appendMessage("RTT: ".concat((n.rttTotal/n.count*1e3).toFixed(2)," ms")),this.appendMessage("jitter: ".concat((n.jitterTotal/n.count*1e3).toFixed(2)," ms")),n.packetsLost>0&&this.appendWarning("packets lost: ".concat((n.packetsLost/n.packetsSent*100).toFixed(2),"%")),n.qualityLimitationDurations.bandwidth>1&&this.appendWarning("bandwidth limited ".concat((n.qualityLimitationDurations.bandwidth/(Fr/1e3)*100).toFixed(2),"%")),n.qualityLimitationDurations.cpu>0&&this.appendWarning("cpu limited ".concat((n.qualityLimitationDurations.cpu/(Fr/1e3)*100).toFixed(2),"%"))})}getInfo(){let e=super.getInfo();return e.data=this.bestStats,e}checkConnectionProtocol(e){return p(this,void 0,void 0,function*(){yield this.connect(),e==="tcp"?yield this.switchProtocol("tcp"):yield this.switchProtocol("udp");let t=document.createElement("canvas");t.width=1280,t.height=720;let n=t.getContext("2d");if(!n)throw new Error("Could not get canvas context");let r=0,s=()=>{r=(r+1)%360,n.fillStyle="hsl(".concat(r,", 100%, 50%)"),n.fillRect(0,0,t.width,t.height),requestAnimationFrame(s)};s();let 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(()=>p(this,void 0,void 0,function*(){let h=yield c.getRTCStatsReport();h?.forEach(m=>{m.type==="outbound-rtp"?(l.packetsSent=m.packetsSent,l.qualityLimitationDurations=m.qualityLimitationDurations,l.bitrateTotal+=m.targetBitrate,l.count++):m.type==="remote-inbound-rtp"&&(l.packetsLost=m.packetsLost,l.rttTotal+=m.roundTripTime,l.jitterTotal+=m.jitter)})}),1e3);return yield new Promise(h=>setTimeout(h,Fr)),clearInterval(u),o.stop(),t.remove(),yield this.disconnect(),l})}},Js=class extends nt{get description(){return"Can publish audio"}perform(){return p(this,void 0,void 0,function*(){var e;let t=yield this.connect(),n=yield Dp();if(yield Hd(n,1e3))throw new Error("unable to detect audio from microphone");this.appendMessage("detected audio from microphone"),t.localParticipant.publishTrack(n),yield new Promise(o=>setTimeout(o,3e3));let s=yield(e=n.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"))})}},$s=class extends nt{get description(){return"Can publish video"}perform(){return p(this,void 0,void 0,function*(){var e;let t=yield this.connect(),n=yield xp();yield this.checkForVideo(n.mediaStreamTrack),t.localParticipant.publishTrack(n),yield new Promise(a=>setTimeout(a,5e3));let r=yield(e=n.sender)===null||e===void 0?void 0:e.getStats();if(!r)throw new Error("Could not get RTCStats");let s=0;if(r.forEach(a=>{a.type==="outbound-rtp"&&(a.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 p(this,void 0,void 0,function*(){let t=new MediaStream;t.addTrack(e.clone());let n=document.createElement("video");n.srcObject=t,n.muted=!0,n.autoplay=!0,n.playsInline=!0,n.setAttribute("playsinline","true"),document.body.appendChild(n),yield new Promise(r=>{n.onplay=()=>{setTimeout(()=>{var s,a,o,d;let c=document.createElement("canvas"),l=e.getSettings(),u=(a=(s=l.width)!==null&&s!==void 0?s:n.videoWidth)!==null&&a!==void 0?a:1280,h=(d=(o=l.height)!==null&&o!==void 0?o:n.videoHeight)!==null&&d!==void 0?d:720;c.width=u,c.height=h;let m=c.getContext("2d");m.drawImage(n,0,0);let g=m.getImageData(0,0,c.width,c.height).data,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)},n.play()}),t.getTracks().forEach(r=>r.stop()),n.remove()})}},Qs=class extends nt{get description(){return"Resuming connection after interruption"}perform(){return p(this,void 0,void 0,function*(){var e;let t=yield this.connect(),n=!1,r=!1,s,a=new Promise(c=>{setTimeout(c,5e3),s=c}),o=()=>{n=!0};t.on(C.SignalReconnecting,o).on(C.Reconnecting,o).on(C.Reconnected,()=>{r=!0,s(!0)}),(e=t.engine.client.ws)===null||e===void 0||e.close();let d=t.engine.client.onClose;if(d&&d(""),yield a,n){if(!r||t.state!==V.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")})}},Ys=class extends nt{get description(){return"Can connect via TURN"}perform(){return p(this,void 0,void 0,function*(){var e,t,n;sn(new URL(this.url))&&(this.appendMessage("Using region specific url"),this.url=(e=yield new Ge(this.url,this.token).getNextBestRegionUrl())!==null&&e!==void 0?e:this.url);let r=new jn,s=yield r.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3},void 0,!0),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(),!((n=(t=this.connectOptions)===null||t===void 0?void 0:t.rtcConfig)===null||n===void 0)&&n.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)))})}},Xs=class extends nt{get description(){return"Establishing WebRTC connection"}perform(){return p(this,void 0,void 0,function*(){let e=!1,t=!1;this.room.on(C.SignalConnected,()=>{var n;let r=this.room.engine.client.onTrickle;this.room.engine.client.onTrickle=(s,a)=>{if(s.candidate){let o=new RTCIceCandidate(s),d="".concat(o.protocol," ").concat(o.address,":").concat(o.port," ").concat(o.type);o.address&&(Up(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)},!((n=this.room.engine.pcManager)===null||n===void 0)&&n.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(),F.info("now the room is connected")}catch(n){throw this.appendWarning("ports need to be open on firewall in order to connect."),n}e||this.appendWarning("Server is not configured for ICE/TCP"),t||this.appendWarning("No public IPv4 UDP candidates were found. Your server is likely not configured correctly")})}};function Up(i){let e=i.split(".");if(e.length===4){if(e[0]==="10")return!0;if(e[0]==="192"&&e[1]==="168")return!0;if(e[0]==="172"){let t=parseInt(e[1],10);if(t>=16&&t<=31)return!0}}return!1}var Zs=class extends nt{get description(){return"Connecting to signal connection via WebSocket"}perform(){return p(this,void 0,void 0,function*(){var e,t,n;(this.url.startsWith("ws:")||this.url.startsWith("http:"))&&this.appendWarning("Server is insecure, clients may block connections to it");let r=new jn,s;try{s=yield r.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3},void 0,!0)}catch(a){if(sn(new URL(this.url))){this.appendMessage("Initial connection failed with error ".concat(a.message,". Retrying with region fallback"));let d=yield new Ge(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)===jc.Cloud&&(!((t=s.serverInfo)===null||t===void 0)&&t.region)&&this.appendMessage("LiveKit Cloud: ".concat((n=s.serverInfo)===null||n===void 0?void 0:n.region))):this.appendError("Websocket connection could not be established"),yield r.close()})}},mc=class extends Ee.EventEmitter{constructor(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.options={},this.checkResults=new Map,this.url=e,this.token=t,this.options=n}getNextCheckId(){let e=this.checkResults.size;return this.checkResults.set(e,{logs:[],status:Le.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!==Le.FAILED)}getResults(){return Array.from(this.checkResults.values())}createAndRunCheck(e){return p(this,void 0,void 0,function*(){let t=this.getNextCheckId(),n=new e(this.url,this.token,this.options),r=a=>{this.updateCheck(t,a)};n.on("update",r);let s=yield n.run();return n.off("update",r),s})}checkWebsocket(){return p(this,void 0,void 0,function*(){return this.createAndRunCheck(Zs)})}checkWebRTC(){return p(this,void 0,void 0,function*(){return this.createAndRunCheck(Xs)})}checkTURN(){return p(this,void 0,void 0,function*(){return this.createAndRunCheck(Ys)})}checkReconnect(){return p(this,void 0,void 0,function*(){return this.createAndRunCheck(Qs)})}checkPublishAudio(){return p(this,void 0,void 0,function*(){return this.createAndRunCheck(Js)})}checkPublishVideo(){return p(this,void 0,void 0,function*(){return this.createAndRunCheck($s)})}checkConnectionProtocol(){return p(this,void 0,void 0,function*(){let e=yield this.createAndRunCheck(zs);if(e.data&&"protocol"in e.data){let t=e.data;this.options.protocol=t.protocol}return e})}checkCloudRegion(){return p(this,void 0,void 0,function*(){return this.createAndRunCheck(Ws)})}};new TextEncoder;var uf=new TextDecoder;var fe=class extends Error{constructor(e,t){var n;super(e,t),H(this,"code","ERR_JOSE_GENERIC"),this.name=this.constructor.name,(n=Error.captureStackTrace)===null||n===void 0||n.call(Error,this,this.constructor)}};H(fe,"code","ERR_JOSE_GENERIC");var ea=class extends fe{constructor(e,t){let n=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:n,reason:r,payload:t}}),H(this,"code","ERR_JWT_CLAIM_VALIDATION_FAILED"),H(this,"claim",void 0),H(this,"reason",void 0),H(this,"payload",void 0),this.claim=n,this.reason=r,this.payload=t}};H(ea,"code","ERR_JWT_CLAIM_VALIDATION_FAILED");var ta=class extends fe{constructor(e,t){let n=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:n,reason:r,payload:t}}),H(this,"code","ERR_JWT_EXPIRED"),H(this,"claim",void 0),H(this,"reason",void 0),H(this,"payload",void 0),this.claim=n,this.reason=r,this.payload=t}};H(ta,"code","ERR_JWT_EXPIRED");var na=class extends fe{constructor(){super(...arguments),H(this,"code","ERR_JOSE_ALG_NOT_ALLOWED")}};H(na,"code","ERR_JOSE_ALG_NOT_ALLOWED");var ia=class extends fe{constructor(){super(...arguments),H(this,"code","ERR_JOSE_NOT_SUPPORTED")}};H(ia,"code","ERR_JOSE_NOT_SUPPORTED");var ra=class extends fe{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),H(this,"code","ERR_JWE_DECRYPTION_FAILED")}};H(ra,"code","ERR_JWE_DECRYPTION_FAILED");var sa=class extends fe{constructor(){super(...arguments),H(this,"code","ERR_JWE_INVALID")}};H(sa,"code","ERR_JWE_INVALID");var aa=class extends fe{constructor(){super(...arguments),H(this,"code","ERR_JWS_INVALID")}};H(aa,"code","ERR_JWS_INVALID");var oa=class extends fe{constructor(){super(...arguments),H(this,"code","ERR_JWT_INVALID")}};H(oa,"code","ERR_JWT_INVALID");var ca=class extends fe{constructor(){super(...arguments),H(this,"code","ERR_JWK_INVALID")}};H(ca,"code","ERR_JWK_INVALID");var da=class extends fe{constructor(){super(...arguments),H(this,"code","ERR_JWKS_INVALID")}};H(da,"code","ERR_JWKS_INVALID");var la=class extends fe{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),H(this,"code","ERR_JWKS_NO_MATCHING_KEY")}};H(la,"code","ERR_JWKS_NO_MATCHING_KEY");var ua=class extends fe{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),H(this,Symbol.asyncIterator,void 0),H(this,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS")}};H(ua,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS");var ha=class extends fe{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),H(this,"code","ERR_JWKS_TIMEOUT")}};H(ha,"code","ERR_JWKS_TIMEOUT");var ma=class extends fe{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),H(this,"code","ERR_JWS_SIGNATURE_VERIFICATION_FAILED")}};H(ma,"code","ERR_JWS_SIGNATURE_VERIFICATION_FAILED");var Fp=1e3,hf=60*Fp;var mf=Symbol.for("lk.serializer");var mt={AgentSnapshotPayload:{additionalProperties:!1,properties:{ack_message_id:{title:"Ack Message Id",type:"string"},capabilities:{additionalProperties:!0,title:"Capabilities",type:"object"},connection_id:{title:"Connection Id",type:"string"},last_client_seq:{minimum:1,title:"Last Client Seq",type:"integer"},profile_revision:{title:"Profile Revision",type:"string"},session_id:{title:"Session Id",type:"string"},status:{enum:["connecting","ready","ended"],title:"Status",type:"string"}},required:["session_id","profile_revision","capabilities","status","ack_message_id","connection_id","last_client_seq"],title:"AgentSnapshotPayload",type:"object"},ClientHelloPayload:{$defs:{ClientReconnectPayload:{additionalProperties:!1,properties:{duration_ms:{maximum:36e5,minimum:0,title:"Duration Ms",type:"integer"},recovered_at:{format:"date-time",title:"Recovered At",type:"string"},started_at:{format:"date-time",title:"Started At",type:"string"}},required:["started_at","recovered_at","duration_ms"],title:"ClientReconnectPayload",type:"object"}},additionalProperties:!1,properties:{last_server_seq:{default:0,minimum:0,title:"Last Server Seq",type:"integer"},reconnect:{anyOf:[{$ref:"#/$defs/ClientReconnectPayload"},{type:"null"}],default:null},sdk:{maxLength:80,minLength:1,title:"Sdk",type:"string"},tool_handlers:{items:{maxLength:80,pattern:"^[a-z][a-z0-9_]{0,79}$",type:"string"},maxItems:128,title:"Tool Handlers",type:"array"}},required:["sdk"],title:"ClientHelloPayload",type:"object"},ClientMessage:{additionalProperties:!1,properties:{client_seq:{minimum:1,title:"Client Seq",type:"integer"},connection_id:{maxLength:120,minLength:1,title:"Connection Id",type:"string"},message_id:{maxLength:120,minLength:1,title:"Message Id",type:"string"},payload:{additionalProperties:!0,title:"Payload",type:"object"},protocol_version:{const:1,default:1,title:"Protocol Version",type:"integer"},type:{maxLength:100,minLength:1,title:"Type",type:"string"}},required:["message_id","connection_id","client_seq","type","payload"],title:"ClientMessage",type:"object"},CommandAckPayload:{additionalProperties:!1,properties:{client_seq:{minimum:1,title:"Client Seq",type:"integer"},command_type:{maxLength:100,minLength:1,title:"Command Type",type:"string"},connection_id:{title:"Connection Id",type:"string"},message_id:{title:"Message Id",type:"string"}},required:["message_id","connection_id","client_seq","command_type"],title:"CommandAckPayload",type:"object"},CommandErrorPayload:{additionalProperties:!1,properties:{client_seq:{minimum:1,title:"Client Seq",type:"integer"},code:{maxLength:100,minLength:1,title:"Code",type:"string"},command_type:{maxLength:100,minLength:1,title:"Command Type",type:"string"},connection_id:{title:"Connection Id",type:"string"},message:{maxLength:500,minLength:1,title:"Message",type:"string"},message_id:{title:"Message Id",type:"string"},retryable:{title:"Retryable",type:"boolean"}},required:["message_id","connection_id","client_seq","command_type","code","message","retryable"],title:"CommandErrorPayload",type:"object"},ContextRejectedPayload:{additionalProperties:!1,properties:{client_seq:{minimum:1,title:"Client Seq",type:"integer"},code:{maxLength:100,minLength:1,title:"Code",type:"string"},command_type:{maxLength:100,minLength:1,title:"Command Type",type:"string"},connection_id:{title:"Connection Id",type:"string"},message:{maxLength:500,minLength:1,title:"Message",type:"string"},message_id:{title:"Message Id",type:"string"},retryable:{title:"Retryable",type:"boolean"}},required:["message_id","connection_id","client_seq","command_type","code","message","retryable"],title:"ContextRejectedPayload",type:"object"},ContextUpdatePayload:{$defs:{ContextImageReference:{additionalProperties:!1,properties:{bytes:{maximum:5242880,minimum:1,title:"Bytes",type:"integer"},detail:{default:"low",enum:["auto","low","high"],title:"Detail",type:"string"},height:{anyOf:[{maximum:8192,minimum:1,type:"integer"},{type:"null"}],default:null,title:"Height"},mime:{enum:["image/jpeg","image/png","image/webp"],title:"Mime",type:"string"},sha256:{pattern:"^[a-f0-9]{64}$",title:"Sha256",type:"string"},stream_id:{maxLength:120,minLength:1,title:"Stream Id",type:"string"},width:{anyOf:[{maximum:8192,minimum:1,type:"integer"},{type:"null"}],default:null,title:"Width"}},required:["stream_id","mime","bytes","sha256"],title:"ContextImageReference",type:"object"},ContextTextStreamReference:{additionalProperties:!1,properties:{bytes:{maximum:262144,minimum:1,title:"Bytes",type:"integer"},sha256:{pattern:"^[a-f0-9]{64}$",title:"Sha256",type:"string"},stream_id:{maxLength:120,minLength:1,title:"Stream Id",type:"string"}},required:["stream_id","bytes","sha256"],title:"ContextTextStreamReference",type:"object"}},additionalProperties:!1,oneOf:[{properties:{image:{type:"null"},text_stream:{type:"null"}},required:["text"],type:"object"},{properties:{image:{type:"null"},text:{type:"null"}},required:["text_stream"],type:"object"},{properties:{mode:{const:"replace"},text:{type:"null"},text_stream:{type:"null"}},required:["image"],type:"object"}],properties:{image:{anyOf:[{$ref:"#/$defs/ContextImageReference"},{type:"null"}],default:null},key:{maxLength:120,minLength:1,pattern:"^[A-Za-z0-9][A-Za-z0-9._:-]*$",title:"Key",type:"string"},label:{default:"",maxLength:200,title:"Label",type:"string"},mode:{enum:["append","replace"],title:"Mode",type:"string"},respond:{default:!1,title:"Respond",type:"boolean"},text:{anyOf:[{maxLength:32768,minLength:1,type:"string"},{type:"null"}],default:null,title:"Text"},text_stream:{anyOf:[{$ref:"#/$defs/ContextTextStreamReference"},{type:"null"}],default:null}},required:["key","mode"],title:"ContextUpdatePayload",type:"object"},ContextUpdatedPayload:{additionalProperties:!1,properties:{client_seq:{minimum:1,title:"Client Seq",type:"integer"},command_type:{maxLength:100,minLength:1,title:"Command Type",type:"string"},connection_id:{title:"Connection Id",type:"string"},context_sequence:{minimum:1,title:"Context Sequence",type:"integer"},key:{title:"Key",type:"string"},message_id:{title:"Message Id",type:"string"},mode:{enum:["append","replace"],title:"Mode",type:"string"},respond:{title:"Respond",type:"boolean"}},required:["message_id","connection_id","client_seq","command_type","key","mode","context_sequence","respond"],title:"ContextUpdatedPayload",type:"object"},RealtimeEvent:{additionalProperties:!1,properties:{event_id:{title:"Event Id",type:"string"},payload:{additionalProperties:!0,title:"Payload",type:"object"},protocol_version:{const:1,default:1,title:"Protocol Version",type:"integer"},server_seq:{anyOf:[{minimum:1,type:"integer"},{type:"null"}],default:null,title:"Server Seq"},stream_id:{title:"Stream Id",type:"string"},stream_seq:{minimum:1,title:"Stream Seq",type:"integer"},ts:{format:"date-time",title:"Ts",type:"string"},type:{maxLength:100,minLength:1,title:"Type",type:"string"}},required:["event_id","stream_id","stream_seq","ts","type","payload"],title:"RealtimeEvent",type:"object"}};function pt(i,e,t){let n=ln(i,e,t,i);if(n)throw new TypeError(n);return e}function ln(i,e,t,n){if(i.$ref){let r="#/$defs/";if(!i.$ref.startsWith(r))return`${t} uses an unsupported schema reference`;let s=n.$defs?.[i.$ref.slice(r.length)];return s?ln(s,e,t,n):`${t} uses a missing schema reference`}if(i.anyOf&&!i.anyOf.some(r=>ln(r,e,t,n)===null))return`${t} does not match any allowed schema`;if(i.oneOf&&i.oneOf.filter(s=>ln(s,e,t,n)===null).length!==1)return`${t} must match exactly one allowed schema`;if(i.allOf)for(let r of i.allOf){let s=ln(r,e,t,n);if(s)return s}if(Object.prototype.hasOwnProperty.call(i,"const")&&e!==i.const)return`${t} must equal ${String(i.const)}`;if(i.enum&&!i.enum.includes(e))return`${t} has an unsupported value`;if(i.type==="object"){if(!e||typeof e!="object"||Array.isArray(e))return`${t} must be an object`;let r=e;for(let s of i.required??[])if(!Object.prototype.hasOwnProperty.call(r,s))return`${t}.${s} is required`;for(let[s,a]of Object.entries(i.properties??{}))if(Object.prototype.hasOwnProperty.call(r,s)){let o=ln(a,r[s],`${t}.${s}`,n);if(o)return o}if(i.additionalProperties===!1){let s=new Set(Object.keys(i.properties??{})),a=Object.keys(r).find(o=>!s.has(o));if(a)return`${t}.${a} is not allowed`}}else if(i.type==="string"){if(typeof e!="string")return`${t} must be a string`;if(i.minLength!==void 0&&e.length<i.minLength)return`${t} is too short`;if(i.maxLength!==void 0&&e.length>i.maxLength)return`${t} is too long`;if(i.pattern!==void 0&&!new RegExp(i.pattern).test(e))return`${t} has an invalid format`;if(i.format==="date-time"&&Number.isNaN(Date.parse(e)))return`${t} must be a date-time`}else if(i.type==="integer"){if(!Number.isInteger(e))return`${t} must be an integer`}else if(i.type==="number"){if(typeof e!="number"||!Number.isFinite(e))return`${t} must be a number`}else{if(i.type==="boolean"&&typeof e!="boolean")return`${t} must be a boolean`;if(i.type==="null"&&e!==null)return`${t} must be null`}if(typeof e=="number"){if(i.minimum!==void 0&&e<i.minimum)return`${t} is below its minimum`;if(i.maximum!==void 0&&e>i.maximum)return`${t} exceeds its maximum`}return null}function hl(i){return pt(mt.RealtimeEvent,i,"RealtimeEvent")}function ml(i){try{return hl(i),!0}catch{return!1}}function Bp(i){return pt(mt.ClientMessage,i,"ClientMessage")}function qp(i){return pt(mt.AgentSnapshotPayload,i,"AgentSnapshotPayload")}function jp(i){return pt(mt.ClientHelloPayload,i,"ClientHelloPayload")}function pl(i){return pt(mt.CommandAckPayload,i,"CommandAckPayload")}function fl(i){try{return pl(i),!0}catch{return!1}}function gl(i){return pt(mt.CommandErrorPayload,i,"CommandErrorPayload")}function vl(i){try{return gl(i),!0}catch{return!1}}function yl(i){return pt(mt.ContextUpdatePayload,i,"ContextUpdatePayload")}function bl(i){try{return yl(i),!0}catch{return!1}}function kl(i){return pt(mt.ContextUpdatedPayload,i,"ContextUpdatedPayload")}function Tl(i){try{return kl(i),!0}catch{return!1}}function Sl(i){return pt(mt.ContextRejectedPayload,i,"ContextRejectedPayload")}function Cl(i){try{return Sl(i),!0}catch{return!1}}var Gn=class extends Error{payload;constructor(e){super(e.message),this.name="CommandError",this.payload=e}};function Va(i){return fl(i)}function Ha(i){return vl(i)}function Ga(i){return Tl(i)}function Ka(i){return bl(i)}function Wa(i){return Cl(i)}function za(i){return ml(i)}function Wn(i,e,t,n){return{protocol_version:1,message_id:`msg_${Vp()}`,connection_id:i,client_seq:e,type:t,payload:n}}var Kn=class{seen=new Set;seenOrder=[];seenLimit;streamSeq=0;streamId=null;serverSeq=0;constructor(e=2048){this.seenLimit=e}get lastStreamSeq(){return this.streamSeq}get currentStreamId(){return this.streamId}get lastServerSeq(){return this.serverSeq}accept(e){if(this.seen.has(e.event_id))return{deliver:!1,gap:null};if(e.stream_id.startsWith("control:"))return this.remember(e,!1),{deliver:!0,gap:null};e.stream_id!==this.streamId&&(this.streamId=e.stream_id,this.streamSeq=0);let t=e.stream_seq>this.streamSeq+1?{expected_stream_seq:this.streamSeq+1,received_stream_seq:e.stream_seq,after_server_seq:this.serverSeq}:null;return e.stream_seq<=this.streamSeq?{deliver:!1,gap:t}:(this.streamSeq=e.stream_seq,this.remember(e),{deliver:!0,gap:t})}acceptReplay(e){return this.seen.has(e.event_id)?!1:(this.remember(e),!0)}remember(e,t=!0){for(this.seen.add(e.event_id),this.seenOrder.push(e.event_id),t&&e.server_seq!==null&&(this.serverSeq=Math.max(this.serverSeq,e.server_seq));this.seenOrder.length>this.seenLimit;){let n=this.seenOrder.shift();n&&this.seen.delete(n)}}};function Vp(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`${Date.now().toString(36)}_${Math.random().toString(36).slice(2)}`}var it=class extends Error{retryAfter;constructor(e,t={}){super(e,t),this.retryAfter=t.retryAfter}};function Ja(i){let e=1e3*2**Math.min(Math.max(i-1,0),3);return Math.min(e*(1+Math.random()*.2),8e3)}var cr=class{constructor(e){this.send=e}paused=!1;generation=0;latest=new Map;pending=new Map;running=new Map;retryTimers=new Map;retryAttempts=new Map;blockedTransfers=new Map;submit(e,t){let n=new Set([...this.pending.keys(),...this.running.keys(),...this.blockedTransfers.keys()]);if(n.size>=64&&!n.has(e.key))return Promise.reject(new Error("Too many pending context keys"));this.latest.delete(e.key),this.latest.set(e.key,e);let r=0,s=0;for(let[o,d]of[...this.latest].reverse())r+="image"in d?d.image.size:new TextEncoder().encode(d.text).byteLength,s+=1,(r>16*1024*1024||s>64)&&this.latest.delete(o);let a=new Promise((o,d)=>{this.pending.get(e.key)?.reject(new Error("Context update superseded by a newer value")),this.pending.set(e.key,{update:e,retainedUpdate:e,timeoutMs:t,resolve:o,reject:d})});return this.start(e.key),a}pause(){this.generation+=1,this.paused=!0;for(let e of this.retryTimers.values())globalThis.clearTimeout(e);this.retryTimers.clear()}async resume(e=!1){let t=this.generation;if(await Promise.all(this.running.values()),t!==this.generation)throw new Error("Context restoration interrupted");if(e)for(let[n,r]of this.latest)this.pending.has(n)||this.pending.set(n,{update:{...r,respond:!1},retainedUpdate:r,timeoutMs:2e4,resolve:()=>{},reject:()=>{}});this.paused=!1;for(let n of this.pending.keys())this.start(n);if(await Promise.all(this.running.values()),t!==this.generation)throw new Error("Context restoration interrupted")}clear(e){this.pause(),this.latest.clear(),this.retryAttempts.clear();for(let t of this.pending.values())t.reject(e);this.pending.clear()}start(e){if(this.paused||this.running.has(e)||this.retryTimers.has(e)||this.blockedTransfers.has(e))return;let t=this.drain(e).finally(()=>{this.running.delete(e),this.pending.has(e)&&this.start(e)});this.running.set(e,t)}async drain(e){for(;!this.paused&&!this.blockedTransfers.has(e);){let t=this.pending.get(e);if(!t)return;this.pending.delete(e);try{t.resolve(await this.send(t.update,t.timeoutMs)),this.retryAttempts.delete(e)}catch(n){n instanceof it&&n.retryAfter&&this.blockUntilTransferSettles(e,n.retryAfter);let r=this.latest.get(e)===t.retainedUpdate;if(this.paused&&!t.update.respond&&!this.pending.has(e)&&r?this.pending.set(e,t):t.reject(n instanceof Error?n:new Error(String(n))),!this.paused){if(n instanceof it){r&&!t.update.respond&&!this.pending.has(e)&&this.pending.set(e,{...t,resolve:()=>{},reject:()=>{}}),this.pending.has(e)&&this.scheduleRetry(e);return}r&&this.latest.delete(e),this.retryAttempts.delete(e);return}}}}blockUntilTransferSettles(e,t){this.blockedTransfers.set(e,t),t.then(()=>{this.blockedTransfers.get(e)===t&&(this.blockedTransfers.delete(e),this.pending.has(e)&&this.start(e))})}scheduleRetry(e){let t=(this.retryAttempts.get(e)??0)+1;this.retryAttempts.set(e,t);let n=globalThis.setTimeout(()=>{this.retryTimers.delete(e),this.start(e)},Ja(t));this.retryTimers.set(e,n)}};var Gt=class extends Error{constructor(t,n=!0,r=0){super(t);this.retryable=n;this.retryAfterMs=r;this.name="DiagnosticDeliveryError"}};function _l(){return globalThis.crypto?.randomUUID?.()??`diag_${Date.now().toString(36)}_${Math.random().toString(36).slice(2)}`}function wl(i){return new TextEncoder().encode(JSON.stringify(i)).byteLength}var Hp=new Set(["context_transfer","command_send","command_result","connection_recovery","tool_rpc"]),Gp=new Set(["started","succeeded","failed","retrying","acknowledged","rejected","timed_out"]),Kp=new Set(["idle","connecting","connected_not_ready","connected","reconnecting","resuming","disconnected","failed"]),Wp=new Set(["client.hello","context.update","command.ack","command.error","context.updated","context.rejected"]),El=/^[a-z0-9_.:-]+$/,zp=/^[A-Za-z0-9][A-Za-z0-9._:-]*$/,Jp=["token_request","room_disconnect","room_connect","hello","agent_ready","remote_audio","complete"],$p=["received","handler_started","response_ready","flush_requested",...Jp],dr=class{entries=[];sdkVersion;limit;throttleMs;now;schedule;startedAt;wallStartedAt=Date.now();instanceId=_l();sequence=0;batchedThrough=0;droppedEntries=0;pending=null;sender=null;trigger="slow_operation";reporting=!1;scheduled=!1;nextAttemptAt=0;failures=0;constructor(e){this.sdkVersion=e.sdkVersion,this.limit=Math.max(1,Math.min(Math.trunc(e.limit??128),128)),this.throttleMs=Math.max(0,e.throttleMs??1e4),this.now=e.now??(()=>performance.now()),this.schedule=e.schedule??((t,n)=>{let r=globalThis.setTimeout(t,n);return r.unref?.(),r}),this.startedAt=this.now()}record(e){let t=Qp(e,Math.max(this.now()-this.startedAt,0));t&&(t.entry_seq=++this.sequence,this.entries.push(t),this.prune())}snapshot(){return this.entries.map(e=>({...e}))}async flush(e,t){return!El.test(e)||e.length>100?!1:(this.trigger=e,this.sender=t,e.startsWith("tool_rpc")&&!this.pending&&!this.reporting&&(this.prune(),this.makeBatch()),this.deliver())}prune(){let e=this.now()-this.startedAt-3e5;for(;this.entries.length&&(this.entries.length>this.limit||wl(this.entries)>65536||this.entries[0].at_ms<=e);)this.entries.shift().entry_seq>this.batchedThrough&&(this.droppedEntries+=1);!this.reporting&&this.pending&&this.now()-this.pending.createdAt>=3e5&&(this.droppedEntries+=this.pending.report.entries.length,this.pending=null,this.failures=0)}makeBatch(){let e={source:"sdk",report_id:_l(),sdk_instance_id:this.instanceId,started_at_ms:this.wallStartedAt,dropped_entries:this.droppedEntries,sdk_version:this.sdkVersion,trigger:this.trigger,entries:[]};for(let t of this.entries)if(!(t.entry_seq<=this.batchedThrough)&&(e.entries.push({...t}),wl(e)>16384)){e.entries.pop();break}e.entries.length&&(this.batchedThrough=e.entries.at(-1).entry_seq,this.pending={report:e,createdAt:this.now()})}hasWork(){return this.pending!==null||this.entries.some(e=>e.entry_seq>this.batchedThrough)}async deliver(){if(this.reporting||!this.sender||(this.prune(),!this.hasWork()))return!1;if(this.now()<this.nextAttemptAt)return this.scheduleNext(),!1;if(this.pending||this.makeBatch(),!this.pending)return!1;let e=this.pending;this.reporting=!0;let t=this.throttleMs;try{return await this.sender(e.report),this.pending=null,this.failures=0,!0}catch(n){if(n instanceof Gt&&!n.retryable)this.droppedEntries+=e.report.entries.length,this.pending=null,this.failures=0;else{this.failures+=1;let r=Math.min(2e3*2**Math.min(this.failures-1,5),6e4);t=Math.max(this.throttleMs,r*(1+Math.random()*.2),n instanceof Gt?n.retryAfterMs:0)}return!1}finally{this.reporting=!1,this.nextAttemptAt=this.now()+t,this.scheduleNext()}}scheduleNext(){this.reporting||this.scheduled||!this.hasWork()||(this.scheduled=!0,this.schedule(()=>{this.scheduled=!1,this.deliver()},Math.min(Math.max(this.nextAttemptAt-this.now(),0),3e5)))}};function Qp(i,e){if(!Hp.has(i.operation)||!Gp.has(i.status))return null;let t={entry_seq:0,at_ms:Rl(e,0,864e5)??0,operation:i.operation,status:i.status},n=Ht(i.reason,100,El),r=Ht(i.message_id,120),s=Ht(i.connection_id,120),a=Ht(i.context_key,120,zp);n!==void 0&&(t.reason=n),r!==void 0&&(t.message_id=r),s!==void 0&&(t.connection_id=s),a!==void 0&&(t.context_key=a);let o=Ht(i.call_id,200),d=Ht(i.rpc_request_id,120),c=Ht(i.tool_name,80);return o!==void 0&&(t.call_id=o),d!==void 0&&(t.rpc_request_id=d),c!==void 0&&(t.tool_name=c),i.stage&&$p.includes(i.stage)&&(t.stage=i.stage),(i.page_visibility==="visible"||i.page_visibility==="hidden")&&(t.page_visibility=i.page_visibility),Ke(t,"rpc_error_code",i.rpc_error_code,0,65535,!0),Ke(t,"http_status",i.http_status,100,599,!0),Ke(t,"event_loop_delay_ms",i.event_loop_delay_ms,0,864e5),Ke(t,"active_context_transfers",i.active_context_transfers,0,1e3,!0),Ke(t,"active_context_bytes",i.active_context_bytes,0,1073741824,!0),Ke(t,"client_seq",i.client_seq,1,Number.MAX_SAFE_INTEGER,!0),Ke(t,"payload_bytes",i.payload_bytes,0,5242880,!0),Ke(t,"duration_ms",i.duration_ms,0,36e5),Ke(t,"retry_count",i.retry_count,0,1e3,!0),Ke(t,"timeout_ms",i.timeout_ms,1,36e5,!0),Ke(t,"buffered_bytes",i.buffered_bytes,0,1073741824,!0),i.connection_state&&Kp.has(i.connection_state)&&(t.connection_state=i.connection_state),i.event_type&&Wp.has(i.event_type)&&(t.event_type=i.event_type),t}function Ht(i,e,t){if(!(typeof i!="string"||i.length===0||i.length>e)&&!(t&&!t.test(i)))return i}function Rl(i,e,t,n=!1){if(!(typeof i!="number"||!Number.isFinite(i))&&!(i<e||i>t))return n?Math.trunc(i):Math.round(i*10)/10}function Ke(i,e,t,n,r,s=!1){let a=Rl(t,n,r,s);a!==void 0&&(i[e]=a)}var zn=class{messages=new Map;get snapshot(){return[...this.messages.values()].sort((e,t)=>e.turnStartedAt-t.turnStartedAt||(e.role===t.role?e.messageSeq-t.messageSeq:e.role==="user"?-1:1))}accept(e){let t=/^transcript\.(user|agent)\.(interim|final)$/.exec(e.type);if(!t)return null;let n=e.payload;if(typeof n.message_id!="string"||!n.message_id||typeof n.turn_id!="string"||typeof n.text!="string"||!Number.isSafeInteger(n.revision)||Number(n.revision)<1||!Number.isSafeInteger(n.message_seq)||Number(n.message_seq)<1)return null;let r=this.messages.get(n.message_id),s=t[2]==="final",a=t[1];if(r&&(Number(n.revision)<=r.revision||r.final&&!s||r.role!==a||r.turnId!==n.turn_id))return null;let o=Object.freeze({messageId:n.message_id,turnId:n.turn_id,turnStartedAt:typeof n.turn_started_at=="number"?n.turn_started_at:Date.parse(e.ts)/1e3,revision:Number(n.revision),messageSeq:Number(n.message_seq),role:a,text:n.text,final:s,interrupted:n.interrupted===!0,playbackAlignment:n.playback_alignment==="estimated"?"estimated":"unknown",event:e});return this.messages.set(o.messageId,o),o}};var Pl="0.3.15",$a=3e4,Yp=5e3,Il=500,Xp=5e3,Zp=[{delayBeforeMs:0,readyTimeoutMs:15e3},{delayBeforeMs:1e3,readyTimeoutMs:2e4},{delayBeforeMs:3e3,readyTimeoutMs:14e4}],ef=18e4,Qn=class extends Error{constructor(){super("Recovery data channel stopped draining before the agent handshake completed"),this.name="RecoveryDataChannelStalledError"}},Yn=class extends Error{status;code;requestId;details;constructor(e,t){super(e),this.name="RealtimeSessionHttpError",this.status=t.status,this.code=t.code??null,this.requestId=t.requestId??null,this.details=t.details??[]}},rt=class extends TypeError{},lr=class extends Error{retryable;constructor(e){let t=e.payload,n=typeof t.message=="string"?t.message:"VoxEvolv reported a session error";super(n),this.name="SessionErrorEventError",this.retryable=t.retryable===!0}},Ml=class i{id;room;accessToken;credentials;stateValue="idle";listeners=new Set;stateListeners=new Set;gapListeners=new Set;connectionQualityListeners=new Set;recoveryListeners=new Set;startupAttemptListeners=new Set;remoteAudioTrackListeners=new Set;remoteAudioTrackUnsubscribedListeners=new Set;readyListeners=new Set;userTranscriptListeners=new Set;agentTranscriptListeners=new Set;transcriptListeners=new Set;transcriptStore=new zn;errorListeners=new Set;endedListeners=new Set;toolCallListeners=new Set;audioPlaybackBlockedListeners=new Set;remoteAudioStreams=new WeakMap;outputMediaStream=null;remoteAudioTrackResolve=null;cursor=new Kn;connectionId=`conn_${Math.random().toString(36).slice(2)}_${Date.now().toString(36)}`;clientSeq=0;lastHelloMessageId=null;reconnectStartedAt=null;pendingReconnect=null;agentReady=!1;agentStreamId=null;contextGeneration=0;replacementContext=new cr((e,t)=>this.sendContextUpdate(e,t));readyResolve=null;replayPromise=null;pendingCommands=new Map;commandPublishTail=Promise.resolve();toolHandlers=new Map;apiBase="/v1";hasConnectedValue=!1;sessionEnded=!1;pendingEndEvent=null;agentDisconnected=!1;terminalSessionError=null;endNotificationDelivered=!1;disconnectMode=null;activeRecovery=null;recoveryStartedAt=null;livekitResumeController=null;terminalReplayController=null;autoRejoinPromise=null;autoRejoinController=null;manualRejoinController=null;startupConnectController=null;startupAttemptController=null;useManagedMicrophone=!0;microphoneEnabled=!0;applicationAudioTrack=null;localApplicationAudioTrack=null;connectDefaults;recoveryReadiness;credentialRefreshGeneration=0;fetcher;endEndpoint;refreshCredentialsCallback;autoRejoinOptions;startupRetryOptions;lifecycleCredentials;diagnostics=new dr({sdkVersion:Pl});activeContextTransfers=0;contextTransferControllers=new Set;activeContextBytes=0;diagnosticLoopTimer;diagnosticLoopExpectedAt=0;diagnosticLoopDelayMs;diagnosticReportTimeoutMs=Xp;onDiagnosticVisibilityChange=()=>{globalThis.document?.visibilityState==="hidden"&&this.flushDiagnostics("page_hidden")};constructor(e,t={}){Ul(e),this.id=e.id,this.accessToken=e.access_token,this.credentials=e.connection,this.connectDefaults=t.connect?.apiBase===void 0?t.connect??{}:{...t.connect,apiBase:hn(t.connect.apiBase)},this.apiBase=this.connectDefaults.apiBase??this.apiBase,this.recoveryReadiness={readyTimeoutMs:this.connectDefaults.readyTimeoutMs??15e3,waitForRemoteAudio:this.connectDefaults.waitForRemoteAudio??!0},this.fetcher=t.fetch??globalThis.fetch.bind(globalThis),this.endEndpoint=t.endEndpoint??null,this.refreshCredentialsCallback=t.refreshCredentials??null,this.autoRejoinOptions=tf(t.autoRejoin),this.startupRetryOptions=nf(t.startupRetry),this.lifecycleCredentials=t.lifecycleCredentials??"same-origin",this.room=new dn({adaptiveStream:!0,dynacast:!0});for(let[n,r]of Object.entries(t.tools??{}))this.registerTool(n,r);this.room.registerRpcMethod("voxevolv.tool.invoke",n=>this.invokeBrowserTool(n)),this.room.registerRpcMethod("voxevolv.diagnostics.flush",async n=>{let r=JSON.parse(n.payload);if(typeof r?.call_id!="string"||r.call_id.length>200)throw new G(1500,"Invalid diagnostic request");return this.recordDiagnostic({operation:"tool_rpc",status:"started",stage:"flush_requested",call_id:r.call_id,rpc_request_id:n.requestId}),this.flushDiagnostics("tool_rpc_worker_request"),"{}"}),this.bindRoomEvents()}async invokeBrowserTool(e){let t=performance.now(),n,r,s,a=o=>this.recordDiagnostic({operation:"tool_rpc",status:"started",rpc_request_id:e.requestId,call_id:n,tool_name:r,duration_ms:performance.now()-t,...o});a({stage:"received"});try{let o;try{o=JSON.parse(e.payload)}catch(u){throw new G(1500,"Tool invocation payload was not valid JSON",void 0,{cause:u})}if(typeof o?.name!="string")throw new G(1500,"Tool invocation did not include a valid name");r=o.name,n=typeof o.call_id=="string"?o.call_id:e.requestId;let d=this.toolHandlers.get(r);if(!d)throw new G(1500,`No browser handler is registered for ${r}`);if(!o.arguments||typeof o.arguments!="object"||Array.isArray(o.arguments))throw new G(1500,"Tool invocation arguments must be an object");let c=o.arguments;this.notifyListeners(this.toolCallListeners,{name:r,callId:n,arguments:c}),a({stage:"handler_started"}),this.flushDiagnostics("tool_rpc_received"),s=globalThis.setTimeout(()=>{a({stage:"handler_started",reason:"handler_slow"}),this.flushDiagnostics("tool_rpc_slow")},2e3);let l;try{let u=await d(c,{callId:n});l=JSON.stringify(u??null)}catch(u){let h=u instanceof Error?u.message:"Browser tool handler failed";throw new G(1500,h,void 0,{cause:u})}return a({stage:"response_ready",status:"succeeded"}),l}catch(o){throw a({status:"failed",rpc_error_code:o instanceof G?o.code:void 0}),o}finally{globalThis.clearTimeout(s),this.flushDiagnostics("tool_rpc_finished")}}static async create(e){if("connect"in e)throw new TypeError("RealtimeSession.create() accepts apiBase and media options at the top level, not in connect");let{endpoint:t,request:n,microphone:r,audioTrack:s,readyTimeoutMs:a,waitForRemoteAudio:o,apiBase:d,...c}=e;if(!t)throw new TypeError("endpoint is required");if(!d)throw new TypeError("apiBase is required so rejoin, replay, and end use the intended VoxEvolv API or application proxy");let l=hn(d),u=c.fetch??globalThis.fetch.bind(globalThis),h=await u(t,{...n,method:"POST"});if(!h.ok)throw await $n(h,"Could not create realtime session");let m=await h.json();return new i(m,{...c,fetch:u,connect:{microphone:r,audioTrack:s,readyTimeoutMs:a,waitForRemoteAudio:o,apiBase:l}})}get state(){return this.stateValue}get hasConnectedBefore(){return this.hasConnectedValue}get outputStream(){return this.outputMediaStream??=new MediaStream,this.outputMediaStream}onEvent(e){return this.listeners.add(e),()=>this.listeners.delete(e)}onStateChange(e){return this.stateListeners.add(e),this.notifyListeners(new Set([e]),this.stateValue),()=>this.stateListeners.delete(e)}onProtocolGap(e){return this.gapListeners.add(e),()=>this.gapListeners.delete(e)}onConnectionQuality(e){return this.connectionQualityListeners.add(e),this.notifyListeners(new Set([e]),this.room.localParticipant.connectionQuality),()=>this.connectionQualityListeners.delete(e)}onRecovery(e){return this.recoveryListeners.add(e),()=>this.recoveryListeners.delete(e)}onStartupAttempt(e){return this.startupAttemptListeners.add(e),()=>this.startupAttemptListeners.delete(e)}waitForState(e,t,n={}){if(!e.length)throw new TypeError("states must contain at least one connection state");if(!Number.isFinite(t)||t<0)throw new TypeError("timeoutMs must be a non-negative finite number");let r=new Set(e);return r.has(this.stateValue)?Promise.resolve(this.stateValue):n.signal?.aborted?Promise.reject(n.signal.reason??new DOMException("Aborted","AbortError")):new Promise((s,a)=>{let o=!1,d=(h,m)=>{o||(o=!0,globalThis.clearTimeout(u),this.stateListeners.delete(c),n.signal?.removeEventListener("abort",l),m!==void 0?a(m):h!==null&&s(h))},c=h=>{r.has(h)&&d(h)},l=()=>{d(null,n.signal?.reason??new DOMException("Aborted","AbortError"))},u=globalThis.setTimeout(()=>{d(null,new Error(`Session did not reach ${e.join(" or ")} within ${t}ms`))},t);this.stateListeners.add(c),n.signal?.addEventListener("abort",l,{once:!0})})}onRemoteAudioTrack(e){return this.remoteAudioTrackListeners.add(e),()=>this.remoteAudioTrackListeners.delete(e)}onRemoteAudioTrackUnsubscribed(e){return this.remoteAudioTrackUnsubscribedListeners.add(e),()=>this.remoteAudioTrackUnsubscribedListeners.delete(e)}onReady(e){return this.readyListeners.add(e),()=>this.readyListeners.delete(e)}onUserTranscript(e){return this.userTranscriptListeners.add(e),()=>this.userTranscriptListeners.delete(e)}onAgentTranscript(e){return this.agentTranscriptListeners.add(e),()=>this.agentTranscriptListeners.delete(e)}get transcript(){return this.transcriptStore.snapshot}onTranscriptUpdated(e){return this.transcriptListeners.add(e),()=>this.transcriptListeners.delete(e)}onError(e){return this.errorListeners.add(e),()=>this.errorListeners.delete(e)}onEnded(e){return this.endedListeners.add(e),()=>this.endedListeners.delete(e)}onToolCall(e){return this.toolCallListeners.add(e),()=>this.toolCallListeners.delete(e)}onAudioPlaybackBlocked(e){return this.audioPlaybackBlockedListeners.add(e),()=>this.audioPlaybackBlockedListeners.delete(e)}registerTool(e,t){if(["connecting","connected_not_ready","connected","reconnecting","resuming"].includes(this.stateValue))throw new Error("Browser tools must be registered before connect()");if(!/^[a-z][a-z0-9_]{0,79}$/.test(e))throw new TypeError("Tool name must be lowercase letters, numbers, and underscores");if(this.toolHandlers.has(e))throw new TypeError(`Tool ${e} is already registered`);return this.toolHandlers.set(e,t),()=>{this.toolHandlers.get(e)===t&&this.toolHandlers.delete(e)}}async connect(e={}){if(this.startupConnectController||this.manualRejoinController)throw new Error("A session connection attempt is already in progress");if(["connecting","connected_not_ready","connected","reconnecting","resuming"].includes(this.stateValue))throw new Error(`Cannot connect while session is ${this.stateValue}`);this.cancelRecovery();let t=new AbortController;this.startupConnectController=t,this.credentialRefreshGeneration+=1;let n={...this.connectDefaults,...e};this.recoveryReadiness={readyTimeoutMs:n.readyTimeoutMs??15e3,waitForRemoteAudio:n.waitForRemoteAudio??!0},this.microphoneEnabled=n.audioTrack?n.audioTrack.enabled!==!1:n.microphone??!0,this.setState("connecting");try{this.startupRetryOptions?await this.connectWithStartupRetry(e,t):(this.startupAttemptController=t,await this.connectWithMode(e,!1,t.signal,!1))}catch(r){throw this.startupConnectController===t&&this.terminalSessionError?(this.sessionEnded=!0,this.setState("failed")):this.startupConnectController===t&&!this.sessionEnded&&this.setState("failed"),r}finally{this.startupAttemptController===t&&(this.startupAttemptController=null),this.startupConnectController===t&&(this.startupConnectController=null)}}async connectWithStartupRetry(e,t){let n=this.startupRetryOptions;if(!n)return;let r=performance.now(),s=globalThis.setTimeout(()=>{t.abort(new Error(`Session startup did not complete within ${n.timeoutMs}ms`))},n.timeoutMs),a=new Error("Session startup failed"),o=this.hasConnectedValue;this.apiBase=hn(e.apiBase??this.connectDefaults.apiBase??this.apiBase);try{for(let[d,c]of n.attempts.entries()){let l=d+1;c.delayBeforeMs>0&&(this.setState("connecting"),await Qa(c.delayBeforeMs,t.signal)),X(t.signal);let u=Ol(t.signal);this.startupAttemptController=u,this.notifyStartupAttempt("started",l,c.readyTimeoutMs);try{if(!o){let h=n.timeoutMs-(performance.now()-r);await this.registerStartupRecovery(h,u.signal),o=!0}X(u.signal),d===0?await this.connectWithMode({...e,readyTimeoutMs:c.readyTimeoutMs},!1,u.signal,!1):await this.performRejoin(this.apiBase,{signal:u.signal,recovering:!1,connect:{...e,readyTimeoutMs:c.readyTimeoutMs},markFailureTerminal:!1}),X(t.signal),this.notifyStartupAttempt("succeeded",l,c.readyTimeoutMs);return}catch(h){if(a=un(h),this.notifyStartupAttempt("failed",l,c.readyTimeoutMs,a),t.signal.aborted)throw We(t.signal);if(rf(h)||l===n.attempts.length)throw h;this.setState("connecting")}finally{this.startupAttemptController===u&&(this.startupAttemptController=null)}}throw a}finally{globalThis.clearTimeout(s)}}async registerStartupRecovery(e,t){let n=Math.min(5e3,e/10),r=Ol(t),s=globalThis.setTimeout(()=>{r.abort(new Error("Startup registration timed out"))},Math.max(1,n));try{let a=()=>Te(this.fetcher(`${this.apiBase}/sessions/${this.id}/startup`,{method:"POST",headers:{Authorization:`Bearer ${this.accessToken}`,"Content-Type":"application/json"},credentials:this.lifecycleCredentials,body:JSON.stringify({timeout_ms:Math.max(1,Math.floor(Math.min(e-n,175e3)))}),signal:r.signal}),r.signal),o=await a();if(o.status===401&&this.refreshCredentialsCallback&&(await this.refreshCredentials(r.signal),o=await a()),!o.ok)throw await $n(o,"Could not register session startup");let d=await Te(o.json(),r.signal);if(typeof d.remaining_ms!="number"||d.remaining_ms<=0)throw new Error("Session startup window has expired")}finally{globalThis.clearTimeout(s)}}notifyStartupAttempt(e,t,n,r){let s=this.startupRetryOptions?.attempts.length??1;this.notifyListeners(this.startupAttemptListeners,{status:e,attempt:t,maxAttempts:s,readyTimeoutMs:n,...r?{error:r}:{}})}async connectWithMode(e,t,n,r=!0){X(n);let s=t?["connecting","connected_not_ready","connected","reconnecting"]:["connecting","connected_not_ready","connected","reconnecting","resuming"],a=!t&&!r&&this.stateValue==="connecting";if(s.includes(this.stateValue)&&!a)throw new Error(`Cannot connect while session is ${this.stateValue}`);let o=this.contextGeneration,d={...this.connectDefaults,...e},c=d.audioTrack??null,l=d.microphone??c===null,u=d.readyTimeoutMs??15e3,h=d.waitForRemoteAudio??!0,m=hn(d.apiBase??this.apiBase);this.validateAudioOptions(l,c),this.useManagedMicrophone=l,this.applicationAudioTrack=c,t?this.setState("resuming"):(this.sessionEnded=!1,this.agentStreamId=null,this.reconnectStartedAt=null,this.pendingEndEvent=null,this.agentDisconnected=!1,this.terminalSessionError=null,this.endNotificationDelivered=!1,this.setState("connecting")),this.apiBase=m,this.agentReady=!1;try{await this.measureRecoveryStage("room_connect",()=>this.connectRoom(n,t),t),X(n),c?await Te(this.publishApplicationAudioTrack(c),n):l&&await Te(this.room.localParticipant.setMicrophoneEnabled(this.microphoneEnabled),n),X(n),this.setState(t?"resuming":"connected_not_ready");let f=this.startupConnectController&&this.startupRetryOptions?Math.max($a,u):$a;await this.measureRecoveryStage("hello",()=>t?this.sendRecoveryHello(n):Te(this.sendHello(f),n),t);let g=Date.now()+u;if(await this.measureRecoveryStage("agent_ready",()=>this.waitForAgentReady(u,n),t),h&&await this.measureRecoveryStage("remote_audio",()=>this.waitForRemoteAudioTrack(g,n),t),X(n),this.sessionEnded||o!==this.contextGeneration)throw new Error("Connection restoration interrupted");if(this.resumeContextDelivery(t),X(n),this.sessionEnded||o!==this.contextGeneration)throw new Error("Connection restoration interrupted");this.hasConnectedValue=!0,this.setState("connected")}catch(f){n?.aborted&&this.rejectPendingCommands(un(We(n))),this.disconnectMode=t?"rejoin":"connect_failure";try{await this.room.disconnect()}catch{}finally{this.disconnectMode=null}throw!t&&r&&this.setState("failed"),f}}connectRoom(e,t){X(e);let n=this.room.connect(this.credentials.url,this.credentials.token);return e?new Promise((r,s)=>{let a=!1,o=()=>{a||(a=!0,e.removeEventListener("abort",c),r())},d=l=>{a||(a=!0,e.removeEventListener("abort",c),s(l))},c=()=>{this.disconnectMode=t?"rejoin":"connect_failure",this.room.disconnect().catch(()=>{}),d(We(e))};e.aborted?c():e.addEventListener("abort",c,{once:!0}),n.then(o,d)}):n}async rejoin(e=this.apiBase){if(this.startupConnectController||this.manualRejoinController)throw new Error("A session connection attempt is already in progress");if(this.sessionEnded)throw this.terminalSessionError??new Error("Cannot rejoin a session that has ended");if(["connecting","connected_not_ready","reconnecting","resuming"].includes(this.stateValue))throw new Error(`Cannot rejoin while session is ${this.stateValue}`);this.cancelRecovery();let t=hn(e),n=this.hasConnectedValue,r=new AbortController;this.manualRejoinController=r,n&&(this.beginRecovery("rejoin",1,{trigger:"manual_rejoin"}),this.setState("resuming"));try{if(await this.performRejoin(t,{recovering:n,signal:r.signal}),this.sessionEnded)return;n&&this.completeRecovery()}catch(s){if(r.signal.aborted&&!this.terminalSessionError)return;let a=un(s);throw n&&this.failRecovery(a),this.setState("failed"),s}finally{this.manualRejoinController===r&&(this.manualRejoinController=null)}}async performRejoin(e,t={}){let{signal:n,recovering:r=!0,connect:s,markFailureTerminal:a=!0}=t;this.contextGeneration+=1,this.replacementContext.pause(),this.rejectPendingCommands(new Error("Restoring the session"));let o=await this.fetchRoomToken(e,n,r);if(o.status===401&&this.refreshCredentialsCallback&&(await this.refreshCredentials(n),X(n),o=await this.fetchRoomToken(e,n,r)),this.sessionEnded){if(this.terminalSessionError)throw this.terminalSessionError;return}if(!o.ok){if(o.status===409&&await this.recoverSessionEnd(e,n))return;throw await Te($n(o,"Could not renew room token"),n)}let d=await Te(o.json(),n);if(X(n),this.credentials=d.connection,this.room.state!==V.Disconnected){this.disconnectMode="rejoin";try{await this.measureRecoveryStage("room_disconnect",()=>Te(this.room.disconnect(),n),r)}finally{this.disconnectMode=null}}X(n),r&&this.reconnectStartedAt!==null&&(this.pendingReconnect={started_at:new Date(this.reconnectStartedAt).toISOString(),recovered_at:new Date().toISOString(),duration_ms:Date.now()-this.reconnectStartedAt});let c=s??{...this.recoveryReadiness,microphone:this.useManagedMicrophone,...this.applicationAudioTrack?{audioTrack:this.applicationAudioTrack}:{}};await this.connectWithMode({...c,apiBase:e},r,n,a)}async setMicrophoneEnabled(e){if(this.microphoneEnabled=e,this.applicationAudioTrack){let t=this.localApplicationAudioTrack;e?await t?.unmute():await t?.mute();return}await this.room.localParticipant.setMicrophoneEnabled(e)}async sendCommand(e,t,n=1e4){let r=Wn(this.connectionId,++this.clientSeq,e,t);return this.sendTrackedCommand(r,n)}async updateContext(e,t=2e4){if(this.sessionEnded||["failed","disconnected"].includes(this.stateValue))throw new Error("Cannot update context while the session is inactive");if(e.mode==="replace")return this.replacementContext.submit(e,t);if(this.activeRecovery)throw new Error("Cannot append context during recovery");return this.sendContextUpdate(e,t)}async sendContextUpdate(e,t){let n=this.contextGeneration,r=new AbortController;this.contextTransferControllers.add(r);let s=af(e),a=Date.now(),o=!1;this.recordDiagnostic({operation:"context_transfer",status:"started",context_key:e.key,payload_bytes:s}),this.activeContextTransfers+=1,this.activeContextBytes+=s;let d=("image"in e?this.uploadImageContext(e,r.signal):this.uploadTextContext(e,r.signal)).finally(()=>{this.contextTransferControllers.delete(r),this.activeContextTransfers-=1,this.activeContextBytes-=s}),c=d.then(()=>{},()=>{}),l,u=new Promise((k,T)=>{l=globalThis.setTimeout(()=>{o=!0;let S=new it(`Context transfer timed out after ${t}ms`,{retryAfter:c});this.recordDiagnostic({operation:"context_transfer",status:"timed_out",reason:"context_transfer_timeout",context_key:e.key,payload_bytes:s,duration_ms:Date.now()-a,timeout_ms:t}),this.flushDiagnostics("context_transfer_timeout"),r.abort(S),T(S)},t)}),h;try{h=await Promise.race([d,u])}catch(k){throw o||(this.recordDiagnostic({operation:"context_transfer",status:"failed",reason:"context_transfer_failed",context_key:e.key,payload_bytes:s,duration_ms:Date.now()-a}),this.flushDiagnostics("command_failed")),k instanceof TypeError||k instanceof it?k:new it(un(k).message,{cause:k})}finally{globalThis.clearTimeout(l)}let m=Date.now()-a;if(this.recordDiagnostic({operation:"context_transfer",status:"succeeded",context_key:e.key,payload_bytes:s,duration_ms:m}),m>2e3&&this.flushDiagnostics("slow_operation"),n!==this.contextGeneration)throw new Error("Context transfer interrupted by recovery");let{payload:f}=h;if(!Ka(f))throw new TypeError("Invalid context update payload");let g=Wn(this.connectionId,++this.clientSeq,"context.update",{...f});return this.sendTrackedCommand(g,t,h.resend)}resumeContextDelivery(e){this.replacementContext.resume(e).catch(()=>{})}async uploadTextContext(e,t){let n=new TextEncoder().encode(e.text);if(n.byteLength===0)throw new TypeError("Context text cannot be empty");if(n.byteLength>262144)throw new TypeError("Context text must be at most 262144 UTF-8 bytes");let r={key:e.key,mode:e.mode,label:e.label??"",respond:e.respond??!1};if(n.byteLength<=32768)return{payload:{...r,text:e.text}};let s=await Ll(n),a=Nl(),o=async d=>{d.throwIfAborted();let c={streamId:a,topic:"voxevolv.context.text",totalSize:n.byteLength,attributes:{sha256:s},signal:d},l=await this.room.localParticipant.streamText(c);await l.write(e.text),await l.close()};return await o(t),{payload:{...r,text_stream:{stream_id:a,bytes:n.byteLength,sha256:s}},resend:o}}async uploadImageContext(e,t){if(!new Set(["image/jpeg","image/png","image/webp"]).has(e.image.type))throw new TypeError("Image context must be JPEG, PNG, or WebP");let r=new Uint8Array(await e.image.arrayBuffer());if(r.byteLength===0||r.byteLength>5242880)throw new TypeError("Image context must be between 1 byte and 5 MiB");let s=await Ll(r),a=Nl(),o=async d=>{d.throwIfAborted();let c={streamId:a,topic:"voxevolv.context.image",name:"context-image",mimeType:e.image.type,totalSize:r.byteLength,attributes:{sha256:s},signal:d},l=await this.room.localParticipant.streamBytes(c);await l.write(r),await l.close()};return await o(t),{payload:{key:e.key,mode:"replace",label:e.label??"",image:{stream_id:a,mime:e.image.type,bytes:r.byteLength,sha256:s,...e.width===void 0?{}:{width:e.width},...e.height===void 0?{}:{height:e.height},detail:e.detail??"low"},respond:e.respond??!1},resend:o}}async disconnect(){if(this.abortStartupConnect(new Error("Session disconnected")),this.startupConnectController=null,this.failRecovery(new Error("Session disconnected during recovery")),this.cancelRecovery(),this.contextGeneration+=1,this.localApplicationAudioTrack=null,this.replacementContext.clear(new Error("Session disconnected")),this.stateValue!=="disconnected"){this.rejectPendingCommands(new Error("Session disconnected before command completion")),this.disconnectMode="intentional";try{await this.room.disconnect()}finally{this.disconnectMode=null,this.activeRecovery=null,this.setState("disconnected")}}}async end(e={}){this.credentialRefreshGeneration+=1,this.abortStartupConnect(new Error("Session ended")),this.startupConnectController=null,this.failRecovery(new Error("Session ended during recovery")),this.cancelRecovery(),this.sessionEnded=!0;let t=e.endpoint??this.endEndpoint??`${this.apiBase}/sessions/${this.id}`,n=e.request??{},r=new Headers(n.headers),s=!e.endpoint&&!this.endEndpoint;!r.has("Authorization")&&s&&r.set("Authorization",`Bearer ${this.accessToken}`);let a=await this.fetcher(t,{...n,method:n.method??"DELETE",headers:r,credentials:n.credentials??this.lifecycleCredentials});if(a.status===401&&s&&this.refreshCredentialsCallback&&(await this.refreshCredentials(n.signal??void 0),r.set("Authorization",`Bearer ${this.accessToken}`),a=await this.fetcher(t,{...n,method:n.method??"DELETE",headers:r,credentials:n.credentials??this.lifecycleCredentials})),!a.ok)throw await $n(a,"Could not end realtime session");(e.disconnect??!0)&&await this.disconnect()}async replay(e=this.apiBase,t=this.cursor.lastServerSeq){if(this.replayPromise)return this.replayPromise;let n=hn(e);return this.replayPromise=this.fetchReplay(n,t).finally(()=>{this.replayPromise=null}),this.replayPromise}setState(e){if(this.stateValue!==e){if(this.stateValue=e,(e==="connecting"||e==="resuming")&&(this.startDiagnosticLoopMonitor(),globalThis.document?.addEventListener?.("visibilitychange",this.onDiagnosticVisibilityChange)),e==="disconnected"||e==="failed"){globalThis.clearInterval(this.diagnosticLoopTimer),this.diagnosticLoopTimer=void 0,this.diagnosticLoopDelayMs=void 0,globalThis.document?.removeEventListener?.("visibilitychange",this.onDiagnosticVisibilityChange),this.flushDiagnostics("session_finished");let t=new Error(`Session ${e}`);this.contextGeneration+=1,this.replacementContext.clear(t),this.rejectPendingCommands(t)}this.notifyListeners(this.stateListeners,e)}}bindRoomEvents(){this.room.on(C.ParticipantDisconnected,e=>{e.isAgent&&!this.disconnectMode&&queueMicrotask(()=>{if(!(this.disconnectMode||this.terminalSessionError||this.terminalReplayController||["disconnected","failed"].includes(this.stateValue))){if(this.sessionEnded){this.agentDisconnected=!0,this.finishPendingEnd();return}if(!(!this.hasConnectedValue||this.room.state===V.Reconnecting||this.activeRecovery!==null||this.autoRejoinPromise!==null||this.manualRejoinController!==null)&&![...this.room.remoteParticipants.values()].some(t=>t.isAgent)){if(this.agentDisconnected=!0,!this.shouldAutoRejoin()){this.recoverDisconnectedSession().catch(()=>{});return}this.startAutoRejoin(new Error("Agent disconnected from the room"),{trigger:"agent_disconnected"})}}})}),this.room.on(C.SignalReconnecting,()=>this.handleLiveKitReconnecting()),this.room.on(C.Reconnecting,()=>this.handleLiveKitReconnecting()),this.room.on(C.Reconnected,()=>{this.handleLiveKitReconnected()}),this.room.on(C.Disconnected,e=>{this.handleLiveKitDisconnected(e)}),this.room.on(C.ConnectionStateChanged,e=>{if(!(this.sessionEnded||this.terminalSessionError||this.terminalReplayController||["disconnected","failed"].includes(this.stateValue))&&e===V.Connected){let t=this.activeRecovery!==null||this.stateValue==="resuming";this.setState(this.agentReady?"connected":t?"resuming":"connected_not_ready")}}),this.room.on(C.ConnectionQualityChanged,(e,t)=>{t.isLocal&&this.notifyListeners(this.connectionQualityListeners,e)}),this.room.on(C.TrackSubscribed,e=>{if(e.kind!==_.Kind.Audio)return;let t=e.attach();t.dataset.voxevolvRemoteAudio="true",t.style.display="none",document.body.appendChild(t);try{t.play().catch(s=>{this.notifyListeners(this.audioPlaybackBlockedListeners,{error:s,element:t,track:e.mediaStreamTrack})})}catch(r){this.notifyListeners(this.audioPlaybackBlockedListeners,{error:r,element:t,track:e.mediaStreamTrack})}let n=new MediaStream([e.mediaStreamTrack]);this.remoteAudioStreams.set(e,n),this.outputStream.addTrack(e.mediaStreamTrack),this.notifyRemoteAudioListeners(this.remoteAudioTrackListeners,e.mediaStreamTrack,n),this.remoteAudioTrackResolve?.()}),this.room.on(C.TrackUnsubscribed,e=>{if(e.kind!==_.Kind.Audio)return;let t=this.remoteAudioStreams.get(e)??new MediaStream([e.mediaStreamTrack]);this.notifyRemoteAudioListeners(this.remoteAudioTrackUnsubscribedListeners,e.mediaStreamTrack,t),this.remoteAudioStreams.delete(e),this.outputMediaStream?.removeTrack(e.mediaStreamTrack),e.detach().forEach(n=>n.remove())}),this.room.on(C.DataReceived,(e,t,n,r)=>{if(r!=="voxevolv.events"||n!==Ze.RELIABLE)return;let s;try{s=JSON.parse(new TextDecoder().decode(e))}catch{return}if(!za(s))return;let a=this.cursor.accept(s);a.gap&&(this.notifyListeners(this.gapListeners,a.gap),this.replay(this.apiBase,a.gap.after_server_seq)),a.deliver&&(this.observeReadiness(s),this.observeCommandResult(s),this.observeConvenienceEvents(s),this.notifyListeners(this.listeners,s))})}handleLiveKitReconnecting(){if(!(this.sessionEnded||this.disconnectMode==="intentional"||this.terminalReplayController||["disconnected","failed"].includes(this.stateValue))){if(this.agentReady=!1,this.autoRejoinPromise!==null||this.activeRecovery?.strategy==="rejoin"||this.disconnectMode==="rejoin"){this.setState("resuming");return}this.contextGeneration+=1,this.livekitResumeController?.abort(new Error("LiveKit connection interrupted again")),this.livekitResumeController=null,this.replacementContext.pause(),this.reconnectStartedAt??=Date.now(),this.rejectPendingCommands(new Error("Connection interrupted before command completion"),!0),this.activeRecovery===null&&(this.beginRecovery("livekit",1,{trigger:"livekit_reconnecting"}),this.recordDiagnostic({operation:"connection_recovery",stage:"room_connect",status:"started"})),this.setState("reconnecting")}}async handleLiveKitReconnected(){if(this.sessionEnded||this.disconnectMode||this.autoRejoinPromise||this.livekitResumeController||this.terminalReplayController||["disconnected","failed"].includes(this.stateValue))return;let e=this.contextGeneration,t=new AbortController;this.livekitResumeController=t;let n=Date.now();this.reconnectStartedAt!==null&&(this.pendingReconnect={started_at:new Date(this.reconnectStartedAt).toISOString(),recovered_at:new Date(n).toISOString(),duration_ms:Math.max(n-this.reconnectStartedAt,0)},this.reconnectStartedAt=null),this.hasConnectedValue&&this.activeRecovery===null&&this.beginRecovery("livekit",1,{trigger:"livekit_reconnecting"}),this.recordDiagnostic({operation:"connection_recovery",stage:"room_connect",status:"succeeded",duration_ms:Math.max(Date.now()-(this.recoveryStartedAt??Date.now()),0)}),this.connectionId=`conn_${Math.random().toString(36).slice(2)}_${Date.now().toString(36)}`,this.clientSeq=0,this.setState(this.hasConnectedValue?"resuming":"connected_not_ready");try{await this.measureRecoveryStage("hello",()=>this.sendRecoveryHello(t.signal));let r=Date.now()+this.recoveryReadiness.readyTimeoutMs;if(await this.measureRecoveryStage("agent_ready",()=>this.waitForAgentReady(Math.max(r-Date.now(),0),t.signal)),this.recoveryReadiness.waitForRemoteAudio&&await this.measureRecoveryStage("remote_audio",()=>this.waitForRemoteAudioTrack(r,t.signal)),this.sessionEnded||e!==this.contextGeneration||(this.resumeContextDelivery(!0),this.sessionEnded||e!==this.contextGeneration))return;this.setState("connected"),this.completeRecovery()}catch(r){if(t.signal.aborted||this.sessionEnded||e!==this.contextGeneration)return;let s=un(r);this.shouldAutoRejoin()?this.startAutoRejoin(s,{trigger:"livekit_resume_failed"}):(this.failRecovery(s),this.setState("failed"))}finally{this.livekitResumeController===t&&(this.livekitResumeController=null)}}handleLiveKitDisconnected(e){if(this.agentReady=!1,this.disconnectMode!=="rejoin"&&(this.pendingReconnect=null),this.outputMediaStream?.getTracks().forEach(t=>{this.outputMediaStream?.removeTrack(t)}),this.rejectPendingCommands(new Error("Session disconnected before command completion")),this.disconnectMode!=="rejoin"&&this.disconnectMode!=="connect_failure"){if(this.disconnectMode==="intentional"){this.activeRecovery=null,this.deliverPendingEndEvent(),this.setState("disconnected");return}if(!(this.terminalSessionError||this.terminalReplayController)){if(this.shouldAutoRejoin(e)){this.startAutoRejoin(new Error(`LiveKit disconnected (${xl(e)})`),{trigger:"livekit_disconnected"});return}if(this.hasConnectedValue&&!this.sessionEnded&&!["disconnected","failed"].includes(this.stateValue)&&(!Al(e)||e===re.ROOM_CLOSED||e===re.ROOM_DELETED)){this.recoverDisconnectedSession().catch(()=>{});return}this.activeRecovery!==null&&this.failRecovery(new Error(`LiveKit disconnected (${xl(e)})`)),this.deliverPendingEndEvent(),this.setState("disconnected")}}}deliverPendingEndEvent(){let e=this.pendingEndEvent;e&&(this.pendingEndEvent=null,this.notifyEnded({...e,type:"session.ended"}))}finishPendingEnd(){this.deliverPendingEndEvent(),this.disconnect().catch(()=>{})}async recoverDisconnectedSession(){if(this.terminalReplayController)return;this.failRecovery(new Error("Transport closed during recovery")),this.cancelRecovery(),this.contextGeneration+=1,this.replacementContext.pause();let e=new AbortController;this.terminalReplayController=e,this.setState("resuming");try{await this.recoverSessionEnd(this.apiBase,e.signal,!0)}finally{this.terminalReplayController===e&&(this.terminalReplayController=null,!e.signal.aborted&&!this.sessionEnded&&!this.terminalSessionError&&await this.disconnect())}}async recoverSessionEnd(e,t,n=!1){let r=new AbortController,s=()=>r.abort(t?.reason);t?.addEventListener("abort",s,{once:!0}),t?.aborted&&s();let a=globalThis.setTimeout(()=>r.abort(),5e3);try{do{try{await this.fetchReplay(e,0,{signal:r.signal,terminalOnly:!0})}catch(o){if(!n||r.signal.aborted||Dl(o))throw o}if(!n||this.sessionEnded||this.terminalSessionError)break;await Qa(500,r.signal)}while(!r.signal.aborted)}catch{}finally{globalThis.clearTimeout(a),t?.removeEventListener("abort",s)}return!this.sessionEnded||this.terminalSessionError?!1:(this.finishPendingEnd(),!0)}notifyEnded(e){this.endNotificationDelivered||(this.endNotificationDelivered=!0,this.notifyListeners(this.endedListeners,e))}beginRecovery(e,t,n){this.recoveryStartedAt??=Date.now(),this.activeRecovery={strategy:e,attempt:t,details:n},this.recordDiagnostic({operation:"connection_recovery",status:"started",reason:n.trigger,message_id:n.messageId,context_key:n.contextKey,timeout_ms:n.timeoutMs,retry_count:t-1}),this.flushDiagnostics("recovery_started"),this.notifyListeners(this.recoveryListeners,{status:"started",strategy:e,attempt:t,...n})}completeRecovery(){let e=this.activeRecovery;e&&(this.recordDiagnostic({operation:"connection_recovery",stage:"complete",status:"succeeded",duration_ms:Math.max(Date.now()-(this.recoveryStartedAt??Date.now()),0),retry_count:e.attempt-1,reason:e.details.trigger}),this.flushDiagnostics("recovery_completed"),this.recoveryStartedAt=null,this.activeRecovery=null,this.notifyListeners(this.recoveryListeners,{status:"succeeded",strategy:e.strategy,attempt:e.attempt,...e.details}))}failRecovery(e){let t=this.activeRecovery;t&&(this.recordDiagnostic({operation:"connection_recovery",stage:"complete",status:"failed",duration_ms:Math.max(Date.now()-(this.recoveryStartedAt??Date.now()),0),retry_count:t.attempt-1,reason:t.details.trigger}),this.flushDiagnostics("recovery_failed"),this.activeRecovery=null,this.notifyListeners(this.recoveryListeners,{status:"failed",strategy:t.strategy,attempt:t.attempt,...t.details,error:e}))}shouldAutoRejoin(e){return this.autoRejoinOptions!==null&&this.hasConnectedValue&&!this.sessionEnded&&!["disconnected","failed"].includes(this.stateValue)&&!Al(e)}startAutoRejoin(e,t){if(this.autoRejoinPromise||!this.shouldAutoRejoin())return;this.recoveryStartedAt??=Date.now(),this.agentReady=!1,this.contextGeneration+=1,this.livekitResumeController?.abort(e),this.replacementContext.pause(),this.rejectPendingCommands(e),this.reconnectStartedAt??=Date.now();let n=new AbortController;this.autoRejoinController=n;let r=Math.max(this.autoRejoinOptions.timeoutMs-(Date.now()-this.recoveryStartedAt),0),s=globalThis.setTimeout(()=>{if(n.signal.aborted)return;let o=new Error("Session recovery timed out");n.abort(o),this.contextGeneration+=1,this.rejectPendingCommands(o),this.replacementContext.clear(o),this.failRecovery(o),this.setState("failed")},r),a=this.runAutoRejoin(e,n.signal,t).finally(()=>{globalThis.clearTimeout(s),this.autoRejoinController===n&&(this.autoRejoinController=null,this.autoRejoinPromise=null)});this.autoRejoinPromise=a}async runAutoRejoin(e,t,n){let r=this.autoRejoinOptions;if(!r)return;let s=e;this.activeRecovery?.strategy==="livekit"&&this.failRecovery(e),this.setState("resuming");for(let a=1;a<=r.maxAttempts;a+=1)try{if(await sf(t),a>1){let o=r.baseDelayMs*2**(a-2),d=Math.min(o,r.maxDelayMs);await Qa(d+Math.random()*Math.min(d,500),t)}if(X(t),this.beginRecovery("rejoin",a,n),await this.performRejoin(this.apiBase,{signal:t}),this.sessionEnded)return;X(t),this.reconnectStartedAt=null,this.completeRecovery();return}catch(o){if(t.aborted)return;if(s=un(o),Dl(o))break}this.failRecovery(s),this.replacementContext.clear(s),this.setState("failed")}cancelRecovery(){this.terminalReplayController?.abort(),this.terminalReplayController=null,this.livekitResumeController?.abort(),this.livekitResumeController=null,this.recoveryStartedAt=null,this.autoRejoinController?.abort(),this.autoRejoinController=null,this.manualRejoinController?.abort(),this.manualRejoinController=null,this.autoRejoinPromise=null,this.activeRecovery=null}notifyListeners(e,t){for(let n of e)try{n(t)}catch(r){console.error("VoxEvolv event listener failed",r)}}notifyRemoteAudioListeners(e,t,n){for(let r of e)try{r(t,n)}catch(s){console.error("VoxEvolv remote audio listener failed",s)}}validateAudioOptions(e,t){if(e&&t)throw new rt("microphone and audioTrack cannot both be enabled");if(t){if(t.kind!=="audio")throw new rt("audioTrack must be an audio MediaStreamTrack");if(t.readyState==="ended")throw new rt("audioTrack has already ended")}}async measureRecoveryStage(e,t,n=!0){if(!n)return t();let r=Date.now();this.recordDiagnostic({operation:"connection_recovery",stage:e,status:"started"});try{let s=await t();return this.recordDiagnostic({operation:"connection_recovery",stage:e,status:"succeeded",duration_ms:Date.now()-r}),s}catch(s){throw this.recordDiagnostic({operation:"connection_recovery",stage:e,status:"failed",duration_ms:Date.now()-r,reason:s instanceof Qn?"data_channel_stalled":"stage_failed"}),this.flushDiagnostics("recovery_stage_failed"),s}}async fetchRoomToken(e,t,n=!0){let r=new AbortController,s=()=>r.abort(t?.reason);t?.addEventListener("abort",s,{once:!0});let a=globalThis.setTimeout(()=>r.abort(),1e4),o=Date.now();n&&this.recordDiagnostic({operation:"connection_recovery",stage:"token_request",status:"started"});try{X(t);let d=await Te(this.fetcher(`${e}/sessions/${this.id}/room-tokens`,{method:"POST",headers:{Authorization:`Bearer ${this.accessToken}`},credentials:this.lifecycleCredentials,signal:r.signal}),r.signal);return n&&(this.recordDiagnostic({operation:"connection_recovery",stage:"token_request",status:d.ok?"succeeded":"failed",http_status:d.status,duration_ms:Date.now()-o}),d.ok||this.flushDiagnostics("recovery_stage_failed")),d}catch(d){throw n&&(this.recordDiagnostic({operation:"connection_recovery",stage:"token_request",status:"failed",duration_ms:Date.now()-o,reason:t?.aborted?"cancelled":r.signal.aborted?"request_timeout":"request_failed"}),this.flushDiagnostics("recovery_stage_failed")),d}finally{globalThis.clearTimeout(a),t?.removeEventListener("abort",s)}}async refreshCredentials(e){if(!this.refreshCredentialsCallback)return;X(e);let t=this.contextGeneration,n=++this.credentialRefreshGeneration,r=await Te(this.refreshCredentialsCallback(),e);if(X(e),t!==this.contextGeneration||n!==this.credentialRefreshGeneration)throw new Error("Credential refresh was superseded");if(Ul(r),r.id!==this.id)throw new Error("Refreshed credentials belong to a different session");this.accessToken=r.access_token,this.credentials=r.connection}async finishSessionFailure(e){this.sessionEnded=!0,this.contextGeneration+=1,this.rejectPendingCommands(e),this.replacementContext.clear(e),this.failRecovery(e),this.cancelRecovery(),this.disconnectMode="connect_failure";try{await this.room.disconnect()}finally{this.disconnectMode=null,this.setState("failed")}}observeConvenienceEvents(e){if(e.type==="session.error"){if(this.sessionEnded)return;let r=new lr(e);r.retryable&&this.startupAttemptController?this.startupAttemptController.abort(r):(this.terminalSessionError=r,this.abortStartupConnect(r),this.startupConnectController||this.finishSessionFailure(r).catch(()=>{}))}if(e.type==="session.ending"||e.type==="session.ended"){if(this.terminalSessionError)return;this.abortStartupConnect(new Error("Session ended during startup")),this.contextGeneration+=1,this.rejectPendingCommands(new Error("Session ended")),this.failRecovery(new Error("Session ended during recovery"))}if(e.type==="session.ending"&&(this.sessionEnded=!0,this.cancelRecovery(),this.replacementContext.clear(new Error("Session ended")),this.pendingEndEvent??=e,(!this.hasConnectedValue||this.agentDisconnected||this.room.state===V.Disconnected)&&this.finishPendingEnd()),e.type==="session.ended"){let r=this.pendingEndEvent;this.pendingEndEvent=null,this.sessionEnded=!0,this.replacementContext.clear(new Error("Session ended")),this.cancelRecovery(),this.notifyEnded(r?{...r,type:"session.ended"}:e),this.disconnect().catch(()=>{})}e.type.endsWith(".error")&&this.notifyListeners(this.errorListeners,e);let t=this.transcriptStore.accept(e);t&&this.notifyListeners(this.transcriptListeners,t);let n=df(e);n&&this.notifyListeners(n.role==="user"?this.userTranscriptListeners:this.agentTranscriptListeners,n)}abortStartupConnect(e){this.startupConnectController?.signal.aborted||this.startupConnectController?.abort(e)}async publishApplicationAudioTrack(e){let t=e.clone(),n=null;try{n=new Et(t,void 0,!0),this.localApplicationAudioTrack=n,this.microphoneEnabled||await n.mute(),await this.room.localParticipant.publishTrack(n,{source:_.Source.Microphone,name:"voxevolv-application-audio"})}catch(r){throw this.localApplicationAudioTrack===n&&(this.localApplicationAudioTrack=null),t.stop(),r}}async sendHello(e=$a){let t=this.pendingReconnect,n=Wn(this.connectionId,++this.clientSeq,"client.hello",{last_server_seq:this.cursor.lastServerSeq,sdk:`@voxevolv/client@${Pl}`,tool_handlers:[...this.toolHandlers.keys()].sort(),...t?{reconnect:t}:{}});this.lastHelloMessageId=n.message_id,await this.sendTrackedCommand(n,e),this.pendingReconnect===t&&(this.pendingReconnect=null)}async sendRecoveryHello(e){X(e);let t=this.reliableDataChannelBufferedBytes(),n=Date.now(),r,s=new Promise((a,o)=>{let d=()=>{let c=this.reliableDataChannelBufferedBytes();if(c===void 0||c===0||t===void 0||t===0||c<t)n=Date.now();else if(Date.now()-n>=Yp){o(new Qn);return}t=c,r=globalThis.setTimeout(d,Il)};r=globalThis.setTimeout(d,Il)});try{await Te(Promise.race([this.sendHello(),s]),e)}catch(a){throw a instanceof Qn&&this.rejectPendingCommands(a),a}finally{r!==void 0&&globalThis.clearTimeout(r)}}async sendTrackedCommand(e,t,n){let r=cf(e),s=of(e.payload),a=Date.now();this.recordDiagnostic({operation:"command_send",status:"started",message_id:e.message_id,connection_id:e.connection_id,client_seq:e.client_seq,context_key:r,payload_bytes:s,retry_count:0,timeout_ms:t,event_type:Jn(e.type)});let o=e.type==="context.update"?new AbortController:void 0,d=()=>{},c=new Promise(u=>{d=()=>{o?.abort(),u()}}),l=new Promise((u,h)=>{let m=globalThis.setTimeout(()=>{let f=this.pendingCommands.get(e.message_id);f&&globalThis.clearTimeout(f.retry),f?.markSettled(),this.pendingCommands.delete(e.message_id);let g=`Command ${e.type} timed out after ${t}ms`,k=e.type==="context.update"?new it(g,{retryAfter:f?.transferSettled}):new Error(g);this.recordDiagnostic({operation:"command_send",status:"timed_out",reason:e.type==="context.update"?"context_command_timeout":"command_timeout",message_id:e.message_id,connection_id:e.connection_id,client_seq:e.client_seq,context_key:r,payload_bytes:s,duration_ms:Date.now()-a,retry_count:f?.retryCount??0,timeout_ms:t,event_type:Jn(e.type)}),this.flushDiagnostics("command_timeout"),h(k)},t);this.pendingCommands.set(e.message_id,{commandType:e.type,message:e,startedAt:a,contextKey:r,payloadBytes:s,retryCount:0,publishQueued:!1,resolve:u,reject:h,timeout:m,settled:c,markSettled:d,retryTransfer:n,sendController:o,transferRetrying:!1,transferRetryRequested:!1}),this.scheduleCommandRetry(e)});return this.publishCommandAttempt(e,!1).catch(()=>{}),l}scheduleCommandRetry(e){let t=this.pendingCommands.get(e.message_id);if(!t)return;let n=e.type==="context.update"?Ja(t.retryCount+1):500;t.retry=globalThis.setTimeout(()=>{this.retryCommand(e).finally(()=>this.scheduleCommandRetry(e))},n)}async retryCommand(e){let t=this.pendingCommands.get(e.message_id);if(t&&!(e.type==="context.update"&&(this.sessionEnded||["reconnecting","resuming","disconnected","failed"].includes(this.stateValue))))try{if(t.transferRetryRequested&&t.retryTransfer&&t.sendController){t.transferRetryRequested=!1,t.transferRetrying=!0;let n=t.retryTransfer(t.sendController.signal);t.transferSettled=n.then(()=>{},()=>{}),t.contextKey&&this.replacementContext.blockUntilTransferSettles(t.contextKey,t.transferSettled),await Promise.race([n,t.settled])}await this.publishCommandAttempt(e,!0)}catch{}finally{t.transferRetrying=!1}}publishCommandAttempt(e,t){let n=this.pendingCommands.get(e.message_id);if(!n||n.publishQueued)return Promise.resolve();n.publishQueued=!0;let r=this.commandPublishTail.then(()=>this.publishCommandAttemptNow(e,t)).finally(()=>{let s=this.pendingCommands.get(e.message_id);s===n&&(s.publishQueued=!1)});return this.commandPublishTail=r.catch(()=>{}),r}async publishCommandAttemptNow(e,t){let n=this.pendingCommands.get(e.message_id);if(!n)return;t&&(n.retryCount+=1,this.recordDiagnostic({operation:"command_send",status:"retrying",message_id:e.message_id,connection_id:e.connection_id,client_seq:e.client_seq,context_key:n.contextKey,payload_bytes:n.payloadBytes,retry_count:n.retryCount,event_type:Jn(e.type)}));let r=Date.now();try{let a=!1,o=this.publishCommand(e,n.sendController?.signal).then(()=>{a=!0});if(await Promise.race([o,n.settled]),!a)return}catch(a){if(n.sendController?.signal.aborted)return;throw this.recordDiagnostic({operation:"command_send",status:"failed",reason:"command_publish_failed",message_id:e.message_id,connection_id:e.connection_id,client_seq:e.client_seq,context_key:n.contextKey,payload_bytes:n.payloadBytes,duration_ms:Date.now()-r,retry_count:n.retryCount,event_type:Jn(e.type)}),this.flushDiagnostics("command_failed"),a}let s=Date.now()-r;this.recordDiagnostic({operation:"command_send",status:"succeeded",message_id:e.message_id,connection_id:e.connection_id,client_seq:e.client_seq,context_key:n.contextKey,payload_bytes:n.payloadBytes,duration_ms:s,retry_count:n.retryCount,event_type:Jn(e.type)}),s>2e3&&this.flushDiagnostics("slow_operation")}async publishCommand(e,t){let n={reliable:!0,topic:"voxevolv.commands",signal:t};await this.room.localParticipant.publishData(new TextEncoder().encode(JSON.stringify(e)),n)}startDiagnosticLoopMonitor(){this.diagnosticLoopTimer===void 0&&(this.diagnosticLoopExpectedAt=performance.now()+1e3,this.diagnosticLoopTimer=globalThis.setInterval(()=>{let e=performance.now();this.diagnosticLoopDelayMs=Math.max(0,e-this.diagnosticLoopExpectedAt),this.diagnosticLoopExpectedAt=e+1e3},1e3),this.diagnosticLoopTimer.unref?.())}recordDiagnostic(e){let t={...e,connection_state:this.stateValue,buffered_bytes:this.reliableDataChannelBufferedBytes()};(e.operation==="tool_rpc"||e.operation==="connection_recovery")&&(t.page_visibility=globalThis.document?.visibilityState,t.active_context_transfers=this.activeContextTransfers,t.active_context_bytes=this.activeContextBytes,this.diagnosticLoopTimer!==void 0&&(t.event_loop_delay_ms=Math.max(this.diagnosticLoopDelayMs??0,performance.now()-this.diagnosticLoopExpectedAt))),this.diagnostics.record(t)}reliableDataChannelBufferedBytes(){try{let e=this.room.engine.dataChannelForKind(0)?.bufferedAmount;return typeof e=="number"?e:void 0}catch{return}}flushDiagnostics(e){this.diagnostics.flush(e,t=>this.postDiagnostics(t))}async postDiagnostics(e){let t=new AbortController,n,r=new Promise((s,a)=>{n=globalThis.setTimeout(()=>{t.abort(),a(new Error(`Diagnostic report timed out after ${this.diagnosticReportTimeoutMs}ms`))},this.diagnosticReportTimeoutMs)});try{let s=async()=>{let a=await this.fetcher(`${this.apiBase}/sessions/${this.id}/diagnostics`,{method:"POST",headers:{Authorization:`Bearer ${this.accessToken}`,"Content-Type":"application/json"},credentials:this.lifecycleCredentials,body:JSON.stringify(e),signal:t.signal,keepalive:!0}),o=await a.json().catch(()=>null);if(!a.ok){let d=a.status===408||a.status===429||a.status>=500,c=Number(a.headers.get("Retry-After"))*1e3,l=typeof o?.retry_after_ms=="number"?o.retry_after_ms:c;throw new Gt(`Diagnostic report failed (${a.status})`,d,Number.isFinite(l)?Math.max(l,0):0)}if(o?.report_id!==e.report_id)throw new Gt("Diagnostic report was not acknowledged")};await Promise.race([s(),r])}finally{n!==void 0&&globalThis.clearTimeout(n)}}waitForRemoteAudioTrack(e,t){return(this.outputMediaStream?.getAudioTracks().length??0)>0?Promise.resolve():(X(t),new Promise((n,r)=>{let s=()=>{globalThis.clearTimeout(a),t?.removeEventListener("abort",o),this.remoteAudioTrackResolve=null},a=globalThis.setTimeout(()=>{s(),r(new Error("Agent audio track did not arrive within the ready timeout; pass waitForRemoteAudio: false to resolve connect() on signaling readiness alone"))},Math.max(e-Date.now(),0)),o=()=>{s(),r(We(t))};this.remoteAudioTrackResolve=()=>{s(),n()},t?.addEventListener("abort",o,{once:!0})}))}waitForAgentReady(e,t){return this.agentReady?Promise.resolve():(X(t),new Promise((n,r)=>{let s=()=>{globalThis.clearTimeout(a),t?.removeEventListener("abort",o),this.readyResolve=null},a=globalThis.setTimeout(()=>{s(),r(new Error(`Agent did not become ready within ${e}ms`))},e),o=()=>{s(),r(We(t))};this.readyResolve=()=>{s(),n()},t?.addEventListener("abort",o,{once:!0})}))}observeReadiness(e){if(e.stream_id==="durable-replay")return;let t=e.payload,n=e.type==="agent.snapshot"&&t.status==="ready"&&t.connection_id===this.connectionId&&t.ack_message_id===this.lastHelloMessageId;if(e.type!=="agent.ready"&&!n)return;if(this.agentStreamId&&this.agentStreamId!==e.stream_id&&!this.activeRecovery){this.startAutoRejoin(new Error("Agent worker was replaced"),{trigger:"worker_replaced"});return}this.agentStreamId=e.stream_id,this.agentDisconnected=!1;let r=this.agentReady;this.agentReady=!0,this.readyResolve?.(),r||this.notifyListeners(this.readyListeners,e)}observeCommandResult(e){if(e.type!=="command.ack"&&e.type!=="command.error"&&e.type!=="context.updated"&&e.type!=="context.rejected")return;let t=this.pendingCommands.get(String(e.payload.message_id??""));if(t){if(e.type==="command.ack"&&Va(e.payload)){this.recordCommandResult(t,e.type,"acknowledged"),globalThis.clearTimeout(t.timeout),globalThis.clearTimeout(t.retry),t.markSettled(),this.pendingCommands.delete(e.payload.message_id),t.resolve(e.payload);return}if(e.type==="context.updated"&&Ga(e.payload)){this.recordCommandResult(t,e.type,"acknowledged"),globalThis.clearTimeout(t.timeout),globalThis.clearTimeout(t.retry),t.markSettled(),this.pendingCommands.delete(e.payload.message_id),t.resolve(e.payload);return}if(e.type==="command.error"&&Ha(e.payload)||e.type==="context.rejected"&&Wa(e.payload)){if(this.recordCommandResult(t,e.type,"rejected",e.payload.code),this.flushDiagnostics("command_rejected"),e.type==="context.rejected"&&e.payload.retryable){e.payload.code==="stream_unavailable"&&t.retryTransfer&&!t.transferRetrying&&(t.transferRetryRequested=!0);return}globalThis.clearTimeout(t.timeout),globalThis.clearTimeout(t.retry),t.markSettled(),this.pendingCommands.delete(e.payload.message_id),t.reject(new Gn(e.payload))}}}rejectPendingCommands(e,t=!1){if(!t)for(let n of this.contextTransferControllers)n.abort(e);for(let[n,r]of this.pendingCommands)t&&r.commandType==="context.update"||(this.recordCommandResult(r,r.commandType==="context.update"?"context.rejected":"command.error","failed","pending_command_cancelled"),globalThis.clearTimeout(r.timeout),globalThis.clearTimeout(r.retry),r.markSettled(),r.reject(r.commandType==="context.update"?new it(e.message,{cause:e,retryAfter:r.transferSettled}):e),this.pendingCommands.delete(n))}recordCommandResult(e,t,n,r){let s=Date.now()-e.startedAt;this.recordDiagnostic({operation:"command_result",status:n,reason:r,message_id:e.message.message_id,connection_id:e.message.connection_id,client_seq:e.message.client_seq,context_key:e.contextKey,payload_bytes:e.payloadBytes,duration_ms:s,retry_count:e.retryCount,event_type:t}),s>2e3&&this.flushDiagnostics("slow_operation")}async fetchReplay(e,t,n={}){let{signal:r,terminalOnly:s=!1}=n,a=t;for(;;){X(r);let o=`${e}/sessions/${this.id}/events?after_seq=${a}&limit=200`+(s?"&terminal_only=true":""),d=await Te(this.fetcher(o,{headers:{Authorization:`Bearer ${this.accessToken}`},credentials:this.lifecycleCredentials,signal:r}),r);if(d.status===401&&this.refreshCredentialsCallback&&(await this.refreshCredentials(r),d=await Te(this.fetcher(o,{headers:{Authorization:`Bearer ${this.accessToken}`},credentials:this.lifecycleCredentials,signal:r}),r)),!d.ok)throw await Te($n(d,"Could not replay session events"),r);let c=await Te(d.json(),r);X(r);for(let l of c.items){a=Math.max(a,l.server_seq);let u={protocol_version:1,event_id:l.event_id,stream_id:"durable-replay",stream_seq:Math.max(this.cursor.lastStreamSeq,1),server_seq:l.server_seq,ts:l.created_at,type:l.type,payload:l.payload};this.cursor.acceptReplay(u)&&(this.observeReadiness(u),this.observeConvenienceEvents(u),this.notifyListeners(this.listeners,u))}if(a=Math.max(a,c.next_after_seq),!c.has_more)return}}};function tf(i){if(!i)return null;let e=i===!0?{}:i,t={maxAttempts:e.maxAttempts??Number.MAX_SAFE_INTEGER,baseDelayMs:e.baseDelayMs??750,maxDelayMs:e.maxDelayMs??5e3,timeoutMs:e.timeoutMs??18e4};if(!Number.isFinite(t.timeoutMs)||t.timeoutMs<=0)throw new TypeError("autoRejoin.timeoutMs must be a positive finite number");if(!Number.isInteger(t.maxAttempts)||t.maxAttempts<1)throw new TypeError("autoRejoin.maxAttempts must be a positive integer");if(!Number.isFinite(t.baseDelayMs)||t.baseDelayMs<0)throw new TypeError("autoRejoin.baseDelayMs must be a non-negative finite number");if(!Number.isFinite(t.maxDelayMs)||t.maxDelayMs<0)throw new TypeError("autoRejoin.maxDelayMs must be a non-negative finite number");return t}function nf(i){if(i===!1)return null;let e=typeof i=="object"?i:{},t=(e.attempts??Zp).map(r=>({readyTimeoutMs:r.readyTimeoutMs,delayBeforeMs:r.delayBeforeMs??0})),n=e.timeoutMs??ef;if(t.length===0)throw new TypeError("startupRetry.attempts must contain at least one attempt");for(let r of t){if(!Number.isFinite(r.readyTimeoutMs)||r.readyTimeoutMs<=0)throw new TypeError("startupRetry.attempts readyTimeoutMs must be a positive finite number");if(!Number.isFinite(r.delayBeforeMs)||r.delayBeforeMs<0)throw new TypeError("startupRetry.attempts delayBeforeMs must be a non-negative finite number")}if(!Number.isFinite(n)||n<=0)throw new TypeError("startupRetry.timeoutMs must be a positive finite number");return{attempts:t,timeoutMs:n}}function Al(i){return i!==void 0&&[re.CLIENT_INITIATED,re.DUPLICATE_IDENTITY,re.PARTICIPANT_REMOVED,re.ROOM_DELETED,re.ROOM_CLOSED,re.USER_UNAVAILABLE,re.USER_REJECTED].includes(i)}function xl(i){return i===void 0?"unknown":re[i]??String(i)}function Dl(i){return i instanceof Yn&&[401,403,409].includes(i.status)}function rf(i){return i instanceof lr?!i.retryable:i instanceof Yn?i.status>=400&&i.status<500&&![408,425,429].includes(i.status):i instanceof rt?!0:i instanceof Error&&["ConstraintNotSatisfiedError","DevicesNotFoundError","InvalidStateError","NotAllowedError","NotFoundError","NotReadableError","NotSupportedError","OverconstrainedError","SecurityError","TrackStartError"].includes(i.name)}function un(i){return i instanceof Error?i:new Error(String(i))}function We(i){return i.reason??new DOMException("Aborted","AbortError")}function Ol(i){let e=new AbortController;return i.aborted?e.abort(We(i)):i.addEventListener("abort",()=>e.abort(We(i)),{once:!0}),e}function X(i){if(i?.aborted)throw We(i)}function Te(i,e){return e?new Promise((t,n)=>{let r=!1,s=d=>{r||(r=!0,e.removeEventListener("abort",o),t(d))},a=d=>{r||(r=!0,e.removeEventListener("abort",o),n(d))},o=()=>a(We(e));e.aborted?o():e.addEventListener("abort",o,{once:!0}),i.then(s,a)}):i}function Qa(i,e){return X(e),i<=0?Promise.resolve():new Promise((t,n)=>{let r=globalThis.setTimeout(()=>{e.removeEventListener("abort",s),t()},i),s=()=>{globalThis.clearTimeout(r),n(We(e))};e.addEventListener("abort",s,{once:!0})})}function sf(i){return X(i),typeof navigator>"u"||navigator.onLine!==!1||typeof globalThis.addEventListener!="function"?Promise.resolve():new Promise((e,t)=>{let n=()=>{globalThis.removeEventListener("online",r),i.removeEventListener("abort",s)},r=()=>{n(),e()},s=()=>{n(),t(We(i))};globalThis.addEventListener("online",r,{once:!0}),i.addEventListener("abort",s,{once:!0})})}async function Ll(i){if(!globalThis.crypto?.subtle)throw new Error("Web Crypto SHA-256 is unavailable");let e=await globalThis.crypto.subtle.digest("SHA-256",Uint8Array.from(i).buffer);return[...new Uint8Array(e)].map(t=>t.toString(16).padStart(2,"0")).join("")}function Nl(){return globalThis.crypto?.randomUUID?globalThis.crypto.randomUUID():`ctx_${Date.now().toString(36)}_${Math.random().toString(36).slice(2)}`}function af(i){return"image"in i?i.image.size:new TextEncoder().encode(i.text).byteLength}function of(i){let e=i.image;if(e&&typeof e=="object"&&"bytes"in e){let n=e.bytes;if(typeof n=="number")return n}let t=i.text_stream;if(t&&typeof t=="object"&&"bytes"in t){let n=t.bytes;if(typeof n=="number")return n}if(typeof i.text=="string")return new TextEncoder().encode(i.text).byteLength;try{return new TextEncoder().encode(JSON.stringify(i)).byteLength}catch{return}}function cf(i){if(i.type!=="context.update")return;let e=i.payload.key;return typeof e=="string"?e:void 0}function Jn(i){return i==="client.hello"||i==="context.update"?i:void 0}function Ul(i){if(!i||typeof i!="object")throw new rt("Session credentials must be an object");if(!i.id||!i.access_token||!i.access_token_expires_at)throw new rt("Session credentials are incomplete");if(!i.connection||!i.connection.url||!i.connection.token||!i.connection.room_name)throw new rt("Session connection credentials are incomplete")}function hn(i){let e=i.trim().replace(/\/+$/,"");if(!e)throw new rt("apiBase must be a non-root relative path or an absolute URL");return e}function df(i){let e=/^transcript\.(user|agent)\.(interim|final)$/.exec(i.type);if(!e)return null;let t=i.payload.text;return typeof t!="string"?null:{role:e[1],text:t,final:e[2]==="final",event:i}}async function $n(i,e){let t={};try{t=await i.json()}catch{}return new Yn(typeof t.message=="string"?t.message:`${e} (${i.status})`,{status:i.status,code:typeof t.error=="string"?t.error:null,requestId:typeof t.request_id=="string"?t.request_id:null,details:Array.isArray(t.details)?t.details:[]})}export{Gn as CommandError,Kn as EventCursor,Ml as RealtimeSession,Yn as RealtimeSessionHttpError,Pl as SDK_VERSION,zn as TranscriptStore,Wn as createClientMessage,qp as decodeAgentSnapshotPayload,jp as decodeClientHelloPayload,Bp as decodeClientMessage,pl as decodeCommandAckPayload,gl as decodeCommandErrorPayload,Sl as decodeContextRejectedPayload,yl as decodeContextUpdatePayload,kl as decodeContextUpdatedPayload,hl as decodeRealtimeEvent,Va as isCommandAckPayload,Ha as isCommandErrorPayload,Wa as isContextRejectedPayload,Ka as isContextUpdatePayload,Ga as isContextUpdatedPayload,za as isRealtimeEvent};
40
40
  //# sourceMappingURL=index.js.map