vendor: 6,917 bytes, line 1
1var xr={};function Ud(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 s=Object.getOwnPropertyDescriptor(t,n);Object.defineProperty(i,n,s.get?s:{enumerable:!0,get:function(){return t[n]}})}})}),Object.freeze(i)}var Fd=Object.defineProperty,Bd=(i,e,t)=>e in i?Fd(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,Ur=(i,e,t)=>Bd(i,typeof e!="symbol"?e+"":e,t);let ge=class{constructor(){Ur(this,"_locking"),Ur(this,"_locks"),this._locking=Promise.resolve(),this._locks=0}isLocked(){return this._locks>0}lock(){this._locks+=1;let e;const t=new Promise(s=>e=()=>{this._locks-=1,s()}),n=this._locking.then(()=>e);return this._locking=this._locking.then(()=>t),n}};function se(i,e){if(!i)throw new Error(e)}const qd=34028234663852886e22,Vd=-34028234663852886e22,Wd=4294967295,jd=2147483647,Hd=-2147483648;function Qn(i){if(typeof i!="number")throw new Error("invalid int 32: "+typeof i);if(!Number.isInteger(i)||i>jd||i<Hd)throw new Error("invalid int 32: "+i)}function ks(i){if(typeof i!="number")throw new Error("invalid uint 32: "+typeof i);if(!Number.isInteger(i)||i>Wd||i<0)throw new Error("invalid uint 32: "+i)}function ho(i){if(typeof i!="number")throw new Error("invalid float 32: "+typeof i);if(Number.isFinite(i)&&(i>qd||i<Vd))throw new Error("invalid float 32: "+i)}const po=Symbol("@bufbuild/protobuf/enum-type");function Kd(i){const e=i[po];return se(e,"missing enum type on enum object"),e}function mo(i,e,t,n){i[po]=fo(e,t.map(s=>({no:s.no,name:s.name,localName:i[s.no]})))}function fo(i,e,t){const n=Object.create(null),s=Object.create(null),r=[];for(const a of e){const o=go(a);r.push(o),n[a.name]=o,s[a.no]=o}return{typeName:i,values:r,findName(a){return n[a]},findNumber(a){return s[a]}}}function Gd(i,e,t){const n={};for(const s of e){const r=go(s);n[r.localName]=r.no,n[r.no]=r.localName}return mo(n,i,e),n}function go(i){return"localName"in i?i:Object.assign(Object.assign({},i),{localName:i.name})}class Qs{equals(e){return this.getType().runtime.util.equals(this.getType(),this,e)}clone(){return this.getType().runtime.util.clone(this)}fromBinary(e,t){const n=this.getType(),s=n.runtime.bin,r=s.makeReadOptions(t);return s.readMessage(this,r.readerFactory(e),e.byteLength,r),this}fromJson(e,t){const n=this.getType(),s=n.runtime.json,r=s.makeReadOptions(t);return s.readMessage(n,e,r,this),this}fromJsonString(e,t){let n;try{n=JSON.parse(e)}catch(s){throw new Error("cannot decode ".concat(this.getType().typeName," from JSON: ").concat(s instanceof Error?s.message:String(s)))}return this.fromJson(n,t)}toBinary(e){const t=this.getType(),n=t.runtime.bin,s=n.makeWriteOptions(e),r=s.writerFactory();return n.writeMessage(this,r,s),r.finish()}toJson(e){const t=this.getType(),n=t.runtime.json,s=n.makeWriteOptions(e);return n.writeMessage(this,s)}toJsonString(e){var t;const 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 zd(i,e,t,n){var s;const r=(s=n?.localName)!==null&&s!==void 0?s:e.substring(e.lastIndexOf(".")+1),a={[r]:function(o){i.util.initFields(this),i.util.initPartial(o,this)}}[r];return Object.setPrototypeOf(a.prototype,new Qs),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 Jd(){let i=0,e=0;for(let n=0;n<28;n+=7){let s=this.buf[this.pos++];if(i|=(s&127)<<n,(s&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 s=this.buf[this.pos++];if(e|=(s&127)<<n,(s&128)==0)return this.assertBounds(),[i,e]}throw new Error("invalid varint")}function Ji(i,e,t){for(let r=0;r<28;r=r+7){const a=i>>>r,o=!(!(a>>>7)&&e==0),d=(o?a|128:a)&255;if(t.push(d),!o)return}const n=i>>>28&15|(e&7)<<4,s=e>>3!=0;if(t.push((s?n|128:n)&255),!!s){for(let r=3;r<31;r=r+7){const a=e>>>r,o=!!(a>>>7),d=(o?a|128:a)&255;if(t.push(d),!o)return}t.push(e>>>31&1)}}const Yn=4294967296;function Fr(i){const e=i[0]==="-";e&&(i=i.slice(1));const t=1e6;let n=0,s=0;function r(a,o){const d=Number(i.slice(a,o));s*=t,n=n*t+d,n>=Yn&&(s=s+(n/Yn|0),n=n%Yn)}return r(-24,-18),r(-18,-12),r(-12,-6),r(-6),e?bo(n,s):Ys(n,s)}function $d(i,e){let t=Ys(i,e);const n=t.hi&2147483648;n&&(t=bo(t.lo,t.hi));const s=vo(t.lo,t.hi);return n?"-"+s:s}function vo(i,e){var t=Qd(i,e);if(i=t.lo,e=t.hi,e<=2097151)return String(Yn*e+i);const n=i&16777215,s=(i>>>24|e<<8)&16777215,r=e>>16&65535;let a=n+s*6777216+r*6710656,o=s+r*8147497,d=r*2;const c=1e7;return a>=c&&(o+=Math.floor(a/c),a%=c),o>=c&&(d+=Math.floor(o/c),o%=c),d.toString()+Br(o)+Br(a)}function Qd(i,e){return{lo:i>>>0,hi:e>>>0}}function Ys(i,e){return{lo:i|0,hi:e|0}}function bo(i,e){return e=~e,i?i=~i+1:e+=1,Ys(i,e)}const Br=i=>{const e=String(i);return"0000000".slice(e.length)+e};function qr(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 Yd(){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 Xd(){const i=new DataView(new ArrayBuffer(8));if(typeof BigInt=="function"&&typeof i.getBigInt64=="function"&&typeof i.getBigUint64=="function"&&typeof i.setBigInt64=="function"&&typeof i.setBigUint64=="function"&&(typeof process!="object"||typeof xr!="object"||xr.BUF_BIGINT_DISABLE!=="1")){const s=BigInt("-9223372036854775808"),r=BigInt("9223372036854775807"),a=BigInt("0"),o=BigInt("18446744073709551615");return{zero:BigInt(0),supported:!0,parse(d){const c=typeof d=="bigint"?d:BigInt(d);if(c>r||c<s)throw new Error("int64 invalid: ".concat(d));return c},uParse(d){const c=typeof d=="bigint"?d:BigInt(d);if(c>o||c<a)throw new Error("uint64 invalid: ".concat(d));return c},enc(d){return 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)}}}const t=s=>se(/^-?[0-9]+$/.test(s),"int64 invalid: ".concat(s)),n=s=>se(/^[0-9]+$/.test(s),"uint64 invalid: ".concat(s));
1return{zero:"0",supported:!1,parse(s){return typeof s!="string"&&(s=s.toString()),t(s),s},uParse(s){return typeof s!="string"&&(s=s.toString()),n(s),s},enc(s){return typeof s!="string"&&(s=s.toString()),t(s),Fr(s)},uEnc(s){return typeof s!="string"&&(s=s.toString()),n(s),Fr(s)},dec(s,r){return $d(s,r)},uDec(s,r){return vo(s,r)}}}const ee=Xd();var 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 wt;(function(i){i[i.BIGINT=0]="BIGINT",i[i.STRING=1]="STRING"})(wt||(wt={}));function vt(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 on(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?ee.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 yo(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 Vr(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 Zd(i){if(Array.isArray(i))return i}function j(i,e,t){return(e=il(e))in i?Object.defineProperty(i,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):i[e]=t,i}function el(i,e){var t=i==null?null:typeof Symbol<"u"&&i[Symbol.iterator]||i["@@iterator"];if(t!=null){var n,s,r,a,o=[],d=!0,c=!1;try{if(r=(t=t.call(i)).next,e===0){if(Object(t)!==t)return;d=!1}else for(;!(d=(n=r.call(t)).done)&&(o.push(n.value),o.length!==e);d=!0);}catch(l){c=!0,s=l}finally{try{if(!d&&t.return!=null&&(a=t.return(),Object(a)!==a))return}finally{if(c)throw s}}return o}}function tl(){throw new TypeError(`Invalid attempt to destructure non-iterable instance. 2In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function L(i,e){return Zd(i)||el(i,e)||sl(i,e)||tl()}function nl(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 il(i){var e=nl(i,"string");return typeof e=="symbol"?e:e+""}function sl(i,e){if(i){if(typeof i=="string")return Vr(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)?Vr(i,e):void 0}}var oe;(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"})(oe||(oe={}));class rl{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 s=0;s<this.chunks.length;s++)e+=this.chunks[s].length;let t=new Uint8Array(e),n=0;for(let s=0;s<this.chunks.length;
vendor: 4,408 bytes, line 2
2s++)t.set(this.chunks[s],n),n+=this.chunks[s].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(ks(e);e>127;)this.buf.push(e&127|128),e=e>>>7;return this.buf.push(e),this}int32(e){return Qn(e),qr(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){ho(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){ks(e);let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!0),this.raw(t)}sfixed32(e){Qn(e);let t=new Uint8Array(4);return new DataView(t.buffer).setInt32(0,e,!0),this.raw(t)}sint32(e){return Qn(e),e=(e<<1^e>>31)>>>0,qr(e,this.buf),this}sfixed64(e){let t=new Uint8Array(8),n=new DataView(t.buffer),s=ee.enc(e);return n.setInt32(0,s.lo,!0),n.setInt32(4,s.hi,!0),this.raw(t)}fixed64(e){let t=new Uint8Array(8),n=new DataView(t.buffer),s=ee.uEnc(e);return n.setInt32(0,s.lo,!0),n.setInt32(4,s.hi,!0),this.raw(t)}int64(e){let t=ee.enc(e);return Ji(t.lo,t.hi,this.buf),this}sint64(e){let t=ee.enc(e),n=t.hi>>31,s=t.lo<<1^n,r=(t.hi<<1|t.lo>>>31)^n;return Ji(s,r,this.buf),this}uint64(e){let t=ee.uEnc(e);return Ji(t.lo,t.hi,this.buf),this}}class al{constructor(e,t){this.varint64=Jd,this.uint32=Yd,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 oe.Varint:for(;this.buf[this.pos++]&128;);break;case oe.Bit64:this.pos+=4;case oe.Bit32:this.pos+=4;break;case oe.LengthDelimited:let s=this.uint32();this.pos+=s;break;case oe.StartGroup:for(;;){const r=this.tag(),a=L(r,2),o=a[0],d=a[1];if(d===oe.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 ee.dec(...this.varint64())}uint64(){return ee.uDec(...this.varint64())}sint64(){let e=this.varint64(),t=L(e,2),n=t[0],s=t[1],r=-(n&1);return n=(n>>>1|(s&1)<<31)^r,s=s>>>1^r,ee.dec(n,s)}bool(){let e=this.varint64(),t=L(e,2),n=t[0],s=t[1];return n!==0||s!==0}fixed32(){return this.view.getUint32((this.pos+=4)-4,!0)}sfixed32(){return this.view.getInt32((this.pos+=4)-4,!0)}fixed64(){return ee.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return ee.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 ol(i,e,t,n){let s;return{typeName:e,extendee:t,get field(){if(!s){const r=typeof n=="function"?n():n;r.name=e.split(".").pop(),r.jsonName="[".concat(e,"]"),s=i.util.newFieldList([r]).list()[0]}return s},runtime:i}}function ko(i){const e=i.field.localName,t=Object.create(null);return t[e]=cl(i),[t,()=>t[e]]}function cl(i){const 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 on(e.T,e.L);case"message":const 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 dl(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)}let ct="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789
2+/".split(""),Ei=[];for(let i=0;i<ct.length;i++)Ei[ct[i].charCodeAt(0)]=i;Ei[45]=ct.indexOf("+");Ei[95]=ct.indexOf("/");const To={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,s=0,r,a=0;for(let o=0;o<i.length;o++){if(r=Ei[i.charCodeAt(o)],r===void 0)switch(i[o]){case"=":s=0;case` 3`:case"\r":case" ":case" ":continue;default:throw Error("invalid base64 string.")}switch(s){case 0:a=r,s=1;break;case 1:t[n++]=a<<2|(r&48)>>4,a=r,s=2;break;case 2:t[n++]=(a&15)<<4|(r&60)>>2,a=r,s=3;break;case 3:t[n++]=(a&3)<<6|r,s=0;break}}if(s==1)throw Error("invalid base64 string.");return t.subarray(0,n)},enc(i){let e="",t=0,n,s=0;for(let r=0;r<i.length;r++)switch(n=i[r],t){case 0:e+=ct[n>>2],s=(n&3)<<4,t=1;break;case 1:e+=ct[s|n>>4],s=(n&15)<<2,t=2;break;case 2:e+=ct[s|n>>6],e+=ct[n&63],t=0;break}return t&&(e+=ct[s],e+="=",t==1&&(e+="=")),e}};function ll(i,e,t){Co(e,i);const n=e.runtime.bin.makeReadOptions(t),s=dl(i.getType().runtime.bin.listUnknownFields(i),e.field),r=ko(e),a=L(r,2),o=a[0],d=a[1];for(const c of s)e.runtime.bin.readField(o,n.readerFactory(c.data),e.field,c.wireType,n);return d()}function ul(i,e,t,n){Co(e,i);const s=e.runtime.bin.makeReadOptions(n),r=e.runtime.bin.makeWriteOptions(n);if(So(i,e)){const c=i.getType().runtime.bin.listUnknownFields(i).filter(l=>l.no!=e.field.no);i.getType().runtime.bin.discardUnknownFields(i);for(const l of c)i.getType().runtime.bin.onUnknownField(i,l.no,l.wireType,l.data)}const a=r.writerFactory();let o=e.field;!o.opt&&!o.repeated&&(o.kind=="enum"||o.kind=="scalar")&&(o=Object.assign(Object.assign({},e.field),{opt:!0})),e.runtime.bin.writeField(o,t,a,r);const d=s.readerFactory(a.finish());for(;d.pos<d.len;){const c=d.tag(),l=L(c,2),u=l[0],h=l[1],p=d.skip(h,u);i.getType().runtime.bin.onUnknownField(i,u,h,p)}}function So(i,e){const t=i.getType();return e.extendee.typeName===t.typeName&&!!t.runtime.bin.listUnknownFields(i).find(n=>n.no==e.field.no)}function Co(i,e){se(i.extendee.typeName==e.getType().typeName,"extension ".concat(i.typeName," can only be applied to message ").concat(i.extendee.typeName))}function Eo(i,e){const 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:!yo(i.T,e[t]);case"message":return e[t]!==void 0;case"map":return Object.keys(e[t]).length>0}}function Wr(i,e){const 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?on(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(Qs.prototype).every(n=>n in i&&typeof i[n]=="function"))return!1;const 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 _o(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;const jr={ignoreUnknownFields:!1},Hr={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0};function hl(i){return i?Object.assign(Object.assign({},jr),i):jr}function pl(i){return i?Object.assign(Object.assign({},Hr),i):Hr}const di=Symbol(),Xn=Symbol();function ml(){return{makeReadOptions:hl,makeWriteOptions:pl,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(Xe(e)));n=n??new i;const s=new Map,r=t.typeRegistry;for(const o of Object.entries(e)){var a=L(o,2);const d=a[0],c=a[1],l=i.fields.findJsonName(d);if(l){if(l.oneof){if(c===null&&l.kind=="scalar")continue;const u=s.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,'"'));s.set(l.oneof,d)}Kr(n,c,l,t,i)}else{let u=!1;if(r?.findExtension&&d.startsWith("[")&&d.endsWith("]")){const h=r.findExtension(d.substring(1,d.length-1));if(h&&h.extendee.typeName==i.typeName){u=!0;const p=ko(h),f=L(p,2),g=f[0],k=f[1];Kr(g,c,h.field,t,h),ul(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){const t=i.getType(),n={};let s;try{for(s of t.fields.byNumber()){if(!Eo(s,i)){if(s.req)throw"required field not set";if(!e.emitDefaultValues||!gl(s))continue}const a=s.oneof?i[s.oneof.localName].value:i[s.localName],o=Gr(s,a,e);o!==void 0&&(n[e.useProtoFieldName?s.name:s.jsonName]=o)}const r=e.typeRegistry;if(r?.findExtensionFor)for(const a of t.runtime.bin.listUnknownFields(i)){const o=r.findExtensionFor(t.typeName,a.no);if(o&&So(i,o)){const d=ll(i,o,e),c=Gr(o.field,d,e);c!==void 0&&(n[o.field.jsonName]=c)}}}catch(r){const a=s?"cannot encode field ".concat(t.typeName,".").concat(s.name," to JSON"):"cannot encode message ".concat(t.typeName," to JSON"),o=r instanceof Error?r.message:String(r);throw new Error(a+(o.length>0?": ".concat(o):""))}return n}
vendor: 33,414 bytes, line 3
3,readScalar(i,e,t){return Tn(i,e,t??wt.BIGINT,!0)},writeScalar(i,e,t){if(e!==void 0&&(t||yo(i,e)))return Zn(i,e)},debug:Xe}}function Xe(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 Kr(i,e,t,n,s){let r=t.localName;if(t.repeated){if(se(t.kind!="map"),e===null)return;if(!Array.isArray(e))throw new Error("cannot decode field ".concat(s.typeName,".").concat(t.name," from JSON: ").concat(Xe(e)));const o=i[r];for(const d of e){if(d===null)throw new Error("cannot decode field ".concat(s.typeName,".").concat(t.name," from JSON: ").concat(Xe(d)));switch(t.kind){case"message":o.push(t.T.fromJson(d,n));break;case"enum":const c=$i(t.T,d,n.ignoreUnknownFields,!0);c!==Xn&&o.push(c);break;case"scalar":try{o.push(Tn(t.T,d,t.L,!0))}catch(l){let u="cannot decode field ".concat(s.typeName,".").concat(t.name," from JSON: ").concat(Xe(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(s.typeName,".").concat(t.name," from JSON: ").concat(Xe(e)));const o=i[r];for(const d of Object.entries(e)){var a=L(d,2);const c=a[0],l=a[1];if(l===null)throw new Error("cannot decode field ".concat(s.typeName,".").concat(t.name," from JSON: map value null"));let u;try{u=fl(t.K,c)}catch(h){let p="cannot decode map key for field ".concat(s.typeName,".").concat(t.name," from JSON: ").concat(Xe(e));throw h instanceof Error&&h.message.length>0&&(p+=": ".concat(h.message)),new Error(p)}switch(t.V.kind){case"message":o[u]=t.V.T.fromJson(l,n);break;case"enum":const h=$i(t.V.T,l,n.ignoreUnknownFields,!0);h!==Xn&&(o[u]=h);break;case"scalar":try{o[u]=Tn(t.V.T,l,wt.BIGINT,!0)}catch(p){let f="cannot decode map value for field ".concat(s.typeName,".").concat(t.name," from JSON: ").concat(Xe(e));throw p instanceof Error&&p.message.length>0&&(f+=": ".concat(p.message)),new Error(f)}break}}}else switch(t.oneof&&(i=i[t.oneof.localName]={case:r},r="value"),t.kind){case"message":const o=t.T;if(e===null&&o.typeName!="google.protobuf.Value")return;let d=i[r];dt(d)?d.fromJson(e,n):(i[r]=d=o.fromJson(e,n),o.fieldWrapper&&!t.oneof&&(i[r]=o.fieldWrapper.unwrapField(d)));break;case"enum":const c=$i(t.T,e,n.ignoreUnknownFields,!1);switch(c){case di:Wr(t,i);break;case Xn:break;default:i[r]=c;break}break;case"scalar":try{const l=Tn(t.T,e,t.L,!1);l===di?Wr(t,i):i[r]=l}catch(l){let u="cannot decode field ".concat(s.typeName,".").concat(t.name," from JSON: ").concat(Xe(e));throw l instanceof Error&&l.message.length>0&&(u+=": ".concat(l.message)),new Error(u)}break}}function fl(i,e){if(i===w.BOOL)switch(e){case"true":e=!0;break;case"false":e=!1;break}return Tn(i,e,wt.BIGINT,!0).toString()}function Tn(i,e,t,n){if(e===null)return n?on(i,t):di;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;const s=Number(e);if(Number.isNaN(s)||!Number.isFinite(s))break;return i==w.FLOAT&&ho(s),s;case w.INT32:case w.FIXED32:case w.SFIXED32:case w.SINT32:case w.UINT32:let r;if(typeof e=="number"?r=e:typeof e=="string"&&e.length>0&&e.trim().length===e.length&&(r=Number(e)),r===void 0)break;return i==w.UINT32||i==w.FIXED32?ks(r):Qn(r),r;case w.INT64:case w.SFIXED64:case w.SINT64:if(typeof e!="number"&&typeof e!="string")break;const a=ee.parse(e);return t?a.toString():a;case w.FIXED64:case w.UINT64:if(typeof e!="number"&&typeof e!="string")break;const o=ee.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 To.dec(e)}throw new Error}function $i(i,e,t,n){if(e===null)return i.typeName=="google.protobuf.NullValue"?0:n?i.values[0].no:di;switch(typeof e){case"number":if(Number.isInteger(e))return e;break;case"string":const s=i.findName(e);if(s!==void 0)return s.no;if(t)return Xn;break}throw new Error("cannot decode enum ".concat(i.typeName," from JSON: ").concat(Xe(e)))}function gl(i){return i.repeated||i.kind=="map"?!0:!(i.oneof||i.kind=="message"||i.opt||i.req)}function Gr(i,e,t){if(i.kind=="map"){se(typeof e=="object"&&e!=null);const a={},o=Object.entries(e);switch(i.V.kind){case"scalar":for(const c of o){var n=L(c,2);const l=n[0],u=n[1];a[l.toString()]=Zn(i.V.T,u)}break;case"message":for(const c of o){var s=L(c,2);const l=s[0],u=s[1];a[l.toString()]=u.toJson(t)}break;case"enum":const d=i.V.T;for(const c of o){var r=L(c,2);const l=r[0],u=r[1];a[l.toString()]=Qi(d,u,t.enumAsInteger)}break}return t.emitDefaultValues||o.length>0?a:void 0}if(i.repeated){se(Array.isArray(e));const a=[];switch(i.kind){case"scalar":for(let o=0;o<e.length;o++)a.push(Zn(i.T,e[o]));break;case"enum":for(let o=0;o<e.length;o++)a.push(Qi(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 Zn(i.T,e);case"enum":return Qi(i.T,e,t.enumAsInteger);case"message":return _o(i.T,e).toJson(t)}}function Qi(i,e,t){var n;if(se(typeof e=="number"),i.typeName=="google.protobuf.NullValue")return null;if(t)return e;const s=i.findNumber(e);return(n=s?.name)!==null&&n!==void 0?n:e}function Zn(i,e){switch(i){case w.INT32:case w.SFIXED32:case w.SINT32:case w.FIXED32:case w.UINT32:return se(typeof e=="number"),e;case w.FLOAT:case w.DOUBLE:return se(typeof e=="number"),Number.isNaN(e)?"NaN":e===Number.POSITIVE_INFINITY?"Infinity":e===Number.NEGATIVE_INFINITY?"-Infinity":e;case w.STRING:return se(typeof e=="string"),e;case w.BOOL:return se(typeof e=="boolean"),e;case w.UINT64:case w.FIXED64:case w.INT64:case w.SFIXED64:case w.SINT64:return se(typeof e=="bigint"||typeof e=="string"||typeof e=="number"),e.toString();case w.BYTES:return se(e instanceof Uint8Array),To.enc(e)}}const Kt=Symbol("@bufbuild/protobuf/unknown-fields"),zr={readUnknownFields:!0,readerFactory:i=>new al(i)},Jr={writeUnknownFields:!0,writerFactory:()=>new rl};function vl(i){return i?Object.assign(Object.assign({},zr),i):zr}function bl(i){return i?Object.assign(Object.assign({},Jr),i):Jr}function yl(){return{makeReadOptions:vl,makeWriteOptions:bl,listUnknownFields(i){var e;return(e=i[Kt])!==null&&e!==void 0?e:[]},discardUnknownFields(i){delete i[Kt]},writeUnknownFields(i,e){const n=i[Kt];if(n)for(const s of n)e.tag(s.no,s.wireType).raw(s.data)},onUnknownField(i,e,t,n){const s=i;Array.isArray(s[Kt])||(s[Kt]=[]),s[Kt].push({no:e,wireType:t,data:n})},readMessage(i,e,t,n,s){const r=i.getType(),a=s?e.len:e.pos+t;let o,d;for(;e.pos<a;){var c=e.tag(),l=L(c,2);if(o=l[0],d=l[1],s===!0&&d==oe.EndGroup)break;const u=r.fields.find(o);if(!u){const h=e.skip(d,o);n.readUnknownFields&&this.onUnknownField(i,o,d,h);continue}$r(i,e,u,d,n)}if(s&&(d!=oe.EndGroup||o!==t))throw new Error("invalid end group tag")},readField:$r,writeMessage(i,e,t){const n=i.getType();for(const s of n.fields.byNumber()){if(!Eo(s,i)){if(s.req)throw new Error("cannot encode field ".concat(n.typeName,".").concat(s.name," to binary: required field not set"));continue}const r=s.oneof?i[s.oneof.localName].value:i[s.localName];Qr(s,r,e,t)}return t.writeUnknownFields&&this.writeUnknownFields(i,e),e},writeField(i,e,t,n){e!==void 0&&Qr(i,e,t,n)}}}function $r(i,e,t,n,s){let r=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":const o=t.kind=="enum"?w.INT32:t.T;let d=li;if(t.kind=="scalar"&&t.L>0&&(d=Tl),r){let f=i[a];if(n==oe.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":const c=t.T;r?i[a].push(ei(e,new c,s,t)):dt(i[a])?ei(e,i[a],s,t):(i[a]=ei(e,new c,s,t),c.fieldWrapper&&!t.oneof&&!t.repeated&&(i[a]=c.fieldWrapper.unwrapField(i[a])));break;case"map":let l=kl(t,e,s),u=L(l,2),h=u[0],p=u[1];i[a][h]=p;break}}function ei(i,e,t,n){const s=e.getType().runtime.bin,r=n?.delimited;return s.readMessage(e,i,r?n.no:i.uint32(),t,r),e}function kl(i,e,t){const n=e.uint32(),s=e.pos+n;let r,a;for(;e.pos<s;){const o=e.tag();switch(L(o,1)[0]){case 1:r=li(e,i.K);break;case 2:switch(i.V.kind){case"scalar":a=li(e,i.V.T);break;case"enum":a=e.int32();break;case"message":a=ei(e,new i.V.T,t,void 0);break}break}}if(r===void 0&&(r=on(i.K,wt.BIGINT)),typeof r!="string"&&typeof r!="number"&&(r=r.toString()),a===void 0)switch(i.V.kind){case"scalar":a=on(i.V.T,wt.BIGINT);break;case"enum":a=i.V.T.values[0].no;break;case"message":a=new i.V.T;break}return[r,a]}function Tl(i,e){const t=li(i,e);return typeof t=="bigint"?t.toString():t}function li(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 Qr(i,e,t,n){se(e!==void 0);const s=i.repeated;switch(i.kind){case"scalar":case"enum":let a=i.kind=="enum"?w.INT32:i.T;if(s)if(se(Array.isArray(e)),i.packed)Cl(t,a,i.no,e);else for(const o of e)Sn(t,a,i.no,o);else Sn(t,a,i.no,e);break;case"message":if(s){se(Array.isArray(e));for(const o of e)Yr(t,n,i,o)}else Yr(t,n,i,e);break;case"map":se(typeof e=="object"&&e!=null);for(const o of Object.entries(e)){var r=L(o,2);const d=r[0],c=r[1];Sl(t,n,i,d,c)}break}}function Sl(i,e,t,n,s){i.tag(t.no,oe.LengthDelimited),i.fork();let r=n;switch(t.K){case w.INT32:case w.FIXED32:case w.UINT32:case w.SFIXED32:case w.SINT32:r=Number.parseInt(n);break;case w.BOOL:se(n=="true"||n=="false"),r=n=="true";break}switch(Sn(i,t.K,1,r),t.V.kind){case"scalar":Sn(i,t.V.T,2,s);break;case"enum":Sn(i,w.INT32,2,s);break;case"message":se(s!==void 0),i.tag(2,oe.LengthDelimited).bytes(s.toBinary(e));break}i.join()}function Yr(i,e,t,n){const s=_o(t.T,n);t.delimited?i.tag(t.no,oe.StartGroup).raw(s.toBinary(e)).tag(t.no,oe.EndGroup):i.tag(t.no,oe.LengthDelimited).bytes(s.toBinary(e))}function Sn(i,e,t,n){se(n!==void 0);let s=wo(e),r=L(s,2),a=r[0],o=r[1];i.tag(t,a)[o](n)}function Cl(i,e,t,n){if(!n.length)return;i.tag(t,oe.LengthDelimited).fork();let s=wo(e),r=L(s,2),a=r[1];for(let o=0;o<n.length;o++)i[a](n[o]);i.join()}function wo(i){let e=oe.Varint;switch(i){case w.BYTES:case w.STRING:e=oe.LengthDelimited;break;case w.DOUBLE:case w.FIXED64:case w.SFIXED64:e=oe.Bit64;break;case w.FIXED32:case w.SFIXED32:case w.FLOAT:e=oe.Bit32;break}const t=w[i].toLowerCase();return[e,t]}function El(){return{setEnumType:mo,initPartial(i,e){if(i===void 0)return;const t=e.getType();for(const s of t.fields.byMember()){const r=s.localName,a=e,o=i;if(o[r]!=null)switch(s.kind){case"oneof":const d=o[r].case;if(d===void 0)continue;const c=s.findField(d);let l=o[r].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[r]={case:d,value:l};break;case"scalar":case"enum":let u=o[r];s.T===w.BYTES&&(u=s.repeated?u.map(pn):pn(u)),a[r]=u;break;case"map":switch(s.V.kind){case"scalar":case"enum":if(s.V.T===w.BYTES)for(const f of Object.entries(o[r])){var n=L(f,2);const g=n[0],k=n[1];a[r][g]=pn(k)}else Object.assign(a[r],o[r]);break;case"message":const p=s.V.T;for(const f of Object.keys(o[r])){let g=o[r][f];p.fieldWrapper||(g=new p(g)),a[r][f]=g}break}break;case"message":const h=s.T;if(s.repeated)a[r]=o[r].map(p=>dt(p,h)?p:new h(p));else{const p=o[r];h.fieldWrapper?h.typeName==="google.protobuf.BytesValue"?a[r]=pn(p):a[r]=p:a[r]=dt(p,h)?p:new h(p)}break}}},equals(i,e,t){return e===t?!0:!e||!t?!1:i.fields.byMember().every(n=>{const s=e[n.localName],r=t[n.localName];if(n.repeated){if(s.length!==r.length)return!1;switch(n.kind){case"message":return s.every((a,o)=>n.T.equals(a,r[o]));case"scalar":return s.every((a,o)=>vt(n.T,a,r[o]));case"enum":return s.every((a,o)=>vt(w.INT32,a,r[o]))}throw new Error("repeated cannot contain ".concat(n.kind))}switch(n.kind){case"message":let a=s,o=r;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 vt(w.INT32,s,r);case"scalar":return vt(n.T,s,r);case"oneof":if(s.case!==r.case)return!1;const d=n.findField(s.case);if(d===void 0)return!0;switch(d.kind){case"message":return d.T.equals(s.value,r.value);case"enum":return vt(w.INT32,s.value,r.value);case"scalar":return vt(d.T,s.value,r.value)}throw new Error("oneof cannot contain ".concat(d.kind));case"map":const c=Object.keys(s).concat(Object.keys(r));switch(n.V.kind){case"message":const l=n.V.T;return c.every(h=>l.equals(s[h],r[h]));case"enum":return c.every(h=>vt(w.INT32,s[h],r[h]));case"scalar":const u=n.V.T;return c.every(h=>vt(u,s[h],r[h]))}break}})},clone(i){const e=i.getType(),t=new e,n=t;for(const r of e.fields.byMember()){const a=i[r.localName];let o;if(r.repeated)o=a.map(jn);else if(r.kind=="map"){o=n[r.localName];for(const d of Object.entries(a)){var s=L(d,2);const c=s[0],l=s[1];o[c]=jn(l)}}else r.kind=="oneof"?o=r.findField(a.case)?{case:a.case,value:jn(a.value)}:{case:void 0}:o=jn(a);n[r.localName]=o}for(const r of e.runtime.bin.listUnknownFields(i))e.runtime.bin.onUnknownField(n,r.no,r.wireType,r.data);return t}}}function jn(i){if(i===void 0)return i;if(dt(i))return i.clone();if(i instanceof Uint8Array){const e=new Uint8Array(i.byteLength);return e.set(i),e}return i}function pn(i){return i instanceof Uint8Array?i:new Uint8Array(i)}function _l(i,e,t){return{syntax:i,json:ml(),bin:yl(),util:Object.assign(Object.assign({},El()),{newFieldList:e,initFields:t}),makeMessageType(n,s,r){return zd(this,n,s,r)},makeEnum:Gd,makeEnumType:fo,getEnumType:Kd,makeExtension(n,s,r){return ol(this,n,s,r)}}}class wl{constructor(e,t){this._fields=e,this._normalizer=t}findJsonName(e){if(!this.jsonNames){const t={};for(const n of this.list())t[n.jsonName]=t[n.name]=n;this.jsonNames=t}return this.jsonNames[e]}find(e){if(!this.numbers){const t={};for(const n of this.list())t[n.no]=n;this.numbers=t}return this.numbers[e]}list(){return this.all||(this.all=this._normalizer(this._fields)),this.all}byNumber(){return this.numbersAsc||(this.numbersAsc=this.list().concat().sort((e,t)=>e.no-t.no)),this.numbersAsc}byMember(){if(!this.members){this.members=[];const e=this.members;let t;for(const n of this.list())n.oneof?n.oneof!==t&&(t=n.oneof,e.push(t)):e.push(n)}return this.members}}function Ro(i,e){const t=Po(i);return e?t:Al(Dl(t))}function Rl(i){return Ro(i,!1)}const Pl=Po;function Po(i){let e=!1;const t=[];for(let n=0;n<i.length;n++){let s=i.charAt(n);switch(s){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(s),e=!1;break;default:e&&(e=!1,s=s.toUpperCase()),t.push(s);break}}return t.join("")}const Il=new Set(["constructor","toString","toJSON","valueOf"]),Ml=new Set(["getType","clone","equals","fromBinary","fromJson","fromJsonString","toBinary","toJson","toJsonString","toObject"]),Io=i=>"".concat(i,"$"),Dl=i=>Ml.has(i)?Io(i):i,Al=i=>Il.has(i)?Io(i):i;class Ol{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=Rl(e)}addField(e){se(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 Nl(i,e){var t,n,s,r,a,o;const d=[];let c;for(const l of typeof i=="function"?i():i){const u=l;if(u.localName=Ro(l.name,l.oneof!==void 0),u.jsonName=(t=l.jsonName)!==null&&t!==void 0?t:Pl(l.name),u.repeated=(n=l.repeated)!==null&&n!==void 0?n:!1,l.kind=="scalar"&&(u.L=(s=l.L)!==null&&s!==void 0?s:wt.BIGINT),u.delimited=(r=l.delimited)!==null&&r!==void 0?r:!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){const h=typeof l.oneof=="string"?l.oneof:l.oneof.name;(!c||c.name!=h)&&(c=new Ol(h)),u.oneof=c,c.addField(u)}d.push(u)}return d}const b=_l("proto3",i=>new wl(i,e=>Nl(e)),i=>{for(const e of i.getType().fields.byMember()){if(e.opt)continue;const 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]=on(e.T,e.L);break}}});class Ie extends Qs{constructor(e){super(),this.seconds=ee.zero,this.nanos=0,b.util.initPartial(e,this)}fromJson(e,t){if(typeof e!="string")throw new Error("cannot decode google.protobuf.Timestamp from JSON: ".concat(b.json.debug(e)));const 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");const s=Date.parse(n[1]+"-"+n[2]+"-"+n[3]+"T"+n[4]+":"+n[5]+":"+n[6]+(n[8]?n[8]:"Z"));if(Number.isNaN(s))throw new Error("cannot decode google.protobuf.Timestamp from JSON: invalid RFC 3339 string");if(s<Date.parse("0001-01-01T00:00:00Z")||s>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=ee.parse(s/1e3),this.nanos=0,n[7]&&(this.nanos=parseInt("1"+n[7]+"0".repeat(9-n[7].length))-1e9),this}toJson(e){const t=Number(this.seconds)*1e3;if(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){const s=(this.nanos+1e9).toString().substring(1);s.substring(3)==="000000"?n="."+s.substring(0,3)+"Z":s.substring(6)==="000"?n="."+s.substring(0,6)+"Z":n="."+s+"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 Ie.fromDate(new Date)}static fromDate(e){const t=e.getTime();return new Ie({seconds:ee.parse(Math.floor(t/1e3)),nanos:t%1e3*1e6})}static fromBinary(e,t){return new Ie().fromBinary(e,t)}static fromJson(e,t){return new Ie().fromJson(e,t)}static fromJsonString(e,t){return new Ie().fromJsonString(e,t)}static equals(e,t){return b.util.equals(Ie,e,t)}}Ie.runtime=b;Ie.typeName="google.protobuf.Timestamp";Ie.fields=b.util.newFieldList(()=>[{no:1,name:"seconds",kind:"scalar",T:3},{no:2,name:"nanos",kind:"scalar",T:5}]);const Ll=b.makeMessageType("livekit.MetricsBatch",()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:Ie},{no:3,name:"str_data",kind:"scalar",T:9,repeated:!0},{no:4,name:"time_series",kind:"message",T:xl,repeated:!0},{no:5,name:"events",kind:"message",T:Fl,repeated:!0}]),xl=b.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:Ul,repeated:!0},{no:5,name:"rid",kind:"scalar",T:13}]),Ul=b.makeMessageType("livekit.MetricSample",()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:Ie},{no:3,name:"value",kind:"scalar",T:2}]),Fl=b.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:Ie},{no:7,name:"normalized_end_timestamp",kind:"message",T:Ie,opt:!0},{no:8,name:"metadata",kind:"scalar",T:9},{no:9,name:"rid",kind:"scalar",T:13}]),Mo=b.makeEnum("livekit.BackupCodecPolicy",[{no:0,name:"PREFER_REGRESSION"},{no:1,name:"SIMULCAST"},{no:2,name:"REGRESSION"}]),Ve=b.makeEnum("livekit.TrackType",[{no:0,name:"AUDIO"},{no:1,name:"VIDEO"},{no:2,name:"DATA"}]),le=b.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"}]),Xs=b.makeEnum("livekit.VideoQuality",[{no:0,name:"LOW"},{no:1,name:"MEDIUM"},{no:2,name:"HIGH"},{no:3,name:"OFF"}]),yn=b.makeEnum("livekit.ConnectionQuality",[{no:0,name:"POOR"},{no:1,name:"GOOD"},{no:2,name:"EXCELLENT"},{no:3,name:"LOST"}]),In=b.makeEnum("livekit.ClientConfigSetting",[{no:0,name:"UNSET"},{no:1,name:"DISABLED"},{no:2,name:"ENABLED"}]),Ke=b.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"}]),Dt=b.makeEnum("livekit.ReconnectReason",[{no:0,name:"RR_UNKNOWN"},{no:1,name:"RR_SIGNAL_DISCONNECTED"},{no:2,name:"RR_PUBLISHER_FAILED"},{no:3,name:"RR_SUBSCRIBER_FAILED"},{no:4,name:"RR_SWITCH_CANDIDATE"}]),Bl=b.makeEnum("livekit.SubscriptionError",[{no:0,name:"SE_UNKNOWN"},{no:1,name:"SE_CODEC_UNSUPPORTED"},{no:2,name:"SE_TRACK_NOTFOUND"}]),me=b.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"}]),cn=b.makeEnum("livekit.PacketTrailerFeature",[{no:0,name:"PTF_USER_TIMESTAMP"},{no:1,name:"PTF_FRAME_ID"},{no:2,name:"PTF_USER_DATA"}]),_i=b.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:ui,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:Ko}]),ui=b.makeMessageType("livekit.Codec",()=>[{no:1,name:"mime",kind:"scalar",T:9},{no:2,name:"fmtp_line",kind:"scalar",T:9}]),ql=b.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:b.getEnumType(le),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}]),Vt=b.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:b.getEnumType(Qt)},{no:4,name:"tracks",kind:"message",T:zt,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:ql},{no:12,name:"region",kind:"scalar",T:9},{no:13,name:"is_publisher",kind:"scalar",T:8},{no:14,name:"kind",kind:"enum",T:b.getEnumType(Mn)},{no:15,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:16,name:"disconnect_reason",kind:"enum",T:b.getEnumType(Ke)},{no:18,name:"kind_details",kind:"enum",T:b.getEnumType(Vl),repeated:!0},{no:19,name:"data_tracks",kind:"message",T:wi,repeated:!0},{no:20,name:"client_protocol",kind:"scalar",T:5},{no:21,name:"capabilities",kind:"enum",T:b.getEnumType(Dn),repeated:!0}]),Qt=b.makeEnum("livekit.ParticipantInfo.State",[{no:0,name:"JOINING"},{no:1,name:"JOINED"},{no:2,name:"ACTIVE"},{no:3,name:"DISCONNECTED"}]),Mn=b.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"}]),Vl=b.makeEnum("livekit.ParticipantInfo.KindDetail",[{no:0,name:"CLOUD_AGENT"},{no:1,name:"FORWARDED"},{no:2,name:"CONNECTOR_WHATSAPP"},{no:3,name:"CONNECTOR_TWILIO"},{no:4,name:"BRIDGE_RTSP"},{no:5,name:"SIMULATION"}]),G=b.makeEnum("livekit.Encryption.Type",[{no:0,name:"NONE"},{no:1,name:"GCM"},{no:2,name:"CUSTOM"}]),Wl=b.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:St,repeated:!0},{no:5,name:"video_layer_mode",kind:"enum",T:b.getEnumType(Oo)},{no:6,name:"sdp_cid",kind:"scalar",T:9}]),zt=b.makeMessageType("livekit.TrackInfo",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"type",kind:"enum",T:b.getEnumType(Ve)},{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:b.getEnumType(le)},{no:10,name:"layers",kind:"message",T:St,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:Wl,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:b.getEnumType(G)},{no:17,name:"stream",kind:"scalar",T:9},{no:18,name:"version",kind:"message",T:Ko},{no:19,name:"audio_features",kind:"enum",T:b.getEnumType(me),repeated:!0},{no:20,name:"backup_codec_policy",kind:"enum",T:b.getEnumType(Mo)},{no:21,name:"packet_trailer_features",kind:"enum",T:b.getEnumType(cn),repeated:!0}]),wi=b.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:b.getEnumType(G)},{no:5,name:"frame_encoding",kind:"message",T:Do,opt:!0},{no:6,name:"schema",kind:"message",T:Zs,opt:!0}]),Do=b.makeMessageType("livekit.DataTrackFrameEncoding",()=>[{no:1,name:"well_known",kind:"enum",T:b.getEnumType(jl),oneof:"value"},{no:2,name:"custom",kind:"scalar",T:9,oneof:"value"}]),jl=b.makeEnum("livekit.DataTrackFrameEncoding.WellKnownFrameEncoding",[{no:0,name:"WELL_KNOWN_FRAME_ENCODING_UNSPECIFIED",localName:"UNSPECIFIED"},{no:1,name:"WELL_KNOWN_FRAME_ENCODING_ROS1",localName:"ROS1"},{no:2,name:"WELL_KNOWN_FRAME_ENCODING_CDR",localName:"CDR"},{no:3,name:"WELL_KNOWN_FRAME_ENCODING_PROTOBUF",localName:"PROTOBUF"},{no:4,name:"WELL_KNOWN_FRAME_ENCODING_FLATBUFFER",localName:"FLATBUFFER"},{no:5,name:"WELL_KNOWN_FRAME_ENCODING_CBOR",localName:"CBOR"},{no:6,name:"WELL_KNOWN_FRAME_ENCODING_MSGPACK",localName:"MSGPACK"},{no:7,name:"WELL_KNOWN_FRAME_ENCODING_JSON",localName:"JSON"}]),Hl=b.makeMessageType("livekit.DataTrackSchemaEncoding",()=>[{no:1,name:"well_known",kind:"enum",T:b.getEnumType(Kl),oneof:"value"},{no:2,name:"custom",kind:"scalar",T:9,oneof:"value"}]),Kl=b.makeEnum("livekit.DataTrackSchemaEncoding.WellKnownSchemaEncoding",[{no:0,name:"WELL_KNOWN_SCHEMA_ENCODING_UNSPECIFIED",localName:"UNSPECIFIED"},{no:1,name:"WELL_KNOWN_SCHEMA_ENCODING_PROTOBUF",localName:"PROTOBUF"},{no:2,name:"WELL_KNOWN_SCHEMA_ENCODING_FLATBUFFER",localName:"FLATBUFFER"},{no:3,name:"WELL_KNOWN_SCHEMA_ENCODING_ROS1_MSG",localName:"ROS1_MSG"},{no:4,name:"WELL_KNOWN_SCHEMA_ENCODING_ROS2_MSG",localName:"ROS2_MSG"},{no:5,name:"WELL_KNOWN_SCHEMA_ENCODING_ROS2_IDL",localName:"ROS2_IDL"},{no:6,name:"WELL_KNOWN_SCHEMA_ENCODING_OMG_IDL",localName:"OMG_IDL"},{no:7,name:"WELL_KNOWN_SCHEMA_ENCODING_JSON_SCHEMA",localName:"JSON_SCHEMA"}]),Zs=b.makeMessageType("livekit.DataTrackSchemaId",()=>[{no:1,name:"name",kind:"scalar",T:9},{no:2,name:"encoding",kind:"message",T:Hl}]),Gl=b.makeMessageType("livekit.DataTrackSubscriptionOptions",()=>[{no:1,name:"target_fps",kind:"scalar",T:13,opt:!0}]),er=b.makeMessageType("livekit.DataBlobKey",()=>[{no:1,name:"generic",kind:"scalar",T:9,oneof:"key"},{no:2,name:"schema_id",kind:"message",T:Zs,oneof:"key"}]),Ao=b.makeMessageType("livekit.DataBlob",()=>[{no:1,name:"key",kind:"message",T:er},{no:2,name:"contents",kind:"scalar",T:12}]),St=b.makeMessageType("livekit.VideoLayer",()=>[{no:1,name:"quality",kind:"enum",T:b.getEnumType(Xs)},{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}]),Oo=b.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"}]),Ee=b.makeMessageType("livekit.DataPacket",()=>[{no:1,name:"kind",kind:"enum",T:b.getEnumType(Ct)},{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:tr,oneof:"value"},{no:3,name:"speaker",kind:"message",T:zl,oneof:"value"},{no:6,name:"sip_dtmf",kind:"message",T:Uo,oneof:"value"},{no:7,name:"transcription",kind:"message",T:Jl,oneof:"value"},{no:8,name:"metrics",kind:"message",T:Ll,oneof:"value"},{no:9,name:"chat_message",kind:"message",T:hi,oneof:"value"},{no:10,name:"rpc_request",kind:"message",T:nr,oneof:"value"},{no:11,name:"rpc_ack",kind:"message",T:Ri,oneof:"value"},{no:12,name:"rpc_response",kind:"message",T:ir,oneof:"value"},{no:13,name:"stream_header",kind:"message",T:Pi,oneof:"value"},{no:14,name:"stream_chunk",kind:"message",T:ht,oneof:"value"},{no:15,name:"stream_trailer",kind:"message",T:sr,oneof:"value"},{no:18,name:"encrypted_packet",kind:"message",T:No,oneof:"value"},{no:16,name:"sequence",kind:"scalar",T:13},{no:17,name:"participant_sid",kind:"scalar",T:9}]),Ct=b.makeEnum("livekit.DataPacket.Kind",[{no:0,name:"RELIABLE"},{no:1,name:"LOSSY"}]),No=b.makeMessageType("livekit.EncryptedPacket",()=>[{no:1,name:"encryption_type",kind:"enum",T:b.getEnumType(G)},{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}]),Lo=b.makeMessageType("livekit.EncryptedPacketPayload",()=>[{no:1,name:"user",kind:"message",T:tr,oneof:"value"},{no:3,name:"chat_message",kind:"message",T:hi,oneof:"value"},{no:4,name:"rpc_request",kind:"message",T:nr,oneof:"value"},{no:5,name:"rpc_ack",kind:"message",T:Ri,oneof:"value"},{no:6,name:"rpc_response",kind:"message",T:ir,oneof:"value"},{no:7,name:"stream_header",kind:"message",T:Pi,oneof:"value"},{no:8,name:"stream_chunk",kind:"message",T:ht,oneof:"value"},{no:9,name:"stream_trailer",kind:"message",T:sr,oneof:"value"}]),zl=b.makeMessageType("livekit.ActiveSpeakerUpdate",()=>[{no:1,name:"speakers",kind:"message",T:xo,repeated:!0}]),xo=b.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}]),tr=b.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}]),Uo=b.makeMessageType("livekit.SipDTMF",()=>[{no:3,name:"code",kind:"scalar",T:13},{no:4,name:"digit",kind:"scalar",T:9}]),Jl=b.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:$l,repeated:!0}]),$l=b.makeMessageType("livekit.TranscriptionSegment",()=>[{no:1,name:"id",kind:"scalar",T:9},{no
vendor: 16,384 bytes, line 3
3:2,name:"text",kind:"scalar",T:9},{no:3,name:"start_time",kind:"scalar",T:4},{no:4,name:"end_time",kind:"scalar",T:4},{no:5,name:"final",kind:"scalar",T:8},{no:6,name:"language",kind:"scalar",T:9}]),hi=b.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}]),nr=b.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}]),Ri=b.makeMessageType("livekit.RpcAck",()=>[{no:1,name:"request_id",kind:"scalar",T:9}]),ir=b.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:Fo,oneof:"value"},{no:4,name:"compressed_payload",kind:"scalar",T:12,oneof:"value"}]),Fo=b.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}]),Bo=b.makeMessageType("livekit.ParticipantTracks",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"track_sids",kind:"scalar",T:9,repeated:!0}]),qo=b.makeMessageType("livekit.ServerInfo",()=>[{no:1,name:"edition",kind:"enum",T:b.getEnumType(Vo)},{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}]),Vo=b.makeEnum("livekit.ServerInfo.Edition",[{no:0,name:"Standard"},{no:1,name:"Cloud"}]),Wo=b.makeMessageType("livekit.ClientInfo",()=>[{no:1,name:"sdk",kind:"enum",T:b.getEnumType(jo)},{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:b.getEnumType(Dn),repeated:!0}]),jo=b.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"}]),Dn=b.makeEnum("livekit.ClientInfo.Capability",[{no:0,name:"CAP_UNUSED"},{no:1,name:"CAP_PACKET_TRAILER"},{no:2,name:"CAP_COMPRESSION_DEFLATE_RAW"}]),Ho=b.makeMessageType("livekit.ClientConfiguration",()=>[{no:1,name:"video",kind:"message",T:Xr},{no:2,name:"screen",kind:"message",T:Xr},{no:3,name:"resume_connection",kind:"enum",T:b.getEnumType(In)},{no:4,name:"disabled_codecs",kind:"message",T:Ql},{no:5,name:"force_relay",kind:"enum",T:b.getEnumType(In)}]),Xr=b.makeMessageType("livekit.VideoConfiguration",()=>[{no:1,name:"hardware_encoder",kind:"enum",T:b.getEnumType(In)}]),Ql=b.makeMessageType("livekit.DisabledCodecs",()=>[{no:1,name:"codecs",kind:"message",T:ui,repeated:!0},{no:2,name:"publish",kind:"message",T:ui,repeated:!0}]),Ko=b.makeMessageType("livekit.TimedVersion",()=>[{no:1,name:"unix_micro",kind:"scalar",T:3},{no:2,name:"ticks",kind:"scalar",T:5}]),Ts=b.makeEnum("livekit.DataStream.OperationType",[{no:0,name:"CREATE"},{no:1,name:"UPDATE"},{no:2,name:"DELETE"},{no:3,name:"REACTION"}]),Te=b.makeEnum("livekit.DataStream.CompressionType",[{no:0,name:"NONE"},{no:1,name:"DEFLATE_RAW"}]),Go=b.makeMessageType("livekit.DataStream.TextHeader",()=>[{no:1,name:"operation_type",kind:"enum",T:b.getEnumType(Ts)},{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"}),zo=b.makeMessageType("livekit.DataStream.ByteHeader",()=>[{no:1,name:"name",kind:"scalar",T:9}],{localName:"DataStream_ByteHeader"}),Pi=b.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:b.getEnumType(G)},{no:8,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:9,name:"text_header",kind:"message",T:Go,oneof:"content_header"},{no:10,name:"byte_header",kind:"message",T:zo,oneof:"content_header"},{no:11,name:"inline_content",kind:"scalar",T:12,opt:!0},{no:12,name:"compression",kind:"enum",T:b.getEnumType(Te)}],{localName:"DataStream_Header"}),ht=b.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"}),sr=b.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"}),Yl=b.makeMessageType("livekit.SubscribedAudioCodec",()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"enabled",kind:"scalar",T:8}]),We=b.makeEnum("livekit.SignalTarget",[{no:0,name:"PUBLISHER"},{no:1,name:"SUBSCRIBER"}]),Ss=b.makeEnum("livekit.StreamState",[{no:0,name:"ACTIVE"},{no:1,name:"PAUSED"}]),Xl=b.makeEnum("livekit.CandidateProtocol",[{no:0,name:"UDP"},{no:1,name:"TCP"},{no:2,name:"TLS"}]),Zl=b.makeMessageType("livekit.SignalRequest",()=>[{no:1,name:"offer",kind:"message",T:Rt,oneof:"message"},{no:2,name:"answer",kind:"message",T:Rt,oneof:"message"},{no:3,name:"trickle",kind:"message",T:Ii,oneof:"message"},{no:4,name:"add_track",kind:"message",T:An,oneof:"message"},{no:5,name:"mute",kind:"message",T:Mi,oneof:"message"},{no:6,name:"subscription",kind:"message",T:Di,oneof:"message"},{no:7,name:"track_setting",kind:"message",T:Qo,oneof:"message"},{no:8,name:"leave",kind:"message",T:Ai,oneof:"message"},{no:10,name:"update_layers",kind:"message",T:Xo,oneof:"message"},{no:11,name:"subscription_permission",kind:"message",T:tc,oneof:"message"},{no:12,name:"sync_state",kind:"message",T:hr,oneof:"message"},{no:13,name:"simulate",kind:"message",T:Ye,oneof:"message"},{no:14,name:"ping",kind:"scalar",T:3,oneof:"message"},{no:15,name:"update_metadata",kind:"message",T:lr,oneof:"message"},{no:16,name:"ping_req",kind:"message",T:sc,oneof:"message"},{no:17,name:"update_audio_track",kind:"message",T:dr,oneof:"message"},{no:18,name:"update_video_track",kind:"message",T:Yo,oneof:"message"},{no:19,name:"publish_data_track_request",kind:"message",T:rr,oneof:"message"},{no:20,name:"unpublish_data_track_request",kind:"message",T:or,oneof:"message"},{no:21,name:"update_data_subscription",kind:"message",T:Jo,oneof:"message"},{no:22,name:"store_data_blob_request",kind:"message",T:ou,oneof:"message"},{no:23,name:"get_data_blob_request",kind:"message",T:du,oneof:"message"}]),Zr=b.makeMessageType("livekit.SignalResponse",()=>[{no:1,name:"join",kind:"message",T:iu,oneof:"message"},{no:2,name:"answer",kind:"message",T:Rt,oneof:"message"},{no:3,name:"offer",kind:"message",T:Rt,oneof:"message"},{no:4,name:"trickle",kind:"message",T:Ii,oneof:"message"},{no:5,name:"update",kind:"message",T:au,oneof:"message"},{no:6,name:"track_published",kind:"message",T:cr,oneof:"message"},{no:8,name:"leave",kind:"message",T:Ai,oneof:"message"},{no:9,name:"mute",kind:"message",T:Mi,oneof:"message"},{no:10,name:"speakers_changed",kind:"message",T:uu,oneof:"message"},{no:11,name:"room_update",kind:"message",T:hu,oneof:"message"},{no:12,name:"connection_quality",kind:"message",T:mu,oneof:"message"},{no:13,name:"stream_state_update",kind:"message",T:gu,oneof:"message"},{no:14,name:"subscribed_quality_update",kind:"message",T:bu,oneof:"message"},{no:15,name:"subscription_permission_update",kind:"message",T:ku,oneof:"message"},{no:16,name:"refresh_token",kind:"scalar",T:9,oneof:"message"},{no:17,name:"track_unpublished",kind:"message",T:ru,oneof:"message"},{no:18,name:"pong",kind:"scalar",T:3,oneof:"message"},{no:19,name:"reconnect",kind:"message",T:su,oneof:"message"},{no:20,name:"pong_resp",kind:"message",T:Su,oneof:"message"},{no:21,name:"subscription_response",kind:"message",T:_u,oneof:"message"},{no:22,name:"request_response",kind:"message",T:wu,oneof:"message"},{no:23,name:"track_subscribed",kind:"message",T:Ru,oneof:"message"},{no:24,name:"room_moved",kind:"message",T:Tu,oneof:"message"},{no:25,name:"media_sections_requirement",kind:"message",T:Mu,oneof:"message"},{no:26,name:"subscribed_audio_codec_update",kind:"message",T:yu,oneof:"message"},{no:27,name:"publish_data_track_response",kind:"message",T:ar,oneof:"message"},{no:28,name:"unpublish_data_track_response",kind:"message",T:eu,oneof:"message"},{no:29,name:"data_track_subscriber_handles",kind:"message",T:tu,oneof:"message"},{no:30,name:"store_data_blob_response",kind:"message",T:cu,oneof:"message"},{no:31,name:"get_data_blob_response",kind:"message",T:lu,oneof:"message"}]),Cs=b.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:St,repeated:!0},{no:5,name:"video_layer_mode",kind:"enum",T:b.getEnumType(Oo)}]),An=b.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:b.getEnumType(Ve)},{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:b.getEnumType(le)},{no:9,name:"layers",kind:"message",T:St,repeated:!0},{no:10,name:"simulcast_codecs",kind:"message",T:Cs,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:b.getEnumType(G)},{no:15,name:"stream",kind:"scalar",T:9},{no:16,name:"backup_codec_policy",kind:"enum",T:b.getEnumType(Mo)},{no:17,name:"audio_features",kind:"enum",T:b.getEnumType(me),repeated:!0},{no:18,name:"packet_trailer_features",kind:"enum",T:b.getEnumType(cn),repeated:!0}]),rr=b.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:b.getEnumType(G)},{no:4,name:"frame_encoding",kind:"message",T:Do,opt:!0},{no:5,name:"schema",kind:"message",T:Zs,opt:!0}]),ar=b.makeMessageType("livekit.PublishDataTrackResponse",()=>[{no:1,name:"info",kind:"message",T:wi}]),or=b.makeMessageType("livekit.UnpublishDataTrackRequest",()=>[{no:1,name:"pub_handle",kind:"scalar",T:13}]),eu=b.makeMessageType("livekit.UnpublishDataTrackResponse",()=>[{no:1,name:"info",kind:"message",T:wi}]),tu=b.makeMessageType("livekit.DataTrackSubscriberHandles",()=>[{no:1,name:"sub_handles",kind:"map",K:13,V:{kind:"message",T:nu}}]),nu=b.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"}),Ii=b.makeMessageType("livekit.TrickleRequest",()=>[{no:1,name:"candidateInit",kind:"scalar",T:9},{no:2,name:"target",kind:"enum",T:b.getEnumType(We)},{no:3,name:"final",kind:"scalar",T:8}]),Mi=b.makeMessageType("livekit.MuteTrackRequest",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"muted",kind:"scalar",T:8}]),iu=b.makeMessageType("livekit.JoinResponse",()=>[{no:1,name:"room",kind:"message",T:_i},{no:2,name:"participant",kind:"message",T:Vt},{no:3,name:"other_participants",kind:"message",T:Vt,repeated:!0},{no:4,name:"server_version",kind:"scalar",T:9},{no:5,name:"ice_servers",kind:"message",T:Zo,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:Ho},{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:qo},{no:13,name:"sif_trailer",kind:"scalar",T:12},{no:14,name:"enabled_publish_codecs",kind:"message",T:ui,repeated:!0},{no:15,name:"fast_publish",kind:"scalar",T:8}]),su=b.makeMessageType("livekit.ReconnectResponse",()=>[{no:1,name:"ice_servers",kind:"message",T:Zo,repeated:!0},{no:2,name:"client_configuration",kind:"message",T:Ho},{no:3,name:"server_info",kind:"message",T:qo},{no:4,name:"last_message_seq",kind:"scalar",T:13}]),cr=b.makeMessageType("livekit.TrackPublishedResponse",()=>[{no:1,name:"cid",kind:"scalar",T:9},{no:2,name:"track",kind:"message",T:zt}]),ru=b.makeMessageType("livekit.TrackUnpublishedResponse",()=>[{no:1,name:"track_sid",kind:"scalar",T:9}]),Rt=b.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}}]),au=b.makeMessageType("livekit.ParticipantUpdate",()=>[{no:1,name:"participants",kind:"message",T:Vt,repeated:!0}]),Di=b.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:Bo,repeated:!0}]),Jo=b.makeMessageType("livekit.UpdateDataSubscription",()=>[{no:1,name:"updates",kind:"message",T:$o,repeated:!0}]),$o=b.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:Gl}],{localName:"UpdateDataSubscription_Update"}),ou=b.makeMessageType("livekit.StoreDataBlobRequest",()=>[{no:1,name:"request_id",kind:"scalar",T:13},{no:2,name:"blob",kind:"message",T:Ao}]),cu=b.makeMessageType("livekit.StoreDataBlobResponse",()=>[{no:1,name:"request_id",kind:"scalar",T:13},{no:2,name:"key",kind:"message",T:er}]),du=b.makeMessageType("livekit.GetDataBlobRequest",()=>[{no:1,name:"request_id",kind:"scalar",T:13},{no:2,name:"participant_identity",kind:"scalar",T:9},{no:3,name:"key",kind:"message",T:er}]),lu=b.makeMessageType("livekit.GetDataBlobResponse",()=>[{no:1,name:"request_id",kind:"scalar",T:13},{no:2,name:"blob",kind:"message",T:Ao}]),Qo=b.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:b.getEnumType(Xs)},{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}]),dr=b.makeMessageType("livekit.UpdateLocalAudioTrack",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"features",kind:"enum",T:b.getEnumType(me),repeated:!0}]),Yo=b.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}]),Ai=b.makeMessageType("livekit.LeaveRequest",()=>[{no:1,name:"can_reconnect",kind:"scalar",T:8},{no:2,name:"reason",kind:"enum",T:b.getEnumType(Ke)},{no:3,name:"action",kind:"enum",T:b.getEnumType(Yt)},{no:4,name:"regions",kind:"message",T:Cu}]),Yt=b.makeEnum("livekit.LeaveRequest.Action",[{no:0,name:"DISCONNECT"},{no:1,name:"RESUME"},{no:2,name:"RECONNECT"}]),Xo=b.makeMessageType("livekit.UpdateVideoLayers",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"layers",kind:"message",T:St,repeated:!0}]),lr=b.makeMessageType("livekit.UpdateParticipantMetadata",()=>[{no
vendor: 5,951 bytes, line 3
3:1,name:"metadata",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",T:9},{no:3,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:4,name:"request_id",kind:"scalar",T:13}]),Zo=b.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}]),uu=b.makeMessageType("livekit.SpeakersChanged",()=>[{no:1,name:"speakers",kind:"message",T:xo,repeated:!0}]),hu=b.makeMessageType("livekit.RoomUpdate",()=>[{no:1,name:"room",kind:"message",T:_i}]),pu=b.makeMessageType("livekit.ConnectionQualityInfo",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"quality",kind:"enum",T:b.getEnumType(yn)},{no:3,name:"score",kind:"scalar",T:2}]),mu=b.makeMessageType("livekit.ConnectionQualityUpdate",()=>[{no:1,name:"updates",kind:"message",T:pu,repeated:!0}]),fu=b.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:b.getEnumType(Ss)}]),gu=b.makeMessageType("livekit.StreamStateUpdate",()=>[{no:1,name:"stream_states",kind:"message",T:fu,repeated:!0}]),ur=b.makeMessageType("livekit.SubscribedQuality",()=>[{no:1,name:"quality",kind:"enum",T:b.getEnumType(Xs)},{no:2,name:"enabled",kind:"scalar",T:8}]),vu=b.makeMessageType("livekit.SubscribedCodec",()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"qualities",kind:"message",T:ur,repeated:!0}]),bu=b.makeMessageType("livekit.SubscribedQualityUpdate",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribed_qualities",kind:"message",T:ur,repeated:!0},{no:3,name:"subscribed_codecs",kind:"message",T:vu,repeated:!0}]),yu=b.makeMessageType("livekit.SubscribedAudioCodecUpdate",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribed_audio_codecs",kind:"message",T:Yl,repeated:!0}]),ec=b.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}]),tc=b.makeMessageType("livekit.SubscriptionPermission",()=>[{no:1,name:"all_participants",kind:"scalar",T:8},{no:2,name:"track_permissions",kind:"message",T:ec,repeated:!0}]),ku=b.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}]),Tu=b.makeMessageType("livekit.RoomMovedResponse",()=>[{no:1,name:"room",kind:"message",T:_i},{no:2,name:"token",kind:"scalar",T:9},{no:3,name:"participant",kind:"message",T:Vt},{no:4,name:"other_participants",kind:"message",T:Vt,repeated:!0}]),hr=b.makeMessageType("livekit.SyncState",()=>[{no:1,name:"answer",kind:"message",T:Rt},{no:2,name:"subscription",kind:"message",T:Di},{no:3,name:"publish_tracks",kind:"message",T:cr,repeated:!0},{no:4,name:"data_channels",kind:"message",T:ic,repeated:!0},{no:5,name:"offer",kind:"message",T:Rt},{no:6,name:"track_sids_disabled",kind:"scalar",T:9,repeated:!0},{no:7,name:"datachannel_receive_states",kind:"message",T:nc,repeated:!0},{no:8,name:"publish_data_tracks",kind:"message",T:ar,repeated:!0}]),nc=b.makeMessageType("livekit.DataChannelReceiveState",()=>[{no:1,name:"publisher_sid",kind:"scalar",T:9},{no:2,name:"last_seq",kind:"scalar",T:13}]),ic=b.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:b.getEnumType(We)}]),Ye=b.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:b.getEnumType(Xl),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"}]),sc=b.makeMessageType("livekit.Ping",()=>[{no:1,name:"timestamp",kind:"scalar",T:3},{no:2,name:"rtt",kind:"scalar",T:3}]),Su=b.makeMessageType("livekit.Pong",()=>[{no:1,name:"last_ping_timestamp",kind:"scalar",T:3},{no:2,name:"timestamp",kind:"scalar",T:3}]),Cu=b.makeMessageType("livekit.RegionSettings",()=>[{no:1,name:"regions",kind:"message",T:Eu,repeated:!0}]),Eu=b.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}]),_u=b.makeMessageType("livekit.SubscriptionResponse",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"err",kind:"enum",T:b.getEnumType(Bl)}]),wu=b.makeMessageType("livekit.RequestResponse",()=>[{no:1,name:"request_id",kind:"scalar",T:13},{no:2,name:"reason",kind:"enum",T:b.getEnumType(At)},{no:3,name:"message",kind:"scalar",T:9},{no:4,name:"trickle",kind:"message",T:Ii,oneof:"request"},{no:5,name:"add_track",kind:"message",T:An,oneof:"request"},{no:6,name:"mute",kind:"message",T:Mi,oneof:"request"},{no:7,name:"update_metadata",kind:"message",T:lr,oneof:"request"},{no:8,name:"update_audio_track",kind:"message",T:dr,oneof:"request"},{no:9,name:"update_video_track",kind:"message",T:Yo,oneof:"request"},{no:10,name:"publish_data_track",kind:"message",T:rr,oneof:"request"},{no:11,name:"unpublish_data_track",kind:"message",T:or,oneof:"request"}]),At=b.makeEnum("livekit.RequestResponse.Reason",[{no:0,name:"OK"},{no:1,name:"NOT_FOUND"},{no:2,name:"NOT_ALLOWED"},{no:3,name:"LIMIT_EXCEEDED"},{no:4,name:"QUEUED"},{no:5,name:"UNSUPPORTED_TYPE"},{no:6,name:"UNCLASSIFIED_ERROR"},{no:7,name:"INVALID_HANDLE"}
vendor: 4,445 bytes, line 3
3,{no:8,name:"INVALID_NAME"},{no:9,name:"DUPLICATE_HANDLE"},{no:10,name:"DUPLICATE_NAME"},{no:11,name:"INVALID_REQUEST"}]),Ru=b.makeMessageType("livekit.TrackSubscribed",()=>[{no:1,name:"track_sid",kind:"scalar",T:9}]),rc=b.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}]),Pu=b.makeMessageType("livekit.JoinRequest",()=>[{no:1,name:"client_info",kind:"message",T:Wo},{no:2,name:"connection_settings",kind:"message",T:rc},{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:An,repeated:!0},{no:6,name:"publisher_offer",kind:"message",T:Rt},{no:7,name:"reconnect",kind:"scalar",T:8},{no:8,name:"reconnect_reason",kind:"enum",T:b.getEnumType(Dt)},{no:9,name:"participant_sid",kind:"scalar",T:9},{no:10,name:"sync_state",kind:"message",T:hr}]),Iu=b.makeMessageType("livekit.WrappedJoinRequest",()=>[{no:1,name:"compression",kind:"enum",T:b.getEnumType(Es)},{no:2,name:"join_request",kind:"scalar",T:12}]),Es=b.makeEnum("livekit.WrappedJoinRequest.Compression",[{no:0,name:"NONE"},{no:1,name:"GZIP"}]),Mu=b.makeMessageType("livekit.MediaSectionsRequirement",()=>[{no:1,name:"num_audios",kind:"scalar",T:13},{no:2,name:"num_videos",kind:"scalar",T:13}]);function Du(i){return i&&i.__esModule&&Object.prototype.hasOwnProperty.call(i,"default")?i.default:i}var ti={exports:{}},Au=ti.exports,ea;function Ou(){return ea||(ea=1,(function(i){(function(e,t){i.exports?i.exports=t():e.log=t()})(Au,function(){var e=function(){},t="undefined",n=typeof window!==t&&typeof window.navigator!==t&&/Trident\/|MSIE /.test(window.navigator.userAgent),s=["trace","debug","info","warn","error"],r={},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<s.length;k++){var T=s[k];this[T]=k<g?e:this.methodFactory(T,g,this.name)}if(this.log=this.debug,typeof console===t&&g<this.levels.SILENT)return"No console available for logging"}function u(g){return function(){typeof console!==t&&(l.call(this),this[g].apply(this,arguments))}}function h(g,k,T){return c(g)||u.apply(this,arguments)}function p(g,k){var T=this,S,N,v,y="loglevel";typeof g=="string"?y+=":"+g:typeof g=="symbol"&&(y=void 0);function E(O){var F=(s[O]||"silent").toUpperCase();if(!(typeof window===t||!y)){try{window.localStorage[y]=F;return}catch{}try{window.document.cookie=encodeURIComponent(y)+"="+F+";"}catch{}}}function I(){var O;if(!(typeof window===t||!y)){try{O=window.localStorage[y]}catch{}if(typeof O===t)try{var F=window.document.cookie,Y=encodeURIComponent(y),te=F.indexOf(Y+"=");te!==-1&&(O=/^([^;]+)/.exec(F.slice(te+Y.length+1))[1])}catch{}return T.levels[O]===void 0&&(O=void 0),O}}function A(){if(!(typeof window===t||!y)){try{window.localStorage.removeItem(y)}catch{}try{window.document.cookie=encodeURIComponent(y)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}function B(O){var F=O;if(typeof F=="string"&&T.levels[F.toUpperCase()]!==void 0&&(F=T.levels[F.toUpperCase()]),typeof F=="number"&&F>=0&&F<=T.levels.SILENT)return F;throw new TypeError("log.setLevel() called with invalid level: "+O)}T.name=g,T.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},T.methodFactory=k||h,T.getLevel=function(){return v??N??S},T.setLevel=function(O,F){return v=B(O),F!==!1&&E(v),l.call(T)},T.setDefaultLevel=function(O){N=B(O),I()||T.setLevel(O,!1)},T.resetLevel=function(){v=null,A(),l.call(T)},T.enableAll=function(O){T.setLevel(T.levels.TRACE,O)},T.disableAll=function(O){T.setLevel(T.levels.SILENT,O)},T.rebuild=function(){if(a!==T&&(S=B(a.getLevel())),l.call(T),a===T)for(var O in r)r[O].rebuild()},S=B(a?a.getLevel():"WARN");var D=I();D!=null&&(v=B(D)),l.call(T)}
3a=new p,a.getLogger=function(k){if(typeof k!="symbol"&&typeof k!="string"||k==="")throw new TypeError("You must supply a name when creating a logger.");var T=r[k];return T||(T=r[k]=new p(k,a.methodFactory)),T};var f=typeof window!==t?window.log:void 0;return a.noConflict=function(){return typeof window!==t&&window.log===a&&(window.log=f),a},a.getLoggers=function(){return r},a.default=a,a})})(ti)),ti.exports}var Oi=Ou(),_s;(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"})(_s||(_s={}));var ce;(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",i.Region="livekit-region",i.ICE="livekit-ice"})(ce||(ce={}));let U=Oi.getLogger(ce.Default);Object.values(ce).map(i=>Oi.getLogger(i));U.setDefaultLevel(_s.info);function ke(i,e){const t=Oi.getLogger(i);return t.setDefaultLevel(U.getLevel()),e?Nu(t,e):t}function Nu(i,e){const t=s=>(r,a)=>{const o=e(),d=o||a?Object.assign(Object.assign({},o),a):void 0;i[s](r,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}const Lu=Oi.getLogger(ce.E2EE),mn=7e3,xu=[0,300,4*300,9*300,16*300,mn,mn,mn,mn,mn];class Uu{constructor(e){this._retryDelays=e!==void 0?[...e]:xu}nextRetryDelayInMs(e){if(e.retryCount>=this._retryDelays.length)return null;const t=this._retryDelays[e.retryCount];return e.retryCount<=1?t:t+Math.random()*1e3}}function Fu(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 s=0,n=Object.getOwnPropertySymbols(i);s<n.length;s++)e.indexOf(n[s])<0&&Object.prototype.propertyIsEnumerable.call(i,n[s])&&(t[n[s]]=i[n[s]]);return t}function m(i,e,t,n){function s(r){return r instanceof t?r:new t(function(a){a(r)})}return new(t||(t=Promise))(function(r,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?r(l.value):s(l.value).then(o,d)}c((n=n.apply(i,e||[])).next())})}function ta(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 pt(i){return this instanceof pt?(this.v=i,this):new pt(i)}function ac(i,e,t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n=t.apply(i,e||[]),s,r=[];return s=Object.create((typeof AsyncIterator=="function"?AsyncIterator:Object).prototype),o("next"),o("throw"),o("return",a),s[Symbol.asyncIterator]=function(){return this},s;function a(p){return function(f){return Promise.resolve(f).then(p,u)}}function o(p,f){n[p]&&(s[p]=function(g){return new Promise(function(k,T){r.push([p,g,k,T])>1||d(p,g)})},f&&(s[p]=f(s[p])))}function d(p,f){try{c(n[p](f))}catch(g){h(r[0][3],g)}}function c(p){p.value instanceof pt?Promise.resolve(p.value.v).then(l,u):h(r[0][2],p)}function l(p){d("next",p)}function u(p){d("throw",p)}function h(p,f){p(f),r.shift(),r.length&&d(r[0][0],r[0][1])}}function Bu(i){var e,t;return e={},n("next"),n("throw",function(s){throw s}),n("return"),e[Symbol.iterator]=function(){return this},e;function n(s,r){e[s]=i[s]?function(a){return(t=!t)?{value:pt(i[s](a)),done:!1}:r?r(a):a}:r}}function xe(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 ta=="function"?ta(i):i[Symbol.iterator](),t={},n("next"),n("throw"),n("return"),t[Symbol.asyncIterator]=function(){return this},t);function n(r){t[r]=i[r]&&function(a){return new Promise(function(o,d){a=i[r](a),s(o,d,a.done,a.value)})}}function s(r,a,o,d){Promise.resolve(d).then(function(c){r({value:c,done:o})},a)}}var Hn={exports:{}},na;function qu(){if(na)return Hn.exports;
vendor: 5,253 bytes, line 3
3na=1;var i=typeof Reflect=="object"?Reflect:null,e=i&&typeof i.apply=="function"?i.apply:function(y,E,I){return Function.prototype.apply.call(y,E,I)},t;i&&typeof i.ownKeys=="function"?t=i.ownKeys:Object.getOwnPropertySymbols?t=function(y){return Object.getOwnPropertyNames(y).concat(Object.getOwnPropertySymbols(y))}:t=function(y){return Object.getOwnPropertyNames(y)};function n(v){console&&console.warn&&console.warn(v)}var s=Number.isNaN||function(y){return y!==y};function r(){r.init.call(this)}Hn.exports=r,Hn.exports.once=T,r.EventEmitter=r,r.prototype._events=void 0,r.prototype._eventsCount=0,r.prototype._maxListeners=void 0;var a=10;function o(v){if(typeof v!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof v)}Object.defineProperty(r,"defaultMaxListeners",{enumerable:!0,get:function(){return a},set:function(v){if(typeof v!="number"||v<0||s(v))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+v+".");a=v}}),r.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},r.prototype.setMaxListeners=function(y){if(typeof y!="number"||y<0||s(y))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+y+".");return this._maxListeners=y,this};function d(v){return v._maxListeners===void 0?r.defaultMaxListeners:v._maxListeners}r.prototype.getMaxListeners=function(){return d(this)},r.prototype.emit=function(y){for(var E=[],I=1;I<arguments.length;I++)E.push(arguments[I]);var A=y==="error",B=this._events;if(B!==void 0)A=A&&B.error===void 0;else if(!A)return!1;if(A){var D;if(E.length>0&&(D=E[0]),D instanceof Error)throw D;var O=new Error("Unhandled error."+(D?" ("+D.message+")":""));throw O.context=D,O}var F=B[y];if(F===void 0)return!1;if(typeof F=="function")e(F,this,E);else for(var Y=F.length,te=f(F,Y),I=0;I<Y;++I)e(te[I],this,E);return!0};function c(v,y,E,I){var A,B,D;if(o(E),B=v._events,B===void 0?(B=v._events=Object.create(null),v._eventsCount=0):(B.newListener!==void 0&&(v.emit("newListener",y,E.listener?E.listener:E),B=v._events),D=B[y]),D===void 0)D=B[y]=E,++v._eventsCount;else if(typeof D=="function"?D=B[y]=I?[E,D]:[D,E]:I?D.unshift(E):D.push(E),A=d(v),A>0&&D.length>A&&!D.warned){D.warned=!0;var O=new Error("Possible EventEmitter memory leak detected. "+D.length+" "+String(y)+" listeners added. Use emitter.setMaxListeners() to increase limit");O.name="MaxListenersExceededWarning",O.emitter=v,O.type=y,O.count=D.length,n(O)}return v}r.prototype.addListener=function(y,E){return c(this,y,E,!1)},r.prototype.on=r.prototype.addListener,r.prototype.prependListener=function(y,E){return c(this,y,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(v,y,E){var I={fired:!1,wrapFn:void 0,target:v,type:y,listener:E},A=l.bind(I);return A.listener=E,I.wrapFn=A,A}r.prototype.once=function(y,E){return o(E),this.on(y,u(this,y,E)),this},r.prototype.prependOnceListener=function(y,E){return o(E),this.prependListener(y,u(this,y,E)),this},r.prototype.removeListener=function(y,E){var I,A,B,D,O;if(o(E),A=this._events,A===void 0)return this;if(I=A[y],I===void 0)return this;if(I===E||I.listener===E)--this._eventsCount===0?this._events=Object.create(null):(delete A[y],A.removeListener&&this.emit("removeListener",y,I.listener||E));else if(typeof I!="function"){for(B=-1,D=I.length-1;D>=0;D--)if(I[D]===E||I[D].listener===E){O=I[D].listener,B=D;break}if(B<0)return this;B===0?I.shift():g(I,B),I.length===1&&(A[y]=I[0]),A.removeListener!==void 0&&this.emit("removeListener",y,O||E)}return this},r.prototype.off=r.prototype.removeListener,r.prototype.removeAllListeners=function(y){var E,I,A;if(I=this._events,I===void 0)return this;if(I.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):I[y]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete I[y]),this;if(arguments.length===0){var B=Object.keys(I),D;for(A=0;A<B.length;++A)D=B[A],D!=="removeListener"&&this.removeAllListeners(D);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(E=I[y],typeof E=="function")this.removeListener(y,E);else if(E!==void 0)for(A=E.length-1;A>=0;A--)this.removeListener(y,E[A]);return this};function h(v,y,E){var I=v._events;if(I===void 0)return[];var A=I[y];return A===void 0?[]:typeof A=="function"?E?[A.listener||A]:[A]:E?k(A):f(A,A.length)}r.prototype.listeners=function(y){return h(this,y,!0)},r.prototype.rawListeners=function(y){return h(this,y,!1)},r.listenerCount=function(v,y){return typeof v.listenerCount=="function"?v.listenerCount(y):p.call(v,y)},r.prototype.listenerCount=p;function p(v){var y=this._events;if(y!==void 0){var E=y[v];if(typeof E=="function")return 1;if(E!==void 0)return E.length}return 0}r.prototype.eventNames=function(){return this._eventsCount>0?t(this._events):[]};function f(v,y){for(var E=new Array(y),I=0;I<y;
3++I)E[I]=v[I];return E}function g(v,y){for(;y+1<v.length;y++)v[y]=v[y+1];v.pop()}function k(v){for(var y=new Array(v.length),E=0;E<y.length;++E)y[E]=v[E].listener||v[E];return y}function T(v,y){return new Promise(function(E,I){function A(D){v.removeListener(y,B),I(D)}function B(){typeof v.removeListener=="function"&&v.removeListener("error",A),E([].slice.call(arguments))}N(v,y,B,{once:!0}),y!=="error"&&S(v,A,{once:!0})})}function S(v,y,E){typeof v.on=="function"&&N(v,"error",y,E)}function N(v,y,E,I){if(typeof v.on=="function")I.once?v.once(y,E):v.on(y,E);else if(typeof v.addEventListener=="function")v.addEventListener(y,function A(B){I.once&&v.removeEventListener(y,A),E(B)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof v)}return Hn.exports}var De=qu();let oc=!0,cc=!0;function kn(i,e,t){const n=i.match(e);return n&&n.length>=t&&parseFloat(n[t],10)}function Ht(i,e,t){if(!i.RTCPeerConnection)return;if(!Object.getOwnPropertyDescriptor(EventTarget.prototype,"addEventListener").writable){pr("Unable to polyfill events");return}const s=i.RTCPeerConnection.prototype,r=s.addEventListener;s.addEventListener=function(o,d){if(o!==e)return r.apply(this,arguments);const c=l=>{const u=t(l);u&&(d.handleEvent?d.handleEvent(u):d(u))};return this._eventMap=this._eventMap||{},this._eventMap[e]||(this._eventMap[e]=new Map),this._eventMap[e].set(d,c),r.apply(this,[o,c])};const a=s.removeEventListener;s.removeEventListener=function(o,d){if(o!==e||!this._eventMap||!this._eventMap[e])return a.apply(this,arguments);if(!this._eventMap[e].has(d))return a.apply(this,arguments);const c=this._eventMap[e].get(d);return this._eventMap[e].delete(d),this._eventMap[e].size===0&&delete this._eventMap[e],Object.keys(this._eventMap).length===0&&delete this._eventMap,a.apply(this,[o,c])},Object.defineProperty(s,"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 Vu(i){return typeof i!="boolean"?new Error("Argument type: "+typeof i+". Please use a boolean."):(oc=i,i?"adapter.js logging disabled":"adapter.js logging enabled")}function Wu(i){return typeof i!="boolean"?new Error("Argument type: "+typeof i+". Please use a boolean."):(cc=!i,"adapter.js deprecation warnings "+(i?"disabled":"enabled"))}function pr(){if(typeof window=="object"){if(oc)return;typeof console<"u"&&typeof console.log=="function"&&console.log.apply(console,arguments)}}function mr(i,e){cc&&console.warn(i+" is deprecated, please use "+e+" instead.")}function ju(i){const e={browser:null,version:null};if(typeof i>"u"||!i.navigator||!i.navigator.userAgent)return e.browser="Not a browser.",e;const t=i.navigator;if(t.userAgentData&&t.userAgentData.brands){const n=t.userAgentData.brands.find(s=>s.brand==="Chromium");if(n){const s=parseInt(n.version,10);if(s>=90)return{browser:"chrome",version:s}}}if(t.mozGetUserMedia)e.browser="firefox",e.version=parseInt(kn(t.userAgent,/Firefox\/(\d+)\./,1));else if(t.webkitGetUserMedia||i.isSecureContext===!1&&i.webkitRTCPeerConnection)e.browser="chrome",e.version=parseInt(kn(t.userAgent,/Chrom(e|ium)\/(\d+)\./,2))||null;else if(i.RTCPeerConnection&&t.userAgent.match(/AppleWebKit\/(\d+)\./))e.browser="safari",e.version=parseInt(kn(t.userAgent,/AppleWebKit\/(\d+)\./,1)),e.supportsUnifiedPlan=i.RTCRtpTransceiver&&"currentDirection"in i.RTCRtpTransceiver.prototype,e._safariVersion=kn(t.userAgent,/Version\/(\d+(\.?\d+))/,1);else return e.browser="Not a supported browser.",e;return e}function ia(i){return Object.prototype.toString.call(i)==="[object Object]"}function dc(i){return ia(i)?Object.keys(i).reduce(function(e,t){const n=ia(i[t]),s=n?dc(i[t]):i[t],r=n&&!Object.keys(s).length;return s===void 0||r?e:Object.assign(e,{[t]:s})},{}):i}function ws(i,e,t){!e||t.has(e.id)||(t.set(e.id,e),Object.keys(e).forEach(n=>{n.endsWith("Id")?ws(i,i.get(e[n]),t):n.endsWith("Ids")&&e[n].forEach(s=>{ws(i,i.get(s),t)})}))}function sa(i,e,t){const n=t?"outbound-rtp":"inbound-rtp",s=new Map;if(e===null)return s;const r=[];
vendor: 13,541 bytes, line 3
3return i.forEach(a=>{a.type==="track"&&a.trackIdentifier===e.id&&r.push(a)}),r.forEach(a=>{i.forEach(o=>{o.type===n&&o.trackId===a.id&&ws(i,o,s)})}),s}const ra=pr;function lc(i,e){if(e.version>=64)return;const t=i&&i.navigator;if(!t.mediaDevices)return;const n=function(o){if(typeof o!="object"||o.mandatory||o.optional)return o;const d={};return Object.keys(o).forEach(c=>{if(c==="require"||c==="advanced"||c==="mediaSource")return;const l=typeof o[c]=="object"?o[c]:{ideal:o[c]};l.exact!==void 0&&typeof l.exact=="number"&&(l.min=l.max=l.exact);const u=function(h,p){return h?h+p.charAt(0).toUpperCase()+p.slice(1):p==="deviceId"?"sourceId":p};if(l.ideal!==void 0){d.optional=d.optional||[];let h={};typeof l.ideal=="number"?(h[u("min",c)]=l.ideal,d.optional.push(h),h={},h[u("max",c)]=l.ideal,d.optional.push(h)):(h[u("",c)]=l.ideal,d.optional.push(h))}l.exact!==void 0&&typeof l.exact!="number"?(d.mandatory=d.mandatory||{},d.mandatory[u("",c)]=l.exact):["min","max"].forEach(h=>{l[h]!==void 0&&(d.mandatory=d.mandatory||{},d.mandatory[u(h,c)]=l[h])})}),o.advanced&&(d.optional=(d.optional||[]).concat(o.advanced)),d},s=function(o,d){if(e.version>=61)return d(o);if(o=JSON.parse(JSON.stringify(o)),o&&typeof o.audio=="object"){const c=function(l,u,h){u in l&&!(h in l)&&(l[h]=l[u],delete l[u])};o=JSON.parse(JSON.stringify(o)),c(o.audio,"autoGainControl","googAutoGainControl"),c(o.audio,"noiseSuppression","googNoiseSuppression"),o.audio=n(o.audio)}if(o&&typeof o.video=="object"){let c=o.video.facingMode;c=c&&(typeof c=="object"?c:{ideal:c});const l=e.version<66;if(c&&(c.exact==="user"||c.exact==="environment"||c.ideal==="user"||c.ideal==="environment")&&!(t.mediaDevices.getSupportedConstraints&&t.mediaDevices.getSupportedConstraints().facingMode&&!l)){delete o.video.facingMode;let u;if(c.exact==="environment"||c.ideal==="environment"?u=["back","rear"]:(c.exact==="user"||c.ideal==="user")&&(u=["front"]),u)return t.mediaDevices.enumerateDevices().then(h=>{h=h.filter(f=>f.kind==="videoinput");let p=h.find(f=>u.some(g=>f.label.toLowerCase().includes(g)));return!p&&h.length&&u.includes("back")&&(p=h[h.length-1]),p&&(o.video.deviceId=c.exact?{exact:p.deviceId}:{ideal:p.deviceId}),o.video=n(o.video),ra("chrome: "+JSON.stringify(o)),d(o)})}o.video=n(o.video)}return ra("chrome: "+JSON.stringify(o)),d(o)},r=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){s(o,l=>{t.webkitGetUserMedia(l,d,u=>{c&&c(r(u))})})};if(t.getUserMedia=a.bind(t),t.mediaDevices.getUserMedia){const o=t.mediaDevices.getUserMedia.bind(t.mediaDevices);t.mediaDevices.getUserMedia=function(d){return s(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(r(l))))}}}function uc(i){i.MediaStream=i.MediaStream||i.webkitMediaStream}function hc(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});const t=i.RTCPeerConnection.prototype.setRemoteDescription;i.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=s=>{s.stream.addEventListener("addtrack",r=>{let a;i.RTCPeerConnection.prototype.getReceivers?a=this.getReceivers().find(d=>d.track&&d.track.id===r.track.id):a={track:r.track};const o=new Event("track");o.track=r.track,o.receiver=a,o.transceiver={receiver:a},o.streams=[s.stream],this.dispatchEvent(o)}),s.stream.getTracks().forEach(r=>{let a;i.RTCPeerConnection.prototype.getReceivers?a=this.getReceivers().find(d=>d.track&&d.track.id===r.id):a={track:r};const o=new Event("track");o.track=r,o.receiver=a,o.transceiver={receiver:a},o.streams=[s.stream],this.dispatchEvent(o)})},this.addEventListener("addstream",this._ontrackpoly)),t.apply(this,arguments)}}else Ht(i,"track",t=>(t.transceiver||Object.defineProperty(t,"transceiver",{value:{receiver:t.receiver}}),t))}function pc(i){if(typeof i=="object"&&i.RTCPeerConnection&&!("getSenders"in i.RTCPeerConnection.prototype)&&"createDTMFSender"in i.RTCPeerConnection.prototype){const e=function(s,r){return{track:r,get dtmf(){return this._dtmf===void 0&&(r.kind==="audio"?this._dtmf=s.createDTMFSender(r):this._dtmf=null),this._dtmf},_pc:s}};if(!i.RTCPeerConnection.prototype.getSenders){i.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};const s=i.RTCPeerConnection.prototype.addTrack;i.RTCPeerConnection.prototype.addTrack=function(o,d){let c=s.apply(this,arguments);return c||(c=e(this,o),this._senders.push(c)),c};const r=i.RTCPeerConnection.prototype.removeTrack;i.RTCPeerConnection.prototype.removeTrack=function(o){r.apply(this,arguments);const d=this._senders.indexOf(o);d!==-1&&this._senders.splice(d,1)}}const t=i.RTCPeerConnection.prototype.addStream;i.RTCPeerConnection.prototype.addStream=function(r){this._senders=this._senders||[],t.apply(this,[r]),r.getTracks().forEach(a=>{this._senders.push(e(this,a))})};const n=i.RTCPeerConnection.prototype.removeStream;i.RTCPeerConnection.prototype.removeStream=function(r){this._senders=this._senders||[],n.apply(this,[r]),r.getTracks().forEach(a=>{const 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)){const e=i.RTCPeerConnection.prototype.getSenders;i.RTCPeerConnection.prototype.getSenders=function(){const n=e.apply(this,[]);return n.forEach(s=>s._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 mc(i,e){if(e.version>=67||!(typeof i=="object"&&i.RTCPeerConnection&&i.RTCRtpSender&&i.RTCRtpReceiver))return;if(!("getStats"in i.RTCRtpSender.prototype)){const n=i.RTCPeerConnection.prototype.getSenders;n&&(i.RTCPeerConnection.prototype.getSenders=function(){const a=n.apply(this,[]);return a.forEach(o=>o._pc=this),a});const s=i.RTCPeerConnection.prototype.addTrack;s&&(i.RTCPeerConnection.prototype.addTrack=function(){const a=s.apply(this,arguments);return a._pc=this,a}),i.RTCRtpSender.prototype.getStats=function(){const a=this;return this._pc.getStats().then(o=>sa(o,a.track,!0))}}if(!("getStats"in i.RTCRtpReceiver.prototype)){const n=i.RTCPeerConnection.prototype.getReceivers;n&&(i.RTCPeerConnection.prototype.getReceivers=function(){const r=n.apply(this,[]);return r.forEach(a=>a._pc=this),r}),Ht(i,"track",s=>(s.receiver._pc=s.srcElement,s)),i.RTCRtpReceiver.prototype.getStats=function(){const r=this;return this._pc.getStats().then(a=>sa(a,r.track,!1))}}if(!("getStats"in i.RTCRtpSender.prototype&&"getStats"in i.RTCRtpReceiver.prototype))return;const t=i.RTCPeerConnection.prototype.getStats;i.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof i.MediaStreamTrack){const s=arguments[0];let r,a,o;return this.getSenders().forEach(d=>{d.track===s&&(r?o=!0:r=d)}),this.getReceivers().forEach(d=>(d.track===s&&(a?o=!0:a=d),d.track===s)),o||r&&a?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):r?r.getStats():a?a.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return t.apply(this,arguments)}}function fc(i){i.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map(a=>this._shimmedLocalStreams[a][0])};const e=i.RTCPeerConnection.prototype.addTrack;i.RTCPeerConnection.prototype.addTrack=function(a,o){if(!o)return e.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};const d=e.apply(this,arguments);return this._shimmedLocalStreams[o.id]?this._shimmedLocalStreams[o.id].indexOf(d)===-1&&this._shimmedLocalStreams[o.id].push(d):this._shimmedLocalStreams[o.id]=[o,d],d};const t=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")});const o=this.getSenders();t.apply(this,arguments);const d=this.getSenders().filter(c=>o.indexOf(c)===-1);this._shimmedLocalStreams[a.id]=[a].concat(d)};const n=i.RTCPeerConnection.prototype.removeStream;i.RTCPeerConnection.prototype.removeStream=function(a){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[a.id],n.apply(this,arguments)};const s=i.RTCPeerConnection.prototype.removeTrack;i.RTCPeerConnection.prototype.removeTrack=function(a){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},a&&Object.keys(this._shimmedLocalStreams).forEach(o=>{const d=this._shimmedLocalStreams[o].indexOf(a);d!==-1&&this._shimmedLocalStreams[o].splice(d,1),this._shimmedLocalStreams[o].length===1&&delete this._shimmedLocalStreams[o]}),s.apply(this,arguments)}}function gc(i,e){if(!i.RTCPeerConnection)return;if(i.RTCPeerConnection.prototype.addTrack&&e.version>=65)return fc(i);const t=i.RTCPeerConnection.prototype.getLocalStreams;i.RTCPeerConnection.prototype.getLocalStreams=function(){const l=t.apply(this);return this._reverseStreams=this._reverseStreams||{},l.map(u=>this._reverseStreams[u.id])};const 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(p=>p.track===u))throw new DOMException("Track already exists.","InvalidAccessError")}),!this._reverseStreams[l.id]){const u=new i.MediaStream(l.getTracks());this._streams[l.id]=u,this._reverseStreams[u.id]=l,l=u}n.apply(this,[l])};const s=i.RTCPeerConnection.prototype.removeStream;i.RTCPeerConnection.prototype.removeStream=function(l){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},s.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");const h=[].slice.call(arguments,1);if(h.length!==1||!h[0].getTracks().find(g=>g===l))throw new DOMException("The adapter.js addTrack polyfill only supports a single stream which is associated with the specified track.","NotSupportedError");if(this.getSenders().find(g=>g.track===l))throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};const f=this._streams[u.id];if(f)f.addTrack(l),Promise.resolve().then(()=>{this.dispatchEvent(new Event("negotiationneeded"))});else{const g=new 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 r(c,l){let u=l.sdp;return Object.keys(c._reverseStreams||[]).forEach(h=>{const p=c._reverseStreams[h],f=c._streams[p.id];u=u.replace(new RegExp(f.id,"g"),p.id)}),new RTCSessionDescription({type:l.type,sdp:u})}function a(c,l){let u=l.sdp;return Object.keys(c._reverseStreams||[]).forEach(h=>{const p=c._reverseStreams[h],f=c._streams[p.id];u=u.replace(new RegExp(p.id,"g"),f.id)}),new RTCSessionDescription({type:l.type,sdp:u})}["createOffer","createAnswer"].forEach(function(c){const l=i.RTCPeerConnection.prototype[c],u={[c](){const h=arguments;return arguments.length&&typeof arguments[0]=="function"?l.apply(this,[f=>{const g=r(this,f);h[0].apply(null,[g])},f=>{h[1]&&h[1].apply(null,f)},arguments[2]]):l.apply(this,arguments).then(f=>r(this,f))}};i.RTCPeerConnection.prototype[c]=u[c]});const o=i.RTCPeerConnection.prototype.setLocalDescription;i.RTCPeerConnection.prototype.setLocalDescription=function(){return!arguments.length||!arguments[0].type?o.apply(this,arguments):(arguments[0]=a(this,arguments[0]),o.apply(this,arguments))};const d=Object.getOwnPropertyDescriptor(i.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(i.RTCPeerConnection.prototype,"localDescription",{get(){const c=d.get.apply(this);return c.type===""?c:r(this,c)}}),i.RTCPeerConnection.prototype.removeTrack=function(l){if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");
3if(!l._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(!(l._pc===this))throw new DOMException("Sender was not created by this connection.","InvalidAccessError");this._streams=this._streams||{};let h;Object.keys(this._streams).forEach(p=>{this._streams[p].getTracks().find(g=>l.track===g)&&(h=this._streams[p])}),h&&(h.getTracks().length===1?this.removeStream(this._reverseStreams[h.id]):h.removeTrack(l.track),this.dispatchEvent(new Event("negotiationneeded")))}}function Rs(i,e){!i.RTCPeerConnection&&i.webkitRTCPeerConnection&&(i.RTCPeerConnection=i.webkitRTCPeerConnection),i.RTCPeerConnection&&e.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(t){const n=i.RTCPeerConnection.prototype[t],s={[t](){return arguments[0]=new(t==="addIceCandidate"?i.RTCIceCandidate:i.RTCSessionDescription)(arguments[0]),n.apply(this,arguments)}};i.RTCPeerConnection.prototype[t]=s[t]})}function vc(i,e){e.version>102||Ht(i,"negotiationneeded",t=>{const n=t.target;if(!((e.version<72||n.getConfiguration&&n.getConfiguration().sdpSemantics==="plan-b")&&n.signalingState!=="stable"))return t})}var aa=Object.freeze({__proto__:null,fixNegotiationNeeded:vc,shimAddTrackRemoveTrack:gc,shimAddTrackRemoveTrackWithNative:fc,shimGetSendersWithDtmf:pc,shimGetUserMedia:lc,shimMediaStream:uc,shimOnTrack:hc,shimPeerConnection:Rs,shimSenderReceiverGetStats:mc});function bc(i,e){const t=i&&i.navigator;if(!t.mediaDevices)return;const n=i&&i.MediaStreamTrack;if(t.getUserMedia=function(s,r,a){mr("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),t.mediaDevices.getUserMedia(s).then(r,a)},!(e.version>55&&"autoGainControl"in t.mediaDevices.getSupportedConstraints())){const s=function(a,o,d){o in a&&!(d in a)&&(a[d]=a[o],delete a[o])},r=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)),s(a.audio,"autoGainControl","mozAutoGainControl"),s(a.audio,"noiseSuppression","mozNoiseSuppression")),r(a)},n&&n.prototype.getSettings){const a=n.prototype.getSettings;n.prototype.getSettings=function(){const o=a.apply(this,arguments);return s(o,"mozAutoGainControl","autoGainControl"),s(o,"mozNoiseSuppression","noiseSuppression"),o}}if(n&&n.prototype.applyConstraints){const a=n.prototype.applyConstraints;n.prototype.applyConstraints=function(o){return this.kind==="audio"&&typeof o=="object"&&(o=JSON.parse(JSON.stringify(o)),s(o,"autoGainControl","mozAutoGainControl"),s(o,"noiseSuppression","mozNoiseSuppression")),a.apply(this,[o])}}}}function Hu(i,e){i.navigator.mediaDevices&&(i.navigator.mediaDevices&&"getDisplayMedia"in i.navigator.mediaDevices||(i.navigator.mediaDevices.getDisplayMedia=function(n){if(!(n&&n.video)){const s=new DOMException("getDisplayMedia without video constraints is undefined");return s.name="NotFoundError",s.code=8,Promise.reject(s)}return n.video===!0?n.video={mediaSource:e}:n.video.mediaSource=e,i.navigator.mediaDevices.getUserMedia(n)}))}function yc(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 Ps(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){const n=i.RTCPeerConnection.prototype[t],s={[t](){return arguments[0]=new(t==="addIceCandidate"?i.RTCIceCandidate:i.RTCSessionDescription)(arguments[0]),n.apply(this,arguments)}};i.RTCPeerConnection.prototype[t]=s[t]}))}function kc(i,e){if(typeof i!="object"||!(i.RTCPeerConnection||i.mozRTCPeerConnection)||e.version>=151)return;const t={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},n=i.RTCPeerConnection.prototype.getStats;i.RTCPeerConnection.prototype.getStats=function(){const r=Array.prototype.slice.call(arguments),a=r[0],o=r[1],d=r[2];return this.signalingState==="closed"?Promise.resolve(new Map):n.apply(this,[a||null]).then(c=>
vendor: 26,103 bytes, lines 3-37
3{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 Tc(i){if(!(typeof i=="object"&&i.RTCPeerConnection&&i.RTCRtpSender)||i.RTCRtpSender&&"getStats"in i.RTCRtpSender.prototype)return;const e=i.RTCPeerConnection.prototype.getSenders;e&&(i.RTCPeerConnection.prototype.getSenders=function(){const s=e.apply(this,[]);return s.forEach(r=>r._pc=this),s});const t=i.RTCPeerConnection.prototype.addTrack;t&&(i.RTCPeerConnection.prototype.addTrack=function(){const s=t.apply(this,arguments);return s._pc=this,s}),i.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}function Sc(i){if(!(typeof i=="object"&&i.RTCPeerConnection&&i.RTCRtpSender)||i.RTCRtpSender&&"getStats"in i.RTCRtpReceiver.prototype)return;const e=i.RTCPeerConnection.prototype.getReceivers;e&&(i.RTCPeerConnection.prototype.getReceivers=function(){const n=e.apply(this,[]);return n.forEach(s=>s._pc=this),n}),Ht(i,"track",t=>(t.receiver._pc=t.srcElement,t)),i.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function Cc(i){!i.RTCPeerConnection||"removeStream"in i.RTCPeerConnection.prototype||(i.RTCPeerConnection.prototype.removeStream=function(t){mr("removeStream","removeTrack"),this.getSenders().forEach(n=>{n.track&&t.getTracks().includes(n.track)&&this.removeTrack(n)})})}function Ec(i){i.DataChannel&&!i.RTCDataChannel&&(i.RTCDataChannel=i.DataChannel)}function _c(i,e){if(!(typeof i=="object"&&i.RTCPeerConnection)||e.version>=110)return;const t=i.RTCPeerConnection.prototype.addTransceiver;t&&(i.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let s=arguments[1]&&arguments[1].sendEncodings;s===void 0&&(s=[]),s=[...s];const r=s.length>0;r&&s.forEach(o=>{if("rid"in o&&!/^[a-z0-9]{0,16}$/i.test(o.rid))throw new TypeError("Invalid RID value provided.");if("scaleResolutionDownBy"in o&&!(parseFloat(o.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in o&&!(parseFloat(o.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")});const a=t.apply(this,arguments);if(r){const o=a.sender,d=o.getParameters();(!("encodings"in d)||d.encodings.length===1&&Object.keys(d.encodings[0]).length===0)&&(d.encodings=s,o.sendEncodings=s,this.setParametersPromises.push(o.setParameters(d).then(()=>{delete o.sendEncodings}).catch(()=>{delete o.sendEncodings})))}return a})}function wc(i,e){if(!(typeof i=="object"&&i.RTCRtpSender)||e.version>=110)return;const t=i.RTCRtpSender.prototype.getParameters;t&&(i.RTCRtpSender.prototype.getParameters=function(){const s=t.apply(this,arguments);return"encodings"in s||(s.encodings=[].concat(this.sendEncodings||[{}])),s})}function Rc(i,e){if(!(typeof i=="object"&&i.RTCPeerConnection)||e.version>=110)return;const t=i.RTCPeerConnection.prototype.createOffer;i.RTCPeerConnection.prototype.createOffer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>t.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):t.apply(this,arguments)}}function Pc(i,e){if(!(typeof i=="object"&&i.RTCPeerConnection)||e.version>=110)return;const t=i.RTCPeerConnection.prototype.createAnswer;i.RTCPeerConnection.prototype.createAnswer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>t.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):t.apply(this,arguments)}}var oa=Object.freeze({__proto__:null,shimAddTransceiver:_c,shimCreateAnswer:Pc,shimCreateOffer:Rc,shimGetDisplayMedia:Hu,shimGetParameters:wc,shimGetStats:kc,shimGetUserMedia:bc,shimOnTrack:yc,shimPeerConnection:Ps,shimRTCDataChannel:Ec,shimReceiverGetStats:Sc,shimRemoveStream:Cc,shimSenderGetStats:Tc});function Ic(i){if(!(typeof i!="object"||!i.RTCPeerConnection)){if("getLocalStreams"in i.RTCPeerConnection.prototype||(i.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in i.RTCPeerConnection.prototype)){const e=i.RTCPeerConnection.prototype.addTrack;i.RTCPeerConnection.prototype.addStream=function(n){this._localStreams||(this._localStreams=[]),this._localStreams.includes(n)||this._localStreams.push(n),n.getAudioTracks().forEach(s=>e.call(this,s,n)),n.getVideoTracks().forEach(s=>e.call(this,s,n))},i.RTCPeerConnection.prototype.addTrack=function(n){for(var s=arguments.length,r=new Array(s>1?s-1:0),a=1;a<s;a++)r[a-1]=arguments[a];return r&&r.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=[]);const n=this._localStreams.indexOf(t);if(n===-1)return;this._localStreams.splice(n,1);const s=t.getTracks();this.getSenders().forEach(r=>{s.includes(r.track)&&this.removeTrack(r)})})}}function Mc(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(s=>{if(this._remoteStreams||(this._remoteStreams=[]),this._remoteStreams.includes(s))return;this._remoteStreams.push(s);const r=new Event("addstream");r.stream=s,this.dispatchEvent(r)})})}});const e=i.RTCPeerConnection.prototype.setRemoteDescription;i.RTCPeerConnection.prototype.setRemoteDescription=function(){const n=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(s){s.streams.forEach(r=>{if(n._remoteStreams||(n._remoteStreams=[]),n._remoteStreams.indexOf(r)>=0)return;n._remoteStreams.push(r);const a=new Event("addstream");a.stream=r,n.dispatchEvent(a)})}),e.apply(n,arguments)}}}function Dc(i){if(typeof i!="object"||!i.RTCPeerConnection)return;const e=i.RTCPeerConnection.prototype,t=e.createOffer,n=e.createAnswer,s=e.setLocalDescription,r=e.setRemoteDescription,a=e.addIceCandidate;e.createOffer=function(c,l){const u=arguments.length>=2?arguments[2]:arguments[0],h=t.apply(this,[u]);return l?(h.then(c,l),Promise.resolve()):h},e.createAnswer=function(c,l){const u=arguments.length>=2?arguments[2]:arguments[0],h=n.apply(this,[u]);return l?(h.then(c,l),Promise.resolve()):h};let o=function(d,c,l){const u=s.apply(this,[d]);return l?(u.then(c,l),Promise.resolve()):u};e.setLocalDescription=o,o=function(d,c,l){const u=r.apply(this,[d]);return l?(u.then(c,l),Promise.resolve()):u},e.setRemoteDescription=o,o=function(d,c,l){const u=a.apply(this,[d]);return l?(u.then(c,l),Promise.resolve()):u},e.addIceCandidate=o}function Ac(i){const e=i&&i.navigator;if(e.mediaDevices&&e.mediaDevices.getUserMedia){const t=e.mediaDevices,n=t.getUserMedia.bind(t);e.mediaDevices.getUserMedia=s=>n(Oc(s))}!e.getUserMedia&&e.mediaDevices&&e.mediaDevices.getUserMedia&&(e.getUserMedia=(function(n,s,r){e.mediaDevices.getUserMedia(n).then(s,r)}).bind(e))}function Oc(i){return i&&i.video!==void 0?Object.assign({},i,{video:dc(i.video)}):i}function Nc(i){if(!i.RTCPeerConnection)return;const e=i.RTCPeerConnection;i.RTCPeerConnection=function(n,s){if(n&&n.iceServers){const r=[];for(let a=0;a<n.iceServers.length;a++){let o=n.iceServers[a];o.urls===void 0&&o.url?(mr("RTCIceServer.url","RTCIceServer.urls"),o=JSON.parse(JSON.stringify(o)),o.urls=o.url,delete o.url,r.push(o)):r.push(n.iceServers[a])}n.iceServers=r}return new e(n,s)},i.RTCPeerConnection.prototype=e.prototype,"generateCertificate"in e&&Object.defineProperty(i.RTCPeerConnection,"generateCertificate",{get(){return e.generateCertificate}})}function Lc(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 xc(i){const e=i.RTCPeerConnection.prototype.createOffer;i.RTCPeerConnection.prototype.createOffer=function(n){if(n){typeof n.offerToReceiveAudio<"u"&&(n.offerToReceiveAudio=!!n.offerToReceiveAudio);const s=this.getTransceivers().find(a=>a.receiver.track.kind==="audio");n.offerToReceiveAudio===!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.offerToReceiveAudio===!0&&!s&&this.addTransceiver("audio",{direction:"recvonly"}),typeof n.offerToReceiveVideo<"u"&&(n.offerToReceiveVideo=!!n.offerToReceiveVideo);const r=this.getTransceivers().find(a=>a.receiver.track.kind==="video");n.offerToReceiveVideo===!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.offerToReceiveVideo===!0&&!r&&this.addTransceiver("video",{direction:"recvonly"})}return e.apply(this,arguments)}}function Uc(i){typeof i!="object"||i.AudioContext||(i.AudioContext=i.webkitAudioContext)}var ca=Object.freeze({__proto__:null,shimAudioContext:Uc,shimCallbacksAPI:Dc,shimConstraints:Oc,shimCreateOfferLegacy:xc,shimGetUserMedia:Ac,shimLocalStreamsAPI:Ic,shimRTCIceServerUrls:Nc,shimRemoteStreamsAPI:Mc,shimTrackEventTransceiver:Lc}),Yi={exports:{}},da;function Ku(){return da||(da=1,(function(i){const e={};e.generateIdentifier=function(){return Math.random().toString(36).substring(2,12)},e.localCName=e.generateIdentifier(),e.splitLines=function(t){return t.trim().split(` 4`).map(n=>n.trim())},e.splitSections=function(t){return t.split(` 5m=`).map((s,r)=>(r>0?"m="+s:s).trim()+`\r 6`)},e.getDescription=function(t){const n=e.splitSections(t);return n&&n[0]},e.getMediaSections=function(t){const n=e.splitSections(t);return n.shift(),n},e.matchPrefix=function(t,n){return e.splitLines(t).filter(s=>s.indexOf(n)===0)},e.parseCandidate=function(t){let n;t.indexOf("a=candidate:")===0?n=t.substring(12).split(" "):n=t.substring(10).split(" ");const s={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 r=8;r<n.length;r+=2)switch(n[r]){case"raddr":s.relatedAddress=n[r+1];break;case"rport":s.relatedPort=parseInt(n[r+1],10);break;case"tcptype":s.tcpType=n[r+1];break;case"ufrag":s.ufrag=n[r+1],s.usernameFragment=n[r+1];break;default:s[n[r]]===void 0&&(s[n[r]]=n[r+1]);break}return s},e.writeCandidate=function(t){const n=[];n.push(t.foundation);const s=t.component;s==="rtp"?n.push(1):s==="rtcp"?n.push(2):n.push(s),n.push(t.protocol.toUpperCase()),n.push(t.priority),n.push(t.address||t.ip),n.push(t.port);const r=t.type;return n.push("typ"),n.push(r),r!=="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(" ");const s={payloadType:parseInt(n.shift(),10)};return n=n[0].split("/"),s.name=n[0],s.clockRate=parseInt(n[1],10),s.channels=n.length===3?parseInt(n[2],10):1,s.numChannels=s.channels,s},e.writeRtpMap=function(t){let n=t.payloadType;t.preferredPayloadType!==void 0&&(n=t.preferredPayloadType);const s=t.channels||t.numChannels||1;return"a=rtpmap:"+n+" "+t.name+"/"+t.clockRate+(s!==1?"/"+s:"")+`\r 7`},e.parseExtmap=function(t){const n=t.substring(9).split(" ");return{id:parseInt(n[0],10),direction:n[0].indexOf("/")>0?n[0].split("/")[1]:"sendrecv",uri:n[1],attributes:n.slice(2).join(" ")}},e.writeExtmap=function(t){return"a=extmap:"+(t.id||t.preferredId)+(t.direction&&t.direction!=="sendrecv"?"/"+t.direction:"")+" "+t.uri+(t.attributes?" "+t.attributes:"")+`\r 8`},e.parseFmtp=function(t){const n={};let s;const r=t.substring(t.indexOf(" ")+1).split(";");for(let a=0;a<r.length;a++)s=r[a].trim().split("="),n[s[0].trim()]=s[1];return n},e.writeFmtp=function(t){let n="",s=t.payloadType;if(t.preferredPayloadType!==void 0&&(s=t.preferredPayloadType),t.parameters&&Object.keys(t.parameters).length){const r=[];Object.keys(t.parameters).forEach(a=>{t.parameters[a]!==void 0?r.push(a+"="+t.parameters[a]):r.push(a)}),n+="a=fmtp:"+s+" "+r.join(";")+`\r 9`}return n},e.parseRtcpFb=function(t){const n=t.substring(t.indexOf(" ")+1).split(" ");return{type:n.shift(),parameter:n.join(" ")}},e.writeRtcpFb=function(t){let n="",s=t.payloadType;return t.preferredPayloadType!==void 0&&(s=t.preferredPayloadType),t.rtcpFeedback&&t.rtcpFeedback.length&&t.rtcpFeedback.forEach(r=>{n+="a=rtcp-fb:"+s+" "+r.type+(r.parameter&&r.parameter.length?" "+r.parameter:"")+`\r 10`}),n},e.parseSsrcMedia=function(t){const n=t.indexOf(" "),s={ssrc:parseInt(t.substring(7,n),10)},r=t.indexOf(":",n);return r>-1?(s.attribute=t.substring(n+1,r),s.value=t.substring(r+1)):s.attribute=t.substring(n+1),s},e.parseSsrcGroup=function(t){const n=t.substring(13).split(" ");return{semantics:n.shift(),ssrcs:n.map(s=>parseInt(s,10))}},e.getMid=function(t){const n=e.matchPrefix(t,"a=mid:")[0];if(n)return n.substring(6)},e.parseFingerprint=function(t){const n=t.substring(14).split(" ");return{algorithm:n[0].toLowerCase(),value:n[1].toUpperCase()}},e.getDtlsParameters=function(t,n){return{role:"auto",fingerprints:e.matchPrefix(t+n,"a=fingerprint:").map(e.parseFingerprint)}},e.writeDtlsParameters=function(t,n){let s="a=setup:"+n+`\r 11`;return t.fingerprints.forEach(r=>{s+="a=fingerprint:"+r.algorithm+" "+r.value+`\r 12`}),s},e.parseCryptoLine=function(t){const n=t.substring(9).split(" ");return{tag:parseInt(n[0],10),cryptoSuite:n[1],keyParams:n[2],sessionParams:n.slice(3)}},e.writeCryptoLine=function(t){return"a=crypto:"+t.tag+" "+t.cryptoSuite+" "+(typeof t.keyParams=="object"?e.writeCryptoKeyParams(t.keyParams):t.keyParams)+(t.sessionParams?" "+t.sessionParams.join(" "):"")+`\r 13`},e.parseCryptoKeyParams=function(t){if(t.indexOf("inline:")!==0)return null;const n=t.substring(7).split("|");return{keyMethod:"inline",keySalt:n[0],lifeTime:n[1],mkiValue:n[2]?n[2].split(":")[0]:void 0,mkiLength:n[2]?n[2].split(":")[1]:void 0}},e.writeCryptoKeyParams=function(t){return t.keyMethod+":"+t.keySalt+(t.lifeTime?"|"+t.lifeTime:"")+(t.mkiValue&&t.mkiLength?"|"+t.mkiValue+":"+t.mkiLength:"")},e.getCryptoParameters=function(t,n){return e.matchPrefix(t+n,"a=crypto:").map(e.parseCryptoLine)},e.getIceParameters=function(t,n){const s=e.matchPrefix(t+n,"a=ice-ufrag:")[0],r=e.matchPrefix(t+n,"a=ice-pwd:")[0];return s&&r?{usernameFragment:s.substring(12),password:r.substring(10)}:null},e.writeIceParameters=function(t){let n="a=ice-ufrag:"+t.usernameFragment+`\r 14a=ice-pwd:`+t.password+`\r 15`;return t.iceLite&&(n+=`a=ice-lite\r 16`),n},e.parseRtpParameters=function(t){const n={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},r=e.splitLines(t)[0].split(" ");n.profile=r[2];for(let o=3;o<r.length;o++){const d=r[o],c=e.matchPrefix(t,"a=rtpmap:"+d+" ")[0];if(c){const l=e.parseRtpMap(c),u=e.matchPrefix(t,"a=fmtp:"+d+" ");switch(l.parameters=u.length?e.parseFmtp(u[0]):{},l.rtcpFeedback=e.matchPrefix(t,"a=rtcp-fb:"+d+" ").map(e.parseRtcpFb),n.codecs.push(l),l.name.toUpperCase()){case"RED":case"ULPFEC":n.fecMechanisms.push(l.name.toUpperCase());break}}}e.matchPrefix(t,"a=extmap:").forEach(o=>{n.headerExtensions.push(e.parseExtmap(o))});const a=e.matchPrefix(t,"a=rtcp-fb:* ").map(e.parseRtcpFb);return n.codecs.forEach(o=>{a.forEach(d=>{o.rtcpFeedback.find(l=>l.type===d.type&&l.parameter===d.parameter)||o.rtcpFeedback.push(d)})}),n},e.writeRtpDescription=function(t,n){let s="";s+="m="+t+" ",s+=n.codecs.length>0?"9":"0",s+=" "+(n.profile||"UDP/TLS/RTP/SAVPF")+" ",s+=n.codecs.map(a=>a.preferredPayloadType!==void 0?a.preferredPayloadType:a.payloadType).join(" ")+`\r 17`,s+=`c=IN IP4 0.0.0.0\r 18`,s+=`a=rtcp:9 IN IP4 0.0.0.0\r 19`,n.codecs.forEach(a=>{s+=e.writeRtpMap(a),s+=e.writeFmtp(a),s+=e.writeRtcpFb(a)});let r=0;return n.codecs.forEach(a=>{a.maxptime>r&&(r=a.maxptime)}),r>0&&(s+="a=maxptime:"+r+`\r 20`),n.headerExtensions&&n.headerExtensions.forEach(a=>{s+=e.writeExtmap(a)}),s},e.parseRtpEncodingParameters=function(t){const n=[],s=e.parseRtpParameters(t),r=s.fecMechanisms.indexOf("RED")!==-1,a=s.fecMechanisms.indexOf("ULPFEC")!==-1,o=e.matchPrefix(t,"a=ssrc:").map(h=>e.parseSsrcMedia(h)).filter(h=>h.attribute==="cname"),d=o.length>0&&o[0].ssrc;let c;const l=e.matchPrefix(t,"a=ssrc-group:FID").map(h=>h.substring(17).split(" ").map(f=>parseInt(f,10)));l.length>0&&l[0].length>1&&l[0][0]===d&&(c=l[0][1]),s.codecs.forEach(h=>{if(h.name.toUpperCase()==="RTX"&&h.parameters.apt){let p={ssrc:d,codecPayloadType:parseInt(h.parameters.apt,10)};d&&c&&(p.rtx={ssrc:c}),n.push(p),r&&(p=JSON.parse(JSON.stringify(p)),p.fec={ssrc:d,mechanism:a?"red+ulpfec":"red"},n.push(p))}}),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){const n={},s=e.matchPrefix(t,"a=ssrc:").map(o=>e.parseSsrcMedia(o)).filter(o=>o.attribute==="cname")[0];s&&(n.cname=s.value,n.ssrc=s.ssrc);const r=e.matchPrefix(t,"a=rtcp-rsize");n.reducedSize=r.length>0,n.compound=r.length===0;const a=e.matchPrefix(t,"a=rtcp-mux");return n.mux=a.length>0,n},e.writeRtcpParameters=function(t){let n="";return t.reducedSize&&(n+=`a=rtcp-rsize\r 21`),t.mux&&(n+=`a=rtcp-mux\r 22`),t.ssrc!==void 0&&t.cname&&(n+="a=ssrc:"+t.ssrc+" cname:"+t.cname+`\r 23`),n},e.parseMsid=function(t){let n;const s=e.matchPrefix(t,"a=msid:");if(s.length===1)return n=s[0].substring(7).split(" "),{stream:n[0],track:n[1]};const r=e.matchPrefix(t,"a=ssrc:").map(a=>e.parseSsrcMedia(a)).filter(a=>a.attribute==="msid");if(r.length>0)return n=r[0].value.split(" "),{stream:n[0],track:n[1]}},e.parseSctpDescription=function(t){const n=e.parseMLine(t),s=e.matchPrefix(t,"a=max-message-size:");let r;s.length>0&&(r=parseInt(s[0].substring(19),10)),isNaN(r)&&(r=65536);const a=e.matchPrefix(t,"a=sctp-port:");if(a.length>0)return{port:parseInt(a[0].substring(12),10),protocol:n.fmt,maxMessageSize:r};const o=e.matchPrefix(t,"a=sctpmap:");if(o.length>0){const d=o[0].substring(10).split(" ");return{port:parseInt(d[0],10),protocol:d[1],maxMessageSize:r}}},e.writeSctpDescription=function(t,n){let s=[];return t.protocol!=="DTLS/SCTP"?s=["m="+t.kind+" 9 "+t.protocol+" "+n.protocol+`\r 24`,`c=IN IP4 0.0.0.0\r 25`,"a=sctp-port:"+n.port+`\r 26`]:s=["m="+t.kind+" 9 "+t.protocol+" "+n.port+`\r 27`,`c=IN IP4 0.0.0.0\r 28`,"a=sctpmap:"+n.port+" "+n.protocol+` 65535\r 29`],n.maxMessageSize!==void 0&&s.push("a=max-message-size:"+n.maxMessageSize+`\r 30`),s.join("")},e.generateSessionId=function(){return Math.random().toString().substr(2,22)},e.writeSessionBoilerplate=function(t,n,s){let r;const a=n!==void 0?n:2;return t?r=t:r=e.generateSessionId(),`v=0\r 31o=`+(s||"thisisadapterortc")+" "+r+" "+a+` IN IP4 127.0.0.1\r 32s=-\r 33t=0 0\r 34`},e.getDirection=function(t,n){const s=e.splitLines(t);for(let r=0;r<s.length;r++)switch(s[r]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return s[r].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){const s=e.splitLines(t)[0].substring(2).split(" ");return{kind:s[0],port:parseInt(s[1],10),protocol:s[2],fmt:s.slice(3).join(" ")}},e.parseOLine=function(t){const s=e.matchPrefix(t,"o=")[0].substring(2).split(" ");return{username:s[0],sessionId:s[1],sessionVersion:parseInt(s[2],10),netType:s[3],addressType:s[4],address:s[5]}},e.isValidSDP=function(t){if(typeof t!="string"||t.length===0)return!1;const n=e.splitLines(t);for(let s=0;s<n.length;s++)if(n[s].length<2||n[s].charAt(1)!=="=")return!1;return!0},i.exports=e})(Yi)),Yi.exports}var Fc=Ku(),Xt=Du(Fc),Gu=Ud({__proto__:null,default:Xt},[Fc]);function ni(i){if(!i.RTCIceCandidate||i.RTCIceCandidate&&"foundation"in i.RTCIceCandidate.prototype)return;const 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){const s=new e(n),r=Xt.parseCandidate(n.candidate);for(const a in r)a in s||Object.defineProperty(s,a,{value:r[a]});return s.toJSON=function(){return{candidate:s.candidate,sdpMid:s.sdpMid,sdpMLineIndex:s.sdpMLineIndex,usernameFragment:s.usernameFragment}},s}return new e(n)},i.RTCIceCandidate.prototype=e.prototype,Ht(i,"icecandidate",t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new i.RTCIceCandidate(t.candidate),writable:"false"}),t))}function Is(i){!i.RTCIceCandidate||i.RTCIceCandidate&&"relayProtocol"in i.RTCIceCandidate.prototype||Ht(i,"icecandidate",e=>{if(e.candidate){const t=Xt.parseCandidate(e.candidate.candidate);t.type==="relay"&&(e.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[t.priority>>24])}return e})}function ii(i,e){if(!i.RTCPeerConnection||e.browser==="chrome"&&e.version>102||e.browser==="firefox"&&e.version>=113)return;"sctp"in i.RTCPeerConnection.prototype||Object.defineProperty(i.RTCPeerConnection.prototype,"sctp",{get(){return typeof this._sctp>"u"?null:this._sctp}});const t=function(o){if(!o||!o.sdp)return!1;const d=Xt.splitSections(o.sdp);return d.shift(),d.some(c=>{const l=Xt.parseMLine(c);return l&&l.kind==="application"&&l.protocol.indexOf("SCTP")!==-1})},n=function(o){const d=o.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(d===null||d.length<2)return-1;const c=parseInt(d[1],10);return c!==c?-1:c},s=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},r=function(o,d){let c=65536;e.browser==="firefox"&&e.version===57&&(c=65535);const l=Xt.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])){const d=n(arguments[0]),c=s(d),l=r(arguments[0],d);let u;c===0&&l===0?u=Number.POSITIVE_INFINITY:c===0||l===0?u=Math.max(c,l):u=Math.min(c,l);const h={};Object.defineProperty(h,"maxMessageSize",{get(){return u}}),this._sctp=h}return a.apply(this,arguments)}}function si(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(s,r){const a=s.send;s.send=function(){const d=arguments[0],c=d.length||d.size||d.byteLength;if(s.readyState==="open"&&r.sctp&&c>r.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+r.sctp.maxMessageSize+" bytes)");return a.apply(s,arguments)}}const n=i.RTCPeerConnection.prototype.createDataChannel;i.RTCPeerConnection.prototype.createDataChannel=function(){const r=n.apply(this,arguments);return t(r,this),r},Ht(i,"datachannel",s=>(t(s.channel,s.target),s))}function Ms(i){if(!i.RTCPeerConnection||"connectionState"in i.RTCPeerConnection.prototype)return;const e=i.RTCPeerConnection.prototype;Object.defineProperty(e,"connectionState",{get(){return{completed:"connected",checking:"connecting"}[this.iceConnectionState]||this.iceConnectionState},enumerable:!0,configurable:!0}),Object.defineProperty(e,"onconnectionstatechange",{get(){return this._onconnectionstatechange||null},set(t){this._onconnectionstatechange&&(this.removeEventListener("connectionstatechange",this._onconnectionstatechange),delete this._onconnectionstatechange),t&&this.addEventListener("connectionstatechange",this._onconnectionstatechange=t)},enumerable:!0,configurable:!0}),["setLocalDescription","setRemoteDescription"].forEach(t=>{const n=e[t];e[t]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=s=>{const r=s.target;if(r._lastConnectionState!==r.connectionState){r._lastConnectionState=r.connectionState;const a=new Event("connectionstatechange",s);r.dispatchEvent(a)}return s},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),n.apply(this,arguments)}})}function Ds(i,e){if(!i.RTCPeerConnection||e.browser==="chrome"&&e.version>=71||e.browser==="safari"&&e._safariVersion>=13.1)return;const t=i.RTCPeerConnection.prototype.setRemoteDescription;i.RTCPeerConnection.prototype.setRemoteDescription=function(s){if(s&&s.sdp&&s.sdp.indexOf(` 35a=extmap-allow-mixed`)!==-1){const r=s.sdp.split(` 36`).filter(a=>a.trim()!=="a=extmap-allow-mixed").join(` 37`);i.RTCSessionDescription&&s instanceof i.RTCSessionDescription?arguments[0]=new i.RTCSessionDescription({type:s.type,sdp:r}):s.sdp=r}return t.apply(this,arguments)}}function ri(i,e){if(!(i.RTCPeerConnection&&i.RTCPeerConnection.prototype))return;const t=i.RTCPeerConnection.prototype.addIceCandidate;!t||t.length===0||(i.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?(e.browser==="chrome"&&e.ver
37sion<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 ai(i,e){if(!(i.RTCPeerConnection&&i.RTCPeerConnection.prototype))return;const t=i.RTCPeerConnection.prototype.setLocalDescription;!t||t.length===0||(i.RTCPeerConnection.prototype.setLocalDescription=function(){let s=arguments[0]||{};if(typeof s!="object"||s.type&&s.sdp)return t.apply(this,arguments);if(s={type:s.type,sdp:s.sdp},!s.type)switch(this.signalingState){case"stable":case"have-local-offer":case"have-remote-pranswer":s.type="offer";break;default:s.type="answer";break}return s.sdp||s.type!=="offer"&&s.type!=="answer"?t.apply(this,[s]):(s.type==="offer"?this.createOffer:this.createAnswer).apply(this).then(a=>t.apply(this,[a]))})}var zu=Object.freeze({__proto__:null,removeExtmapAllowMixed:Ds,shimAddIceCandidateNullOrEmpty:ri,shimConnectionState:Ms,shimMaxMessageSize:ii,shimParameterlessSetLocalDescription:ai,shimRTCIceCandidate:ni,shimRTCIceCandidateRelayProtocol:Is,shimSendThrowTypeError:si});function Ju(){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};const n=pr,s=ju(e),r={browserDetails:s,commonShim:zu,extractVersion:kn,disableLog:Vu,disableWarnings:Wu,sdp:Gu};switch(s.browser){case"chrome":if(!aa||!Rs||!t.shimChrome)return n("Chrome shim is not included in this adapter release."),r;if(s.version===null)return n("Chrome shim can not determine version, not shimming."),r;n("adapter.js shimming chrome."),r.browserShim=aa,ri(e,s),ai(e),lc(e,s),uc(e),Rs(e,s),hc(e,s),gc(e,s),pc(e),mc(e,s),vc(e,s),ni(e),Is(e),Ms(e),ii(e,s),si(e,s),Ds(e,s);break;case"firefox":if(!oa||!Ps||!t.shimFirefox)return n("Firefox shim is not included in this adapter release."),r;n("adapter.js shimming firefox."),r.browserShim=oa,ri(e,s),ai(e),bc(e,s),Ps(e,s),kc(e,s),yc(e),Cc(e),Tc(e),Sc(e),Ec(e),_c(e,s),wc(e,s),Rc(e,s),Pc(e,s),ni(e),Ms(e),ii(e,s),si(e,s);break;case"safari":if(!ca||!t.shimSafari)return n("Safari shim is not included in this adapter release."),r;n("adapter.js shimming safari."),r.browserShim=ca,ri(e,s),ai(e),Nc(e),xc(e),Dc(e),Ic(e),Mc(e),Lc(e),Ac(e),Uc(e),ni(e),Is(e),ii(e,s),si(e,s),Ds(e,s);break;default:n("Unsupported browser!");break}return r}Ju({window:typeof window>"u"?void 0:window});var As,Bc;class _e extends(Bc=Promise){constructor(e){super(e)}catch(e){return super.catch(e)}static reject(e){return super.reject(e)}static all(e){return super.all(e)}static race(e){return super.race(e)}}As=_e;_e.resolve=i=>Reflect.get(Bc,"resolve",As).call(As,i);const $u=/version\/(\d+(\.?_?\d+)+)/i;let Xi;function we(i){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;if(typeof navigator>"u")return;const t=navigator.userAgent.toLowerCase();if(Xi===void 0||e){const n=Qu.find(s=>s.test.test(t));Xi=n?.describe(t)}return Xi}const Qu=[{test:/firefox|iceweasel|fxios/i,describe(i){return{name:"Firefox",version:oi(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,i),os:i.toLowerCase().includes("fxios")?"iOS":void 0,osVersion:Zi(i)}}},{test:/chrom|crios|crmo/i,describe(i){return{name:"Chrome",version:oi(/(?:chrome|chromium|crios|crmo)\/(\d+(\.?_?\d+)+)/i,i),os:i.toLowerCase().includes("crios")?"iOS":void 0,osVersion:Zi(i)}}},{test:/safari|applewebkit/i,describe(i){return{name:"Safari",version:oi($u,i),os:i.includes("mobile/")?"iOS":"macOS",osVersion:Zi(i)}}}];function oi(i,e){let t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:1;const n=e.match(i);return n&&n.length>=t&&n[t]||""}function Zi(i){return i.includes("mac os")?oi(/\(.+?(\d+_\d+(:?_\d+)?)/,i,1).replace(/_/g,"."):void 0}var Yu="2.21.0";const Xu=Yu,Zu=17,qc=0,Os=1,Vc=2,eh=Vc;class ft 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)}}class Ue extends ft{}var Q;(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"})(Q||(Q={}));class x extends Ue{constructor(e,t,n,s){super(1,e),this.name="ConnectionError",this.status=n,this.reason=t,this.context=s,this.reasonName=Q[t]}static notAllowed(e,t,n){return new x(e,Q.NotAllowed,t,n)}static timeout(e){return new x(e,Q.Timeout)}static leaveRequest(e,t){return new x(e,Q.LeaveRequest,void 0,t)}static internal(e,t){return new x(e,Q.InternalError,void 0,t)}static cancelled(e){return new x(e,Q.Cancelled)}static serverUnreachable(e,t){return new x(e,Q.ServerUnreachable,t)}static websocket(e,t,n){return new x(e,Q.WebSocket,t,n)}static serviceNotFound(e,t){return new x(e,Q.ServiceNotFound,void 0,t)}}class fr extends ft{constructor(e){super(21,e??"device is unsupported"),this.name="DeviceUnsupportedError"}}
37class lt extends ft{constructor(e){super(20,e??"track is invalid"),this.name="TrackInvalidError"}}class th extends ft{constructor(e){super(10,e||"unsupported server"),this.name="UnsupportedServer"}}class X extends ft{constructor(e){super(12,e||"unexpected connection state"),this.name="UnexpectedConnectionState"}}class Bt extends ft{constructor(e){super(13,e||"unable to negotiate"),this.name="NegotiationError"}}class nh extends ft{constructor(e){super(14,e||"unable to publish data"),this.name="PublishDataError"}}class la extends ft{constructor(e,t){super(15,e),this.name="PublishTrackError",this.status=t}}class ua extends Ue{constructor(e,t){super(15,e),this.name="SignalRequestError",this.reason=t,this.reasonName=typeof t=="string"?t:At[t]}}var ie;(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",i[i.HeaderTooLarge=9]="HeaderTooLarge",i[i.PayloadTooLarge=10]="PayloadTooLarge"})(ie||(ie={}));class ue extends Ue{constructor(e,t){super(16,e),this.name="DataStreamError",this.reason=t,this.reasonName=ie[t]}}class Gt extends ft{constructor(e){super(18,e),this.name="SignalReconnectError"}}var pi;(function(i){i.PermissionDenied="PermissionDenied",i.NotFound="NotFound",i.DeviceInUse="DeviceInUse",i.Other="Other"})(pi||(pi={}));(function(i){function e(t){if(t&&"name"in t)return t.name==="NotFoundError"||t.name==="DevicesNotFoundError"?i.NotFound:t.name==="NotAllowedError"||t.name==="PermissionDeniedError"?i.PermissionDenied:t.name==="NotReadableError"||t.name==="TrackStartError"?i.DeviceInUse:i.Other}i.getFailure=e})(pi||(pi={}));class ae{}ae.setTimeout=function(){return setTimeout(...arguments)};ae.setInterval=function(){return setInterval(...arguments)};ae.clearTimeout=function(){return clearTimeout(...arguments)};ae.clearInterval=function(){return clearInterval(...arguments)};var _;(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"})(_||(_={}));var M;(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"})(M||(M={}));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 ih(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))}class J{constructor(e,t,n,s,r){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:s,priority:r};else throw new TypeError("Unsupported options: provide at least width, height and maxBitrate")}get resolution(){return{width:this.width,height:this.height,frameRate:this.encoding.maxFramerate,aspectRatio:this.aspectRatio}}}const sh=["vp8","h264"],rh=["vp8","h264","vp9","av1","h265"];function Wc(i){return!!sh.find(e=>e===i)}const ah=Wc;var ha;(function(i){i[i.PREFER_REGRESSION=0]="PREFER_REGRESSION",i[i.SIMULCAST=1]="SIMULCAST",i[i.REGRESSION=2]="REGRESSION"})(ha||(ha={}));var Ns;(function(i){i.telephone={maxBitrate:12e3}
37,i.speech={maxBitrate:24e3},i.music={maxBitrate:48e3},i.musicStereo={maxBitrate:64e3},i.musicHighQuality={maxBitrate:96e3},i.musicHighQualityStereo={maxBitrate:128e3}})(Ns||(Ns={}));const On={h90:new J(160,90,9e4,20),h180:new J(320,180,16e4,20),h216:new J(384,216,18e4,20),h360:new J(640,360,45e4,20),h540:new J(960,540,8e5,25),h720:new J(1280,720,17e5,30),h1080:new J(1920,1080,3e6,30),h1440:new J(2560,1440,5e6,30),h2160:new J(3840,2160,8e6,30)},Ls={h120:new J(160,120,7e4,20),h180:new J(240,180,125e3,20),h240:new J(320,240,14e4,20),h360:new J(480,360,33e4,20),h480:new J(640,480,5e5,20),h540:new J(720,540,6e5,25),h720:new J(960,720,13e5,30),h1080:new J(1440,1080,23e5,30),h1440:new J(1920,1440,38e5,30)},gr={h360fps3:new J(640,360,2e5,3,"medium"),h360fps15:new J(640,360,4e5,15,"medium"),h720fps5:new J(1280,720,8e5,5,"medium"),h720fps15:new J(1280,720,15e5,15,"medium"),h720fps30:new J(1280,720,2e6,30,"medium"),h1080fps15:new J(1920,1080,25e5,15,"medium"),h1080fps30:new J(1920,1080,5e6,30,"medium"),original:new J(0,0,7e6,30,"medium")};function jc(i,e,t){var n,s,r,a;const o=Gc(i??{}),d=o.optionsWithoutProcessor,c=o.audioProcessor,l=o.videoProcessor,u=e?.processor,h=t?.processor,p=d??{};return p.audio===!0&&(p.audio={}),p.video===!0&&(p.video={}),p.audio&&(xs(p.audio,e),(n=(r=p.audio).deviceId)!==null&&n!==void 0||(r.deviceId={ideal:"default"}),(c||u)&&(p.audio.processor=c??u)),p.video&&(xs(p.video,t),(s=(a=p.video).deviceId)!==null&&s!==void 0||(a.deviceId={ideal:"default"}),(l||h)&&(p.video.processor=l??h)),p}function xs(i,e){return Object.keys(e).forEach(t=>{i[t]===void 0&&(i[t]=e[t])}),i}function vr(i){var e,t,n,s;const r={};if(i.video)if(typeof i.video=="object"){const a={},o=a,d=i.video;Object.keys(d).forEach(c=>{c==="resolution"?xs(o,d.resolution):o[c]=d[c]}),r.video=a,(e=(n=r.video).deviceId)!==null&&e!==void 0||(n.deviceId={ideal:"default"})}else r.video=i.video?{deviceId:{ideal:"default"}}:!1;else r.video=!1;return i.audio?typeof i.audio=="object"?(r.audio=i.audio,(t=(s=r.audio).deviceId)!==null&&t!==void 0||(s.deviceId={ideal:"default"})):r.audio={deviceId:{ideal:"default"}}:r.audio=!1,r}function Hc(i){return m(this,arguments,void 0,function(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:200;return(function*(){const n=Kc();if(n){const s=n.createAnalyser();s.fftSize=2048;const r=s.frequencyBinCount,a=new Uint8Array(r);n.createMediaStreamSource(new MediaStream([e.mediaStreamTrack])).connect(s),yield Se(t),s.getByteTimeDomainData(a);const d=a.some(c=>c!==128&&c!==0);return n.close(),!d}return!1})()})}function Kc(){var i;const e=typeof window<"u"&&(window.AudioContext||window.webkitAudioContext);if(e){const t=new e({latencyHint:"interactive"});if(t.state==="suspended"&&typeof window<"u"&&(!((i=window.document)===null||i===void 0)&&i.body)){const n=()=>m(this,void 0,void 0,function*(){var s;try{t.state==="suspended"&&(yield t.resume())}catch(r){console.warn("Error trying to auto-resume audio context",r)}finally{(s=window.document.body)===null||s===void 0||s.removeEventListener("click",n)}});t.addEventListener("statechange",()=>{var s;t.state==="closed"&&((s=window.document.body)===null||s===void 0||s.removeEventListener("click",n))}),window.document.body.addEventListener("click",n)}return t}}function oh(i){return i==="audioinput"?C.Source.Microphone:i==="videoinput"?C.Source.Camera:C.Source.Unknown}function Us(i){return i===C.Source.Microphone?"audioinput":i===C.Source.Camera?"videoinput":void 0}function ch(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,jt()?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 Cn(i){return i.split("/")[1].toLowerCase()}function dh(i){const e=[];
37return i.forEach(t=>{t.track!==void 0&&e.push(new cr({cid:t.track.mediaStreamID,track:t.trackInfo}))}),e}function V(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?V(i.track):{})}}function lh(){return typeof RTCRtpReceiver<"u"&&typeof RTCRtpReceiver.prototype.getSynchronizationSources=="function"}function uh(i,e){var t;i===void 0&&(i={}),e===void 0&&(e={});const n=[...Object.keys(e),...Object.keys(i)],s={};for(const r of n)i[r]!==e[r]&&(s[r]=(t=e[r])!==null&&t!==void 0?t:"");return s}function Gc(i){const e=Object.assign({},i);let 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:ih(e)}}function hh(i){switch(i){case le.CAMERA:return C.Source.Camera;case le.MICROPHONE:return C.Source.Microphone;case le.SCREEN_SHARE:return C.Source.ScreenShare;case le.SCREEN_SHARE_AUDIO:return C.Source.ScreenShareAudio;default:return C.Source.Unknown}}function pa(i,e){return i.width*i.height<e.width*e.height}function ph(i,e){var t;return(t=i.layers)===null||t===void 0?void 0:t.find(n=>n.quality===e)}const mh=5e3,fn=[];var Ae;(function(i){i[i.LOW=0]="LOW",i[i.MEDIUM=1]="MEDIUM",i[i.HIGH=2]="HIGH"})(Ae||(Ae={}));class C extends De.EventEmitter{get streamState(){return this._streamState}setStreamState(e){this._streamState!==e&&this.log.debug("stream state changed: ".concat(this._streamState," -> ").concat(e)),this._streamState=e}constructor(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};var s;super(),this.attachedElements=[],this.isMuted=!1,this._streamState=C.StreamState.Active,this.isInBackground=!1,this._currentBitrate=0,this.log=U,this.appVisibilityChangedListener=()=>{this.backgroundTimeout&&clearTimeout(this.backgroundTimeout),document.visibilityState==="hidden"?this.backgroundTimeout=setTimeout(()=>this.handleAppVisibilityChanged(),mh):this.handleAppVisibilityChanged()},this.loggerContextCb=n.loggerContextCb,this.log=ke((s=n.loggerName)!==null&&s!==void 0?s:ce.Track,()=>this.logContext),this.setMaxListeners(100),this.kind=t,this._mediaStreamTrack=e,this._mediaStreamID=e.id,this.source=C.Source.Unknown}get logContext(){var e;return Object.assign(Object.assign({},(e=this.loggerContextCb)===null||e===void 0?void 0:e.call(this)),V(this))}get currentBitrate(){return this._currentBitrate}get mediaStreamTrack(){return this._mediaStreamTrack}get mediaStreamID(){return this._mediaStreamID}attach(e){let t="audio";this.kind===C.Kind.Video&&(t="video"),this.attachedElements.length===0&&this.kind===C.Kind.Video&&this.addAppVisibilityListener(),e||(t==="audio"&&(fn.forEach(r=>{r.parentElement===null&&!e&&(e=r)}),e&&fn.splice(fn.indexOf(e),1)),e||(e=document.createElement(t))),this.attachedElements.includes(e)||this.attachedElements.push(e),Jt(this.mediaStreamTrack,e);const n=e.srcObject.getTracks(),s=n.some(r=>r.kind==="audio");return e.play().then(()=>{this.emit(s?P.AudioPlaybackStarted:P.VideoPlaybackStarted)}).catch(r=>{r.name==="NotAllowedError"?this.emit(s?P.AudioPlaybackFailed:P.VideoPlaybackFailed,r):r.name==="AbortError"?this.log.debug("".concat(s?"audio":"video"," playback aborted, likely due to new play request")):this.log.warn("could not playback ".concat(s?"audio":"video"),{error:r}),s&&e&&n.some(a=>a.kind==="video")&&r.name==="NotAllowedError"&&(e.muted=!0,e.play().catch(()=>{}))}),this.emit(P.ElementAttached,e),e}detach(e){try{if(e){Zt(this.mediaStreamTrack,e);const n=this.attachedElements.indexOf(e);return n>=0&&(this.attachedElements.splice(n,1),this.recycleElement(e),this.emit(P.ElementDetached,e)),e}const t=[];
37return this.attachedElements.forEach(n=>{Zt(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.log.debug("stopping track"),this.stopMonitor(),this._mediaStreamTrack.stop()}enable(){this._mediaStreamTrack.enabled=!0}disable(){this._mediaStreamTrack.enabled=!1}stopMonitor(){this.monitorInterval&&clearInterval(this.monitorInterval),this.timeSyncHandle&&cancelAnimationFrame(this.timeSyncHandle)}updateLoggerOptions(e){e.loggerContextCb&&(this.loggerContextCb=e.loggerContextCb),e.loggerName&&(this.log=ke(e.loggerName,()=>this.logContext))}recycleElement(e){if(e instanceof HTMLAudioElement){let t=!0;e.pause(),fn.forEach(n=>{n.parentElement||(t=!1)}),t&&fn.push(e)}}handleAppVisibilityChanged(){return m(this,void 0,void 0,function*(){this.isInBackground=document.visibilityState==="hidden",!this.isInBackground&&this.kind===C.Kind.Video&&setTimeout(()=>this.attachedElements.forEach(e=>e.play().catch(()=>{})),0)})}addAppVisibilityListener(){Me()?(this.isInBackground=document.visibilityState==="hidden",document.addEventListener("visibilitychange",this.appVisibilityChangedListener)):this.isInBackground=!1}removeAppVisibilityListener(){Me()&&document.removeEventListener("visibilitychange",this.appVisibilityChangedListener)}}function Jt(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(s=>{t.removeTrack(s)}),t.addTrack(i)),(!jt()||!(e instanceof HTMLVideoElement))&&(e.autoplay=!0),e.muted=t.getAudioTracks().length===0,e instanceof HTMLVideoElement&&(e.playsInline=!0),e.srcObject!==t&&(e.srcObject=t,(jt()||Wt())&&e instanceof HTMLVideoElement&&setTimeout(()=>{e.srcObject=t,e.play().catch(()=>{})},0))}function Zt(i,e){if(e.srcObject instanceof MediaStream){const t=e.srcObject;t.removeTrack(i),t.getTracks().length>0?e.srcObject=t:e.srcObject=null}}(function(i){let e;(function(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 s(c){switch(c){case e.Audio:return Ve.AUDIO;case e.Video:return Ve.VIDEO;default:return Ve.DATA}}i.kindToProto=s;function r(c){switch(c){case Ve.AUDIO:return e.Audio;case Ve.VIDEO:return e.Video;default:return e.Unknown}}i.kindFromProto=r;function a(c){switch(c){case t.Camera:return le.CAMERA;case t.Microphone:return le.MICROPHONE;case t.ScreenShare:return le.SCREEN_SHARE;case t.ScreenShareAudio:return le.SCREEN_SHARE_AUDIO;default:return le.UNKNOWN}}i.sourceToProto=a;function o(c){switch(c){case le.CAMERA:return t.Camera;case le.MICROPHONE:return t.Microphone;case le.SCREEN_SHARE:return t.ScreenShare;case le.SCREEN_SHARE_AUDIO:return t.ScreenShareAudio;default:return t.Unknown}}i.sourceFromProto=o;function d(c){switch(c){case Ss.ACTIVE:return n.Active;case Ss.PAUSED:return n.Paused;default:return n.Unknown}}i.streamStateFromProto=d})(C||(C={}));const fh="|",ma="https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension";function gh(i){const e=i.split(fh);return e.length>1?[e[0],i.substr(e[0].length+1)]:[i,""]}function Se(i){return new _e(e=>ae.setTimeout(e,i))}function Fs(){return"addTransceiver"in RTCPeerConnection.prototype}function Bs(){return"addTrack"in RTCPeerConnection.prototype}function vh(){if(!("getCapabilities"in RTCRtpSender)||jt()||Wt())return!1;const i=RTCRtpSender.getCapabilities("video");let e=!1;if(i){for(const t of i.codecs)if(t.mimeType.toLowerCase()==="video/av1"){e=!0;break}}return e}function bh(){if(!("getCapabilities"in RTCRtpSender)||Wt())return!1;if(jt()){const t=we();if(t?.version&&nt(t.version,"16")<0||t?.os==="iOS"&&t?.osVersion&&nt(t.osVersion,"16")<0)return!1}const i=RTCRtpSender.getCapabilities("video");let e=!1;if(i){for(const t of i.codecs)if(t.mimeType.toLowerCase()==="video/vp9"){e=!0;break}}return e}function Ze(i){return i==="av1"||i==="vp9"}function qs(i){return!document||Nn()?!1:(i||(i=document.createElement("audio")),"setSinkId"in i)}function yh(){return typeof RTCPeerConnection>"u"?!1:Fs()||Bs()}function Wt(){var i;return((i=we())===null||i===void 0?void 0:i.name)==="Firefox"}function kh(){const i=we();return!!i&&i.name==="Chrome"&&i.os!=="iOS"}function Vs(){return typeof window<"u"&&typeof window.RTCRtpScriptTransform<"u"&&!kh()}function jt(){var i;return((i=we())===null||i===void 0?void 0:i.name)==="Safari"}function Nn(){const i=we();return i?.name==="Safari"||i?.os==="iOS"}function Th(){const i=we();return i?.name==="Safari"&&i.version.startsWith("17.")||i?.os==="iOS"&&!!i?.osVersion&&nt(i.osVersion,"17")>=0}
37function Sh(i){return i||(i=we()),i?.name==="Safari"&&nt(i.version,"18.3")>0||i?.os==="iOS"&&!!i?.osVersion&&nt(i.osVersion,"18.3")>0}function zc(){var i,e;return Me()?(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 Ch(){const i=we(),e="17.2";if(i)return i.name!=="Safari"&&i.os!=="iOS"||i.os==="iOS"&&i.osVersion&&nt(i.osVersion,e)>=0?!0:i.name==="Safari"&&nt(i.version,e)>=0}function Me(){return typeof document<"u"}function Je(){return navigator.product=="ReactNative"}function dn(i){return i.hostname.endsWith(".livekit.cloud")||i.hostname.endsWith(".livekit.run")}function es(i){return dn(i)?i.hostname.split(".")[0]:null}function Jc(){if(global&&global.LiveKitReactNativeGlobal)return global.LiveKitReactNativeGlobal}function $c(){if(!Je())return;let i=Jc();if(i)return i.platform}function fa(){if(Me())return window.devicePixelRatio;if(Je()){let i=Jc();if(i)return i.devicePixelRatio}return 1}function nt(i,e){const t=i.split("."),n=e.split("."),s=Math.min(t.length,n.length);for(let r=0;r<s;++r){const a=parseInt(t[r],10),o=parseInt(n[r],10);if(a>o)return 1;if(a<o)return-1;if(r===s-1&&a===o)return 0}return i===""&&e!==""?-1:e===""?1:t.length==n.length?0:t.length<n.length?-1:1}function Eh(i){for(const e of i)e.target.handleResize(e)}function _h(i){for(const e of i)e.target.handleVisibilityChanged(e)}let ts=null;const ga=()=>(ts||(ts=new ResizeObserver(Eh)),ts);let ns=null;const va=()=>(ns||(ns=new IntersectionObserver(_h,{root:null,rootMargin:"0px"})),ns);function wh(i){var e;const t=new Wo({capabilities:i,sdk:jo.JS,protocol:Zu,clientProtocol:eh,version:Xu});return Je()&&(t.os=(e=$c())!==null&&e!==void 0?e:""),t}function ba(){let i=arguments.length>0&&arguments[0]!==void 0?arguments[0]:16,e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:16,t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1,n=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1;const s=document.createElement("canvas");s.width=i,s.height=e;const r=s.getContext("2d");r?.fillRect(0,0,s.width,s.height),n&&r&&(r.beginPath(),r.arc(i/2,e/2,50,0,Math.PI*2,!0),r.closePath(),r.fillStyle="grey",r.fill());const o=s.captureStream().getTracks(),d=L(o,1),c=d[0];if(!c)throw Error("Could not get empty media stream video track");return c.enabled=t,c}let gn;function is(){if(!gn){const t=new AudioContext,n=t.createOscillator(),s=t.createGain();s.gain.setValueAtTime(0,0);const r=t.createMediaStreamDestination();n.connect(s),s.connect(r),n.start();var i=r.stream.getAudioTracks(),e=L(i,1);if(gn=e[0],!gn)throw Error("Could not get empty media stream audio track");gn.enabled=!1}return gn.clone()}class ye{get isResolved(){return this._isResolved}constructor(e,t){this._isResolved=!1,this.onFinally=t,this.promise=new Promise((n,s)=>m(this,void 0,void 0,function*(){this.resolve=n,this.reject=s,e&&(yield e(n,s))})).finally(()=>{var n;this._isResolved=!0,(n=this.onFinally)===null||n===void 0||n.call(this)})}}function Qc(i){return rh.includes(i)}function en(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 Rh(i){return i.startsWith("http")?i.replace(/^(http)/,"ws"):i}function Ln(i){return i.startsWith("ws")?i.replace(/^(ws)/,"http"):i}function Ph(i,e){return i.segments.map(t=>{let n=t.id,s=t.text,r=t.language,a=t.startTime,o=t.endTime,d=t.final;var c;const 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:s,startTime:Number.parseInt(a.toString()),endTime:Number.parseInt(o.toString()),final:d,language:r,firstReceivedTime:l,lastReceivedTime:u}})}function Ih(i){const e=i.id,t=i.timestamp,n=i.message,s=i.editTimestamp;return{id:e,timestamp:Number.parseInt(t.toString()),editTimestamp:s?Number.parseInt(s.toString()):void 0,message:n}}function ya(i){switch(i.reason){case Q.LeaveRequest:return i.context;case Q.Cancelled:return Ke.CLIENT_INITIATED;case Q.NotAllowed:return Ke.USER_REJECTED;case Q.ServerUnreachable:return Ke.JOIN_FAILURE;default:return Ke.UNKNOWN_REASON}}function Ot(i){return i!==void 0?Number(i):void 0}function ze(i){return i!==void 0?BigInt(i):void 0}function tn(i){return!!i&&!(i instanceof MediaStreamTrack)&&i.isLocal}function tt(i){return!!i&&i.kind==C.Kind.Audio}function mt(i){return!!i&&i.kind==C.Kind.Video}function Qe(i){return tn(i)&&mt(i)}function st(i){return tn(i)&&tt(i)}function Ws(i){return!!i&&!i.isLocal}function Mh(i){return!!i&&!i.isLocal}function ss(i){return Ws(i)&&mt(i)}function Dh(i){return i.isLocal}function Ah(i,e){const t=[];let n=new TextEncoder().encode(i);for(;n.length>e;){let s=e;for(;s>0;){const r=n[s];if(r!==void 0&&(r&192)!==128)break;s--}t.push(n.slice(0,s)),n=n.slice(s)}return n.length>0&&t.push(n),t}function ci(i){return new ReadableStream({start(e){e.enqueue(i),e.close()}})}function Oh(i,e){return ac(this,arguments,function*(){const n=i.getReader();let s=new Uint8Array(0);try{for(;;){const r=yield pt(n.read()),a=r.done,o=r.value;if(a)break;if(o.byteLength===0)continue;const d=new Uint8Array(s.byteLength+o.byteLength);for(d.set(s),d.set(o,s.byteLength),s=d;s.byteLength>=e;)yield yield pt(s.slice(0,e)),s=s.slice(e)}s.byteLength>0&&(yield yield pt(s))}finally{n.releaseLock()}})}function Nh(i){var e;const t=i.get("Cache-Control");if(t){const n=(e=t.match(/(?:^|[,\s])max-age=(\d+)/))===null||e===void 0?void 0:e[1];if(n)return parseInt(n,10)}}function Et(){return typeof CompressionStream<"u"}function Lh(){return Et()&&!Wt()}function xh(i,e){let t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1;const n=Uh(i,e);return t?n:br(n,"v1")}function Uh(i,e){const t=new URL(Rh(i));return e.forEach((n,s)=>{t.searchParams.set(s,n)}),br(t,"rtc")}function Fh(i){const e=new URL(Ln(i));return br(e,"validate")}function Yc(i){return i.endsWith("/")?i:"".concat(i,"/")}function br(i,e){return i.pathname="".concat(Yc(i.pathname)).concat(e),i}function ka(i){if(typeof i=="string")return Zr.fromJson(JSON.parse(i),{ignoreUnknownFields:!0});if(i instanceof ArrayBuffer)return Zr.fromBinary(new Uint8Array(i));throw new Error("could not decode websocket message: ".concat(typeof i))}function Bh(i){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"Unknown reason";if(!(i instanceof AbortSignal))return e;const 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}}const qh=10,vn="lk_e2ee",Vh="LKFrameEncryptionKey",Wh={sharedKey:!1,ratchetSalt:Vh,ratchetWindowSize:8,failureTolerance:qh,keyringSize:16,keySize:128};var _t;(function(i){i.SetKey="setKey",i.RatchetRequest="ratchetRequest",i.KeyRatcheted="keyRatcheted"})(_t||(_t={}));var Ta;(function(i){i.KeyRatcheted="keyRatcheted"})(Ta||(Ta={}));var yt;(function(i){i.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",i.EncryptionError="encryptionError"})(yt||(yt={}));var Sa;(function(i){i.Error="cryptorError"})(Sa||(Sa={}));function jh(){return yr()||Hh()}function Hh(){return typeof window<"u"&&typeof window.RTCRtpScriptTransform<"u"}function yr(){return typeof window<"u"&&typeof window.RTCRtpSender<"u"&&typeof window.RTCRtpSender.prototype.createEncodedStreams<"u"}function Kh(i){var e,t,n,s,r;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"&&((s=i.value)===null||s===void 0?void 0:s.case)!=="transcription"&&((r=i.value)===null||r===void 0?void 0:r.case)!=="encryptedPacket")return new Lo({value:i.value})}class of extends De.EventEmitter{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};super(),this.latestManuallySetKeyIndex=0,this.onKeyRatcheted=(t,n,s)=>{U.debug("key ratcheted event received",{ratchetResult:t,participantId:n,keyIndex:s})},this.keyInfoMap=new Map,this.options=Object.assign(Object.assign({},Wh),e),this.on(_t.KeyRatcheted,this.onKeyRatcheted)}onSetEncryptionKey(e,t,n){const s={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),s),n!==void 0&&(this.latestManuallySetKeyIndex=n),this.emit
37(_t.SetKey,s,n!==void 0)}getKeys(){return Array.from(this.keyInfoMap.values())}getLatestManuallySetKeyIndex(){return this.latestManuallySetKeyIndex}getOptions(){return this.options}ratchetKey(e,t){this.emit(_t.RatchetRequest,e,t)}}var Ca;(function(i){i[i.InvalidKey=0]="InvalidKey",i[i.MissingKey=1]="MissingKey",i[i.InternalError=2]="InternalError"})(Ca||(Ca={}));function xn(){return Vs()}function Un(i){return!!i?.worker&&(yr()||xn())}function mi(i){return!!(i?.timestamp||i?.frameId)}function Gh(i){const e=[];return i?.timestamp&&e.push(cn.PTF_USER_TIMESTAMP),i?.frameId&&e.push(cn.PTF_FRAME_ID),e}function zh(i){if(!i||i.length===0)return;const e={};return i.includes(cn.PTF_USER_TIMESTAMP)&&(e.timestamp=!0),i.includes(cn.PTF_FRAME_ID)&&(e.frameId=!0),e.timestamp||e.frameId?e:void 0}function kr(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,s;let r;const a=(n=t.isImmediate)!==null&&n!==void 0?n:!1,o=(s=t.callback)!==null&&s!==void 0?s:!1,d=t.maxWait;let c=Date.now(),l=[];function u(){if(d!==void 0){const p=Date.now()-c;if(p+e>=d)return d-p}return e}const h=function(){for(var p=arguments.length,f=new Array(p),g=0;g<p;g++)f[g]=arguments[g];const k=this;return new Promise((T,S)=>{const N=function(){if(r=void 0,c=Date.now(),!a){const y=i.apply(k,f);o&&o(y),l.forEach(E=>{let I=E.resolve;return I(y)}),l=[]}},v=a&&r===void 0;if(r!==void 0&&ae.clearTimeout(r),r=ae.setTimeout(N,u()),v){const y=i.apply(k,f);return o&&o(y),T(y)}l.push({resolve:T,reject:S})})};return h.cancel=function(p){r!==void 0&&ae.clearTimeout(r),l.forEach(f=>{let g=f.reject;return g(p)}),l=[]},h}const Tr=2e3;function Ni(i,e){if(!e)return 0;let t,n;return"bytesReceived"in i?(t=i.bytesReceived,n=e.bytesReceived):"bytesSent"in i&&(t=i.bytesSent,n=e.bytesSent),t===void 0||n===void 0||i.timestamp===void 0||e.timestamp===void 0?0:(t-n)*8*1e3/(i.timestamp-e.timestamp)}class Xc extends C{constructor(e,t,n,s,r){super(e,n,r),this.sid=t,this.receiver=s}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;const 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 m(this,void 0,void 0,function*(){var e;return!((e=this.receiver)===null||e===void 0)&&e.getStats?yield this.receiver.getStats():void 0})}setPlayoutDelay(e){this.receiver?"playoutDelayHint"in this.receiver?this.receiver.playoutDelayHint=e:this.log.warn("Playout delay not supported in this browser"):this.log.warn("Cannot set playout delay, track already ended")}getPlayoutDelay(){if(this.receiver){if("playoutDelayHint"in this.receiver)return this.receiver.playoutDelayHint;this.log.warn("Playout delay not supported in this browser")}else this.log.warn("Cannot get playout delay, track already ended");return 0}startMonitor(){this.monitorInterval||(this.monitorInterval=setInterval(()=>this.monitorReceiver(),Tr)),lh()&&this.registerTimeSyncUpdate()}registerTimeSyncUpdate(){const e=()=>{var t;this.timeSyncHandle=requestAnimationFrame(()=>e());const n=(t=this.receiver)===null||t===void 0?void 0:t.getSynchronizationSources()[0];if(n){const s=n.timestamp,r=n.rtpTimestamp;
vendor: 4,147 bytes, line 37
37r&&this.rtpTimestamp!==r&&(this.emit(P.TimeSyncUpdate,{timestamp:s,rtpTimestamp:r}),this.rtpTimestamp=r)}};e()}}const rs=100;class Sr extends Xc{constructor(e,t,n,s,r){super(e,t,C.Kind.Video,n,r),this.elementInfos=[],this.monitorReceiver=()=>m(this,void 0,void 0,function*(){if(!this.receiver){this._currentBitrate=0;return}const a=yield this.getReceiverStats();a&&this.prevStats&&this.receiver&&(this._currentBitrate=Ni(a,this.prevStats)),this.prevStats=a}),this.debouncedHandleResize=kr(()=>{this.updateDimensions()},rs),this.adaptiveStreamSettings=s}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===C.StreamState.Active&&this.updateVisibility()}get mediaStreamTrack(){return this._mediaStreamTrack}setMuted(e){super.setMuted(e),this.attachedElements.forEach(t=>{e?Zt(this._mediaStreamTrack,t):Jt(this._mediaStreamTrack,t)})}attach(e){if(e?super.attach(e):e=super.attach(),this.adaptiveStreamSettings&&this.elementInfos.find(t=>t.element===e)===void 0){const t=new Jh(e);this.observeElementInfo(t)}return e}observeElementInfo(e){this.adaptiveStreamSettings&&this.elementInfos.find(t=>t===e)===void 0?(e.handleResize=()=>{this.debouncedHandleResize()},e.handleVisibilityChanged=()=>{this.updateVisibility()},this.elementInfos.push(e),e.observe(),this.debouncedHandleResize(),this.updateVisibility()):this.log.warn("visibility resize observer not triggered",this.logContext)}stopObservingElementInfo(e){if(!this.isAdaptiveStream){this.log.warn("stopObservingElementInfo ignored",this.logContext);return}const t=this.elementInfos.filter(n=>n===e);for(const 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);const t=super.detach();for(const n of t)this.stopObservingElement(n);return t}getDecoderImplementation(){var e;return(e=this.prevStats)===null||e===void 0?void 0:e.decoderImplementation}getReceiverStats(){return m(this,void 0,void 0,function*(){if(!this.receiver||!this.receiver.getStats)return;const e=yield this.receiver.getStats();let t,n="",s=new Map;return e.forEach(r=>{r.type==="inbound-rtp"?(n=r.codecId,t={type:"video",streamId:r.id,framesDecoded:r.framesDecoded,framesDropped:r.framesDropped,framesReceived:r.framesReceived,packetsReceived:r.packetsReceived,packetsLost:r.packetsLost,frameWidth:r.frameWidth,frameHeight:r.frameHeight,pliCount:r.pliCount,firCount:r.firCount,nackCount:r.nackCount,jitter:r.jitter,timestamp:r.timestamp,bytesReceived:r.bytesReceived,decoderImplementation:r.decoderImplementation}):r.type==="codec"&&s.set(r.id,r)}),t&&n!==""&&s.get(n)&&(t.mimeType=s.get(n).mimeType),t})}stopObservingElement(e){const t=this.elementInfos.filter(n=>n.element===e);for(const n of t)this.stopObservingElementInfo(n)}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return m(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),this.isAdaptiveStream&&this.updateVisibility()})}updateVisibility(e){var t,n;const s=this.elementInfos.reduce((d,c)=>Math.max(d,c.visibilityChangedAt||0),0),r=!((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)&&!r||a;if(!(this.lastVisible===o&&!e)){if(!o&&Date.now()-s<rs){ae.setTimeout(()=>{this.updateVisibility()},rs);return}this.lastVisible=o,this.emit(P.VisibilityChanged,o,this)}}updateDimensions(){var e,t;let n=0,s=0;const r=this.getPixelDensity();for(const a of this.elementInfos){const o=a.width()*r,d=a.height()*r;o+d>n+s&&(n=o,s=d)}((e=this.lastDimensions)===null||e===void 0?void 0:e.width)===n&&((t=this.lastDimensions)===null||t===void 0?void 0:t.height)===s||(this.lastDimensions={width:n,height:s}
37,this.emit(P.VideoDimensionsChanged,this.lastDimensions,this))}getPixelDensity(){var e;const t=(e=this.adaptiveStreamSettings)===null||e===void 0?void 0:e.pixelDensity;return t==="screen"?fa():t||(fa()>2?2:1)}}class Jh{get visible(){return this.isPiP||this.isIntersecting}get pictureInPicture(){return this.isPiP}constructor(e,t){this.onVisibilityChanged=n=>{var s;const r=n.target,a=n.isIntersecting;r===this.element&&(this.isIntersecting=a,this.isPiP=bn(this.element),this.visibilityChangedAt=Date.now(),(s=this.handleVisibilityChanged)===null||s===void 0||s.call(this))},this.onEnterPiP=()=>{var n,s;(s=(n=window.documentPictureInPicture)===null||n===void 0?void 0:n.window)===null||s===void 0||s.addEventListener("pagehide",this.onLeavePiP),queueMicrotask(()=>{requestAnimationFrame(()=>{var r;this.isPiP=bn(this.element),(r=this.handleVisibilityChanged)===null||r===void 0||r.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??js(e),this.isPiP=Me()&&bn(e),this.visibilityChangedAt=0}width(){return this.element.clientWidth}height(){return this.element.clientHeight}observe(){var e,t,n;this.isIntersecting=js(this.element),this.isPiP=bn(this.element),this.element.handleResize=()=>{var s;(s=this.handleResize)===null||s===void 0||s.call(this)},this.element.handleVisibilityChanged=this.onVisibilityChanged,va().observe(this.element),ga().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,s,r;(e=va())===null||e===void 0||e.unobserve(this.element),(t=ga())===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),(r=(s=window.documentPictureInPicture)===null||s===void 0?void 0:s.window)===null||r===void 0||r.removeEventListener("pagehide",this.onLeavePiP)}}function bn(i){var e,t;return document.pictureInPictureElement===i?!0:!((e=window.documentPictureInPicture)===null||e===void 0)&&e.window?js(i,(t=window.documentPictureInPicture)===null||t===void 0?void 0:t.window):!1}function js(i,e){const t=e||window;let n=i.offsetTop,s=i.offsetLeft;const r=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,s+=i.offsetLeft;return n<t.pageYOffset+t.innerHeight&&s<t.pageXOffset+t.innerWidth&&n+a>t.pageYOffset&&s+r>t.pageXOffset&&!d&&l!=="none"}class $h extends De.EventEmitter{constructor(e,t){super(),this.decryptDataRequests=new Map,this.encryptDataRequests=new Map,this.onWorkerMessage=n=>{var s,r;const a=n.data,o=a.kind,d=a.data;switch(o){case"error":if(U.error(d.error.message),d.uuid){const u=this.decryptDataRequests.get(d.uuid);if(u?.reject){u.reject(d.error);break}const h=this.encryptDataRequests.get(d.uuid);if(h?.reject){h.reject(d.error);break}}this.emit(yt.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===((s=this.room)===null||s===void 0?void 0:s.localParticipant.identity))this.emit(yt.ParticipantEncryptionStatusChanged,d.enabled,this.room.localParticipant),this.encryptionEnabled=d.enabled;else if(d.participantIdentity){const u=(r=this.room)===null||r===void 0?void 0:r.getParticipantByIdentity(d.participantIdentity);if(!u)throw TypeError("couldn't set encryption status, participant not found".concat(d.participantIdentity));
37this.emit(yt.ParticipantEncryptionStatusChanged,d.enabled,u)}break;case"ratchetKey":this.keyProvider.emit(_t.KeyRatcheted,d.ratchetResult,d.participantIdentity,d.keyIndex);break;case"decryptDataResponse":const c=this.decryptDataRequests.get(d.uuid);c?.resolve&&c.resolve(d);break;case"encryptDataResponse":const 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=>{U.error("e2ee worker encountered an error:",{error:n.error}),this.emit(yt.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(!jh())throw new fr("tried to setup end-to-end encryption on an unsupported browser");if(U.info("setting up e2ee"),e!==this.room){this.room=e,this.setupEventListeners(e,this.keyProvider);const t={kind:"init",data:{keyProviderOptions:this.keyProvider.getOptions(),loglevel:Lu.getLevel()}};this.worker&&(U.info("initializing worker",{worker:this.worker}),this.worker.onmessage=this.onWorkerMessage,this.worker.onerror=this.onWorkerError,this.worker.postMessage(t))}}setParticipantCryptorEnabled(e,t){U.debug("set e2ee to ".concat(e," for participant ").concat(t)),this.postEnable(e,t)}setSifTrailer(e){!e||e.length===0?U.warn("ignoring server sent trailer as it's empty"):this.postSifTrailer(e)}handleFrameMetadata(e,t,n,s){if(this.room){for(const r of[this.room.localParticipant,...this.room.remoteParticipants.values()])for(const a of r.trackPublications.values())if(a.track&&a.track.mediaStreamID===e&&a.track instanceof Sr&&a.track.frameMetadataExtractor){a.track.frameMetadataExtractor.storeMetadata(t,n,s);return}}}setupEngine(e){e.on(R.RTPVideoMapUpdate,t=>{this.postRTPMap(t)})}setupEventListeners(e,t){e.on(_.TrackPublished,(n,s)=>this.setParticipantCryptorEnabled(n.trackInfo.encryption!==G.NONE,s.identity)),e.on(_.ConnectionStateChanged,n=>
37{n===K.Connected&&e.remoteParticipants.forEach(s=>{s.trackPublications.forEach(r=>{this.setParticipantCryptorEnabled(r.trackInfo.encryption!==G.NONE,s.identity)})})}).on(_.TrackUnsubscribed,(n,s,r)=>{var a;const o={kind:"removeTransform",data:{participantIdentity:r.identity,trackId:n.mediaStreamID}};(a=this.worker)===null||a===void 0||a.postMessage(o)}).on(_.TrackSubscribed,(n,s,r)=>{this.setupE2EEReceiver(n,r.identity,s.trackInfo)}).on(_.SignalConnected,()=>{if(!this.room)throw new TypeError("expected room to be present on signal connect");const n=t.getLatestManuallySetKeyIndex();t.getKeys().forEach(s=>{var r;this.postKey(s,n===((r=s.keyIndex)!==null&&r!==void 0?r:0))}),this.setParticipantCryptorEnabled(this.room.localParticipant.isE2EEEnabled,this.room.localParticipant.identity)}),e.localParticipant.on(M.LocalSenderCreated,(n,s)=>m(this,void 0,void 0,function*(){this.setupE2EESender(s,n)})),e.localParticipant.on(M.LocalTrackPublished,n=>{if(!mt(n.track)||!Nn())return;const s={kind:"updateCodec",data:{trackId:n.track.mediaStreamID,codec:Cn(n.trackInfo.codecs[0].mimeType),participantIdentity:this.room.localParticipant.identity,hasPacketTrailer:!1}};this.worker.postMessage(s)}),t.on(_t.SetKey,(n,s)=>this.postKey(n,s??!0)).on(_t.RatchetRequest,(n,s)=>this.postRatchetRequest(n,s))}encryptData(e){return m(this,void 0,void 0,function*(){if(!this.worker)throw Error("could not encrypt data, worker is missing");const t=crypto.randomUUID(),n={kind:"encryptDataRequest",data:{uuid:t,payload:e,participantIdentity:this.room.localParticipant.identity}},s=new ye;return s.onFinally=()=>{this.encryptDataRequests.delete(t)},this.encryptDataRequests.set(t,s),this.worker.postMessage(n),s.promise})}handleEncryptedData(e,t,n,s){if(!this.worker)throw Error("could not handle encrypted data, worker is missing");const r=crypto.randomUUID(),a={kind:"decryptDataRequest",data:{uuid:r,payload:e,iv:t,participantIdentity:n,keyIndex:s}},o=new ye;return o.onFinally=()=>{this.decryptDataRequests.delete(r)},this.decryptDataRequests.set(r,o),this.worker.postMessage(a),o.promise}postRatchetRequest(e,t){if(!this.worker)throw Error("could not ratchet key, worker is missing");const n={kind:"ratchetRequest",data:{participantIdentity:e,keyIndex:t}};this.worker.postMessage(n)}postKey(e,t){let n=e.key,s=e.participantIdentity,r=e.keyIndex;var a;if(!this.worker)throw Error("could not set key, worker is missing");const o={kind:"setKey",data:{participantIdentity:s,isPublisher:s===((a=this.room)===null||a===void 0?void 0:a.localParticipant.identity),key:n,keyIndex:r,updateCurrentKeyIndex:t}};this.worker.postMessage(o)}postEnable(e,t){if(this.worker){const n={kind:"enable",data:{enabled:e,participantIdentity:t}};this.worker.postMessage(n)}else throw new ReferenceError("failed to enable e2ee, worker is not ready")}postRTPMap(e){var t;if(!this.worker)throw TypeError("could not post rtp map, worker is missing");if(!(!((t=this.room)===null||t===void 0)&&t.localParticipant.identity))throw TypeError("could not post rtp map, local participant identity is missing");const n={kind:"setRTPMap",data:{map:e,participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(n)}postSifTrailer(e){if(!this.worker)throw Error("could not post SIF trailer, worker is missing");const t={kind:"setSifTrailer",data:{trailer:e}};this.worker.postMessage(t)}setupE2EEReceiver(e,t,n){if(!e.receiver)return;if(!n?.mimeType||n.mimeType==="")throw new TypeError("MimeType missing from trackInfo, cannot set up E2EE cryptor");const s=e.kind==="video"&&!!n.packetTrailerFeatures&&n.packetTrailerFeatures.length>0;this.handleReceiver(e.receiver,e.mediaStreamID,t,e.kind==="video"?Cn(n.mimeType):void 0,s)}setupE2EESender(e,t){var n,s,r;if(!tn(e)||!t){t||U.warn("early return because sender is not ready");return}this.handleSender(t,e.mediaStreamID,void 0,mt(e)?(s=(n=e.publishOptions)===null||n===void 0?void 0:n.frameMetadata)!==null&&s!==void 0?s:(r=e.publishOptions)===null||r===void 0?void 0:r.packetTrailer:void 0)}handleReceiver(e,t,n,s,r){return m(this,void 0,void 0,function*(){if(this.worker){if(Vs()){const a={kind:"decode",participantIdentity:n,trackId:t,codec:s,hasPacketTrailer:r};e.transform=new RTCRtpScriptTransform(this.worker,a)}else{if(vn in e&&s){const c={kind:"updateCodec",data:{trackId:t,codec:s,participantIdentity:n,hasPacketTrailer:r}};this.worker.postMessage(c);return}let a=e.writableStream,o=e.readableStream;if(!a||!o){const c=e.createEncodedStreams();e.writableStream=c.writable,a=c.writable,e.readableStream=c.readable,o=c.readable}const d={kind:"decode",data:{readableStream:o,writableStream:a,trackId:t,codec:s,participantIdentity:n,isReuse:vn in e,hasPacketTrailer:r}};this.worker.postMessage(d,[o,a])}e[vn]=!0}})}handleSender(e,t,n,s){var r;if(!(vn in e||!this.worker)){if(!(!((r=this.room)===null||r===void 0)&&r.localParticipant.identity)||this.room.localParticipant.identity==="")throw TypeError("local identity needs to be known in order to set up encrypted sender");if(Vs()){U.info("initialize script transform");const a={kind:"encode",participantIdentity:this.room.localParticipant.identity,trackId:t,codec:n,hasPacketTrailer:mi(s),packetTrailer:s};e.transform=new RTCRtpScriptTransform(this.worker,a)}else{U.info("initialize encoded streams");const a=e.createEncodedStreams(),o={kind:"encode",data:{readableStream:a.readable,writableStream:a.writable,codec:n,trackId:t,participantIdentity:this.room.localParticipant.identity,isReuse:!1,hasPacketTrailer:mi(s),packetTrailer:s}};this.worker.postMessage(o,[a.readable,a.writable])}e[vn]=!0}}}const Qh=300;class Yh{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>=Qh;){const s=this.metadataMap.keys().next().value;this.metadataMap.delete(s)}this.metadataMap.set(e,n)}lookupMetadata(e){return this.metadataMap.get(e)}dispose(){this.metadataMap.clear(),this.activeSsrc=0}}class Xh{constructor(e){this.extractors=new Map,this.workerPipelines=new Map,this.onWorkerMessage=t=>{const n=t.data;if(n.kind==="metadata"){const s=this.extractors.get(n.data.trackId);s&&s.storeMetadata(n.data.rtpTimestamp,n.data.ssrc,n.data.metadata)}},this.onWorkerError=t=>{U.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(_.TrackSubscribed,(t,n,s)=>{t.kind==="video"&&this.setupReceiver(t,n.trackInfo)}).on(_.TrackUnsubscribed,t=>{this.teardownTrack(t)}).on(_.Disconnected,()=>{this.cleanup()}))}setupReceiver(e,t){var n,s,r;const 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(!Un(this.worker?{worker:this.worker}:void 0)&&!(!((s=this.room)===null||s===void 0)&&s.hasE2EESetup)){U.warn("frame metadata transform not supported; skipping extraction");return}const d=new Yh,c=e.mediaStreamID;this.extractors.set(c,d),e.frameMetadataExtractor=d,!(!((r=this.room)===null||r===void 0)&&r.hasE2EESetup)&&this.setupWorkerReceiver(a,c,!0)}setupPassthroughReceiver(e,t){if(xn()){"transform"in e&&(e.transform=null);return}if(this.worker&&Un({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;const s=this.worker;if(!s)return;if(xn()){e.transform=new RTCRtpScriptTransform(s,{kind:"decode",trackId:t});return}const r=this.workerPipelines.get(e);if(r){const d={kind:"updateTrackId",data:{oldTrackId:r,newTrackId:t,hasPacketTrailer:n}};s.postMessage(d),this.workerPipelines.set(e,t);return}if(!("createEncodedStreams"in e)){U.warn("createEncodedStreams not supported");return}let a;try{a=e.createEncodedStreams()}catch(d){U.warn("failed to create encoded streams",{error:d});return}const o={kind:"decode",data:{readableStream:a.readable,writableStream:a.writable,trackId:t,hasPacketTrailer:n}};s.postMessage(o,[a.readable,a.writable]),this.workerPipelines.set(e,t)}teardownTrack(e){const t=e.mediaStreamID,n=this.extractors.get(t);n&&(n.dispose(),this.extractors.delete(t)),e instanceof Sr&&(e.frameMetadataExtractor=void 0)}cleanup(){var e;
37for(const t of this.extractors.values())t.dispose();this.extractors.clear(),this.workerPipelines.clear(),(e=this.worker)===null||e===void 0||e.terminate()}}const Zh=500,ep=15e3;class nn{constructor(){this.failedConnectionAttempts=new Map,this.backOffPromises=new Map}static getInstance(){return this._instance||(this._instance=new nn),this._instance}addFailedConnectionAttempt(e){var t;const n=new URL(e),s=es(n);if(!s)return;let r=(t=this.failedConnectionAttempts.get(s))!==null&&t!==void 0?t:0;this.failedConnectionAttempts.set(s,r+1),this.backOffPromises.set(s,Se(Math.min(Zh*Math.pow(2,r),ep)))}getBackOffPromise(e){const t=new URL(e),n=t&&es(t);return n&&this.backOffPromises.get(n)||Promise.resolve()}resetFailedConnectionAttempts(e){const t=new URL(e),n=t&&es(t);n&&(this.failedConnectionAttempts.set(n,0),this.backOffPromises.set(n,Promise.resolve()))}resetAll(){this.backOffPromises.clear(),this.failedConnectionAttempts.clear()}}nn._instance=null;const as="default";class fe{constructor(){this._previousDevices=[]}static getInstance(){return this.instance===void 0&&(this.instance=new fe),this.instance}get previousDevices(){return this._previousDevices}getDevices(e){return m(this,arguments,void 0,function(t){var n=this;let s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return(function*(){var r;if(((r=fe.userMediaPromiseMap)===null||r===void 0?void 0:r.size)>0){U.debug("awaiting getUserMedia promise");try{t?yield fe.userMediaPromiseMap.get(t):yield Promise.all(fe.userMediaPromiseMap.values())}catch{U.warn("error waiting for media permissons")}}let a=yield navigator.mediaDevices.enumerateDevices();if(s&&!(jt()&&n.hasDeviceInUse(t))&&(a.filter(d=>d.kind===t).length===0||a.some(d=>{const c=d.label==="",l=t?d.kind===t:!0;return c&&l}))){const d={video:t!=="audioinput"&&t!=="audiooutput",audio:t!=="videoinput"&&{deviceId:{ideal:"default"}}},c=yield navigator.mediaDevices.getUserMedia(d);a=yield navigator.mediaDevices.enumerateDevices(),c.getTracks().forEach(l=>{l.stop()})}return n._previousDevices=a,t&&(a=a.filter(o=>o.kind===t)),a})()})}normalizeDeviceId(e,t,n){return m(this,void 0,void 0,function*(){if(t!==as)return t;const s=yield this.getDevices(e),r=s.find(o=>o.deviceId===as);if(!r){U.warn("could not reliably determine default device");return}const a=s.find(o=>o.deviceId!==as&&o.groupId===(n??r.groupId));if(!a){U.warn("could not reliably determine default device");return}return a?.deviceId})}hasDeviceInUse(e){return e?fe.userMediaPromiseMap.has(e):fe.userMediaPromiseMap.size>0}}fe.mediaDeviceKinds=["audioinput","audiooutput","videoinput"];fe.userMediaPromiseMap=new Map;const Cr=65535,Zc=4294967295;class Ge{static u16(e){return new Ge(e,Cr)}static u32(e){return new Ge(e,Zc)}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 Ge(this.value,this.maxSize)}update(e){this.value=e(this.value),this.clamp()}increment(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:1;this.update(t=>t+e)}decrement(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:1;this.update(t=>t-e)}getThenIncrement(){const e=this.value;return this.increment(),new Ge(e,this.maxSize)}isBefore(e){const t=this.value>>>0,s=(e.value>>>0)-t>>>0;return s!==0&&s<this.maxSize+1}}class sn{static fromRtpTicks(e){return new sn(e,9e4)}static rtpRandom(){const e=Math.round(Math.random()*Zc);return sn.fromRtpTicks(e)}constructor(e,t){this.timestamp=Ge.u32(e),this.rateInHz=t}asTicks(){return this.timestamp.value}clone(){return new sn(this.timestamp.value,this.rateInHz)}wrappingAdd(e){this.timestamp.increment(e)}isBefore(e){return this.timestamp.isBefore(e.timestamp)}}class Nt{constructor(e,t,n){this.epoch=t,this.base=n,this.previous=n.clone(),this.rateInHz=e}static startingNow(e,t){return new Nt(t,new Date,e)}static startingAtTime(e,t,n){return new Nt(n,e,t)}static rtpStartingNow(e){return Nt.startingNow(e,9e4)}static rtpStartingAtTime(e,t){return Nt.startingAtTime(e,t,9e4)}now(){return this.at(new Date)}at(e){let t=e.getTime()-this.epoch.getTime(),n=Nt.durationInMsToTicks(t,this.rateInHz),s=this.base.clone();return s.wrappingAdd(n),s.isBefore(this.previous)&&(s=this.previous),this.previous=s.clone(),s.clone()}static durationInMsToTicks(e,t){let s=(e*1e6*t+5e8)/1e9;return Math.round(s)}}function Er(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 qt;(function(i){i[i.Reserved=0]="Reserved",i[i.TooLarge=1]="TooLarge"})(qt||(qt={}));class ln extends Ue{constructor(e,t){super(19,e),this.name="DataTrackHandleError",this.reason=t,this.reasonName=qt[t]}isReason(e){return this.reason===e}static tooLarge(){return new ln("Value too large to be a valid track handle",qt.TooLarge)}static reserved(e){return new ln("0x".concat(e.toString(16)," is a reserved value."),qt.Reserved)}}const tp={fromNumber(i){if(i===0)throw ln.reserved(i);if(i>Cr)throw ln.tooLarge();return i}};
37class np{constructor(){this.value=0}get(){return this.value+=1,this.value>Cr?null:this.value}reset(){this.value=0}}const fi={from(i){return{sid:i.sid,pubHandle:i.pubHandle,name:i.name,usesE2ee:i.encryption!==G.NONE}},toProtobuf(i){return new wi({sid:i.sid,pubHandle:i.pubHandle,name:i.name,encryption:i.usesE2ee?G.GCM:G.NONE})}};var En;(function(i){i[i.WAITING=0]="WAITING",i[i.RUNNING=1]="RUNNING",i[i.COMPLETED=2]="COMPLETED"})(En||(En={}));class ip{constructor(){this.pendingTasks=new Map,this.taskMutex=new ge,this.nextTaskIndex=0}run(e){return m(this,void 0,void 0,function*(){const t={id:this.nextTaskIndex++,enqueuedAt:Date.now(),status:En.WAITING};this.pendingTasks.set(t.id,t);const n=yield this.taskMutex.lock();try{return t.executedAt=Date.now(),t.status=En.RUNNING,yield e()}finally{t.status=En.COMPLETED,this.pendingTasks.delete(t.id),n()}})}flush(){return m(this,void 0,void 0,function*(){return this.run(()=>m(this,void 0,void 0,function*(){}))})}snapshot(){return Array.from(this.pendingTasks.values())}}class sp{get readyState(){return this.ws.readyState}constructor(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};var n,s;if(!((n=t.signal)===null||n===void 0)&&n.aborted)throw new DOMException("This operation was aborted","AbortError");this.url=e;const r=new WebSocket(e,(s=t.protocols)!==null&&s!==void 0?s:[]);r.binaryType="arraybuffer",this.ws=r;const a=function(){let o=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},d=o.closeCode,c=o.reason;return r.close(d,c)};this.opened=new _e((o,d)=>{const c=()=>{d(x.websocket("Encountered websocket error during connection establishment"))};r.onopen=()=>{o({readable:new ReadableStream({start(l){r.onmessage=u=>{let h=u.data;return l.enqueue(h)},r.onerror=u=>l.error(u)},cancel:a}),writable:new WritableStream({write(l){r.send(l)},abort(){r.close()},close:a}),protocol:r.protocol,extensions:r.extensions}),r.removeEventListener("error",c)},r.addEventListener("error",c)}),this.closed=new _e((o,d)=>{const c=()=>m(this,void 0,void 0,function*(){const l=new _e(h=>{r.readyState!==WebSocket.CLOSED&&r.addEventListener("close",p=>{h(p)},{once:!0})}),u=yield _e.race([Se(250),l]);u?o(u):d(x.websocket("Encountered unspecified websocket error without a timely close event"))});r.onclose=l=>{let u=l.code,h=l.reason;o({closeCode:u,reason:h}),r.removeEventListener("error",c)},r.addEventListener("error",c)}),t.signal&&(t.signal.onabort=()=>r.close()),this.close=a}}const rp=["syncState","trickle","offer","answer","simulate","leave"];function ap(i){const e=rp.indexOf(i.case)>=0;return U.trace("request allowed to bypass queue:",{canPass:e,req:i}),e}var $;(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"})($||($={}));const op=250,cp=5e3;class _r{get currentState(){return this.state}get isDisconnected(){return this.state===$.DISCONNECTING||this.state===$.DISCONNECTED}get isEstablishingConnection(){return this.state===$.CONNECTING||this.state===$.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=$.DISCONNECTED,this.log=U,this._requestId=0,this.useV0SignalPath=!1,this.resetCallbacks=()=>{this.onAnswer=void 0,this.onLeave=void 0,this.onLocalTrackPublished=void 0,this.onLocalTrackUnpublished=void 0,this.onNegotiateRequested=void 0,this.onOffer=void 0,this.onRemoteMuteChanged=void 0,this.onSubscribedQualityUpdate=void 0,this.onTokenRefresh=void 0,this.onTrickle=void 0,this.onClose=void 0,this.onMediaSectionsRequirement=void 0},this.loggerContextCb=t.loggerContextCb,this.log=ke((n=t.loggerName)!==null&&n!==void 0?n:ce.Signal,()=>this.logContext),this.useJSON=e,this.requestQueue=new ip,this.queuedRequests=[],this.closingLock=new ge,this.connectionLock=new ge,this.state=$.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,s){return m(this,arguments,void 0,function(r,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=$.CONNECTING,c.options=o,yield c.connect(r,a,o,d,l,u)})()})}reconnect(e,t,n,s){return m(this,void 0,void 0,function*(){if(!this.options){this.log.warn("attempted to reconnect without signal options being set, ignoring");return}return this.state=$.RECONNECTING,this.clearPingInterval(),yield this.connect(e,t,Object.assign(Object.assign({},this.options),{reconnect:!0,sid:n,reconnectReason:s}),void 0,this.useV0SignalPath)})}connect(e,t,n,s){return m(this,arguments,void 0,function(r,a,o,d){var c=this;let l=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!1,u=arguments.length>5?arguments[5]:void 0;return(function*(){const h=yield c.connectionLock.lock();c.connectOptions=o,c.useV0SignalPath=l;const p=wh(o.clientInfoCapabilities),f=l?dp(a,p,o):yield lp(a,p,o,u),g=xh(r,f,l).toString(),k=Fh(g).toString();return new Promise((T,S)=>m(c,void 0,void 0,function*(){var N,v;try{let y=!1;const E=O=>m(this,void 0,void 0,function*(){if(y)return;y=!0;const F=O instanceof Event?O.currentTarget:O,Y=Bh(F,"Abort handler called");this.streamWriter&&!this.isDisconnected?this.sendLeave().then(()=>this.close(Y)).catch(te=>{this.log.error(te),this.close()}):this.close(),I(),S(x.cancelled(Y))});d?.addEventListener("abort",E);const I=()=>{clearTimeout(A),d?.removeEventListener("abort",E)},A=setTimeout(()=>{E(x.timeout("room connection has timed out (signal)"))},o.websocketTimeout),B=(O,F)=>{this.handleSignalConnected(O,A,F)},D=new URL(g);if(D.searchParams.has("access_token")&&D.searchParams.set("access_token","<redacted>"),this.ws){const O=performance.now();yield this.close(!1),this.log.debug("closed previous ws connection in ".concat(performance.now()-O,"ms"))}this.log.info("signal connecting to ".concat(D),{reconnect:o.reconnect,reconnectReason:o.reconnectReason}),this.ws=new sp(g);try{this.ws.closed.then(pe=>{this.isEstablishingConnection&&S(x.internal("Websocket got closed during a (re)connection attempt: ".concat(pe.reason))),pe.closeCode!==1e3&&(this.log.warn("websocket closed",{reason:pe.reason,code:pe.closeCode,wasClean:pe.closeCode===1e3,state:this.state}),this.state===$.CONNECTED&&this.handleOnClose(pe.reason||"Unexpected WS error"))}).catch(pe=>{this.isEstablishingConnection&&S(x.internal("Websocket error during a (re)connection attempt: ".concat(pe)))});
37const O=yield this.ws.opened.catch(pe=>m(this,void 0,void 0,function*(){if(this.state!==$.CONNECTED){this.state=$.DISCONNECTED,clearTimeout(A);const It=yield this.handleConnectionError(pe,k);S(It);return}this.handleWSError(pe),S(pe)}));if(clearTimeout(A),!O)return;const F=O.readable.getReader();this.streamWriter=O.writable.getWriter();let Y,te;try{Y=yield Promise.race([F.read(),new Promise((pe,It)=>{te=setTimeout(()=>{It(x.timeout("signal connection timed out while waiting for the first message"))},cp)})])}catch(pe){F.releaseLock(),S(pe),this.close();return}finally{clearTimeout(te)}if(F.releaseLock(),!Y.value)throw x.internal("no message received as first message");const ve=ka(Y.value),$e=this.validateFirstMessage(ve,(N=o.reconnect)!==null&&N!==void 0?N:!1);if(!$e.isValid){S($e.error);return}((v=ve.message)===null||v===void 0?void 0:v.case)==="join"&&(this.pingTimeoutDuration=ve.message.value.pingTimeout,this.pingIntervalDuration=ve.message.value.pingInterval,this.pingTimeoutDuration&&this.pingTimeoutDuration>0&&this.log.debug("ping config",{timeout:this.pingTimeoutDuration,interval:this.pingIntervalDuration}),this.onJoined&&this.onJoined(ve.message.value));const gt=$e.shouldProcessFirstMessage?ve:void 0;B(O,gt),T($e.response)}catch(O){S(O)}finally{I()}}finally{h()}}))})()})}startReadingLoop(e,t){return m(this,void 0,void 0,function*(){for(t&&this.handleSignalResponse(t);;){this.signalLatency&&(yield Se(this.signalLatency));const n=yield e.read(),s=n.done,r=n.value;if(s)break;const a=ka(r);
37this.handleSignalResponse(a)}})}close(){return m(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0,n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"Close method called on signal client";return(function*(){if([$.DISCONNECTING||$.DISCONNECTED].includes(e.state)){e.log.debug("ignoring signal close as it's already in disconnecting state");return}const s=yield e.closingLock.lock();try{if(e.clearPingInterval(),t&&(e.state=$.DISCONNECTING),e.ws){e.ws.close({closeCode:1e3,reason:n});const r=e.ws.closed;e.ws=void 0,e.streamWriter=void 0,yield Promise.race([r,Se(op)])}}catch(r){e.log.debug("websocket error while closing",{error:r})}finally{t&&(e.state=$.DISCONNECTED),s()}})()})}sendOffer(e,t){this.log.debug("sending offer",{offerSdp:e.sdp}),this.sendRequest({case:"offer",value:Lt(e,t)})}sendAnswer(e,t){return this.log.debug("sending answer",{answerSdp:e.sdp}),this.sendRequest({case:"answer",value:Lt(e,t)})}sendIceCandidate(e,t){return this.log.debug("sending ice candidate",{candidate:e}),this.sendRequest({case:"trickle",value:new Ii({candidateInit:JSON.stringify(e),target:t})})}sendMuteTrack(e,t){return this.sendRequest({case:"mute",value:new Mi({sid:e,muted:t})})}sendAddTrack(e){return this.sendRequest({case:"addTrack",value:e})}sendUpdateLocalMetadata(e,t){return m(this,arguments,void 0,function(n,s){var r=this;let a=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return(function*(){const o=r.getNextRequestId();return yield r.sendRequest({case:"updateMetadata",value:new lr({requestId:o,metadata:n,name:s,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 Xo({trackSid:e,layers:t})})}sendUpdateSubscriptionPermissions(e,t){return this.sendRequest({case:"subscriptionPermission",value:new tc({allParticipants:e,trackPermissions:t})})}sendSimulateScenario(e){return this.sendRequest({case:"simulate",value:e})}sendPing(){return Promise.all([this.sendRequest({case:"ping",value:ee.parse(Date.now())}),this.sendRequest({case:"pingReq",value:new sc({timestamp:ee.parse(Date.now()),rtt:ee.parse(this.rtt)})})])}sendUpdateLocalAudioTrack(e,t){return this.sendRequest({case:"updateAudioTrack",value:new dr({trackSid:e,features:t})})}sendLeave(){return this.sendRequest({case:"leave",value:new Ai({reason:Ke.CLIENT_INITIATED,action:Yt.DISCONNECT})})}sendPublishDataTrackRequest(e,t,n){return this.sendRequest({case:"publishDataTrackRequest",value:new rr({pubHandle:e,name:t,encryption:n?G.GCM:G.NONE})})}sendUnPublishDataTrackRequest(e){return this.sendRequest({case:"unpublishDataTrackRequest",value:new or({pubHandle:e})})}sendUpdateDataSubscription(e,t){return this.sendRequest({case:"updateDataSubscription",value:new Jo({updates:[new $o({trackSid:e,subscribe:t})]})})}sendRequest(e){return m(this,arguments,void 0,function(t){var n=this;let s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1;return(function*(){if(!s&&!ap(t)&&n.state===$.RECONNECTING){n.queuedRequests.push(()=>m(n,void 0,void 0,function*(){yield this.sendRequest(t,!0)}));return}if(s||(yield n.requestQueue.flush()),n.signalLatency&&(yield Se(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}const a=new Zl({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;const s=e.message;if(s==null){this.log.debug("received unsupported message");return}let r=!1;if(s.case==="answer"){const a=Ea(s.value);this.onAnswer&&this.onAnswer(a,s.value.id,s.value.midToTrackId)}else if(s.case==="offer"){const a=Ea(s.value);this.onOffer&&this.onOffer(a,s.value.id,s.value.midToTrackId)}else if(s.case==="trickle"){const a=JSON.parse(s.value.candidateInit);this.onTrickle&&this.onTrickle(a,s.value.target)}else s.case==="update"?this.onParticipantUpdate&&this.onParticipantUpdate((t=s.value.participants)!==null&&t!==void 0?t:[]):s.case==="trackPublished"?this.onLocalTrackPublished&&this.onLocalTrackPublished(s.value):s.case==="speakersChanged"?this.onSpeakersChanged&&this.onSpeakersChanged((n=s.value.speakers)!==null&&n!==void 0?n:[]):s.case==="leave"?this.onLeave&&this.onLeave(s.value):s.case==="mute"?this.onRemoteMuteChanged&&this.onRemoteMuteChanged(s.value.sid,s.value.muted):s.case==="roomUpdate"?this.onRoomUpdate&&s.value.room&&this.onRoomUpdate(s.value.room):s.case==="connectionQuality"?this.onConnectionQuality&&this.onConnectionQuality(s.value):s.case==="streamStateUpdate"?this.onStreamStateUpdate&&this.onStreamStateUpdate(s.value):s.case==="subscribedQualityUpdate"?this.onSubscribedQualityUpdate&&this.onSubscribedQualityUpdate(s.value):s.case==="subscriptionPermissionUpdate"?this.onSubscriptionPermissionUpdate&&this.onSubscriptionPermissionUpdate(s.value):s.case==="refreshToken"?this.onTokenRefresh&&this.onTokenRefresh(s.value):s.case==="trackUnpublished"?this.onLocalTrackUnpublished&&this.onLocalTrackUnpublished(s.value):s.case==="subscriptionResponse"?this.onSubscriptionError&&this.onSubscriptionError(s.value):s.case==="pong"||(s.case==="pongResp"?(this.rtt=Date.now()-Number.parseInt(s.value.lastPingTimestamp.toString()),this.resetPingTimeout(),r=!0):s.case==="requestResponse"?this.onRequestResponse&&this.onRequestResponse(s.value):s.case==="trackSubscribed"?this.onLocalTrackSubscribed&&this.onLocalTrackSubscribed(s.value.trackSid):s.case==="roomMoved"?(this.onTokenRefresh&&this.onTokenRefresh(s.value.token),this.onRoomMoved&&this.onRoomMoved(s.value)):s.case==="mediaSectionsRequirement"?this.onMediaSectionsRequirement&&this.onMediaSectionsRequirement
37(s.value):s.case==="publishDataTrackResponse"?this.onPublishDataTrackResponse&&this.onPublishDataTrackResponse(s.value):s.case==="unpublishDataTrackResponse"?this.onUnPublishDataTrackResponse&&this.onUnPublishDataTrackResponse(s.value):s.case==="dataTrackSubscriberHandles"?this.onDataTrackSubscriberHandles&&this.onDataTrackSubscriberHandles(s.value):this.log.debug("unsupported message",{msgCase:s.case}));r||this.resetPingTimeout()}setReconnected(){for(;this.queuedRequests.length>0;){const e=this.queuedRequests.shift();e&&this.requestQueue.run(e)}}handleOnClose(e){return m(this,void 0,void 0,function*(){if(this.state===$.DISCONNECTED)return;const t=this.onClose;yield this.close(void 0,e),this.log.info("websocket connection closed: ".concat(e),{reason:e}),t&&t(e)})}handleWSError(e){this.log.error("websocket error",{error:e})}resetPingTimeout(){if(this.clearPingTimeout(),!this.pingTimeoutDuration){this.log.warn("ping timeout duration not set");return}this.pingTimeout=ae.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&&ae.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=ae.setInterval(()=>{this.sendPing()},this.pingIntervalDuration*1e3)}clearPingInterval(){this.log.debug("clearing ping interval"),this.clearPingTimeout(),this.pingInterval&&ae.clearInterval(this.pingInterval)}handleSignalConnected(e,t,n){this.state=$.CONNECTED,this.log.info("signal connected"),clearTimeout(t),this.startPingInterval(),this.startReadingLoop(e.readable.getReader(),n)}validateFirstMessage(e,t){var n,s,r,a,o;return((n=e.message)===null||n===void 0?void 0:n.case)==="join"?{isValid:!0,response:e.message.value}:this.state===$.RECONNECTING&&((s=e.message)===null||s===void 0?void 0:s.case)!=="leave"?((r=e.message)===null||r===void 0?void 0:r.case)==="reconnect"?{isValid:!0,response:e.message.value}:(this.log.debug("declaring signal reconnected without reconnect response received"),{isValid:!0,response:void 0,shouldProcessFirstMessage:!0}):this.isEstablishingConnection&&((a=e.message)===null||a===void 0?void 0:a.case)==="leave"?{isValid:!1,error:x.leaveRequest("Received leave request while trying to (re)connect",e.message.value.reason)}:t?{isValid:!1,error:x.internal("Unexpected first message")}:{isValid:!1,error:x.internal("did not receive join response, got ".concat((o=e.message)===null||o===void 0?void 0:o.case," instead"))}}handleConnectionError(e,t){return m(this,void 0,void 0,function*(){try{const n=yield fetch(t);switch(n.status){case 404:const s=yield n.text();return s.includes("requested room does not exist")?x.notAllowed(s,n.status):x.serviceNotFound("v1 RTC path not found. Consider upgrading your LiveKit server version","v0-rtc");case 401:case 403:const r=yield n.text();return x.notAllowed(r,n.status);default:break}return e instanceof x?e:x.internal("Encountered unknown websocket error during connection: ".concat(e),{status:n.status,statusText:n.statusText})}catch(n){return n instanceof x?n:x.serverUnreachable(n instanceof Error?n.message:"server was not reachable")}})}}function Ea(i){const e={type:"offer",sdp:i.sdp};switch(i.type){case"answer":case"offer":case"pranswer":case"rollback":e.type=i.type;break}return e}function Lt(i,e){return new Rt({sdp:i.sdp,type:i.type,id:e})}function dp(i,e,t){var n;const s=new URLSearchParams;return s.set("access_token",i),t.reconnect&&(s.set("reconnect","1"),t.sid&&s.set("sid",t.sid)),s.set("auto_subscribe",t.autoSubscribe?"1":"0"),s.set("sdk",Je()?"reactnative":"js"),s.set("version",e.version),s.set("protocol",e.protocol.toString()),s.set("client_protocol",e.clientProtocol.toString()),e.deviceModel&&s.set("device_model",e.deviceModel),e.os&&s.set("os",e.os),e.osVersion&&s.set("os_version",e.osVersion),e.browser&&s.set("browser",e.browser),e.browserVersion&&s.set("browser_version",e.browserVersion),t.adaptiveStream&&s.set("adaptive_stream","1"),t.reconnectReason&&s.set("reconnect_reason",t.reconnectReason.toString()),!((n=navigator.connection)===null||n===void 0)&&n.type&&s.set("network",navigator.connection.type),s}function lp(i,e,t,n){return m(this,void 0,void 0,function*(){const s=new URLSearchParams;s.set("access_token",i);const r=new Pu({clientInfo:e,connectionSettings:new rc({autoSubscribe:!!t.autoSubscribe,adaptiveStream:!!t.adaptiveStream}),reconnect:!!t.reconnect,participantSid:t.sid?t.sid:void 0,publisherOffer:n});t.reconnectReason&&(r.reconnectReason=t.reconnectReason);const a=r.toBinary();let o,d;if(Et()){const h=new CompressionStream("gzip"),p=h.writable.getWriter();p.write(new Uint8Array(a)),p.close();const f=[],g=h.readable.getReader();for(;;){const N=yield g.read(),v=N.done,y=N.value;if(v)break;f.push(y)}const k=f.reduce((N,v)=>N+v.length,0),T=new Uint8Array(k);let S=0;for(const N of f)T.set(N,S),S+=N.length;o=T,d=Es.GZIP}else o=a,d=Es.NONE;const l=new Iu({joinRequest:o,compression:d}).toBinary(),u=h=>{const p=Array.from(h,f=>String.fromCodePoint(f)).join("");return btoa(p)};return s.set("join_request",u(l).replace(/\+/g,"-").replace(/\//g,"_")),s})}class up{constructor(e){this._map=new Map,this._lastCleanup=0,this.ttl=e}set(e,t){const n=Date.now();n-this._lastCleanup>this.ttl/2&&this.cleanup();const s=n+this.ttl;return this._map.set(e,{value:t,expiresAt:s}),this}get(e){const t=this._map.get(e);if(t){if(t.expiresAt<Date.now()){this._map.delete(e);return}return t.value}}has(e){const t=this._map.get(e);return t?t.expiresAt<Date.now()?(this._map.delete(e),!1):!0:!1}delete(e){return this._map.delete(e)}clear(){this._map.clear()}cleanup(){const e=Date.now();for(const n of this._map.entries()){var t=L(n,2);const s=t[0];t[1].expiresAt<e&&this._map.delete(s)}this._lastCleanup=e}get size(){return this.cleanup(),this._map.size}forEach(e){this.cleanup();for(const n of this._map.entries()){var t=L(n,2);const s=t[0],r=t[1];r.expiresAt>=Date.now()&&e(r.value,s,this.asValueMap())}}map(e){this.cleanup();const t=[],n=this.asValueMap();for(const r of n.entries()){var s=L(r,2);const a=s[0],o=s[1];t.push(e(o,a,n))}return t}asValueMap(){const e=new Map;for(const n of this._map.entries()){var t=L(n,2);const s=t[0],r=t[1];r.expiresAt>=Date.now()&&e.set(s,r.value)}return e}}var Fe={},os={},cs={exports:{}},_a;function wr(){if(_a)return cs.exports;_a=1;var i=cs
vendor: 6,910 bytes, line 37
37.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")})}),
vendor: 2,509 bytes, line 37
37cs.exports}var wa;function hp(){return wa||(wa=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)},s=wr(),r=RegExp.prototype.test.bind(/^([a-z])=(.*)/);i.parse=function(o){var d={},c=[],l=d;return o.split(/(\r\n|\r|\n)/).filter(r).forEach(function(u){var h=u[0],p=u.slice(2);h==="m"&&(c.push({rtp:[],fmtp:[]}),l=c[c.length-1]);for(var f=0;f<(s[h]||[]).length;f+=1){var g=s[h][f];if(g.reg.test(p))return n(g,l,p)}}),d.media=c,d};var a=function(o,d){var c=d.split(/=(.+)/,2);return c.length===2?o[c[0]]=e(c[1]):c.length===1&&d.length>1&&(o[c[0]]=void 0),o};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}})})}})(os)),os}var ds,Ra;function pp(){if(Ra)return ds;Ra=1;var i=wr(),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)},s=["v","o","s","i","u","e","p","c","b","t","r","z","a"],r=["i","c","b","a"];return ds=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||s,c=o.innerOrder||r,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].forEac
37h(function(p){l.push(n(u,h,p))})})}),a.media.forEach(function(u){l.push(n("m",i.m[0],u)),c.forEach(function(h){i[h].forEach(function(p){p.name in u&&u[p.name]!=null?l.push(n(h,p,u)):p.push in u&&u[p.push]!=null&&u[p.push].forEach(function(f){l.push(n(h,p,f))})})})}),l.join(`\r 38`)+`\r 39`},ds}var Pa;function mp(){if(Pa)return Fe;Pa=1;var i=hp(),e=pp(),t=wr();return Fe.grammar=t,Fe.write=e,Fe.parse=i.parse,Fe.parseParams=i.parseParams,Fe.parseFmtpConfig=i.parseFmtpConfig,Fe.parsePayloads=i.parsePayloads,Fe.parseRemoteCandidates=i.parseRemoteCandidates,Fe.parseImageAttributes=i.parseImageAttributes,Fe.parseSimulcastStreamList=i.parseSimulcastStreamList,Fe}var Ne=mp();const fp=.9,gp=1e3,vp=20,kt={NegotiationStarted:"negotiationStarted",NegotiationComplete:"negotiationComplete",OfferAnswered:"offerAnswered",RTPVideoPayloadTypes:"rtpVideoPayloadTypes"};class Ia extends De.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=U,this.iceLog=U,this.ddExtID=0,this.latestOfferId=0,this.latestAcknowledgedOfferId=0,this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate=!1,this.trackBitrates=[],this.remoteStereoMids=[],this.remoteNackMids=[],this.negotiate=kr(s=>m(this,void 0,void 0,function*(){this.emit(kt.NegotiationStarted);try{yield this.createAndSendOffer()}catch(r){if(s)s(r);else throw r}}),vp),this.close=()=>{this._pc&&(this.log.debug("closing peer connection"),this.pendingInitialOffer=void 0,this._pc.close(),this._pc.onconnectionstatechange=null,this._pc.oniceconnectionstatechange=null,this._pc.onicegatheringstatechange=null,this._pc.ondatachannel=null,this._pc.onnegotiationneeded=null,this._pc.onsignalingstatechange=null,this._pc.onicecandidate=null,this._pc.ondatachannel=null,this._pc.ontrack=null,this._pc.onconnectionstatechange=null,this._pc.oniceconnectionstatechange=null,this._pc=null)},this.loggerOptions=t,this.log=ke((n=t.loggerName)!==null&&n!==void 0?n:ce.PCTransport,()=>this.logContext),this.iceLog=ke(ce.ICE,()=>this.logContext),this.config=e,this._pc=this.createPC(),this.offerLock=new ge}createPC(){const e=new RTCPeerConnection(this.config);return e.onicecandidate=t=>{var n;t.candidate&&(this.iceLog.debug("local ICE candidate gathered",{candidate:t.candidate.candidate}),(n=this.onIceCandidate)===null||n===void 0||n.call(this,t.candidate))},e.onicecandidateerror=t=>{var n;this.iceLog.debug("ICE candidate error",{event:t}),(n=this.onIceCandidateError)===null||n===void 0||n.call(this,t)},e.oniceconnectionstatechange=()=>{var t;this.iceLog.debug("ICE connection state: ".concat(e.iceConnectionState)),(t=this.onIceConnectionStateChange)===null||t===void 0||t.call(this,e.iceConnectionState)},e.onsignalingstatechange=()=>{var t;this.log.debug("signaling state: ".concat(e.signalingState)),(t=this.onSignalingStatechange)===null||t===void 0||t.call(this,e.signalingState)},e.onconnectionstatechange=()=>{var t;this.log.debug("connection state: ".concat(e.connectionState)),(t=this.onConnectionStateChange)===null||t===void 0||t.call(this,e.connectionState)},e.ondatachannel=t=>{var n;this.log.debug("data channel opened by peer",{label:t.channel.label,id:t.channel.id}),(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 m(this,void 0,void 0,function*(){if(this.pc.remoteDescription&&!this.restartingIce)return this.pc.addIceCandidate(e);this.iceLog.debug("queuing remote ICE candidate until remote description applied",{pendingCount:this.pendingCandidates.length+1}),this.pendingCandidates.push(e)})}setRemoteDescription(e,t){return m(this,void 0,void 0,function*(){var n,s;if(e.type==="answer"&&this.latestOfferId>0&&t>0&&t!==this.latestOfferId)return this.log.warn("ignoring answer for old offer",{offerId:t,latestOfferId:this.latestOfferId}),!1;let r;if(e.type==="offer"){let a=yp(e),o=a.stereoMids,d=a.nackMids;this.remoteStereoMids=o,this.remoteNackMids=d}else if(e.type==="answer"){if(this.pendingInitialOffer&&this._pc){const d=this.pendingInitialOffer;this.pendingInitialOffer=void 0;const c=Ne.parse((n=d.sdp)!==null&&n!==void 0?n:"");
39c.media.forEach(l=>{Kn(l)}),this.log.debug("setting pending initial offer before processing answer"),yield this.setMungedSDP(d,Ne.write(c))}const a=Ne.parse((s=e.sdp)!==null&&s!==void 0?s:"");a.media.forEach(d=>{const c=_n(d.mid);d.type==="audio"&&this.trackBitrates.some(l=>{if(!l.transceiver||c!=l.transceiver.mid)return!1;let u=0;if(d.rtp.some(p=>p.codec.toUpperCase()===l.codec.toUpperCase()?(u=p.payload,!0):!1),u===0)return!0;let h=!1;for(const p of d.fmtp)if(p.payload===u){p.config=p.config.split(";").filter(f=>!f.includes("maxaveragebitrate")).join(";"),l.maxbr>0&&(p.config+=";maxaveragebitrate=".concat(l.maxbr*1e3)),h=!0;break}return h||l.maxbr>0&&d.fmtp.push({payload:u,config:"maxaveragebitrate=".concat(l.maxbr*1e3)}),!0})});const o=this.getPlaceholderMids();o.size>0&&Da(a.media,d=>o.has(_n(d.mid))),r=Ne.write(a)}return yield this.setMungedSDP(e,r,!0),this.pendingCandidates.length>0&&this.iceLog.debug("flushing queued ICE candidates",{count:this.pendingCandidates.length}),this.pendingCandidates.forEach(a=>{this.pc.addIceCandidate(a)}),this.pendingCandidates=[],this.restartingIce=!1,e.type==="answer"&&(this.latestAcknowledgedOfferId=t,this.emit(kt.OfferAnswered,t)),this.renegotiate?(this.renegotiate=!1,yield this.createAndSendOffer()):e.type==="answer"&&(this.emit
39(kt.NegotiationComplete),e.sdp&&Ne.parse(e.sdp).media.forEach(o=>{o.type==="video"&&this.emit(kt.RTPVideoPayloadTypes,o.rtp)})),!0})}createInitialOffer(){return m(this,void 0,void 0,function*(){var e;const t=yield this.offerLock.lock();try{if(this.pc.signalingState!=="stable"){this.log.warn("signaling state is not stable, cannot create initial offer");return}const n=this.latestOfferId+1;this.latestOfferId=n;const s=yield this.pc.createOffer();this.pendingInitialOffer={sdp:s.sdp,type:s.type};const r=Ne.parse((e=s.sdp)!==null&&e!==void 0?e:"");return r.media.forEach(a=>{Kn(a)}),s.sdp=Ne.write(r),{offer:s,offerId:n}}finally{t()}})}createAndSendOffer(e){return m(this,void 0,void 0,function*(){var t;const n=yield this.offerLock.lock();try{if(this.onOffer===void 0)return;if(e?.iceRestart&&(this.iceLog.debug("restarting ICE"),this.restartingIce=!0),this._pc&&(this._pc.signalingState==="have-local-offer"||this.pendingInitialOffer)){const d=this._pc.remoteDescription;if(e?.iceRestart&&d)yield this._pc.setRemoteDescription(d);else{this.renegotiate=!0,this.log.debug("requesting renegotiation");return}}else if(!this._pc||this._pc.signalingState==="closed"){this.log.warn("could not createOffer with closed peer connection");return}this.log.debug("starting to negotiate");const s=this.latestOfferId+1;this.latestOfferId=s;const r=yield this.pc.createOffer(e);this.log.debug("original offer",{sdp:r.sdp});const a=Ne.parse((t=r.sdp)!==null&&t!==void 0?t:"");a.media.forEach(d=>{Kn(d),d.type==="audio"?Ma(d,["all"],[]):d.type==="video"&&this.trackBitrates.some(c=>{if(!d.msid||!c.cid||!d.msid.includes(c.cid))return!1;let l=0;if(d.rtp.some(f=>f.codec.toUpperCase()===c.codec.toUpperCase()?(l=f.payload,!0):!1),l===0)return!0;Ze(c.codec)&&!jt()&&this.ensureVideoDDExtensionForSVC(d,a);const u=Math.round(c.maxbr*fp),h=c.isScreenShare?u:Math.min(u,gp);let p=!1;for(const f of d.fmtp)if(f.payload===l){p=!0,f.config.includes("x-google-start-bitrate")||(f.config+=";x-google-start-bitrate=".concat(h));break}return p||d.fmtp.push({payload:l,config:"x-google-start-bitrate=".concat(h)}),!0})});const o=this.getPlaceholderMids();if(o.size>0&&Da(a.media,d=>o.has(_n(d.mid))),this.latestOfferId>s){this.log.warn("latestOfferId mismatch",{latestOfferId:this.latestOfferId,offerId:s});return}yield this.setMungedSDP(r,Ne.write(a)),this.onOffer(r,this.latestOfferId)}finally{n()}})}createAndSetAnswer(){return m(this,void 0,void 0,function*(){var e;const t=yield this.pc.createAnswer(),n=Ne.parse((e=t.sdp)!==null&&e!==void 0?e:"");return n.media.forEach(s=>{Kn(s),s.type==="audio"&&Ma(s,this.remoteStereoMids,this.remoteNackMids)}),yield this.setMungedSDP(t,Ne.write(n)),t})}getPlaceholderMids(){var e,t;return bp((t=(e=this._pc)===null||e===void 0?void 0:e.getTransceivers())!==null&&t!==void 0?t:[])}createDataChannel(e,t){return this.pc.createDataChannel(e,t)}addTransceiver(e,t){return this.pc.addTransceiver(e,t)}addTransceiverOfKind(e,t){return this.pc.addTransceiver(e,t)}addTrack(e){if(!this._pc)throw new X("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 X("PC closed, cannot configure");return(t=this._pc)===null||t===void 0?void 0:t.setConfiguration(e)}canRemoveTrack(){var e;return!!(!((e=this._pc)===null||e===void 0)&&e.removeTrack)}removeTrack(e){var t;return(t=this._pc)===null||t===void 0?void 0:t.removeTrack(e)}getConnectionState(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.connectionState)!==null&&t!==void 0?t:"closed"}getICEConnectionState(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.iceConnectionState)!==null&&t!==void 0?t:"closed"}getSignallingState(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.signalingState)!==null&&t!==void 0?t:"closed"}getTransceivers(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.getTransceivers())!==null&&t!==void 0?t:[]}getSenders(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.getSenders())!==null&&t!==void 0?t:[]}getLocalDescription(){var e;return(e=this._pc)===null||e===void 0?void 0:e.localDescription}getRemoteDescription(){var e;return(e=this.pc)===null||e===void 0?void 0:e.remoteDescription}getStats(){return this.pc.getStats()}getMaxMessageSize(){var e,t;return(t=(e=this._pc)===null||e===void 0?void 0:e.sctp)===null||t===void 0?void 0:t.maxMessageSize}getConnectedAddress(){return m(this,void 0,void 0,function*(){var e;if(!this._pc)return;let t="";const n=new Map,s=new Map;
39if((yield this._pc.getStats()).forEach(o=>{switch(o.type){case"transport":t=o.selectedCandidatePairId;break;case"candidate-pair":t===""&&o.selected&&(t=o.id),n.set(o.id,o);break;case"remote-candidate":s.set(o.id,"".concat(o.address,":").concat(o.port));break}}),t==="")return;const a=(e=n.get(t))===null||e===void 0?void 0:e.remoteCandidateId;if(a!==void 0)return s.get(a)})}setMungedSDP(e,t,n){return m(this,void 0,void 0,function*(){var s,r;const a=e.sdp;if(t){e.sdp=t;try{this.log.debug("setting munged ".concat(n?"remote":"local"," description")),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"),{error:o,mungedSdp:t,originalSdp:a}),e.sdp=a}}try{n?yield(s=this._pc)===null||s===void 0?void 0:s.setRemoteDescription(e):yield(r=this._pc)===null||r===void 0?void 0:r.setLocalDescription(e)}catch(o){let d="unknown error";o instanceof Error?d=o.message:typeof o=="string"&&(d=o);const c={error:d,sdp:e.sdp};throw t&&t!==a&&(c.mungedSdp=t),!n&&this.pc.remoteDescription&&(c.remoteSdp=this.pc.remoteDescription),this.log.error("unable to set ".concat(e.type),{fields:c}),new Bt(d)}})}ensureVideoDDExtensionForSVC(e,t){var n,s;if(!((n=e.ext)===null||n===void 0?void 0:n.some(a=>a.uri===ma))){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}(s=e.ext)===null||s===void 0||s.push({value:this.ddExtID,uri:ma})}}}function Ma(i,e,t){const n=_n(i.mid);let s=0;i.rtp.some(r=>r.codec==="opus"?(s=r.payload,!0):!1),s>0&&(i.rtcpFb||(i.rtcpFb=[]),t.includes(n)&&!i.rtcpFb.some(r=>r.payload===s&&r.type==="nack")&&i.rtcpFb.push({payload:s,type:"nack"}),(e.includes(n)||e.length===1&&e[0]==="all")&&i.fmtp.some(r=>r.payload===s?(r.config.includes("stereo=1")||(r.config+=";stereo=1"),!0):!1))}function bp(i){const e=new Set;for(const t of i)t.mid&&!t.sender.track&&e.add(t.mid);return e}function Da(i,e){var t,n;const s=new Map,r=new Set;for(const a of i){const o=e(a);for(const d of(t=a.fmtp)!==null&&t!==void 0?t:[])o?s.has(d.payload)||s.set(d.payload,d.config):(s.set(d.payload,d.config),r.add(d.payload))}if(s.size!==0){for(const a of i)if(e(a))for(const o of(n=a.fmtp)!==null&&n!==void 0?n:[]){const d=s.get(o.payload);d!==void 0&&o.config!==d&&(o.config=d)}}}function yp(i){var e;const t=[],n=[],s=Ne.parse((e=i.sdp)!==null&&e!==void 0?e:"");let r=0;return s.media.forEach(a=>{var o;const d=_n(a.mid);a.type==="audio"&&(a.rtp.some(c=>c.codec==="opus"?(r=c.payload,!0):!1),!((o=a.rtcpFb)===null||o===void 0)&&o.some(c=>c.payload===r&&c.type==="nack")&&n.push(d),a.fmtp.some(c=>c.payload===r?(c.config.includes("sprop-stereo=1")&&t.push(d),!0):!1))}),{stereoMids:t,nackMids:n}}function Kn(i){if(i.connection){const 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 _n(i){return typeof i=="number"?i.toFixed(0):i}const Hs="vp8",kp={audioPreset:Ns.music,dtx:!0,red:!0,forceStereo:!1,simulcast:!0,screenShareEncoding:gr.h1080fps15.encoding,stopMicTrackOnMute:!1,videoCodec:Hs,backupCodec:!0,preConnectBuffer:!1},ed={deviceId:{ideal:"default"},autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0,voiceIsolation:!0},td={deviceId:{ideal:"default"},resolution:On.h720.resolution},Tp={adaptiveStream:!1,dynacast:!1,stopLocalTrackOnUnpublish:!0,reconnectPolicy:new Uu,disconnectOnPageLeave:!0,webAudioMix:!1,singlePeerConnection:!0},Rr={autoSubscribe:!0,maxRetries:1,peerConnectionTimeout:15e3,websocketTimeout:15e3};var ne;(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"})(ne||(ne={}));class Aa{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 s;this.peerConnectionTimeout=Rr.peerConnectionTimeout,this.log=U,this.iceLog=U,this.updateState=()=>{var r,a;const o=this.state,d=this.requiredTransports.map(c=>c.getConnectionState());d.every(c=>c==="connected")?this.state=ne.CONNECTED:d.some(c=>c==="failed")?this.state=ne.FAILED:d.some(c=>c==="connecting")?this.state=ne.CONNECTING:d.every(c=>c==="closed")?this.state=ne.CLOSED:d.some(c=>c==="closed")?this.state=ne.CLOSING:d.every(c=>c==="new")&&(this.state=ne.NEW),o!==this.state&&(this.log.debug("pc state change: from ".concat(ne[o]," to ").concat(ne[this.state])),(r=this.onStateChange)===null||r===void 0||r.call(this,this.state,this.publisher.getConnectionState(),(a=this.subscriber)===null||a===void 0?void 0:a.getConnectionState()))},this.loggerOptions=t,this.log=ke((s=t.loggerName)!==null&&s!==void 0?s:ce.PCManager,()=>this.logContext),this.iceLog=ke(ce.ICE,()=>this.logContext),this.isPublisherConnectionRequired=e!=="subscriber-primary",this.isSubscriberConnectionRequired=e==="subscriber-primary",this.publisher=new Ia(n,t),this._mode=e,e!=="publisher-only"&&(this.subscriber=new Ia(n,t),this.subscriber.onConnectionStateChange=this.updateState,this.subscriber.onIceConnectionStateChange=this.updateState,this.subscriber.onSignalingStatechange=this.updateState,this.subscriber.onIceCandidate=r=>{var a;(a=this.onIceCandidate)===null||a===void 0||a.call(this,r,We.SUBSCRIBER)},this.subscriber.onDataChannel=r=>{var a;(a=this.onDataChannel)===null||a===void 0||a.call(this,r)},this.subscriber.onTrack=r=>{var a;(a=this.onTrack)===null||a===void 0||a.call(this,r)}),this.publisher.onConnectionStateChange=this.updateState,this.publisher.onIceConnectionStateChange=this.updateState,this.publisher.onSignalingStatechange=this.updateState,this.publisher.onIceCandidate=r=>{var a;(a=this.onIceCandidate)===null||a===void 0||a.call(this,r,We.PUBLISHER)},this.publisher.onTrack=r=>{var a;(a=this.onTrack)===null||a===void 0||a.call(this,r)},this.publisher.onOffer=(r,a)=>{var o;(o=this.onPublisherOffer)===null||o===void 0||o.call(this,r,a)},this.state=ne.NEW,this.connectionLock=new ge,this.remoteOfferLock=new ge}get logContext(){var e,t;return Object.assign({},(t=(e=this.loggerOptions).loggerContextCb)===null||t===void 0?void 0:t.call(e))}requirePublisher(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;this.isPublisherConnectionRequired=e,this.updateState()}createAndSendPublisherOffer(e){return this.publisher.createAndSendOffer(e)}setPublisherAnswer(e,t){return this.publisher.setRemoteDescription(e,t)}removeTrack(e){return this.publisher.removeTrack(e)}close(){return m(this,void 0,void 0,function*(){var e;if(this.publisher&&this.publisher.getSignallingState()!=="closed"){const t=this.publisher;for(const n of t.getSenders())try{t.canRemoveTrack()&&t.removeTrack(n)}catch(s){this.log.warn("could not removeTrack",{error:s})}}yield Promise.all([this.publisher.close(),(e=this.subscriber)===null||e===void 0?void 0:e.close()]),this.updateState()})}triggerIceRestart(){return m(this,void 0,void 0,function*(){this.iceLog.warn("triggering ICE restart"),this.subscriber&&(this.subscriber.restartingIce=!0),this.needsPublisher&&(yield this.createAndSendPublisherOffer({iceRestart:!0}))})}addIceCandidate(e,t){return m(this,void 0,void 0,function*(){var n;this.iceLog.debug("adding remote ICE candidate",{target:t,candidate:e}),t===We.PUBLISHER?yield this.publisher.addIceCandidate(e):yield(n=this.subscriber)===null||n===void 0?void 0:n.addIceCandidate(e)})}createSubscriberAnswerFromOffer(e,t){return m(this,void 0,void 0,function*(){var n,s,r;this.log.debug("received server offer",{RTCSdpType:e.type,sdp:e.sdp,signalingState:(n=this.subscriber)===null||n===void 0?void 0:n.getSignallingState().toString()});const a=yield this.remoteOfferLock.lock();try{return(yield(s=this.subscriber)===null||s===void 0?void 0:s.setRemoteDescription(e,t))?yield(r=this.subscriber)===null||r===void 0?void 0:r.createAndSetAnswer():void 0}finally{a()}})}updateConfiguration(e,t){var n;
39this.log.debug("updating rtc configuration",{iceRestart:t}),this.publisher.setConfiguration(e),(n=this.subscriber)===null||n===void 0||n.setConfiguration(e),t&&this.triggerIceRestart()}ensurePCTransportConnection(e,t){return m(this,void 0,void 0,function*(){var n;const s=yield this.connectionLock.lock();try{this.isPublisherConnectionRequired&&this.publisher.getConnectionState()!=="connected"&&this.publisher.getConnectionState()!=="connecting"&&(this.log.debug("negotiation required, start negotiating"),this.publisher.negotiate()),yield Promise.all((n=this.requiredTransports)===null||n===void 0?void 0:n.map(r=>this.ensureTransportConnected(r,e,t)))}finally{s()}})}negotiate(e){return m(this,void 0,void 0,function*(){return new _e((t,n)=>{const s=this.publisher.latestOfferId;if(this.publisher.latestAcknowledgedOfferId>s){this.log.debug("negotiation already handled in more recent acknowledged offer",this.logContext),t();return}let r=!1;const a=()=>{r||(r=!0,clearTimeout(c),this.publisher.off(kt.OfferAnswered,o),e.signal.removeEventListener("abort",d))},o=l=>{l>s&&(a(),t())},d=()=>{a(),n(new Bt("negotiation aborted"))},c=setTimeout(()=>{a(),n(new Bt("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){const n=(this.subscriber?this.subscriber.getTransceivers():this.publisher.getTransceivers()).find(s=>s.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===We.PUBLISHER?this.publisher.getConnectedAddress():e===We.SUBSCRIBER?this.publisher.getConnectedAddress():this.requiredTransports[0].getConnectedAddress()}get requiredTransports(){const e=[];return this.isPublisherConnectionRequired&&e.push(this.publisher),this.isSubscriberConnectionRequired&&this.subscriber&&e.push(this.subscriber),e}ensureTransportConnected(e,t){return m(this,arguments,void 0,function(n,s){var r=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)=>m(r,void 0,void 0,function*(){const l=()=>{this.log.warn("abort transport connection"),ae.clearTimeout(u),c(x.cancelled("room connection has been cancelled"))};s?.signal.aborted&&l(),s?.signal.addEventListener("abort",l);const u=ae.setTimeout(()=>{s?.signal.removeEventListener("abort",l),c(x.internal("could not establish pc connection"))},a);for(;this.state!==ne.CONNECTED;)if(yield Se(50),s?.signal.aborted){c(x.cancelled("room connection has been cancelled"));return}ae.clearTimeout(u),s?.signal.removeEventListener("abort",l),d()}))})()})}}class nd{constructor(e){this.bufferStatusLow=!0,this.headroomLock=new ge,this.waiterAbortController=new AbortController,this.kind=e.kind,this.lowWaterMark=e.lowWaterMark,this.highWaterMark=e.highWaterMark,this.isEngineClosed=e.isEngineClosed,this.onBufferStatusChanged=e.onBufferStatusChanged}get channelHandle(){return this.handle}attach(e){this.handle&&this.handle!==e&&this.invalidateWaiters("data channel replaced"),this.handle=e}detach(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"data channel torn down";this.handle&&this.invalidateWaiters(e),this.handle=void 0}getChannel(){return this.handle}isBelowHighWaterMark(e){return e.bufferedAmount<=this.highWaterMark}isBelowLowWaterMark(e){return e.bufferedAmount<=e.bufferedAmountLowThreshold}lockHeadroom(){return this.headroomLock.lock()}waitForHeadroomWithLock(){return m(this,void 0,void 0,function*(){const e=yield this.lockHeadroom();try{yield this.waitForHeadroomWithoutLock()}finally{e()}})}waitForHeadroomWithoutLock(){return m(this,void 0,void 0,function*(){if(this.isEngineClosed())throw new X("engine closed");const e=this.getChannel();if(!e)throw new X("DataChannel not found, kind: ".concat(this.kind));if(this.isBelowHighWaterMark(e))return;const t=this.waiterAbortController.signal;yield new _e((n,s)=>{const r=()=>{d(),n()},a=()=>{d(),s(new X("DataChannel ".concat(this.kind," closed while draining the buffer")))},o=()=>{d(),s(new X("DataChannel ".concat(this.kind," was replaced or torn down while waiting for headroom")))},d=()=>{e.removeEventListener("bufferedamountlow",r),e.removeEventListener("close",a),t.removeEventListener("abort",o)};if(t.aborted){o();return}e.addEventListener("bufferedamountlow",r),e.addEventListener("close",a),t.addEventListener("abort",o)})})}invalidateWaiters(e){this.waiterAbortController.abort(e),this.waiterAbortController=new AbortController}refreshBufferStatus(){var e;const t=this.getChannel();if(!t)return;const n=this.isBelowLowWaterMark(t);n!==this.bufferStatusLow&&(this.bufferStatusLow=n,(e=this.onBufferStatusChanged)===null||e===void 0||e.call(this,n))}}class Oa extends nd{constructor(e){super(e),this.statCurrentBytes=0,this.statByterate=0,this.dropCount=0,this.bufferFullBehavior=e.bufferFullBehavior,this.shouldSkipSends=e.shouldSkipSends}send(e){return m(this,void 0,void 0,function*(){const t=this.getChannel();if(t){switch(this.bufferFullBehavior){case"wait":this.isBelowHighWaterMark(t)||(yield this.waitForHeadroomWithLock());break;case"drop":if(!this.isBelowLowWaterMark(t)){this.dropCount+=1,this.dropCount%100===0&&U.warn("dropping lossy data channel messages, total dropped: ".concat(this.dropCount));return}}if(this.statCurrentBytes+=e.byteLength,!this.shouldSkipSends())try{t.send(e),this.refreshBufferStatus()}catch(n){if(n instanceof TypeError)U.error(n);else throw n}}})}startThresholdTuning(){this.stopThresholdTuning(),this.statInterval=ae.setInterval(()=>{this.statByterate=this.statCurrentBytes,this.statCurrentBytes=0;const e=this.getChannel();if(e){const t=this.statByterate/10;e.bufferedAmountLowThreshold=Math.min(Math.max(t,this.lowWaterMark),this.highWaterMark)}},1e3)}stopThresholdTuning(){this.statByterate=0,this.statCurrentBytes=0,this.statInterval&&(ae.clearInterval(this.statInterval),this.statInterval=void 0),this.dropCount=0}}class Na{constructor(){this.buffer=[],this._totalSize=0,this._sentSize=0}push(e){this.buffer.push(e),this._totalSize+=e.data.byteLength,e.sent&&(this._sentSize+=e.data.byteLength)}pop(){const e=this.buffer.shift();return e&&(this._totalSize-=e.data.byteLength,e.sent&&(this._sentSize-=e.data.byteLength)),e}getAll(){return this.buffer.slice()}getUnsent(){return this.buffer.filter(e=>!e.sent)}markSent(e){e.sent||(e.sent=!0,this._sentSize+=e.data.byteLength)}markAllUnsent(){for(const e of this.buffer)e.sent=!1;this._sentSize=0}popToSequence(e){for(;this.buffer.length>0&&this.buffer[0].sequence<=e;)this.pop()}alignBufferedAmount(e){for(;this.buffer.length>0;){const t=this.buffer[0];if(!t.sent||this._sentSize-t.data.byteLength<=e)break;this.pop()}}get length(){return this.buffer.length}}class Sp extends nd{constructor(e){super(e),this.messageBuffer=new Na,this.sequence=1,this.isDeferringSends=e.isDeferringSends}nextSequence(){const e=this.sequence;return this.sequence+=1,e}send(e,t){return m(this,void 0,void 0,function*(){if(this.isDeferringSends()){this.messageBuffer.push({data:e,sequence:t,sent:!1});return}const n=this.getChannel();if(n){try{yield this.waitForHeadroomWithLock()}catch(s){if(this.isEngineClosed())throw s;this.messageBuffer.push({data:e,sequence:t,sent:!1});return}if(this.isDeferringSends()){this.messageBuffer.push({data:e,sequence:t,sent:!1});return}this.messageBuffer.push({data:e,sequence:t,sent:!0}),n.send(e),this.refreshBufferStatus()}})}replay(e){return m(this,void 0,void 0,function*(){const t=this.getChannel();if(!t)return;this.messageBuffer.popToSequence(e);const n=yield this.lockHeadroom();try{this.messageBuffer.markAllUnsent();for(let s=this.messageBuffer.getUnsent();s.length>0;s=this.messageBuffer.getUnsent())for(const r of s)yield this.waitForHeadroomWithoutLock(),t.send(r.data),this.messageBuffer.markSent(r)}finally{n()}this.refreshBufferStatus()})}refreshBufferStatus(){const e=this.channelHandle;e&&this.messageBuffer.alignBufferedAmount(e.bufferedAmount),super.refreshBufferStatus()}reset(){this.messageBuffer=new Na,this.sequence=1}}var q;(function(i){i[i.RELIABLE=0]="RELIABLE",i[i.LOSSY=1]="LOSSY",i[i.DATA_TRACK_LOSSY=2]="DATA_TRACK_LOSSY"})(q||(q={}));const Cp=64*1024,Ep=1024*1024,_p=8*1024,wp=256*1024;function Rp(i){return i===q.RELIABLE?Cp:_p}function Pp(i){return i===q.RELIABLE?Ep:wp}const La="_lossy",xa="_reliable",Ua="_data_track";class Ip{constructor(e){this.opts=e;const t=n=>({kind:n,lowWaterMark:Rp(n),highWaterMark:Pp(n),isEngineClosed:e.isEngineClosed,onBufferStatusChanged:s=>e.onBufferStatusChanged(n,s)});this.reliable=new Sp(Object.assign(Object.assign({},t(q.RELIABLE)),{isDeferringSends:e.isReconnecting})),this.lossy=new Oa(Object.assign(Object.assign({},t(q.LOSSY)),{bufferFullBehavior:"drop",shouldSkipSends:e.isReconnecting})),this.dataTrack=new Oa(Object.assign(Object.assign({},t(q.DATA_TRACK_LOSSY)),{bufferFullBehavior:"wait",shouldSkipSends:e.isReconnecting}))}channelFor(e){switch(e){case q.RELIABLE:return this.reliable;case q.LOSSY:return this.lossy;case q.DATA_TRACK_LOSSY:return this.dataTrack}}getHandle(e){if(!(arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1))return this.channelFor(e).channelHandle;switch(e){case q.RELIABLE:return this.reliableSub;case q.LOSSY:return this.lossySub;case q.DATA_TRACK_LOSSY:return this.dataTrackSub}}get hasPublisherChannels(){return!!(this.reliable.channelHandle||this.lossy.channelHandle||this.dataTrack.channelHandle)}createPublisherChannels(e){for(const n of[this.lossy,this.reliable,this.dataTrack]){const s=n.channelHandle;
39s&&(s.onmessage=null,s.onerror=null,s.onclose=null)}const t=(n,s,r)=>{s.onmessage=r,s.onerror=this.opts.onDataError,s.onclose=()=>this.opts.onChannelClose(n.kind),s.bufferedAmountLowThreshold=n.lowWaterMark,s.onbufferedamountlow=()=>n.refreshBufferStatus(),n.attach(s)};t(this.lossy,e.createPublisherDataChannel(La,{ordered:!1,maxRetransmits:0}),this.opts.onDataMessage),t(this.reliable,e.createPublisherDataChannel(xa,{ordered:!0}),this.opts.onDataMessage),t(this.dataTrack,e.createPublisherDataChannel(Ua,{ordered:!1,maxRetransmits:0}),this.opts.onDataTrackMessage),this.lossy.startThresholdTuning()}adoptSubscriberChannel(e){let t;if(e.label===xa)this.reliableSub=e,t=this.opts.onDataMessage;else if(e.label===La)this.lossySub=e,t=this.opts.onDataMessage;else if(e.label===Ua)this.dataTrackSub=e,t=this.opts.onDataTrackMessage;else return!1;return e.onmessage=t,!0}teardown(){const e=t=>{t&&(t.onbufferedamountlow=null,t.onclose=null,t.onclosing=null,t.onerror=null,t.onmessage=null,t.onopen=null,t.close())};for(const t of[this.lossy,this.reliable,this.dataTrack]){const n=t.channelHandle;t.detach("peer connections cleaned up"),e(n)}e(this.lossySub),e(this.reliableSub),e(this.dataTrackSub),this.lossySub=void 0,this.reliableSub=void 0,this.dataTrackSub=void 0,this.reliable.reset()}}const Pr=typeof MediaRecorder<"u";class Mp{constructor(){throw new Error("MediaRecorder is not available in this environment")}}const Dp=Pr?MediaRecorder:Mp;class Ap extends Dp{constructor(e,t){if(!Pr)throw new Error("MediaRecorder is not available in this environment");super(new MediaStream([e.mediaStreamTrack]),t);let n,s;const r=()=>s===void 0,a=()=>{this.removeEventListener("dataavailable",n),this.removeEventListener("stop",a),this.removeEventListener("error",o),s?.close(),s=void 0},o=d=>{s?.error(d),this.removeEventListener("dataavailable",n),this.removeEventListener("stop",a),this.removeEventListener("error",o),s=void 0};this.byteStream=new ReadableStream({start:d=>{s=d,n=c=>m(this,void 0,void 0,function*(){let l;if(c.data.arrayBuffer){const u=yield c.data.arrayBuffer();l=new Uint8Array(u)}else if(c.data.byteArray)l=c.data.byteArray;else throw new Error("no data available!");r()||d.enqueue(l)}),this.addEventListener("dataavailable",n)},cancel:()=>{a()}}),this.addEventListener("stop",a),this.addEventListener("error",o)}}function Op(){return Pr}const Np=1e3,Lp=1e4;class id extends C{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 s=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1,r=arguments.length>4?arguments[4]:void 0;super(e,t,r),this.manuallyStopped=!1,this.pendingDeviceChange=!1,this._isUpstreamPaused=!1,this.handleTrackMuteEvent=()=>this.debouncedTrackMuteHandler().catch(()=>this.log.debug("track mute bounce got cancelled by an unmute event",this.logContext)),this.debouncedTrackMuteHandler=kr(()=>m(this,void 0,void 0,function*(){yield this.pauseUpstream()}),5e3),this.handleTrackUnmuteEvent=()=>m(this,void 0,void 0,function*(){this.debouncedTrackMuteHandler.cancel("unmute"),yield this.resumeUpstream()}),this.handleEnded=()=>{this.isInBackground&&(this.reacquireTrack=!0),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent),this.emit(P.Ended,this)},this.reacquireTrack=!1,this.providedByUser=s,this.muteLock=new ge,this.pauseUpstreamLock=new ge,this.trackChangeLock=new ge,this.trackChangeLock.lock().then(a=>m(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!==C.Kind.Video)return;const 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 m(this,void 0,void 0,function*(){var s;if(e===this._mediaStreamTrack&&!t)return;
39this._mediaStreamTrack&&(this.attachedElements.forEach(a=>{Zt(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 r;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&&(Jt(e,this.processorElement),this.processorElement.muted=!0),yield this.processor.restart({track:e,kind:this.kind,element:this.processorElement,localTrack:this}),r=this.processor.processedTrack}this.sender&&((s=this.sender.transport)===null||s===void 0?void 0:s.state)!=="closed"&&(yield this.sender.replaceTrack(r??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=>{Jt(r??e,a)}))})}waitForDimensions(){return m(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===C.Kind.Audio)throw new Error("cannot get dimensions for audio tracks");((n=we())===null||n===void 0?void 0:n.os)==="iOS"&&(yield Se(10));const s=Date.now();for(;Date.now()-s<t;){const r=e.dimensions;if(r)return r;yield Se(50)}throw new lt("unable to get track dimensions after timeout")})()})}setDeviceId(e){return m(this,void 0,void 0,function*(){return this._constraints.deviceId===e&&this._mediaStreamTrack.getSettings().deviceId===en(e)?!0:(this._constraints.deviceId=e,this.isMuted?(this.pendingDeviceChange=!0,!0):(yield this.restartTrack(),en(e)===this._mediaStreamTrack.getSettings().deviceId))})}getDeviceId(){return m(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return(function*(){if(e.source===C.Source.ScreenShare)return;const n=e._mediaStreamTrack.getSettings(),s=n.deviceId,r=n.groupId,a=e.kind===C.Kind.Audio?"audioinput":"videoinput";return t?fe.getInstance().normalizeDeviceId(a,s,r):s})()})}mute(){return m(this,void 0,void 0,function*(){return this.setTrackMuted(!0),this})}unmute(){return m(this,void 0,void 0,function*(){return this.setTrackMuted(!1),this})}replaceTrack(e,t){return m(this,void 0,void 0,function*(){const n=yield this.trackChangeLock.lock();try{if(!this.sender)throw new lt("unable to replace an unpublished track");let s,r;typeof t=="boolean"?s=t:t!==void 0&&(s=t.userProvidedTrack,r=t.stopProcessor),this.providedByUser=s??!0,this.log.debug("replace MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(e),r&&this.processor&&(yield this.internalStopProcessor())}finally{n()}return yield this.onSenderTrackSwapped(),this})}onSenderTrackSwapped(){return m(this,void 0,void 0,function*(){})}restart(e,t){return m(this,void 0,void 0,function*(){this.manuallyStopped=!1;const n=yield this.trackChangeLock.lock();try{e||(e=this._constraints);const s=e,r=s.deviceId,a=s.facingMode,o=Fu(e,["deviceId","facingMode"]);this.log.debug("restarting track with constraints",Object.assign(Object.assign({},this.logContext),{constraints:e}));const d={audio:!1,video:!1};this.kind===C.Kind.Video?d.video=r||a?{deviceId:r,facingMode:a}:!0:d.audio=r?Object.assign({deviceId:r},o):!0,this.attachedElements.forEach(u=>{Zt(this.mediaStreamTrack,u)}),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.stop();const l=(yield navigator.mediaDevices.getUserMedia(d)).getTracks()[0];return this.kind===C.Kind.Video&&(yield l.applyConstraints(o)),l.addEventListener("ended",this.handleEnded),this.log.debug("re-acquired MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(l,!1,t),this._constraints=e,this.pendingDeviceChange=!1,this.emit
39(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(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return m(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),zc()&&(this.log.debug("visibility changed, is in Background: ".concat(this.isInBackground),this.logContext),!this.isInBackground&&this.needsReAcquisition&&!this.isUserProvided&&!this.isMuted&&(this.log.debug("track needs to be reacquired, restarting ".concat(this.source),this.logContext),yield this.restart(),this.reacquireTrack=!1))})}stop(){var e;this.manuallyStopped=!0,super.stop(),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent),(e=this.processor)===null||e===void 0||e.destroy(),this.processor=void 0}pauseUpstream(){return m(this,void 0,void 0,function*(){var e;const t=yield this.pauseUpstreamLock.lock();try{if(this._isUpstreamPaused===!0)return;if(!this.sender){this.log.warn("unable to pause upstream for an unpublished track",this.logContext);return}this._isUpstreamPaused=!0,this.emit(P.UpstreamPaused,this);const n=we();if(n?.name==="Safari"&&nt(n.version,"12.0")<0)throw new fr("pauseUpstream is not supported on Safari < 12.");((e=this.sender.transport)===null||e===void 0?void 0:e.state)!=="closed"&&(yield this.sender.replaceTrack(null))}finally{t()}})}resumeUpstream(){return m(this,void 0,void 0,function*(){var e;const t=yield this.pauseUpstreamLock.lock();try{if(this._isUpstreamPaused===!1)return;if(!this.sender){this.log.warn("unable to resume upstream for an unpublished track",this.logContext);return}this._isUpstreamPaused=!1,this.emit(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 m(this,void 0,void 0,function*(){var e;return!((e=this.sender)===null||e===void 0)&&e.getStats?yield this.sender.getStats():void 0})}setProcessor(e){return m(this,arguments,void 0,function(t){var n=this;let s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return(function*(){var r;const a=yield n.trackChangeLock.lock();try{n.log.debug("setting up processor",n.logContext);const 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(Jt(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(const c of n.attachedElements)c!==n.processorElement&&s&&(Zt(n._mediaStreamTrack,c),Jt(n.processor.processedTrack,c));yield(r=n.sender)===null||r===void 0?void 0:r.replaceTrack(n.processor.processedTrack)}n.emit(P.TrackProcessorUpdate,n.processor)}finally{a()}yield n.onSenderTrackSwapped()})()})}getProcessor(){return this.processor}stopProcessor(){return m(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return(function*(){const n=yield e.trackChangeLock.lock();try{yield e.internalStopProcessor(t)}finally{n()}yield e.onSenderTrackSwapped()})()})}internalStopProcessor(){return m(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return(function*(){var n,s;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||((s=e.processorElement)===null||s===void 0||s.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(!Op()){this.log.warn("MediaRecorder is not available, cannot start prec
39onnect buffer",this.logContext);return}if(this.localTrackRecorder){this.log.warn("preconnect buffer already started");return}else{let t="audio/webm;codecs=opus";MediaRecorder.isTypeSupported(t)||(t="video/mp4"),this.localTrackRecorder=new Ap(this,{mimeType:t})}this.localTrackRecorder.start(e),this.autoStopPreConnectBuffer=setTimeout(()=>{this.log.warn("preconnect buffer timed out, stopping recording automatically",this.logContext),this.stopPreConnectBuffer()},Lp)}stopPreConnectBuffer(){clearTimeout(this.autoStopPreConnectBuffer),this.localTrackRecorder&&(this.localTrackRecorder.stop(),this.localTrackRecorder=void 0)}getPreConnectBuffer(){var e;return(e=this.localTrackRecorder)===null||e===void 0?void 0:e.byteStream}getPreConnectBufferMimeType(){var e;return(e=this.localTrackRecorder)===null||e===void 0?void 0:e.mimeType}}class gi extends id{get enhancedNoiseCancellation(){return this.isKrispNoiseFilterEnabled}constructor(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,s=arguments.length>3?arguments[3]:void 0,r=arguments.length>4?arguments[4]:void 0;super(e,C.Kind.Audio,t,n,r),this.stopOnMute=!1,this.isKrispNoiseFilterEnabled=!1,this.monitorSender=()=>m(this,void 0,void 0,function*(){if(!this.sender){this._currentBitrate=0;return}let a;try{a=yield this.getSenderStats()}catch(o){this.log.error("could not get audio sender stats",Object.assign(Object.assign({},this.logContext),{error:o}));return}a&&this.prevStats&&(this._currentBitrate=Ni(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,me.TF_ENHANCED_NOISE_CANCELLATION,!0)},this.handleKrispNoiseFilterDisable=()=>{this.isKrispNoiseFilterEnabled=!1,this.log.debug("Krisp noise filter disabled",this.logContext),this.emit(P.AudioTrackFeatureUpdate,this,me.TF_ENHANCED_NOISE_CANCELLATION,!1)},this.audioContext=s,this.checkForSilence()}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return m(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.log.debug("Track already muted",this.logContext),this):(this.source===C.Source.Microphone&&this.stopOnMute&&!this.isUserProvided&&(this.log.debug("stopping mic track",this.logContext),this._mediaStreamTrack.stop()),yield e.mute.call(this),this)}finally{t()}})}unmute(){const e=Object.create(null,{unmute:{get:()=>super.unmute}});return m(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.source===C.Source.Microphone&&(this.stopOnMute||this._mediaStreamTrack.readyState==="ended"||this.pendingDeviceChange)&&!this.isUserProvided&&(this.log.debug("reacquiring mic track",this.logContext),yield this.restart(void 0,!0)),yield e.unmute.call(this),this):(this.log.debug("Track already unmuted",this.logContext),this)}finally{t()}})}restartTrack(e){return m(this,void 0,void 0,function*(){let t;if(e){const n=vr({audio:e});typeof n.audio!="boolean"&&(t=n.audio)}yield this.restart(t)})}applyConstraints(e){return m(this,void 0,void 0,function*(){const t=yield this.trackChangeLock.lock();try{const n=yield this._mediaStreamTrack.applyConstraints(e);return this._constraints=Object.assign(Object.assign({},this._constraints),e),n}finally{t()}})}restart(e,t){const n=Object.create(null,{restart:{get:()=>super.restart}});return m(this,void 0,void 0,function*(){const s=yield n.restart.call(this,e,t);return this.checkForSilence(),s})}startMonitor(){Me()&&(this.monitorInterval||(this.monitorInterval=setInterval(()=>{this.monitorSender()},Tr)))}setProcessor(e){return m(this,void 0,void 0,function*(){var t;const n=yield this.trackChangeLock.lock();try{if(!Je()&&!this.audioContext)throw Error("Audio context needs to be set on LocalAudioTrack in order to enable processors");this.processor&&(yield this.internalStopProcessor());const s={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(s),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
39(P.TrackProcessorUpdate,this.processor)}finally{n()}})}setAudioContext(e){this.audioContext=e}getSenderStats(){return m(this,void 0,void 0,function*(){var e;if(!(!((e=this.sender)===null||e===void 0)&&e.getStats))return;const t=yield this.sender.getStats();let n;return t.forEach(s=>{s.type==="outbound-rtp"&&(n={type:"audio",streamId:s.id,packetsSent:s.packetsSent,packetsLost:s.packetsLost,bytesSent:s.bytesSent,timestamp:s.timestamp,roundTripTime:s.roundTripTime,jitter:s.jitter})}),n})}checkForSilence(){return m(this,void 0,void 0,function*(){const e=yield Hc(this);return e&&(this.isMuted||this.log.debug("silence detected on local audio track",this.logContext),this.emit(P.AudioSilenceDetected)),e})}}function xp(i,e,t){switch(i.kind){case"audio":return new gi(i,e,!1,void 0,t);case"video":return new bi(i,e,!1,t);default:throw new lt("unsupported track type: ".concat(i.kind))}}const Up=Object.values(On),Fp=Object.values(Ls),Bp=Object.values(gr),qp=[On.h180,On.h360],Vp=[Ls.h180,Ls.h360],Wp=i=>[{scaleResolutionDownBy:2,fps:i.encoding.maxFramerate}].map(t=>{var n,s;return new J(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)/((s=t.fps)!==null&&s!==void 0?s:30))))),t.fps,i.encoding.priority)}),Ks=["q","h","f"];function vi(i,e,t,n){var s,r;let a=n?.videoEncoding;i&&(a=n?.screenShareEncoding);const o=n?.simulcast,d=n?.scalabilityMode,c=n?.videoCodec;if(!a&&!o&&!d||!e||!t)return[{}];a||(a=jp(i,e,t,c),U.debug("using video encoding",a));const l=a.maxFramerate,u=new J(e,t,a.maxBitrate,a.maxFramerate,a.priority);if(d&&Ze(c)){const k=new rd(d),T=[];if(k.spatial>3)throw new Error("unsupported scalabilityMode: ".concat(d));const S=we();if(Nn()||Je()||S?.name==="Chrome"&&nt(S?.version,"113")<0){const N=k.suffix=="h"?2:3,v=Sh(S);for(let y=0;y<k.spatial;y+=1)T.push({rid:Ks[2-y],maxBitrate:a.maxBitrate/Math.pow(N,y),maxFramerate:u.encoding.maxFramerate,scaleResolutionDownBy:v?Math.pow(2,y):void 0});T[0].scalabilityMode=d}else T.push({maxBitrate:a.maxBitrate,maxFramerate:u.encoding.maxFramerate,scalabilityMode:d});return u.encoding.priority&&(T[0].priority=u.encoding.priority,T[0].networkPriority=u.encoding.priority),U.debug("using svc encoding",{encodings:T}),T}if(!o)return[a];let h;i?h=(s=Ba(n?.screenShareSimulcastLayers))!==null&&s!==void 0?s:Fa(i,u):h=(r=Ba(n?.videoSimulcastLayers))!==null&&r!==void 0?r:Fa(i,u);let p;if(h.length>0){const k=h[0];if(h.length>1){var f=h,g=L(f,2);p=g[1]}const T=Math.max(e,t);if(T>=960&&p)return ls(e,t,[k,p,u],l);if(T>=480)return ls(e,t,[k,u],l)}return ls(e,t,[u])}function sd(i,e,t){var n,s,r,a;if(!t.backupCodec||t.backupCodec===!0||t.backupCodec.codec===t.videoCodec)return;e!==t.backupCodec.codec&&U.warn("requested a different codec than specified as backup",{serverRequested:e,backup:t.backupCodec.codec}),t.videoCodec=e,t.videoEncoding=t.backupCodec.encoding;const o=i.mediaStreamTrack.getSettings(),d=(n=o.width)!==null&&n!==void 0?n:(s=i.dimensions)===null||s===void 0?void 0:s.width,c=(r=o.height)!==null&&r!==void 0?r:(a=i.dimensions)===null||a===void 0?void 0:a.height;return i.source===C.Source.ScreenShare&&t.simulcast&&(t.simulcast=!1),vi(i.source===C.Source.ScreenShare,d,c,t)}function jp(i,e,t,n){const s=Hp(i,e,t);let r=s[0].encoding;const a=Math.max(e,t);for(let o=0;o<s.length;o+=1){const d=s[o];if(r=d.encoding,d.width>=a)break}if(n)switch(n){case"av1":case"h265":r=Object.assign({},r),r.maxBitrate=r.maxBitrate*.7;break;case"vp9":r=Object.assign({},r),r.maxBitrate=r.maxBitrate*.85;break}return r}function Hp(i,e,t){if(i)return Bp;const n=e>t?e/t:t/e;return Math.abs(n-16/9)<Math.abs(n-4/3)?Up:Fp}function Fa(i,e){if(i)return Wp(e);const t=e.width,n=e.height,s=t>n?t/n:n/t;return Math.abs(s-16/9)<Math.abs(s-4/3)?qp:Vp}function ls(i,e,t,n){const s=[];if(t.forEach((r,a)=>{if(a>=Ks.length)return;const o=Math.min(i,e),c={rid:Ks[a],scaleResolutionDownBy:Math.max(1,o/Math.min(r.width,r.height)),maxBitrate:r.encoding.maxBitrate},l=n&&r.encoding.maxFramerate?Math.min(n,r.encoding.maxFramerate):r.encoding.maxFramerate;l&&(c.maxFramerate=l);const u=we(),h=u?.name==="Firefox"&&u.os!=="iOS"||a===0;r.encoding.priority&&h&&(c.priority=r.encoding.priority,c.networkPriority=r.encoding.priority),s.push(c)}),Je()&&$c()==="ios"){let r;
vendor: 6,583 bytes, line 39
39s.forEach(o=>{r?o.maxFramerate&&o.maxFramerate>r&&(r=o.maxFramerate):r=o.maxFramerate});let a=!0;s.forEach(o=>{var d;o.maxFramerate!=r&&(a&&(a=!1,U.info("Simulcast on iOS React-Native requires all encodings to share the same framerate.")),U.info('Setting framerate of encoding "'.concat((d=o.rid)!==null&&d!==void 0?d:"",'" to ').concat(r)),o.maxFramerate=r)})}return s}function Ba(i){if(i)return i.slice().sort((e,t)=>{const n=e.encoding,s=t.encoding;return n.maxBitrate>s.maxBitrate?1:n.maxBitrate<s.maxBitrate?-1:n.maxBitrate===s.maxBitrate&&n.maxFramerate&&s.maxFramerate?n.maxFramerate>s.maxFramerate?1:-1:0})}class rd{constructor(e){const t=e.match(/^L(\d)T(\d)(h|_KEY|_KEY_SHIFT){0,1}$/);if(!t)throw new Error("invalid scalability mode");if(this.spatial=parseInt(t[1]),this.temporal=parseInt(t[2]),t.length>3)switch(t[3]){case"h":case"_KEY":case"_KEY_SHIFT":this.suffix=t[3]}}toString(){var e;return"L".concat(this.spatial,"T").concat(this.temporal).concat((e=this.suffix)!==null&&e!==void 0?e:"")}}function Kp(i){switch(i.source){case C.Source.Camera:return"maintain-framerate";case C.Source.ScreenShare:return"maintain-resolution";default:return"balanced"}}const Gp=5e3;class bi extends id{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,s=arguments.length>3?arguments[3]:void 0;super(e,C.Kind.Video,t,n,s),this.simulcastCodecs=new Map,this.degradationPreference="balanced",this.isCpuConstrained=!1,this.optimizeForPerformance=!1,this.monitorSender=()=>m(this,void 0,void 0,function*(){if(!this.sender){this._currentBitrate=0;return}let r;try{r=yield this.getSenderStats()}catch(d){this.log.error("could not get video sender stats",Object.assign(Object.assign({},this.logContext),{error:d}));return}const a=new Map(r.map(d=>[d.rid,d])),o=r.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;const h=(u=this.prevStats)===null||u===void 0?void 0:u.get(l);d+=Ni(c,h)}),this._currentBitrate=d}this.prevStats=a}),this.senderLock=new ge}get isSimulcast(){return!!(this.sender&&this.sender.getParameters().encodings.length>1)}startMonitor(e){var t;if(this.signalClient=e,!Me())return;const n=(t=this.sender)===null||t===void 0?void 0:t.getParameters();n&&(this.encodings=n.encodings),!this.monitorInterval&&(this.monitorInterval=setInterval(()=>{this.monitorSender()},Tr))}stop(){this._mediaStreamTrack.getConstraints(),this.simulcastCodecs.forEach(e=>{e.mediaStreamTrack.stop()}),super.stop()}pauseUpstream(){const e=Object.create(null,{pauseUpstream:{get:()=>super.pauseUpstream}});return m(this,void 0,void 0,function*(){var t,n,s,r,a;yield e.pauseUpstream.call(this);try{for(var o=!0,d=xe(this.simulcastCodecs.values()),c;c=yield d.next(),t=c.done,!t;o=!0)r=c.value,o=!1,yield(a=r.sender)===null||a===void 0?void 0:a.replaceTrack(null)}catch(l){n={error:l}}finally{try{!o&&!t&&(s=d.return)&&(yield s.call(d))}finally{if(n)throw n.error}}})}resumeUpstream(){const e=Object.create(null,{resumeUpstream:{get:()=>super.resumeUpstream}});return m(this,void 0,void 0,function*(){var t,n,s,r,a;yield e.resumeUpstream.call(this);try{for(var o=!0,d=xe(this.simulcastCodecs.values()),c;c=yield d.next(),t=c.done,!t;o=!0){r=c.value,o=!1;const l=r;yield(a=l.sender)===null||a===void 0?void 0:a.replaceTrack(l.mediaStreamTrack)}}catch(l){n={error:l}}finally{try{!o&&!t&&(s=d.return)&&(yield s.call(d))}finally{if(n)throw n.error}}})}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return m(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.log.debug("Track already muted",this.logContext),this):(this.source===C.Source.Camera&&!this.isUserProvided&&(this.log.debug("stopping camera track",this.logContext),this._mediaStreamTrack.stop()),yield e.mute.call(this),this)}finally{t()}})}unmute(){const e=Object.create(null,{unmute:{get:()=>super.unmute}});return m(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.source===C.Source.Camera&&!this.isUserProvided&&(this.log.debug("reacquiring camera track",this.logContext),yield this.restart(void 0,!0)),yield e.unmute.call(this),this):(this.log.debug("Track already unmuted",this.logContext),this)}finally{t()}})}setTrackMuted(e){super.setTrackMuted(e);for(const t of this.simulcastCodecs.values())t.mediaStreamTrack.enabled=!e}getSenderStats(){return m(this,void 0,void 0,function*(){var e;if(!(!((e=this.sender)===null||e===void 0)&&e.getStats))return[];const t=[],n=yield this.sender.getStats();return n.forEach(s=>{var r;if(s.type==="outbound-rtp"){const a={type:"video",streamId:s.id,frameHeight:s.frameHeight,frameWidth:s.frameWidth,framesPerSecond:s.framesPerSecond,framesSent:s.framesSent,firCount:s.firCount,pliCount:s.pliCount,nackCount:s.nackCount,packetsSent:s.packetsSent,bytesSent:s.bytesSent,qualityLimitationReason:s.qualityLimitationReason,qualityLimitationDurations:s.qualityLimitationDurations,qualityLimitationResolutionChanges:s.qualityLimitationResolutionChanges,rid:(r=s.rid)!==null&&r!==void 0?r:s.id,retransmittedPacketsSent:s.retransmittedPacketsSent,targetBitrate:s.targetBitrate,timestamp:s.timestamp},o=n.get(s.remoteId);o&&(a.jitter=o.jitter,a.packetsLost=o.packetsLost,a.roundTripTime=o.roundTripTime),t.push(a)}}),t.sort((s,r)=>{var a,o;return((a=r.frameWidth)!==null&&a!==void 0?a:0)-((o=s.frameWidth)!==null&&o!==void 0?o:0)}),t})}setPublishingQuality(e){const t=[];for(let n=Ae.LOW;n<=Ae.HIGH;n+=1)t.push(new ur({quality:n,enabled:n<=e}));this.log.debug("setting publishing quality. max quality ".concat(e),this.logContext),this.setPublishingLayers(Ze(this.codec),t)}restartTrack(e){return m(this,void 0,void 0,function*(){var t,n,s,r,a;let o;if(e){const u=vr({video:e});typeof u.video!="boolean"&&(o=u.video)}yield this.restart(o),this.isCpuConstrained=!1;try{for(var d=!0,c=xe(this.simulcastCodecs.values()),l;l=yield c.next(),t=l.done,!t;d=!0){r=l.value,d=!1;const u=r;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&&(s=c.return)&&(yield s.call(c))}finally{if(n)throw n.error}}yield this.onSenderTrackSwapped()})}onSenderTrackSwapped(){return m(this,void 0,void 0,function*(){yield this.refreshSen
39derEncodings()})}refreshSenderEncodings(){return m(this,void 0,void 0,function*(){var e;if(!this.sender||!this.publishOptions||this.optimizeForPerformance)return;const t=yield this.senderLock.lock();try{let s;try{s=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===s.width&&this.lastEncodedDimensions.height===s.height)return;const r=this.source===C.Source.ScreenShare,a=vi(r,s.width,s.height,Object.assign({},this.publishOptions));yield this.applyEncodingsToSender(this.sender,a),this.encodings=a,this.lastEncodedDimensions=s;for(const o of this.simulcastCodecs){var n=L(o,2);const d=n[0],c=n[1];if(!c.sender||((e=c.sender.transport)===null||e===void 0?void 0:e.state)==="closed"||!Wc(d))continue;const l=Object.assign({},this.publishOptions),u=sd(this,d,l);u&&(yield this.applyEncodingsToSender(c.sender,u),c.encodings=u)}}catch(s){this.log.warn("failed to apply recomputed encodings",Object.assign(Object.assign({},this.logContext),{error:s}))}finally{t()}})}applyEncodingsToSender(e,t){return m(this,void 0,void 0,function*(){const n=e.getParameters();!n.encodings||n.encodings.length!==t.length||(n.encodings.forEac
39h((s,r)=>{if(s.active===!1)return;const a=t[r];a.scaleResolutionDownBy!==void 0&&(s.scaleResolutionDownBy=a.scaleResolutionDownBy),a.maxBitrate!==void 0&&(s.maxBitrate=a.maxBitrate),a.maxFramerate!==void 0&&(s.maxFramerate=a.maxFramerate),a.priority!==void 0&&(s.priority=a.priority,s.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){const t=Object.create(null,{setProcessor:{get:()=>super.setProcessor}});return m(this,arguments,void 0,function(n){var s=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return(function*(){var a,o,d,c,l,u;if(yield t.setProcessor.call(s,n,r),!((l=s.processor)===null||l===void 0)&&l.processedTrack)try{for(var h=!0,p=xe(s.simulcastCodecs.values()),f;f=yield p.next(),a=f.done,!a;h=!0)c=f.value,h=!1,yield(u=c.sender)===null||u===void 0?void 0:u.replaceTrack(s.processor.processedTrack)}catch(g){o={error:g}}finally{try{!h&&!a&&(d=p.return)&&(yield d.call(p))}finally{if(o)throw o.error}}})()})}setDegradationPreference(e){return m(this,void 0,void 0,function*(){if(this.degradationPreference=e,this.sender)try{this.log.debug("setting degradationPreference to ".concat(e),this.logContext);const 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}const n={codec:e,mediaStreamTrack:this.mediaStreamTrack.clone(),sender:void 0,encodings:t};return this.simulcastCodecs.set(e,n),n}setSimulcastTrackSender(e,t){const n=this.simulcastCodecs.get(e);n&&(n.sender=t,setTimeout(()=>{this.subscribedCodecs&&this.setPublishingCodecs(this.subscribedCodecs)},Gp))}setPublishingCodecs(e){return m(this,void 0,void 0,function*(){var t,n,s,r,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(Ze(e[0].codec),e[0].qualities),[];this.subscribedCodecs=e;const c=[];try{for(t=!0,n=xe(e);s=yield n.next(),r=s.done,!r;t=!0){d=s.value,t=!1;const l=d;if(!this.codec||this.codec===l.codec)yield this.setPublishingLayers(Ze(l.codec),l.qualities);else{const u=this.simulcastCodecs.get(l.codec);if(this.log.debug("try setPublishingCodec for ".concat(l.codec),Object.assign(Object.assign({},this.logContext),{simulcastCodecInfo:u})),!u||!u.sender){for(const h of l.qualities)if(h.enabled){c.push(l.codec);break}}else u.encodings&&(this.log.debug("try setPublishingLayersForSender ".concat(l.codec),this.logContext),yield qa(u.sender,u.encodings,l.qualities,this.senderLock,Ze(l.codec),this.log,this.logContext))}}}catch(l){a={error:l}}finally{try{!t&&!r&&(o=n.return)&&(yield o.call(n))}finally{if(a)throw a.error}}return c})}setPublishingLayers(e,t){return m(this,void 0,void 0,function*(){if(this.optimizeForPerformance){this.log.info("skipping setPublishingLayers due to optimized publishing performance",Object.assign(Object.assign({},this.logContext),{qualities:t}));return}this.log.debug("setting publishing layers",Object.assign(Object.assign({},this.logContext),{qualities:t})),!(!this.sender||!this.encodings)&&(yield qa(this.sender,this.encodings,t,this.senderLock,e,this.log,this.logContext))})}prioritizePerformance(){return m(this,void 0,void 0,function*(){if(!this.sender)throw new Error("sender not found");const e=yield this.senderLock.lock();try{this.optimizeForPerformance=!0;const t=this.sender.getParameters();t.encodings=t.encodings.map((n,s)=>{var r;return Object.assign(Object.assign({},n),{active:s===0,scaleResolutionDownBy:Math.max(1,Math.ceil(((r=this.mediaStreamTrack.getSettings().height)!==null&&r!==void 0?r:360)/360)),scalabilityMode:s===0&&Ze(this.codec)?"L1T3":void 0,maxFramerate:s===0?15:0,maxBitrate:s===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(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return m(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),zc()&&this.isInBackgroun
39d&&this.source===C.Source.Camera&&(this._mediaStreamTrack.enabled=!1)})}}function qa(i,e,t,n,s,r,a){return m(this,void 0,void 0,function*(){const o=yield n.lock();r.debug("setPublishingLayersForSender",Object.assign(Object.assign({},a),{sender:i,qualities:t,senderEncodings:e}));try{const d=i.getParameters(),c=d.encodings;if(!c)return;if(c.length!==e.length){r.warn("cannot set publishing layers, encodings mismatch",Object.assign(Object.assign({},a),{encodings:c,senderEncodings:e}));return}let l=!1;!1&&c[0].scalabilityMode||(s&&t.some(p=>p.enabled)&&t.forEach(p=>p.enabled=!0),c.forEach((h,p)=>{var f;let g=(f=h.rid)!==null&&f!==void 0?f:"";g===""&&(g="q");const k=ad(g),T=t.find(S=>S.quality===k);T&&h.active!==T.enabled&&(l=!0,h.active=T.enabled,r.debug("setting layer ".concat(T.quality," to ").concat(h.active?"enabled":"disabled"),a),Wt()&&(T.enabled?(h.scaleResolutionDownBy=e[p].scaleResolutionDownBy,h.maxBitrate=e[p].maxBitrate,h.maxFrameRate=e[p].maxFrameRate):(h.scaleResolutionDownBy=4,h.maxBitrate=10,h.maxFrameRate=2)))})),l&&(d.encodings=c,r.debug("setting encodings",Object.assign(Object.assign({},a),{encodings:d.encodings})),yield i.setParameters(d))}finally{o()}})}function ad(i){switch(i){case"f":return Ae.HIGH;case"h":return Ae.MEDIUM;case"q":return Ae.LOW;default:return Ae.HIGH}}function Va(i,e,t,n){if(!t)return[new St({quality:Ae.HIGH,width:i,height:e,bitrate:0,ssrc:0})];if(n){const s=t[0].scalabilityMode,r=new rd(s),a=[],o=r.suffix=="h"?1.5:2,d=r.suffix=="h"?2:3;for(let c=0;c<r.spatial;c+=1)a.push(new St({quality:Math.min(Ae.HIGH,r.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(s=>{var r,a,o;const d=(r=s.scaleResolutionDownBy)!==null&&r!==void 0?r:1;let c=ad((a=s.rid)!==null&&a!==void 0?a:"");return new St({quality:c,width:Math.ceil(i/d),height:Math.ceil(e/d),bitrate:(o=s.maxBitrate)!==null&&o!==void 0?o:0,ssrc:0})})}const zp=2*1e3,us="leave-reconnect",Jp=3e4,$p=3,Qp=3;var Le;(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"})(Le||(Le={}));const Wa=64e3;class Yp extends De.EventEmitter{get isClosed(){return this._isClosed}get isNewlyCreated(){return this._isNewlyCreated}get pendingReconnect(){return!!this.reconnectTimeout}get reliableChannel(){return this.dataChannels.reliable}get lossyChannel(){return this.dataChannels.lossy}get dataTrackChannel(){return this.dataChannels.dataTrack}constructor(e){var t;super(),this.options=e,this.rtcConfig={},this.peerConnectionTimeout=Rr.peerConnectionTimeout,this.fullReconnectOnNext=!1,this.latestRemoteOfferId=0,this.subscriberPrimary=!1,this.pcState=Le.New,this._isClosed=!0,this._isNewlyCreated=!0,this.pendingTrackResolvers={},this.reconnectAttempts=0,this.reconnectStart=0,this.attemptingReconnect=!1,this.joinAttempts=0,this.maxJoinAttempts=1,this.shouldFailNext=!1,this.shouldFailOnV1Path=!1,this.log=U,this.reliableReceivedState=new up(Jp),this.midToTrackId={},this.isWaitingForNetworkReconnect=!1,this.handleDataChannel=n=>m(this,[n],void 0,function(s){var r=this;let a=s.channel;return(function*(){a&&r.dataChannels.adoptSubscriberChannel(a)&&r.log.debug("on data channel ".concat(a.id,", ").concat(a.label))})()}),this.handleDataMessage=n=>m(this,void 0,void 0,function*(){var s,r,a,o,d;const c=yield this.dataProcessLock.lock();try{const l=yield this.decodeDataMessage(n);if(!l)return;const u=Ee.fromBinary(l);if(u.sequence>0&&u.participantSid!==""){const h=this.reliableReceivedState.get(u.participantSid);if(h&&u.sequence<=h)return;this.reliableReceivedState.set(u.participantSid,u.sequence)}if(((s=u.value)===null||s===void 0?void 0:s.case)==="speaker")this.emit(R.ActiveSpeakersUpdate,u.value.value.speakers);else if(((r=u.value)===null||r===void 0?void 0:r.case)==="encryptedPacket"){if(!this.e2eeManager){this.log.error("Received encrypted packet but E2EE not set up");return}const h=yield(a=this.e2eeManager)===null||a===void 0?void 0:a.handleEncryptedData(u.value.value.encryptedValue,u.value.value.iv,u.participantIdentity,u.value.value.keyIndex),p=Lo.fromBinary(h.payload),f=new Ee({value:p.value,participantIdentity:u.participantIdentity,participantSid:u.participantSid});((o=f.value)===null||o===void 0?void 0:o.case)==="user"&&ja(f,f.value.value),this.emit
39(R.DataPacketReceived,f,u.value.value.encryptionType)}else((d=u.value)===null||d===void 0?void 0:d.case)==="user"&&ja(u,u.value.value),this.emit(R.DataPacketReceived,u,G.NONE)}finally{c()}}),this.handleDataTrackMessage=n=>m(this,void 0,void 0,function*(){const s=yield this.decodeDataMessage(n);s&&this.emit("dataTrackPacketReceived",s)}),this.handleDataError=n=>{if(this._isClosed)return;const r=n.currentTarget.maxRetransmits===0?"lossy":"reliable";if(typeof RTCErrorEvent<"u"&&n instanceof RTCErrorEvent&&n.error){const a=n.error;this.log.error("DataChannel error on ".concat(r,": ").concat(a.message),{error:a,errorDetail:a.errorDetail,sctpCauseCode:a.sctpCauseCode})}else this.log.error("Unknown DataChannel error on ".concat(r),{event:n})},this.handleDataChannelClose=n=>()=>{var s;!this._isClosed&&((s=this.pcManager)===null||s===void 0?void 0:s.publisher.getConnectionState())==="connected"&&this.log.error("publisher data channel '".concat(q[n],"' closed unexpectedly"),this.logContext)},this.handleDisconnect=(n,s)=>{if(this._isClosed)return;this.log.warn("".concat(n," disconnected")),this.reconnectAttempts===0&&(this.reconnectStart=Date.now());const r=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;let o=this.getNextRetryDelay({elapsedMs:a,retryCount:this.reconnectAttempts});if(o===null){r(a);return}n===us&&(o=0),this.log.debug("reconnecting in ".concat(o,"ms")),this.clearReconnectTimeout(),this.token&&this.emit(R.TokenRefreshed,this.token),this.reconnectTimeout=ae.setTimeout(()=>this.attemptReconnect(s).finally(()=>this.reconnectTimeout=void 0),o)},this.waitForRestarted=()=>new Promise((n,s)=>{this.pcState===Le.Connected&&n();const r=()=>{this.off(R.Disconnected,a),n()},a=()=>{this.off(R.Restarted,r),s()};this.once(R.Restarted,r),this.once(R.Disconnected,a)}),this.onRtpMapAvailable=n=>{const s=new Map;n.forEach(r=>{const a=r.codec.toLowerCase();Qc(a)&&s.set(r.payload,a)}),this.emit(R.RTPVideoMapUpdate,s)},this.handleBrowserOnLine=()=>m(this,void 0,void 0,function*(){!this.url||!(yield fetch(Ln(this.url),{method:"HEAD"}).then(s=>s.ok).catch(()=>!1))||(this.log.info("detected network reconnected"),(this.client.currentState===$.RECONNECTING||this.isWaitingForNetworkReconnect&&this.client.currentState===$.CONNECTED)&&(this.clearReconnectTimeout(),this.attemptReconnect(Dt.RR_SIGNAL_DISCONNECTED),this.isWaitingForNetworkReconnect=!1))}),this.handleBrowserOffline=()=>m(this,void 0,void 0,function*(){if(this.url)try{yield Promise.race([fetch(Ln(this.url),{method:"HEAD"}),Se(4e3).then(()=>Promise.reject())])}catch{window.navigator.onLine===!1&&(this.log.info("detected network interruption"),this.isWaitingForNetworkReconnect=!0)}}),this.log=ke((t=e.loggerName)!==null&&t!==void 0?t:ce.Engine,()=>this.logContext),this.loggerOptions={loggerName:e.loggerName,loggerContextCb:()=>this.logContext},this.client=new _r(void 0,this.loggerOptions),this.client.signalLatency=this.options.expSignalLatency,this.reconnectPolicy=this.options.reconnectPolicy,this.closingLock=new ge,this.dataProcessLock=new ge,this.dataChannels=new Ip({isEngineClosed:()=>this.isClosed,isReconnecting:()=>this.attemptingReconnect,onDataMessage:n=>this.handleDataMessage(n),onDataTrackMessage:n=>this.handleDataTrackMessage(n),onDataError:n=>this.handleDataError(n),onChannelClose:n=>this.handleDataChannelClose(n)(),onBufferStatusChanged:(n,s)=>
39this.emit(R.DCBufferStatusChanged,s,n)}),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)}get logContext(){var e,t,n,s,r,a;return{room:(t=(e=this.latestJoinResponse)===null||e===void 0?void 0:e.room)===null||t===void 0?void 0:t.name,roomID:(s=(n=this.latestJoinResponse)===null||n===void 0?void 0:n.room)===null||s===void 0?void 0:s.sid,participant:(a=(r=this.latestJoinResponse)===null||r===void 0?void 0:r.participant)===null||a===void 0?void 0:a.identity,participantID:this.participantSid}}join(e,t,n,s){return m(this,arguments,void 0,function(r,a,o,d){var c=this;let l=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!1;return(function*(){var u,h,p;c._isNewlyCreated=!1,c.url=r,c.token=a,c.signalOpts=o,c.maxJoinAttempts=o.maxRetries;try{c.joinAttempts+=1,c.setupSignalClientCallbacks();const f=!l&&Lh();let g;if(f){c.pcManager||(yield c.configure(),c.applyInitialPublisherLayout());const S=yield(u=c.pcManager)===null||u===void 0?void 0:u.publisher.createInitialOffer();S&&(g=Lt(S.offer,S.offerId))}if(d?.aborted)throw x.cancelled("Connection aborted");if(!l&&c.shouldFailOnV1Path)throw c.shouldFailOnV1Path=!1,x.serviceNotFound("Simulated v1 path failure","v0-rtc");const k=yield c.client.join(r,a,o,d,l,g);c._isClosed=!1,c.latestJoinResponse=k,c.participantSid=(h=k.participant)===null||h===void 0?void 0:h.sid,c.subscriberPrimary=k.subscriberPrimary,f?(p=c.pcManager)===null||p===void 0||p.updateConfiguration(c.makeRTCConfiguration(k)):(c.pcManager||(yield c.configure(k,!l),l||c.applyInitialPublisherLayout()),(!c.subscriberPrimary||k.fastPublish)&&c.negotiate().catch(S=>{c.log.error(S)})),c.registerOnLineListener(),c.clientConfiguration=k.clientConfiguration,c.emit(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 N=L(S,2),v=N[0],y=N[1];return"".concat(v,": ").concat(y)}).join(", "))),{joinResponse:k,serverInfo:T}}catch(f){if(f instanceof x){if(f.reason===Q.ServerUnreachable){if(c.log.warn("Couldn't connect to server, attempt ".concat(c.joinAttempts," of ").concat(c.maxJoinAttempts)),c.joinAttempts<c.maxJoinAttempts)return c.join(r,a,o,d,l)}else if(f.reason===Q.ServiceNotFound)return c.log.warn("Initial connection failed: ".concat(f.message," – Retrying")),c.pcManager&&(c.pcManager.onStateChange=void 0,yield c.cleanupPeerConnections()),c.join(r,a,o,d,!0)}throw f}})()})}close(){return m(this,void 0,void 0,function*(){const e=yield this.closingLock.lock();if(this.isClosed){e();return}try{this._isClosed=!0,this.joinAttempts=0,this.emit(R.Closing),this.removeAllListeners(),this.deregisterOnLineListener(),this.clearPendingReconnect(),this.cleanupLossyDataStats(),yield this.cleanupPeerConnections(),yield this.cleanupClient()}finally{e()}})}cleanupPeerConnections(){return m(this,void 0,void 0,function*(){var e;this.dataChannels.teardown(),yield(e=this.pcManager)===null||e===void 0?void 0:e.close(),this.pcManager=void 0,this.reliableReceivedState.clear()})}cleanupLossyDataStats(){this.lossyChannel.stopThresholdTuning()}cleanupClient(){return m(this,void 0,void 0,function*(){yield this.client.close(),this.client.resetCallbacks();for(const e of Object.keys(this.pendingTrackResolvers))this.pendingTrackResolvers[e].reject();this.pendingTrackResolvers={}})}addTrack(e){if(this.pendingTrackResolvers[e.cid])throw new lt("a track with the same ID has already been published");return new Promise((t,n)=>{const s=setTimeout(()=>{delete this.pendingTrackResolvers[e.cid],n(x.timeout("publication of local track timed out, no response from server"))},1e4);this.pendingTrackResolvers[e.cid]={resolve:r=>{clearTimeout(s),t(r)},reject:()=>{clearTimeout(s),n(new Error("Cancelled publication by calling unpublish"))}},this.client.sendAddTrack(e)})}removeTrack(e){if(e.track&&this.pendingTrackResolvers[e.track.id]){const t=this.pendingTrackResolvers[e.track.id].reject;t&&t(),delete this.pendingTrackResolvers[e.track.id]}try{return this.pcManager.removeTrack(e),!0}catch(t){this.log.warn("failed to remove track",{error:t})}return!1}updateMuteStatus(e,t){this.client.sendMuteTrack(e,t)}get dataSubscriberReadyState(){var e;return(e=this.dataChannelForKind(q.RELIABLE,!0))===null||e===void 0?void 0:e.readyState}getConnectedServerAddress(){return m(this,void 0,void 0,function*(){var e;return(e=this.pcManager)===null||e===void 0?void 0:e.getConnectedAddress()})}setRegionStrategy(e){this.regionStrategy=e}configure(e,t){return m(this,void 0,void 0,function*(){var n;if(!(this.pcManager&&this.pcManager.currentState!==ne.NEW)){if(e){this.participantSid=(n=e.participant)===null||n===void 0?void 0:n.sid;const s=this.makeRTCConfiguration(e);this.pcManager=new Aa(t?"publisher-only":e.subscriberPrimary?"subscriber-primary":"publisher-primary",this.loggerOptions,s)}else{const s=this.makeRTCConfiguration();this.pcManager=new Aa("publisher-only",this.loggerOptions,s)}
39this.emit(R.TransportsCreated,this.pcManager.publisher,this.pcManager.subscriber),this.pcManager.onIceCandidate=(s,r)=>{this.client.sendIceCandidate(s,r)},this.pcManager.onPublisherOffer=(s,r)=>{this.client.sendOffer(s,r)},this.pcManager.onDataChannel=this.handleDataChannel,this.pcManager.onStateChange=(s,r,a)=>m(this,void 0,void 0,function*(){if(this.log.debug("primary PC state changed ".concat(s)),["closed","disconnected","failed"].includes(r)&&(this.publisherConnectionPromise=void 0),s===ne.CONNECTED){const c=this.pcState===Le.New;this.pcState=Le.Connected,c&&this.emit(R.Connected,this.latestJoinResponse)}else s===ne.FAILED&&(this.pcState===Le.Connected||this.pcState===Le.Reconnecting)&&(this.pcState=Le.Disconnected,this.handleDisconnect("peerconnection failed",a==="failed"?Dt.RR_SUBSCRIBER_FAILED:Dt.RR_PUBLISHER_FAILED));const o=this.client.isDisconnected||this.client.currentState===$.RECONNECTING,d=[ne.FAILED,ne.CLOSING,ne.CLOSED].includes(s);o&&d&&!this._isClosed&&this.emit(R.Offline)}),this.pcManager.onTrack=s=>{s.streams.length!==0&&this.emit(R.MediaTrackAdded,s.track,s.streams[0],s.receiver)}}})}setupSignalClientCallbacks(){this.client.onAnswer=(e,t,n)=>m(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)=>m(this,void 0,void 0,function*(){if(this.latestRemoteOfferId=t,!this.pcManager)return;this.midToTrackId=n;const s=yield this.pcManager.createSubscriberAnswerFromOffer(e,t);s&&this.client.sendAnswer(s,t)}),this.client.onLocalTrackPublished=e=>{var t;if(this.log.debug("received trackPublishedResponse",{cid:e.cid,track:(t=e.track)===null||t===void 0?void 0:t.sid}),!this.pendingTrackResolvers[e.cid]){this.log.error("missing track resolver for ".concat(e.cid),{cid:e.cid});return}const 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",Dt.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 Yt.DISCONNECT:this.emit(R.Disconnected,e?.reason),this.close();break;case Yt.RECONNECT:this.fullReconnectOnNext=!0,this.handleDisconnect(us);break;case Yt.RESUME:this.handleDisconnect(us)}}}makeRTCConfiguration(e){var t;const n=Object.assign({},this.rtcConfig);if((!((t=this.signalOpts)===null||t===void 0)&&t.e2eeEnabled||this.frameMetadataWorker&&!xn())&&yr()&&(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){const r=[];e.iceServers.forEach(a=>{const o={urls:a.urls};a.username&&(o.username=a.username),a.credential&&(o.credential=
39a.credential),r.push(o)}),n.iceServers=r}return e.clientConfiguration&&e.clientConfiguration.forceRelay===In.ENABLED&&(n.iceTransportPolicy="relay"),n}applyInitialPublisherLayout(){this.createDataChannels(),Je()||this.addMediaSections($p,Qp)}addMediaSections(e,t){var n,s;const r={direction:"recvonly"};for(let a=0;a<e;a++)(n=this.pcManager)===null||n===void 0||n.addPublisherTransceiverOfKind("audio",r);for(let a=0;a<t;a++)(s=this.pcManager)===null||s===void 0||s.addPublisherTransceiverOfKind("video",r)}createDataChannels(){this.pcManager&&this.dataChannels.createPublisherChannels(this.pcManager)}decodeDataMessage(e){return m(this,void 0,void 0,function*(){if(e.data instanceof ArrayBuffer)return new Uint8Array(e.data);if(e.data instanceof Blob)return new Uint8Array(yield e.data.arrayBuffer());this.log.error("unsupported data type",{data:e.data})})}createSender(e,t,n){return m(this,void 0,void 0,function*(){let s;if(Fs())s=yield this.createTransceiverRTCRtpSender(e,t,n);else if(Bs())this.log.warn("using add-track fallback"),s=yield this.createRTCRtpSender(e.mediaStreamTrack);else throw new X("Required webRTC APIs not supported on this device");return this.setupFrameMetadataSender(s,t),s})}createSimulcastSender(e,t,n,s){return m(this,void 0,void 0,function*(){let r;if(Fs())r=yield this.createSimulcastTransceiverSender(e,t,n,s);else if(Bs())this.log.debug("using add-track fallback"),r=yield this.createRTCRtpSender(e.mediaStreamTrack);else throw new X("Cannot stream on this device");return r&&this.setupFrameMetadataSender(r,n),r})}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,s,r;const a=this.frameMetadataWorker;if(!a||!((n=this.signalOpts)===null||n===void 0)&&n.e2eeEnabled)return;const o=(s=t.frameMetadata)!==null&&s!==void 0?s:t.packetTrailer,d=mi(o);if(xn()){d&&(e.transform=new RTCRtpScriptTransform(a,{kind:"encode",packetTrailer:o}));return}if(!Un((r=this.options.frameMetadata)!==null&&r!==void 0?r:this.options.packetTrailer)||!("createEncodedStreams"in e)){d&&this.log.warn("frame metadata transform not supported; skipping write",this.logContext);return}const c=e.createEncodedStreams(),l=c.readable,u=c.writable;d?a.postMessage({kind:"encode",data:{readableStream:l,writableStream:u,packetTrailer:o}},[l,u]):l.pipeTo(u)}createTransceiverRTCRtpSender(e,t,n){return m(this,void 0,void 0,function*(){if(!this.pcManager)throw new X("publisher is closed");const s=[];e.mediaStream&&s.push(e.mediaStream),mt(e)&&(e.codec=t.videoCodec);const r={direction:"sendonly",streams:s};return n&&(r.sendEncodings=n),(yield this.pcManager.addPublisherTransceiver(e.mediaStreamTrack,r)).sender})}createSimulcastTransceiverSender(e,t,n,s){return m(this,void 0,void 0,function*(){if(!this.pcManager)throw new X("publisher is closed");const r={direction:"sendonly"};s&&(r.sendEncodings=s);const a=yield this.pcManager.addPublisherTransceiver(t.mediaStreamTrack,r);if(n.videoCodec)return e.setSimulcastTrackSender(n.videoCodec,a.sender),a.sender})}createRTCRtpSender(e){return m(this,void 0,void 0,function*(){if(!this.pcManager)throw new X("publisher is closed");return this.pcManager.addPublisherTrack(e)})}attemptReconnect(e){return m(this,void 0,void 0,function*(){var t,n,s;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)===In.DISABLED||((s=(n=this.pcManager)===null||n===void 0?void 0:n.currentState)!==null&&s!==void 0?s:ne.NEW)===ne.NEW)&&(this.fullReconnectOnNext=!0);try{this.attemptingReconnect=!0,this.fullReconnectOnNext?yield this.restartConnection():yield this.resumeConnection(e),this.clearPendingReconnect(),this.fullReconnectOnNext=!1}catch(r){this.reconnectAttempts+=1;let a=!0;r instanceof X?(this.log.debug("received unrecoverable error",{error:r}),a=!1):r instanceof Gt||(this.fullReconnectOnNext=!0),a?this.handleDisconnect("reconnect",Dt.RR_UNKNOWN):(this.log.info("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(Date.now()-this.reconnectStart,"ms. giving up")),this.emit
39(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 m(this,void 0,void 0,function*(){var t,n,s;try{if(!this.url||!this.token)throw new X("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 r;try{if(!this.signalOpts)throw this.log.warn("attempted connection restart, without signal options present"),new Gt;r=(yield this.join(e??this.url,this.token,this.signalOpts,void 0,!this.options.singlePeerConnection)).joinResponse}catch(a){throw a instanceof x&&a.reason===Q.NotAllowed?new X("could not reconnect, token might be expired"):new Gt}if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(this.client.setReconnected(),this.emit(R.SignalRestarted,r),yield this.waitForPCReconnected(),this.client.currentState!==$.CONNECTED)throw new Gt("Signal connection got severed during reconnect");(t=this.regionStrategy)===null||t===void 0||t.resetAttempts(),this.emit(R.Restarted)}catch(r){const a=yield(n=this.regionStrategy)===null||n===void 0?void 0:n.getNextUrl();if(a){yield this.restartConnection(a);return}else throw(s=this.regionStrategy)===null||s===void 0||s.resetAttempts(),r}})}resumeConnection(e){return m(this,void 0,void 0,function*(){if(!this.url||!this.token)throw new X("could not reconnect, url or token not saved");if(!this.pcManager)throw new X("publisher and subscriber connections unset");this.log.info("resuming signal connection, attempt ".concat(this.reconnectAttempts)),this.emit(R.Resuming);let t;try{this.setupSignalClientCallbacks(),t=yield this.client.reconnect(this.url,this.token,this.participantSid,e)}catch(s){let r="";throw s instanceof Error&&(r=s.message,this.log.error(s.message,{error:s})),s instanceof x&&s.reason===Q.NotAllowed?new X("could not reconnect, token might be expired"):s instanceof x&&s.reason===Q.LeaveRequest?s:new Gt(r)}
39if(this.emit(R.SignalResumed),t){const s=this.makeRTCConfiguration(t);this.pcManager.updateConfiguration(s),this.latestJoinResponse&&(this.latestJoinResponse.serverInfo=t.serverInfo)}else this.log.warn("Did not receive reconnect response");if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(yield this.pcManager.triggerIceRestart(),yield this.waitForPCReconnected(),this.client.currentState!==$.CONNECTED)throw new Gt("Signal connection got severed during reconnect");this.client.setReconnected();const n=this.dataChannelForKind(q.RELIABLE);n?.readyState==="open"&&n.id===null&&this.createDataChannels(),t?.lastMessageSeq&&this.resendReliableMessagesForResume(t.lastMessageSeq).catch(s=>{this.log.warn("failed to resend reliable messages after resume",Object.assign(Object.assign({},this.logContext),{error:s}))}),this.emit(R.Resumed)})}waitForPCInitialConnection(e,t){return m(this,void 0,void 0,function*(){if(!this.pcManager)throw new X("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(t,e)})}waitForPCReconnected(){return m(this,void 0,void 0,function*(){this.pcState=Le.Reconnecting,this.log.debug("waiting for peer connection to reconnect");try{if(yield Se(zp),!this.pcManager)throw new X("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(void 0,this.peerConnectionTimeout),this.pcState=Le.Connected}catch(e){throw this.pcState=Le.Disconnected,x.internal("could not establish PC connection, ".concat(e.message))}})}publishRpcAck(e,t){return m(this,void 0,void 0,function*(){const n=new Ee({destinationIdentities:[e],kind:Ct.RELIABLE,value:{case:"rpcAck",value:new Ri({requestId:t})}});yield this.sendDataPacket(n,q.RELIABLE)})}sendDataPacket(e,t){return m(this,void 0,void 0,function*(){var n,s;if(yield this.ensurePublisherConnected(t),this.e2eeManager&&this.e2eeManager.isDataChannelEncryptionEnabled){const o=Kh(e);if(o){const d=yield this.e2eeManager.encryptData(o.toBinary());e.value={case:"encryptedPacket",value:new No({encryptedValue:d.payload,iv:d.iv,keyIndex:d.keyIndex})}}}t===q.RELIABLE&&(e.sequence=this.reliableChannel.nextSequence());const r=e.toBinary(),a=Math.min((s=(n=this.pcManager)===null||n===void 0?void 0:n.getMaxPublisherMessageSize())!==null&&s!==void 0?s:Wa,Wa);if(typeof a<"u"&&a!==0&&r.byteLength>a)throw new nh("cannot publish data packet larger than ".concat(a," bytes (got ").concat(r.byteLength,")"));t===q.RELIABLE?yield this.reliableChannel.send(r,e.sequence):yield this.lossyChannel.send(r)})}sendDataTrackFrame(e){return m(this,void 0,void 0,function*(){yield this.ensurePublisherConnected(q.DATA_TRACK_LOSSY),yield this.dataTrackChannel.send(e)})}resendReliableMessagesForResume(e){return m(this,void 0,void 0,function*(){yield this.ensurePublisherConnected(q.RELIABLE),yield this.reliableChannel.replay(e)})}flowControlFor(e){return this.dataChannels.channelFor(e)}waitForBufferHeadroom(e){return m(this,void 0,void 0,function*(){return this.flowControlFor(e).waitForHeadroomWithLock()})}ensureDataTransportConnected(e){return m(this,arguments,void 0,function(t){var n=this;let s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.subscriberPrimary;return(function*(){var r;if(!n.pcManager)throw new X("PC manager is closed");const a=s?n.pcManager.subscriber:n.pcManager.publisher,o=s?"Subscriber":"Publisher";if(!a)throw x.internal("".concat(o," connection not set"));let d=!1;!s&&!n.dataChannelForKind(t,s)&&(n.createDataChannels(),d=!0),!d&&!s&&!n.pcManager.publisher.isICEConnected&&n.pcManager.publisher.getICEConnectionState()!=="checking"&&(d=!0),d&&n.negotiate().catch(u=>{n.log.error(u)});const c=n.dataChannelForKind(t,s);if(c?.readyState==="open")return;const l=new Date().getTime()+n.peerConnectionTimeout;for(;new Date().getTime()<l;){if(a.isICEConnected&&((r=n.dataChannelForKind(t,s))===null||r===void 0?void 0:r.readyState)==="open")return;yield Se(50)}throw x.internal("could not establish ".concat(o," connection, state: ").concat(a.getICEConnectionState()))})()})}ensurePublisherConnected(e){return m(this,void 0,void 0,function*(){this.publisherConnectionPromise||(this.publisherConnectionPromise=this.ensureDataTransportConnected(e,!1)),yield this.publisherConnectionPromise})}verifyTransport(){return!(!this.pcManager||![ne.CONNECTING,ne.CONNECTED].includes(this.pcManager.currentState)||!this.client.ws||this.client.ws.readyState===WebSocket.CLOSED)}negotiate(){return m(this,void 0,void 0,function*(){return new _e((e,t)=>m(this,void 0,void 0,function*(){if(!this.pcManager){t(new Bt("PC manager is closed"));return}this.pcManager.requirePublisher(),this.pcManager.publisher.getTransceivers().length==0&&!this.dataChannels.hasPublisherChannels&&this.createDataChannels();const n=new AbortController,s=()=>{n.abort(),this.log.debug("engine disconnected while negotiation was ongoing"),e()};this.isClosed&&t(new Bt("cannot negotiate on closed engine")),this.on(R.Closing,s),this.on(R.Restarting,s),this.pcManager.publisher.off(kt.RTPVideoPayloadTypes,this.onRtpMapAvailable),this.pcManager.publisher.once(kt.RTPVideoPayloadTypes,this.onRtpMapAvailable);try{yield this.pcManager.negotiate(n),e()}catch(r){if(n.signal.aborted){e();return}r instanceof Bt&&(this.fullReconnectOnNext=!0),this.handleDisconnect("negotiation",Dt.RR_UNKNOWN),r instanceof Error?t(r):t(new Error(String(r)))}finally{this.off(R.Closing,s),this.off(R.Restarting,s)}}))})}dataChannelForKind(e,t){return this.dataChannels.getHandle(e,t)}sendSyncState(e,t,n){var s,r,a,o;if(!this.pcManager){this.log.warn("sync state cannot be sent without peer connection setup");return}const d=this.pcManager.publisher.getLocalDescription(),c=this.pcManager.publisher.getRemoteDescription(),l=(s=this.pcManager.subscriber)===null||s===void 0?void 0:s.getRemoteDescription(),u=(r=this.pcManager.subscriber)===null||r===void 0?void 0:r.getLocalDescription(),h=(o=(a=this.signalOpts)===null||a===void 0?void 0:a.autoSubscribe)!==null&&o!==void 0?o:!0,p=new Array,f=new Array;e.forEach(g=>{g.isDesired!==h&&p.push(g.trackSid),g.isEnabled||f.push(g.trackSid)}),this.client.sendSyncState(new hr({answer:this.pcManager.mode==="publisher-only"?c?Lt({sdp:c.sdp,type:c.type}):void 0:u?Lt({sdp:u.sdp,type:u.type}
39):void 0,offer:this.pcManager.mode==="publisher-only"?d?Lt({sdp:d.sdp,type:d.type}):void 0:l?Lt({sdp:l.sdp,type:l.type}):void 0,subscription:new Di({trackSids:p,subscribe:!h,participantTracks:[]}),publishTracks:dh(t),dataChannels:this.dataChannelsInfo(),trackSidsDisabled:f,datachannelReceiveStates:this.reliableReceivedState.map((g,k)=>new nc({publisherSid:k,lastSeq:g})),publishDataTracks:n.map(g=>new ar({info:fi.toProtobuf(g)}))}))}failNext(){this.shouldFailNext=!0}failNextV1Path(){this.shouldFailOnV1Path=!0}dataChannelsInfo(){const e=[],t=(n,s)=>{n?.id!==void 0&&n.id!==null&&e.push(new ic({label:n.label,id:n.id,target:s}))};return t(this.dataChannelForKind(q.LOSSY),We.PUBLISHER),t(this.dataChannelForKind(q.RELIABLE),We.PUBLISHER),t(this.dataChannelForKind(q.LOSSY,!0),We.SUBSCRIBER),t(this.dataChannelForKind(q.RELIABLE,!0),We.SUBSCRIBER),e}clearReconnectTimeout(){this.reconnectTimeout&&ae.clearTimeout(this.reconnectTimeout)}clearPendingReconnect(){this.clearReconnectTimeout(),this.reconnectAttempts=0}registerOnLineListener(){Me()&&(window.addEventListener("online",this.handleBrowserOnLine),window.addEventListener("offline",this.handleBrowserOffline))}deregisterOnLineListener(){Me()&&(window.removeEventListener("online",this.handleBrowserOnLine),window.removeEventListener("offline",this.handleBrowserOffline))}getTrackIdForReceiver(e){var t;const n=(t=this.pcManager)===null||t===void 0?void 0:t.getMidForReceiver(e);if(n){const s=Object.entries(this.midToTrackId).find(r=>L(r,1)[0]===n);if(s)return s[1]}}}function ja(i,e){const t=i.participantIdentity?i.participantIdentity:e.participantIdentity;i.participantIdentity=t,e.participantIdentity=t;const n=i.destinationIdentities.length!==0?i.destinationIdentities:e.destinationIdentities;i.destinationIdentities=n,e.destinationIdentities=n}const Gn=ke(ce.Region),Gs=5e3,Xp=3e4;class H{static fetchRegionSettings(e,t,n){return m(this,void 0,void 0,function*(){const s=yield H.fetchLock.lock();try{const r=yield fetch("".concat(Zp(e),"/regions"),{headers:{authorization:"Bearer ".concat(t)},signal:n});if(r.ok){const a=Nh(r.headers),o=a?a*1e3:Gs;return{regionSettings:yield r.json(),updatedAtInMs:Date.now(),maxAgeInMs:o}}else throw r.status===401?x.notAllowed("Could not fetch region settings: ".concat(r.statusText),r.status):x.internal("Could not fetch region settings: ".concat(r.statusText))}catch(r){throw r instanceof x?r:n?.aborted?x.cancelled("Region fetching was aborted"):x.serverUnreachable("Could not fetch region settings, ".concat(r instanceof Error?"".concat(r.name,": ").concat(r.message):r))}finally{s()}})}static scheduleRefetch(e,t,n){return m(this,void 0,void 0,function*(){const s=H.settingsTimeouts.get(e.hostname);clearTimeout(s),H.settingsTimeouts.set(e.hostname,setTimeout(()=>m(this,void 0,void 0,function*(){try{const r=yield H.fetchRegionSettings(e,t);H.updateCachedRegionSettings(e,t,r)}catch(r){if(r instanceof x&&r.reason===Q.NotAllowed){Gn.debug("token is not valid, cancelling auto region refresh");return}Gn.debug("auto refetching of region settings failed",{error:r}),H.scheduleRefetch(e,t,n)}}),n))})}static updateCachedRegionSettings(e,t,n){H.cache.set(e.hostname,n),H.scheduleRefetch(e,t,n.maxAgeInMs)}static stopRefetch(e){const t=H.settingsTimeouts.get(e);t&&(clearTimeout(t),H.settingsTimeouts.delete(e))}static scheduleCleanup(e){let t=H.connectionTrackers.get(e);t&&(t.cleanupTimeout&&clearTimeout(t.cleanupTimeout),t.cleanupTimeout=setTimeout(()=>{const n=H.connectionTrackers.get(e);n&&n.connectionCount===0&&(Gn.debug("stopping region refetch after disconnect delay",{hostname:e}),H.stopRefetch(e)),n&&(n.cleanupTimeout=void 0)},Xp))}static cancelCleanup(e){const t=H.connectionTrackers.get(e);t?.cleanupTimeout&&(clearTimeout(t.cleanupTimeout),t.cleanupTimeout=void 0)}notifyConnected(){const e=this.serverUrl.hostname;let t=H.connectionTrackers.get(e);t||(t={connectionCount:0},H.connectionTrackers.set(e,t)),t.connectionCount++,H.cancelCleanup(e)}notifyDisconnected(){const e=this.serverUrl.hostname,t=H.connectionTrackers.get(e);t&&(t.connectionCount=Math.max(0,t.connectionCount-1),t.connectionCount===0&&H.scheduleCleanup(e))}constructor(e,t){this.attemptedRegions=[],this.serverUrl=new URL(e),this.token=t}updateToken(e){var t;this.token=e;const n=this.getServerUrl(),s=H.cache.get(n.hostname);H.scheduleRefetch(this.serverUrl,this.token,(t=s?.maxAgeInMs)!==null&&t!==void 0?t:Gs)}isCloud(){return dn(this.serverUrl)}getServerUrl(){return this.serverUrl}fetchRegionSettings(e){return m(this,void 0,void 0,function*(){return H.fetchRegionSettings(this.serverUrl,this.token,e)})}getNextBestRegionUrl(e){return m(this,void 0,void 0,function*(){if(!this.isCloud())throw Error("region availability is only supported for LiveKit Cloud domains");let t=H.cache.get(this.serverUrl.hostname);(!t||Date.now()-t.updatedAtInMs>t.maxAgeInMs)&&(t=yield this.fetchRegionSettings(e),H.updateCachedRegionSettings(this.serverUrl,this.token,t));
39const n=t.regionSettings.regions.filter(s=>!this.attemptedRegions.find(r=>r.url===s.url));if(n.length>0){const s=n[0];return this.attemptedRegions.push(s),Gn.info("switching to region: ".concat(s.region),{region:s.region}),s.url}else return null})}resetAttempts(){this.attemptedRegions=[]}setServerReportedRegions(e){H.updateCachedRegionSettings(this.serverUrl,this.token,e)}}H.cache=new Map;H.settingsTimeouts=new Map;H.connectionTrackers=new Map;H.fetchLock=new ge;function Zp(i){return"".concat(i.protocol.replace("ws","http"),"//").concat(i.host,"/settings")}function hs(){return new CompressionStream("deflate-raw")}function od(){return new DecompressionStream("deflate-raw")}function Ha(i,e){return m(this,void 0,void 0,function*(){const t=new DecompressionStream("deflate-raw"),n=t.writable.getWriter();return n.write(i).catch(()=>{}),n.close().catch(()=>{}),cd(t.readable,e)})}function cd(i,e){return m(this,void 0,void 0,function*(){const t=i.getReader(),n=[];let s=0;for(;;){const o=yield t.read(),d=o.done,c=o.value;if(d)break;if(n.push(c),s+=c.byteLength,typeof e=="number"&&s>e)throw yield t.cancel(),new ue("Decompressed payload exceeds the maximum payload size of ".concat(e," bytes"),ie.PayloadTooLarge)}const r=new Uint8Array(s);let a=0;for(const o of n)r.set(o,a),a+=o.byteLength;return r})}const xt=15e3,em=5e9;class dd{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 ue("Not enough chunk(s) received - expected ".concat(this.totalByteSize," bytes of data total, only received ").concat(this.bytesReceived," bytes"),ie.Incomplete);if(this.bytesReceived>this.totalByteSize)throw new ue("Extra chunk(s) received - expected ".concat(this.totalByteSize," bytes of data total, received ").concat(this.bytesReceived," bytes"),ie.LengthExceeded)}}constructor(e,t,n){this.reader=t,this.totalByteSize=n,this._info=e,this.bytesReceived=0}}class Ka extends dd{handleChunkReceived(e){var t;this.bytesReceived+=e.content.byteLength,this.validateBytesReceived();const n=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;(t=this.onProgress)===null||t===void 0||t.call(this,n)}[Symbol.asyncIterator](){const e=this.reader.getReader();e.closed.catch(()=>{});const t=()=>{e.releaseLock(),this.signal=void 0};return{next:()=>m(this,void 0,void 0,function*(){var n;try{const s=this.signal;if(s?.aborted)throw s.reason;const r=yield new Promise((a,o)=>{if(s){const d=()=>o(s.reason);s.addEventListener("abort",d,{once:!0}),e.read().then(a,o).finally(()=>{s.removeEventListener("abort",d)})}else e.read().then(a,o)});return r.done?(this.validateBytesReceived(!0),typeof this.totalByteSize=="number"&&((n=this.onProgress)===null||n===void 0||n.call(this,1)),{done:!0,value:void 0}):(this.handleChunkReceived(r.value),{done:!1,value:r.value.content})}catch(s){throw t(),s}}),return(){return m(this,void 0,void 0,function*(){return t(),{done:!0,value:void 0}})}}}withAbortSignal(e){return this.signal=e,this}readAll(){return m(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return(function*(){var n,s,r,a;let o=new Set;const d=t.signal?e.withAbortSignal(t.signal):e;try{for(var c=!0,l=xe(d),u;u=yield l.next(),n=u.done,!n;c=!0){a=u.value,c=!1;const h=a;o.add(h)}}catch(h){s={error:h}}finally{try{!c&&!n&&(r=l.return)&&(yield r.call(l))}finally{if(s)throw s.error}}return Array.from(o)})()})}}class Ga extends dd{constructor(e,t,n){super(e,t,n),this.receivedChunks=new Map}handleChunkReceived(e){var t;const n=Ot(e.chunkIndex),s=this.receivedChunks.get(n);if(s&&s.version>e.version)return;this.receivedChunks.set(n,e),this.bytesReceived+=e.content.byteLength,this.validateBytesReceived();const r=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;(t=this.onProgress)===null||t===void 0||t.call(this,r)}[Symbol.asyncIterator](){const e=this.reader.getReader();e.closed.catch(()=>{});const t=new TextDecoder("utf-8",{fatal:!0}),n=this.signal,s=()=>{e.releaseLock(),this.signal=void 0};return{next:()=>m(this,void 0,void 0,function*(){var r;try{if(n?.aborted)throw n.reason;const a=yield new Promise((o,d)=>
39{if(n){const c=()=>d(n.reason);n.addEventListener("abort",c,{once:!0}),e.read().then(o,d).finally(()=>{n.removeEventListener("abort",c)})}else e.read().then(o,d)});if(a.done)return this.validateBytesReceived(!0),typeof this.totalByteSize=="number"&&((r=this.onProgress)===null||r===void 0||r.call(this,1)),{done:!0,value:void 0};{this.handleChunkReceived(a.value);let o;try{o=t.decode(a.value.content)}catch(d){throw new ue("Cannot decode datastream chunk ".concat(a.value.chunkIndex," as text: ").concat(d),ie.DecodeFailed)}return{done:!1,value:o}}}catch(a){throw s(),a}}),return(){return m(this,void 0,void 0,function*(){return s(),{done:!0,value:void 0}})}}}withAbortSignal(e){return this.signal=e,this}readAll(){return m(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return(function*(){var n,s,r,a;let o="";const d=t.signal?e.withAbortSignal(t.signal):e;try{for(var c=!0,l=xe(d),u;u=yield l.next(),n=u.done,!n;c=!0)a=u.value,c=!1,o+=a}catch(h){s={error:h}}finally{try{!c&&!n&&(r=l.return)&&(yield r.call(l))}finally{if(s)throw s.error}}return o})()})}}class tm{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:em;this.log=U,this.byteStreamControllers=new Map,this.textStreamControllers=new Map,this.byteStreamHandlers=new Map,this.textStreamHandlers=new Map,this.isConnected=!1,this.bufferedPackets=[],this.maxPayloadByteLength=e}setConnected(e){this.isConnected=e,e&&this.flushBufferedPackets()}flushBufferedPackets(){const e=this.bufferedPackets;this.bufferedPackets=[];for(const t of e){const n=t.packet,s=t.encryptionType;this.handleDataStreamPacket(n,s)}}registerTextStreamHandler(e,t){if(this.textStreamHandlers.has(e))throw new ue('A text stream handler for topic "'.concat(e,'" has already been set.'),ie.HandlerAlreadyRegistered);this.textStreamHandlers.set(e,t)}unregisterTextStreamHandler(e){this.textStreamHandlers.delete(e)}registerByteStreamHandler(e,t){if(this.byteStreamHandlers.has(e))throw new ue('A byte stream handler for topic "'.concat(e,'" has already been set.'),ie.HandlerAlreadyRegistered);this.byteStreamHandlers.set(e,t)}unregisterByteStreamHandler(e){this.byteStreamHandlers.delete(e)}clearControllers(){this.byteStreamControllers.clear(),this.textStreamControllers.clear(),this.bufferedPackets=[]}validateParticipantHasNoActiveDataStreams(e){const t=Array.from(this.textStreamControllers.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){const a=new ue("Participant ".concat(e," unexpectedly disconnected in the middle of sending data"),ie.AbnormalEnd);for(const o of n){var s=L(o,2);const d=s[0];s[1].controller.error(a),this.byteStreamControllers.delete(d)}for(const o of t){var r=L(o,2);const d=r[0];r[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 s;switch(e.contentHeader.case){case"byteHeader":{const r=this.byteStreamHandlers.get(e.topic);if(!r){this.log.debug("ignoring incoming byte stream due to no handler for topic",e.topic);return}let a;const o={id:e.streamId,name:(s=e.contentHeader.value.name)!==null&&s!==void 0?s:"unknown",mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:Ot(e.timestamp),attributes:e.attributes,encryptionType:n};let d;switch(e.compression){case Te.DEFLATE_RAW:if(!Et()){U.warn("Data stream ".concat(e.streamId," received with deflate-raw compression, but this browser does not have support for DecompressionStream. Dropping..."));return}d=!0;break;case Te.NONE:d=!1;break;default:U.warn("Data stream ".concat(e.streamId," received with unknown compression type ").concat(e.compression,", dropping..."));return}const c=e.inlineContent;if(typeof c<"u"){r(new Ka(o,za(e.streamId,d?Ha(c,this.maxPayloadByteLength):c),Ot(e.totalLength)),{identity:t});return}const l=new ReadableStream({start:u=>{if(a=u,this.byteStreamControllers.has(e.streamId))throw new ue("A data stream read is already in progress for a stream with i
39d ".concat(e.streamId,"."),ie.AlreadyOpened);this.byteStreamControllers.set(e.streamId,{info:o,controller:a,startTime:Date.now(),sendingParticipantIdentity:t})}});r(new Ka(o,d?sm(l,e.streamId,this.maxPayloadByteLength):l,Ot(e.totalLength)),{identity:t});return}case"textHeader":{const r=this.textStreamHandlers.get(e.topic);if(!r){this.log.debug("ignoring incoming text stream due to no handler for topic",e.topic);return}let a;const o={id:e.streamId,mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:Number(e.timestamp),attributes:e.attributes,encryptionType:n,attachedStreamIds:e.contentHeader.value.attachedStreamIds};let d;switch(e.compression){case Te.DEFLATE_RAW:if(!Et()){U.warn("Data stream ".concat(e.streamId," received with deflate-raw compression, but this browser does not have support for DecompressionStream. Dropping..."));return}d=!0;break;case Te.NONE:d=!1;break;default:U.warn("Data stream ".concat(e.streamId," received with unknown compression type ").concat(e.compression,", dropping..."));return}const c=e.inlineContent;if(typeof c<"u"){const u=d?Ha(c,this.maxPayloadByteLength):c;r(new Ga(o,za(e.streamId,u),Ot(e.totalLength)),{identity:t});return}const l=new ReadableStream({start:u=>{if(a=u,this.textStreamControllers.has(e.streamId))throw new ue("A data stream read is already in progress for a stream with id ".concat(e.streamId,"."),ie.AlreadyOpened);this.textStreamControllers.set(e.streamId,{info:o,controller:a,startTime:Date.now(),sendingParticipantIdentity:t})}});r(new Ga(o,d?rm(l,e.streamId,this.maxPayloadByteLength):l,Ot(e.totalLength)),{identity:t});return}}}handleStreamChunk(e,t){const n=this.byteStreamControllers.get(e.streamId);n&&(n.info.encryptionType!==t?(n.controller.error(new ue("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(n.info.encryptionType),ie.EncryptionTypeMismatch)),this.byteStreamControllers.delete(e.streamId)):e.content.length>0&&n.controller.enqueue(e));const s=this.textStreamControllers.get(e.streamId);s&&(s.info.encryptionType!==t?(s.controller.error(new ue("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(s.info.encryptionType),ie.EncryptionTypeMismatch)),this.textStreamControllers.delete(e.streamId)):e.content.length>0&&s.controller.enqueue(e))}handleStreamTrailer(e,t){const n=this.textStreamControllers.get(e.streamId);n&&(n.info.encryptionType!==t?n.controller.error(new ue("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(n.info.encryptionType),ie.EncryptionTypeMismatch)):(n.info.attributes=Object.assign(Object.assign({},n.info.attributes),e.attributes),e.reason?n.controller.error(new ue("Data stream ".concat(e.streamId," closed abnormally: ").concat(e.reason),ie.AbnormalEnd)):n.controller.close()),this.textStreamControllers.delete(e.streamId));const s=this.byteStreamControllers.get(e.streamId);s&&(s.info.encryptionType!==t?s.controller.error(new ue("Encryption type mismatch for stream ".concat(e.streamId,". Expected ").concat(t,", got ").concat(s.info.encryptionType),ie.EncryptionTypeMismatch)):(s.info.attributes=Object.assign(Object.assign({},s.info.attributes),e.attributes),e.reason?s.controller.error(new ue("Data stream ".concat(e.streamId," closed abnormally: ").concat(e.reason),ie.AbnormalEnd)):s.controller.close()),this.byteStreamControllers.delete(e.streamId))}}function za(i,e){return new ReadableStream({start:t=>m(this,void 0,void 0,function*(){try{const n=yield e;t.enqueue(new ht({streamId:i,chunkIndex:BigInt(0),content:n})),t.close()}catch(n){t.error(n)}})})}function ld(i){let e=-1;return new TransformStream({transform:(t,n)=>{const s=Ot(t.chunkIndex);if(s<=e){U.warn("ignoring duplicate chunk ".concat(s," for compressed data stream ").concat(i," (last processed: ").concat(e,")"));return}if(s>e+1)throw new ue("Missing chunk(s) ".concat(e+1,"..").concat(s-1," for compressed data stream ").concat(i," - cannot continue decompressing"),ie.Incomplete);e=s,n.enqueue(t)}})}function ud(){return new TransformStream({transform:(i,e)=>{e.enqueue(i.content)}})}function nm(i){let e=0;return new TransformStream({transform:(t,n)=>{t.byteLength>0&&(n.enqueue(new ht({streamId:i,chunkIndex:ze(e),content:t})),e+=1)}})}function im(i){const e=new TextDecoder("utf-8",{fatal:!0}),t=new TextEncoder;let n=0;const s=r=>{try{return r?e.decode(r,{stream:!0}):e.decode()}catch(a){throw new ue("Cannot decode compressed data stream ".concat(i," as text: ").concat(a),ie.DecodeFailed)}};return new TransformStream({transform:(r,a)=>{const o=s(r);o.length>0&&(a.enqueue(new ht({streamId:i,chunkIndex:ze(n),content:t.encode(o)})),n+=1)},flush:r=>{const a=s();a.length>0&&(r.enqueue(new ht({streamId:i,chunkIndex:ze(n),content:t.encode(a)})),n+=1)}})}function sm(i,e,t){return i.pipeThrough(ld(e)).pipeThrough(ud()).pipeThrough(od()).pipeThrough(hd(e,t)).pipeThrough(nm(e))}function rm(i,e,t){return i.pipeThrough(ld(e)).pipeThrough(ud()).pipeThrough(od()).pipeThrough(hd(e,t)).pipeThrough(im(e))}function hd(i,e){let t=0;return new TransformStream({transform:(n,s)=>{if(t+=n.byteLength,t>e)throw new ue("Data stream ".concat(i," exceeds the maximum payload size of ").concat(e," bytes"),ie.PayloadTooLarge);s.enqueue(n)}})}class pd{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 m(this,void 0,void 0,function*(){var e;yield this.defaultWriter.close(),this.defaultWriter.releaseLock(),(e=this.onClose)===null||e===void 0||e.call(this)})}}class am extends pd{}class om extends pd{}function ps(i,e,t){var n;return new Pi({streamId:i.id,mimeType:i.mimeType,topic:i.topic,timestamp:ze(i.timestamp),totalLength:ze(i.size),attributes:i.attributes,compression:(n=t?.compression)!==null&&n!==void 0?n:Te.NONE,inlineContent:t?.inlineContent,contentHeader:{case:"textHeader",value:new Go({version:e?.version,attachedStreamIds:i.attachedStreamIds,replyToStreamId:e?.replyToStreamId,operationType:e?.type==="update"?Ts.UPDATE:Ts.CREATE})}})}function zn(i,e){var t;return new Pi({streamId:i.id,mimeType:i.mimeType,topic:i.topic,timestamp:ze(i.timestamp),totalLength:ze(i.size),attributes:i.attributes,compression:(t=e?.compression)!==null&&t!==void 0?t:Te.NONE,inlineContent:e?.inlineContent,contentHeader:{case:"byteHeader",value:new zo({name:i.name})}})}function Mt(i,e){return new Ee({destinationIdentities:e,value:{case:"streamHeader",value:i}})}const cm=new TextEncoder;class dm{constructor(e,t,n,s,r){this.engine=e,this.log=t,this.getRemoteParticipantClientProtocol=n,this.getRemoteParticipantCapabilities=s,this.getAllRemoteParticipantIdentities=r}setupEngine(e){this.engine=e}sendText(e,t){return m(this,void 0,void 0,function*(){var n,s,r,a,o;const d=crypto.randomUUID(),c=cm.encode(e),l=c.byteLength,u=(n=t?.compress)!==null&&n!==void 0?n:!0;let h={id:d,mimeType:"text/plain",timestamp:Date.now(),topic:(s=t?.topic)!==null&&s!==void 0?s:"",size:l,attributes:t?.attributes,encryptionType:!((r=this.engine.e2eeManager)===null||r===void 0)&&r.isDataChannelEncryptionEnabled?G.GCM:G.NONE},f=u&&Et()&&this.allRecipientsSupportV2(t?.destinationIdentities)&&this.allRecipientsSupportCompression(t?.destinationIdentities)?yi.fromStream(ci(c).pipeThrough(hs())):null;if((!t?.attachments||t.attachments.length===0)&&this.allRecipientsSupportV2(t?.destinationIdentities)){let v=c,y=Te.NONE;if(f){const A=yield f.collect();A.byteLength<c.byteLength&&(v=A,y=Te.DEFLATE_RAW)}const E=ps(h,void 0,{compression:y,inlineContent:v}),I=Mt(E,t?.destinationIdentities);if(I.toBinary().byteLength<=xt)return yield this.engine.sendDataPacket(
39I,q.RELIABLE),(a=t?.onProgress)===null||a===void 0||a.call(t,1),h}const k=(o=t?.attachments)===null||o===void 0?void 0:o.map(()=>crypto.randomUUID()),T=k?k.length+1:1,S=new Array(T).fill(0),N=(v,y)=>{var E;S[y]=v,(E=t?.onProgress)===null||E===void 0||E.call(t,S.reduce((I,A)=>I+A,0)/T)};if(f){h.attachedStreamIds=k;const v=ps(h,void 0,{compression:Te.DEFLATE_RAW}),y=Mt(v,t?.destinationIdentities);yield this.sendChunkedByteStream(y,d,t?.destinationIdentities,f.stream().pipeThrough(ms(c.length,E=>N(E,0)))),c.length===0&&N(1,0)}else{const v=yield this.streamText({streamId:d,totalSize:l,destinationIdentities:t?.destinationIdentities,topic:t?.topic,attachedStreamIds:k,attributes:t?.attributes});yield v.write(e),N(1,0),yield v.close(),h=v.info}return t?.attachments&&k&&(yield Promise.all(t.attachments.map((v,y)=>m(this,void 0,void 0,function*(){return this._sendFile(k[y],v,{topic:t.topic,mimeType:v.type,destinationIdentities:t.destinationIdentities,compress:t.compress,onProgress:E=>{N(E,y+1)}})})))),h})}sendBytes(e,t){return m(this,void 0,void 0,function*(){var n,s,r,a,o,d,c;const l=crypto.randomUUID(),u=t?.destinationIdentities,h=(n=t?.compress)!==null&&n!==void 0?n:!0,p={id:l,name:(s=t?.name)!==null&&s!==void 0?s:"unknown",mimeType:(r=t?.mimeType)!==null&&r!==void 0?r:"application/octet-stream",timestamp:Date.now(),topic:(a=t?.topic)!==null&&a!==void 0?a:"",size:e.byteLength,attributes:t?.attributes,encryptionType:!((o=this.engine.e2eeManager)===null||o===void 0)&&o.isDataChannelEncryptionEnabled?G.GCM:G.NONE},f=ms(e.length,t?.onProgress);let k=h&&Et()&&this.allRecipientsSupportV2(u)&&this.allRecipientsSupportCompression(u)?yi.fromStream(ci(e).pipeThrough(f).pipeThrough(hs())):null;if(this.allRecipientsSupportV2(u)){let v=e,y=Te.NONE;if(k){const A=yield k.collect();A.byteLength<e.byteLength&&(v=A,y=Te.DEFLATE_RAW)}const E=zn(p,{compression:y,inlineContent:v}),I=Mt(E,u);if(I.toBinary().byteLength<=xt)return yield this.engine.sendDataPacket(I,q.RELIABLE),(d=t?.onProgress)===null||d===void 0||d.call(t,1),p}const T=zn(p,{compression:k?Te.DEFLATE_RAW:Te.NONE}),S=Mt(T,u),N=k?k.stream():ci(e).pipeThrough(f);return yield this.sendChunkedByteStream(S,l,u,N),e.length===0&&((c=t?.onProgress)===null||c===void 0||c.call(t,1)),p})}allRecipientsSupportV2(e){return(e&&e.length>0?e:this.getAllRemoteParticipantIdentities()).every(n=>this.getRemoteParticipantClientProtocol(n)>=Vc)}allRecipientsSupportCompression(e){return(e&&e.length>0?e:this.getAllRemoteParticipantIdentities()).every(n=>this.getRemoteParticipantCapabilities(n).includes(Dn.CAP_COMPRESSION_DEFLATE_RAW))}sendChunkedByteStream(e,t,n,s){return m(this,void 0,void 0,function*(){var r,a,o,d;const c=this.engine;yield fs(c,e);let l=0;try{for(var u=!0,h=xe(Oh(s,xt)),p;p=yield h.next(),r=p.done,!r;u=!0){d=p.value,u=!1;const f=d,g=new Ee({destinationIdentities:n,value:{case:"streamChunk",value:new ht({content:f,streamId:t,chunkIndex:ze(l)})}});yield c.sendDataPacket(g,q.RELIABLE),l+=1}}catch(f){a={error:f}}finally{try{!u&&!r&&(o=h.return)&&(yield o.call(h))}finally{if(a)throw a.error}}yield gs(t,n,c)})}streamText(e){return m(this,void 0,void 0,function*(){var t,n,s;const r=(t=e?.streamId)!==null&&t!==void 0?t:crypto.randomUUID(),a=e?.destinationIdentities,o={id:r,mimeType:"text/plain",timestamp:Date.now(),topic:(n=e?.topic)!==null&&n!==void 0?n:"",size:e?.totalSize,attributes:e?.attributes,encryptionType:!((s=this.engine.e2eeManager)===null||s===void 0)&&s.isDataChannelEncryptionEnabled?G.GCM:G.NONE,attachedStreamIds:e?.attachedStreamIds},d=ps(o,e),c=Mt(d,a);yield fs(this.engine,c);let l=0;const u=this.engine,h=new WritableStream({write(g){return m(this,void 0,void 0,function*(){for(const k of Ah(g,xt)){const T=new ht({content:k,streamId:r,chunkIndex:ze(l)}),S=new Ee({destinationIdentities:a,value:{case:"streamChunk",value:T}});yield u.sendDataPacket(S,q.RELIABLE),l+=1}})},close(){return m(this,void 0,void 0,function*(){yield gs(r,a,u)})},abort(g){console.log("Sink error:",g)}});let p=()=>m(this,void 0,void 0,function*(){yield f.close()});u.once(R.Closing,p);const f=new am(h,o,()=>this.engine.off(R.Closing,p));return f})}sendFile(e,t){return m(this,void 0,void 0,function*(){const n=crypto.randomUUID();return yield this._sendFile(n,e,t),{id:n}})}_sendFile(e,t,n){return m(this,void 0,void 0,function*(){var s,r,a,o,d;const c=n?.destinationIdentities,l=((s=n?.compress)!==null&&s!==void 0?s:!0)&&Et()&&this.allRecipientsSupportV2(c)&&this.allRecipientsSupportCompression(c),u={id:e,name:t.name,mimeType:(r=n?.mimeType)!==null&&r!==void 0?r:t.type,topic:(a=n?.topic)!==null&&a!==void 0?a:"",timestamp:Date.now(),size:t.size,encryptionType:!((o=this.engine.e2eeManager)===null||o===void 0)&&o.isDataChannelEncryptionEnabled?G.GCM:G.NONE},h=zn(u,{compression:l?Te.DEFLATE_RAW:Te.NONE}),p=Mt(h,c),f=t.stream().pipeThrough(ms(t.size,n?.onProgress)),g=l?f.pipeThrough(hs()):f;return yield this.sendChunkedByteStream(p,e,c,g),t.size===0&&((d=n?.onProgress)===null||d===void 0||d.call(n,1)),u})}streamBytes(e){return m(this,void 0,void 0,function*(){var t,n,s,r,a;const 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:(s=e?.topic)!==null&&s!==void 0?s:"",timestamp:Date.now(),attributes:e?.attributes,size:e?.totalSize,name:(r=e?.name)!==null&&r!==void 0?r:"unknown",encryptionType:!((a=this.engine.e2eeManager)===null||a===void 0)&&a.isDataChannelEncryptionEnabled?G.GCM:G.NONE}
39,l=zn(c),u=Mt(l,d);yield fs(this.engine,u);let h=0;const p=new ge,f=this.engine,g=this.log,k=new WritableStream({write(S){return m(this,void 0,void 0,function*(){const N=yield p.lock();let v=0;try{for(;v<S.byteLength;){const y=S.slice(v,v+xt),E=new Ee({destinationIdentities:d,value:{case:"streamChunk",value:new ht({content:y,streamId:o,chunkIndex:ze(h)})}});yield f.sendDataPacket(E,q.RELIABLE),h+=1,v+=y.byteLength}}finally{N()}})},close(){return m(this,void 0,void 0,function*(){yield gs(o,d,f)})},abort(S){g.error("Sink error:",S)}});return new om(k,c)})}}class yi{constructor(e){this.state=e}static fromStream(e){return new yi({type:"stream",stream:e})}collect(){return m(this,void 0,void 0,function*(){switch(this.state.type){case"stream":const e=yield cd(this.state.stream);return this.state={type:"collected",bytes:e},e;case"collected":return this.state.bytes}})}stream(){switch(this.state.type){case"stream":return this.state.stream;case"collected":return ci(this.state.bytes)}}}function ms(i,e){let t=0;return new TransformStream({transform(n,s){t+=n.byteLength,e&&typeof i=="number"&&i>0&&e(Math.min(t/i,1)),s.enqueue(n)}})}function fs(i,e){return m(this,void 0,void 0,function*(){if(e.toBinary().byteLength>xt)throw new ue("data stream header exceeds the ".concat(xt,"-byte limit; reduce attribute size"),ie.HeaderTooLarge);yield i.sendDataPacket(e,q.RELIABLE)})}function gs(i,e,t){return m(this,void 0,void 0,function*(){const n=new Ee({destinationIdentities:e,value:{case:"streamTrailer",value:new sr({streamId:i})}});yield t.sendDataPacket(n,q.RELIABLE)})}function md(i){if(i.length===0)return new AbortController().signal;if(i.length===1)return i[0];for(const s of i)if(s.aborted)return s;const e=new AbortController,t=Array(i.length),n=()=>{for(const s of t)s()};return i.forEach((s,r)=>{const a=()=>{e.abort(s.reason),n()};s.addEventListener("abort",a),t[r]=()=>s.removeEventListener("abort",a)}),e.signal}function fd(i){const e=new AbortController;return setTimeout(()=>{e.abort(new DOMException("signal timed out after ".concat(i," ms"),"TimeoutError"))},i),e.signal}const re=1,it=2,Ja=4,lm=8,$a=0,Qa=12,Ya=5,um=7,Xa=3,hm=3,Za=2,eo=1,to=0,no=3,Jn=2,io=2,pm=1,mm=0;var rt;(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"})(rt||(rt={}));class Ce extends Ue{constructor(e,t,n){super(19,e,n),this.name="DataTrackDeserializeError",this.reason=t,this.reasonName=rt[t]}static tooShort(){return new Ce("Too short to contain a valid header",rt.TooShort)}static headerOverrun(){return new Ce("Header exceeds total packet length",rt.HeaderOverrun)}static missingExtWords(){return new Ce("Extension word indicator is missing",rt.MissingExtWords)}static unsupportedVersion(e){return new Ce("Unsupported version ".concat(e),rt.UnsupportedVersion)}static invalidHandle(e){return new Ce("invalid track handle: ".concat(e.message),rt.InvalidHandle,{cause:e})}static malformedExt(e){return new Ce("Extension with tag ".concat(e," is malformed"),rt.MalformedExt)}}var wn;(function(i){i[i.TooSmallForHeader=0]="TooSmallForHeader",i[i.TooSmallForPayload=1]="TooSmallForPayload"})(wn||(wn={}));class Fn extends Ue{constructor(e,t,n){super(19,e,n),this.name="DataTrackSerializeError",this.reason=t,this.reasonName=wn[t]}static tooSmallForHeader(){return new Fn("Buffer cannot fit header",wn.TooSmallForHeader)}static tooSmallForPayload(){return new Fn("Buffer cannot fit payload",wn.TooSmallForPayload)}}class Li{toBinary(){const e=this.toBinaryLengthBytes(),t=new ArrayBuffer(e),n=new DataView(t),s=this.toBinaryInto(n);if(e!==s)throw new Error("".concat(this.constructor.name,".toBinary: written bytes (").concat(s," bytes) not equal to allocated array buffer length (").concat(e," bytes)."));return new Uint8Array(t)}}var un;(function(i){i[i.UserTimestamp=2]="UserTimestamp",i[i.E2ee=1]="E2ee"})(un||(un={}));class gd extends Li{}class je extends gd{constructor(e){super(),this.timestamp=e}toBinaryLengthBytes(){return re+re+je.lengthBytes}toBinaryInto(e){let t=0;e.setUint8(t,je.tag),t+=re,e.setUint8(t,je.lengthBytes),t+=re,e.setBigUint64(t,this.timestamp),t+=lm;const n=this.toBinaryLengthBytes();if(t!==n)throw new Error("DataTrackUserTimestampExtension.toBinaryInto: Wrote ".concat(t," bytes but expected length
39was ").concat(n," bytes"));return t}toJSON(){return{tag:je.tag,lengthBytes:je.lengthBytes,timestamp:this.timestamp}}}je.tag=un.UserTimestamp;je.lengthBytes=8;class He extends gd{constructor(e,t){super(),this.keyIndex=e,this.iv=t}toBinaryLengthBytes(){return re+re+He.lengthBytes}toBinaryInto(e){let t=0;e.setUint8(t,He.tag),t+=re,e.setUint8(t,He.lengthBytes),t+=re,e.setUint8(t,this.keyIndex),t+=re;for(let s=0;s<this.iv.length;s+=1)e.setUint8(t,this.iv[s]),t+=re;const 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:He.tag,lengthBytes:He.lengthBytes,keyIndex:this.keyIndex,iv:this.iv}}}He.tag=un.E2ee;He.lengthBytes=13;class rn extends Li{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};super(),this.userTimestamp=e.userTimestamp,this.e2ee=e.e2ee}toBinaryLengthBytes(){let e=0;return this.userTimestamp&&(e+=this.userTimestamp.toBinaryLengthBytes()),this.e2ee&&(e+=this.e2ee.toBinaryLengthBytes()),e}toBinaryInto(e){let t=0;if(this.e2ee){const s=this.e2ee.toBinaryInto(e);t+=s}if(this.userTimestamp){const s=this.userTimestamp.toBinaryInto(new DataView(e.buffer,e.byteOffset+t));t+=s}const 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){const t=Er(e);let n,s,r=0;for(;t.byteLength-r>=re+re;){const a=t.getUint8(r);r+=re;const o=t.getUint8(r);if(r+=re,a!==mm)switch(a){case un.UserTimestamp:if(t.byteLength-r<je.lengthBytes)throw Ce.malformedExt(a);n=new je(t.getBigUint64(r)),r+=o;break;case un.E2ee:if(t.byteLength-r<He.lengthBytes)throw Ce.malformedExt(a);const d=t.getUint8(r),c=new Uint8Array(12);for(let l=0;l<c.length;l+=1){let u=r;u+=re,u+=l*re,c[l]=t.getUint8(u)}s=new He(d,c),r+=o;break;default:if(t.byteLength-r<o)throw Ce.malformedExt(a);r+=o;break}}return[new rn({userTimestamp:n,e2ee:s}),t.byteLength]}toJSON(){var e,t,n,s;return{userTimestamp:(t=(e=this.userTimestamp)===null||e===void 0?void 0:e.toJSON())!==null&&t!==void 0?t:null,e2ee:(s=(n=this.e2ee)===null||n===void 0?void 0:n.toJSON())!==null&&s!==void 0?s:null}}}const vd={from(i){return{payload:i.payload,extensions:new rn({userTimestamp:i.userTimestamp?new je(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}}},bd=Symbol.for("lk.track"),yd=Symbol.for("lk.data-track");class kd{constructor(e,t,n){this.trackSymbol=bd,this.isLocal=!1,this.typeSymbol=yd,this.info=e,this.manager=t,this.publisherIdentity=n.publisherIdentity}subscribe(e){try{const t=this.manager.openSubscriptionStream(this.info.sid,e?.signal,e?.bufferSize),n=L(t,2),s=n[0];return n[1].catch(()=>{}),s}catch(t){throw t}}setPipelineOptions(e){this.manager.setPipelineOptions(this.info.sid,e)}}class Bn extends Li{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 rn}extensionsMetrics(){const e=this.extensions.toBinaryLengthBytes(),t=Math.ceil((Jn+e)/4),n=t*4-Jn-e;return{lengthBytes:e,lengthWords:t,paddingLengthBytes:n}}toBinaryLengthBytes(){const e=this.extensionsMetrics(),t=e.lengthBytes,n=e.paddingLengthBytes;let s=Qa;return t>0&&(s+=Jn+t+n),s}toBinaryInto(e){if(e.byteLength<this.toBinaryLengthBytes())throw Fn.tooSmallForHeader();let t=$a<<Ya,n;switch(this.marker){case Z.Inter:n=to;break;case Z.Final:n=eo;break;case Z.Start:n=Za;break;case Z.Single:n=no;break}t|=n<<Xa;const s=this.extensionsMetrics(),r=s.lengthBytes,a=s.lengthWords,o=s.paddingLengthBytes;r>0&&(t|=1<<io);let d=0;if(e.setUint8(d,t),d+=re,e.setUint8(d,0),d+=re,e.setUint16(d,this.trackHandle),d+=it,e.setUint16(d,this.sequence.value),d+=it,e.setUint16(d,this.frameNumber.value),d+=it,e.setUint32(d,this.timestamp.asTicks()),d+=Ja,r>0){const l=a-1;e.setUint16(d,l),d+=it;const u=this.extensions.toBinaryInto(new DataView(e.buffer,e.byteOffset+d));d+=u;for(let h=0;h<o;h+=1)e.setUint8(d,0),d+=re}const c=this.toBinaryLengthBytes();if(d!==c)throw new Error("DataTrackPacketHeader.toBinaryInto: Wrote ".concat(d," bytes but expected length
39was ").concat(c," bytes"));return c}static fromBinary(e){const t=Er(e);if(t.byteLength<Qa)throw Ce.tooShort();let n=0;const s=t.getUint8(n);n+=re;const r=s>>Ya&um;if(r>$a)throw Ce.unsupportedVersion(r);let a;switch(s>>Xa&hm){case Za:a=Z.Start;break;case eo:a=Z.Final;break;case no:a=Z.Single;break;case to:default:a=Z.Inter;break}const o=(s>>io&pm)>0;n+=re;let d;try{d=tp.fromNumber(t.getUint16(n))}catch(p){throw p instanceof ln&&(p.isReason(qt.Reserved)||p.isReason(qt.TooLarge))?Ce.invalidHandle(p):p}n+=it;const c=Ge.u16(t.getUint16(n));n+=it;const l=Ge.u16(t.getUint16(n));n+=it;const u=sn.fromRtpTicks(t.getUint32(n));n+=Ja;let h=new rn;if(o){if(t.byteLength-n<it)throw Ce.missingExtWords();let p=t.getUint16(n);n+=it;let g=4*(p+1)-Jn;if(n+g>t.byteLength)throw Ce.headerOverrun();let k=new DataView(t.buffer,t.byteOffset+n,g);const T=rn.fromBinary(k),S=L(T,2),N=S[0],v=S[1];h=N,n+=v}return[new Bn({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()}}}var Z;(function(i){i[i.Start=0]="Start",i[i.Inter=1]="Inter",i[i.Final=2]="Final",i[i.Single=3]="Single"})(Z||(Z={}));class xi extends Li{constructor(e,t){super(),this.header=e,this.payload=t}toBinaryLengthBytes(){return this.header.toBinaryLengthBytes()+this.payload.byteLength}toBinaryInto(e){let t=0;const n=this.header.toBinaryInto(e);if(t+=n,e.byteLength-t<this.payload.byteLength)throw Fn.tooSmallForPayload();for(let r=0;r<this.payload.length;r+=1)e.setUint8(t,this.payload[r]),t+=re;const s=this.toBinaryLengthBytes();if(t!==s)throw new Error("DataTrackPacket.toBinaryInto: Wrote ".concat(t," bytes but expected length was ").concat(s," bytes"));return s}static fromBinary(e){const t=Er(e),n=Bn.fromBinary(t),s=L(n,2),r=s[0],a=s[1],o=t.buffer.slice(t.byteOffset+a,t.byteOffset+t.byteLength);return[new xi(r,new Uint8Array(o)),t.byteLength]}toJSON(){return{header:this.header.toJSON(),payload:this.payload}}}const vs=ke(ce.DataTracks);class et extends Ue{constructor(e,t,n,s){super(19,"Frame ".concat(n," dropped: ").concat(e),s),this.name="DataTrackDepacketizerDropError",this.reason=t,this.reasonName=Ut[t],this.frameNumber=n}static interrupted(e,t){return new et("Interrupted by the start of a new frame ".concat(t),Ut.Interrupted,e)}static unknownFrame(e){return new et("Initial packet was never received.",Ut.UnknownFrame,e)}static bufferFull(e){return new et("Reorder buffer is full.",Ut.BufferFull,e)}static incomplete(e,t,n){return new et("Not all packets received before final packet. Received ".concat(t," packets, expected ").concat(n," packets."),Ut.Incomplete,e)}}var Ut;(function(i){i[i.Interrupted=0]="Interrupted",i[i.UnknownFrame=1]="UnknownFrame",i[i.BufferFull=2]="BufferFull",i[i.Incomplete=3]="Incomplete"})(Ut||(Ut={}));class Ui{constructor(){this.partials=new Map}push(e,t){switch(e.header.marker){case Z.Single:return this.frameFromSingle(e,t);case Z.Start:return this.beginPartial(e,t);case Z.Inter:case Z.Final:return this.pushToPartial(e)}}reset(){this.partials.clear()}peekOldestPartialFrameNumber(){const e=this.partials.keys().next();return e.done?null:e.value}frameFromSingle(e,t){var n;if(e.header.marker!==Z.Single)throw new Error("Depacketizer.frameFromSingle: packet.header.marker was not FrameMarker.Single, found ".concat(e.header.marker,"."));const s=(n=t?.maxPartialFrames)!==null&&n!==void 0?n:1;if(this.partials.size>=s){const r=this.peekOldestPartialFrameNumber();if(typeof r!="number")throw new Error("Depacketizer.frameFromSingle: no olde
39st frame number found, but partials.size is ".concat(this.partials.size,"."));if(this.partials.delete(r),t?.throwOnInterruption)throw et.interrupted(r,e.header.frameNumber.value);vs.warn("Data track frame ".concat(r," 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!==Z.Start)throw new Error("Depacketizer.beginPartial: packet.header.marker was not FrameMarker.Start, found ".concat(e.header.marker,"."));const s=e.header.sequence,r=e.header.frameNumber.value,a={startSequence:s,extensions:e.header.extensions,payloads:new Map([[s.value,e.payload]])},o=(n=t?.maxPartialFrames)!==null&&n!==void 0?n:1;for(;this.partials.size>=o;){const d=this.peekOldestPartialFrameNumber();if(typeof d!="number")break;if(this.partials.delete(d),t?.throwOnInterruption)throw et.interrupted(d,r);vs.warn("Data track partials full (max ".concat(o,"), evicted oldest frame ").concat(d," to make room for new frame ").concat(r,"."))}return this.partials.set(r,a),null}pushToPartial(e){if(e.header.marker!==Z.Inter&&e.header.marker!==Z.Final)throw new Error("Depacketizer.pushToPartial: packet.header.marker was not FrameMarker.Inter or FrameMarker.Final, found ".concat(e.header.marker,"."));const t=e.header.frameNumber.value,n=this.partials.get(t);if(!n)throw this.partials.delete(t),et.unknownFrame(t);if(n.payloads.size>=Ui.MAX_BUFFER_PACKETS)throw this.partials.delete(t),et.bufferFull(t);return n.payloads.has(e.header.sequence.value)&&vs.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===Z.Final?this.finalize(t,n,e.header.sequence.value):null}finalize(e,t,n){const s=t.payloads.size;let r=0;for(const c of t.payloads.values())r+=c.length;const a=new Uint8Array(r);let o=t.startSequence.clone(),d=0;for(;;){const c=t.payloads.get(o.value);if(!c)break;t.payloads.delete(o.value);const l=a.length-d;if(c.length>l)throw new Error("Depacketizer.finalize: Expected at least ".concat(c.length," more bytes left in the payload buffer, only got ").concat(l," bytes."));if(a.set(c,d),d+=c.length,o.value!=n){o.increment();continue}return this.partials.delete(e),{payload:a,extensions:t.extensions}}throw this.partials.delete(e),et.incomplete(e,s,n-t.startSequence.value+1)}}Ui.MAX_BUFFER_PACKETS=128;var Ft;(function(i){i[i.Unpublished=0]="Unpublished",i[i.Timeout=1]="Timeout",i[i.Disconnected=2]="Disconnected",i[i.Cancelled=4]="Cancelled"})(Ft||(Ft={}));class Pe extends Ue{constructor(e,t,n){super(22,e,n),this.name="DataTrackSubscribeError",this.reason=t,this.reasonName=Ft[t]}static unpublished(){return new Pe("The track has been unpublished and is no longer available",Ft.Unpublished)}static timeout(){return new Pe("Request to subscribe to data track timed-out",Ft.Timeout)}static disconnected(){return new Pe("Cannot subscribe to data track when disconnected",Ft.Disconnected)}static cancelled(){return new Pe("Subscription to data track cancelled by caller",Ft.Cancelled)}}const bs=ke(ce.DataTracks);class fm{constructor(e){var t,n;const s=e.e2eeManager!==null;if(e.info.usesE2ee!==s)throw new Error("IncomingDataTrackPipeline: DataTrackInfo.usesE2ee must match presence of decryptionProvider");const r=new Ui;this.publisherIdentity=e.publisherIdentity,this.e2eeManager=(t=e.e2eeManager)!==null&&t!==void 0?t:null,this.depacketizer=r,this.options=(n=e.pipelineOptions)!==null&&n!==void 0?n:{}}updateE2eeManager(e){this.e2eeManager=e}setOptions(e){this.options=e}processPacket(e){return m(this,void 0,void 0,function*(){const t=this.depacketize(e);if(!t)return null;const 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 bs.warn("Data frame depacketize error: ".concat(n)),null}return t}decryptIfNeeded(e){return m(this,void 0,void 0,function*(){var t,n;const s=this.e2eeManager;if(!s)return e;const r=(n=(t=e.extensions)===null||t===void 0?void 0:t.e2ee)!==null&&n!==void 0?n:null;if(!r)return bs.error("Missing E2EE meta"),null;let a;try{a=yield s.handleEncryptedData(e.payload,r.iv,this.publisherIdentity,r.keyIndex)}catch(o){return bs.error("Error decrypting packet: ".concat(o)),null}return e.payload=a.payload,e})}}const de=ke(ce.DataTracks),gm=1e4,vm=16;class bm extends De.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(const t of this.descriptors.values())t.subscription.type==="active"&&t.subscription.pipeline.updateE2eeManager(e)}setPipelineOptions(e,t){const n=this.descriptors.get(e);if(!n){de.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]:vm,s=null;const r=new ye,a=this.descriptors.get(e),o=()=>{t?.removeEventListener("abort",c)},d=()=>
39{if(o(),!s){de.warn("ReadableStream subscribed to ".concat(e," was not started."));return}if(!a||this.descriptors.get(a.info.sid)!==a){de.warn("Unknown track ".concat(e,", skipping cancel..."));return}if(a.subscription.type!=="active"){de.warn("Subscription for track ".concat(e," is not active, skipping cancel..."));return}a.subscription.streamControllers.delete(s),a.subscription.streamControllers.size===0&&this.unSubscribeRequest(a.info.sid)},c=()=>{var u;s&&(a?.subscription.type==="active"&&a.subscription.streamControllers.delete(s),s.error(Pe.cancelled()),(u=r.reject)===null||u===void 0||u.call(r,Pe.cancelled()),d())};return[new ReadableStream({start:u=>{s=u,this.subscribeRequest(e,t).then(()=>m(this,void 0,void 0,function*(){var h,p,f;if(!a||this.descriptors.get(a.info.sid)!==a){de.error("Unknown track ".concat(e));const g=Pe.disconnected();u.error(g),(h=r.reject)===null||h===void 0||h.call(r,g);return}if(a.subscription.type!=="active"){de.error("Subscription for track ".concat(e," is not active"));const g=Pe.disconnected();u.error(g),(p=r.reject)===null||p===void 0||p.call(r,g);return}if(t?.aborted){c();return}t?.addEventListener("abort",c),a.subscription.streamControllers.set(u,o),(f=r.resolve)===null||f===void 0||f.call(r)})).catch(h=>{var p;u.error(h),(p=r.reject)===null||p===void 0||p.call(r,h)})},cancel:()=>{d()}},new CountQueuingStrategy({highWaterMark:n})),r.promise]}subscribeRequest(e,t){return m(this,void 0,void 0,function*(){const n=this.descriptors.get(e);if(!n)throw new Error("Cannot subscribe to unknown track");const s=(r,a,o)=>m(this,void 0,void 0,function*(){if(r.subscription.type==="active")return;if(r.subscription.type!=="pending")throw new Error("Descriptor for track ".concat(e," is not pending, found ").concat(r.subscription.type));const d=md([a,o].filter(u=>typeof u<"u")),c=new ye;r.subscription.completionFuture.promise.then(()=>{var u;return(u=c.resolve)===null||u===void 0?void 0:u.call(c)}).catch(u=>{var h;return(h=c.reject)===null||h===void 0?void 0:h.call(c,u)});const l=()=>{var u;if(r.subscription.type==="pending"){if(r.subscription.pendingRequestCount-=1,o?.aborted){r.subscription.cancel();return}if(r.subscription.pendingRequestCount<=0){r.subscription.cancel();return}(u=c.reject)===null||u===void 0||u.call(c,Pe.cancelled())}};d.aborted&&l(),d.addEventListener("abort",l),yield c.promise,d.removeEventListener("abort",l)});switch(n.subscription.type){case"none":{n.subscription={type:"pending",completionFuture:new ye,pendingRequestCount:1,cancel:()=>{var a,o;const d=n.subscription;n.subscription={type:"none"},this.emit("sfuUpdateSubscription",{sid:n.info.sid,subscribe:!1}),d.type==="pending"&&((o=(a=d.completionFuture).reject)===null||o===void 0||o.call(a,r.aborted?Pe.timeout():Pe.cancelled()))}},this.emit("sfuUpdateSubscription",{sid:e,subscribe:!0});const r=fd(gm);yield s(n,t,r);return}case"pending":{n.subscription.pendingRequestCount+=1,yield s(n,t);return}case"active":return}})}querySubscribed(){return m(this,void 0,void 0,function*(){return Array.from(this.descriptors.values()).filter(t=>t.subscription.type==="active").map(t=>[t.info,t.publisherIdentity])})}unSubscribeRequest(e){var t;const n=this.descriptors.get(e);if(!n)throw new Error("Cannot subscribe to unknown track");if(n.subscription.type!=="active"){de.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);const s=n.subscription;n.subscription={type:"none"},this.subscriptionHandles.delete(s.subcriptionHandle),this.emit("sfuUpdateSubscription",{sid:e,subscribe:!1})}closeStreamControllers(e,t){for(const s of e){var n=L(s,2);const r=n[0],a=n[1];a();try{r.close()}catch(o){de.warn("Failed to close readable stream for track ".concat(t,": ").concat(o))}}}receiveSfuPublicationUpdates(e){return m(this,void 0,void 0,function*(){if(e.size===0)return;const t=new Map;for(const r of e.entries()){var n=L(r,2);const a=n[0],o=n[1],d=new Set;for(const c of o)d.add(c.sid),!this.descriptors.has(c.sid)&&(this.handleSidReassigned(a,c)||(yield this.handleTrackPublished(a,c)));t.set(a,d)}for(const r of t.entries()){var s=L(r,2);const a=s[0],o=s[1];let c=Array.from(this.descriptors.entries()).filter(l=>{let u=L(l,2);return u[0],u[1].publisherIdentity===a}).map(l=>L(l,1)[0]).filter(l=>!o.has(l));for(const l of c)this.handleTrackUnpublished(l)}})}queryPublications(){return m(this,void 0,void 0,function*(){return Array.from(this.descriptors.values()).map(e=>e.info)})}handleTrackPublished(e,t){return m(this,void 0,void 0,function*(){if(this.descriptors.has(t.sid)){de.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);const s=new kd(n.info,this,{publisherIdentity:e});
39this.emit("trackPublished",{track:s})})}handleSidReassigned(e,t){const n=Array.from(this.descriptors.entries()).find(u=>{let h=L(u,2);h[0];let p=h[1];return p.publisherIdentity===e&&p.info.pubHandle===t.pubHandle});if(!n)return!1;const s=L(n,2),r=s[0],a=s[1],o=a.info,d=o.name,c=o.usesE2ee;if(d!==t.name||c!==t.usesE2ee)return de.warn("Info mismatch for ".concat(r,", treating as new publication")),!1;const l=t.sid;if(de.debug("SID reassigned: ".concat(r," -> ").concat(l)),!this.descriptors.delete(r))return!1;switch(a.info.sid=l,a.subscription.type){case"none":break;case"pending":case"active":this.emit("sfuUpdateSubscription",{sid:l,subscribe:!0});break}return a.subscription.type==="active"&&this.subscriptionHandles.set(a.subscription.subcriptionHandle,l),this.descriptors.set(l,a),!0}handleTrackUnpublished(e){const t=this.descriptors.get(e);if(!t){de.error("Unknown track ".concat(e));return}this.descriptors.delete(e),t.subscription.type==="active"&&(this.closeStreamControllers(t.subscription.streamControllers,e),this.subscriptionHandles.delete(t.subscription.subcriptionHandle)),this.emit("trackUnpublished",{sid:e,publisherIdentity:t.publisherIdentity})}receivedSfuSubscriberHandles(e){for(const n of e.entries()){var t=L(n,2);const s=t[0],r=t[1];this.registerSubscriberHandle(s,r)}}registerSubscriberHandle(e,t){var n,s;const r=this.descriptors.get(t);if(!r){de.error("Unknown track ".concat(t));return}switch(r.subscription.type){case"none":{de.warn("No subscription for ".concat(t));return}case"active":{this.subscriptionHandles.delete(r.subscription.subcriptionHandle),r.subscription.subcriptionHandle=e,this.subscriptionHandles.set(e,t);return}case"pending":{de.debug("data track subscription activated",{sid:t,handle:e});const a=new fm({info:r.info,publisherIdentity:r.publisherIdentity,e2eeManager:this.e2eeManager,pipelineOptions:r.pipelineOptions}),o=r.subscription;r.subscription={type:"active",subcriptionHandle:e,pipeline:a,streamControllers:new Map},this.subscriptionHandles.set(e,t),(s=(n=o.completionFuture).resolve)===null||s===void 0||s.call(n)}}}packetReceived(e){return m(this,void 0,void 0,function*(){let t;try{var n=xi.fromBinary(e),s=L(n,1);t=s[0]}catch(d){de.error("Failed to deserialize packet: ".concat(d));return}const r=this.subscriptionHandles.get(t.header.trackHandle);if(!r){de.warn("Unknown subscriber handle ".concat(t.header.trackHandle));return}const a=this.descriptors.get(r);if(!a){de.error("Missing descriptor for track ".concat(r));return}if(a.subscription.type!=="active"){de.warn("Received packet for track ".concat(r," without active subscription"));return}const o=yield a.subscription.pipeline.processPacket(t);if(o)for(const d of a.subscription.streamControllers.keys()){if(d.desiredSize!==null&&d.desiredSize<=0){de.warn("Cannot send frame to subscribers: readable stream is full (desiredSize is ".concat(d.desiredSize,"). To increase this threshold, set a higher 'options.highWaterMark' when calling .subscribe()."));continue}const c=vd.lossyIntoFrame(o);d.enqueue(c)}})}resendSubscriptionUpdates(){for(const t of this.descriptors){var e=L(t,2);const n=e[0];e[1].subscription.type!=="none"&&this.emit("sfuUpdateSubscription",{sid:n,subscribe:!0})}}handleRemoteParticipantDisconnected(e){var t,n;for(const s of this.descriptors.values())if(s.publisherIdentity===e)switch(s.subscription.type){case"none":break;case"pending":(n=(t=s.subscription.completionFuture).reject)===null||n===void 0||n.call(t,Pe.disconnected());break;case"active":this.unSubscribeRequest(s.info.sid);break}}reset(){var e,t;
39for(const 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,Pe.disconnected())),n.subscription.type==="active"&&this.closeStreamControllers(n.subscription.streamControllers,n.info.sid);this.descriptors.clear(),this.subscriptionHandles.clear()}}class Fi extends Ue{constructor(e,t,n){super(19,e,n),this.name="DataTrackPacketizerError",this.reason=t,this.reasonName=ki[t]}static mtuTooShort(){return new Fi("MTU is too short to send frame",ki.MtuTooShort)}}var ki;(function(i){i[i.MtuTooShort=0]="MtuTooShort"})(ki||(ki={}));class Ir{constructor(e,t){this.sequence=Ge.u16(0),this.frameNumber=Ge.u16(0),this.clock=Nt.rtpStartingNow(sn.rtpRandom()),this.handle=e,this.mtuSizeBytes=t}static computeFrameMarker(e,t){return t<=1?Z.Single:e===0?Z.Start:e===t-1?Z.Final:Z.Inter}*packetize(e,t){var n;const s=this.frameNumber.getThenIncrement(),r={marker:Z.Inter,trackHandle:this.handle,sequence:Ge.u16(0),frameNumber:s,timestamp:(n=t?.now)!==null&&n!==void 0?n:this.clock.now(),extensions:e.extensions},a=new Bn(r).toBinaryLengthBytes();if(a>=this.mtuSizeBytes)throw Fi.mtuTooShort();const o=this.mtuSizeBytes-a,d=Math.ceil(e.payload.byteLength/o);for(let l=0,u=0;u<e.payload.byteLength;c=[l+1,u+o],l=c[0],u=c[1],c){var c;const h=this.sequence.getThenIncrement(),p=new Bn(Object.assign(Object.assign({},r),{marker:Ir.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 xi(p,g)}}}var Be;(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"})(Be||(Be={}));class he extends Ue{constructor(e,t,n){super(21,e,n),this.name="DataTrackPublishError",this.reason=t,this.reasonName=Be[t],this.rawMessage=n?.rawMessage}static notAllowed(e){return new he("Data track publishing unauthorized",Be.NotAllowed,{rawMessage:e})}static duplicateName(e){return new he("Track name already taken",Be.DuplicateName,{rawMessage:e})}static invalidName(e){return new he("Track name is invalid",Be.InvalidName,{rawMessage:e})}static timeout(){return new he("Publish data track timed-out. Does the LiveKit server support data tracks?",Be.Timeout)}static limitReached(e){return new he("Data track publication limit reached",Be.LimitReached,{rawMessage:e})}static unknown(e,t){return new he("Received RequestResponse for publishDataTrack, but reason was unrecognised (".concat(e,", ").concat(t,")"),Be.Unknown)}static disconnected(){return new he("Room disconnected",Be.Disconnected)}static cancelled(){return new he("Publish data track cancelled by caller",Be.Cancelled)}}var Rn;(function(i){i[i.TrackUnpublished=0]="TrackUnpublished",i[i.Dropped=1]="Dropped"})(Rn||(Rn={}));class Tt extends Ue{constructor(e,t,n){super(22,e,n),this.name="DataTrackPushFrameError",this.reason=t,this.reasonName=Rn[t]}static trackUnpublished(){return new Tt("Track is no longer published",Rn.TrackUnpublished)}static dropped(e){return new Tt("Frame was dropped",Rn.Dropped,{cause:e})}}var Pn;(function(i){i[i.Packetizer=0]="Packetizer",i[i.Encryption=1]="Encryption"})(Pn||(Pn={}));class qn extends Ue{constructor(e,t,n){super(21,e,n),this.name="DataTrackOutgoingPipelineError",this.reason=t,this.reasonName=Pn[t]}static packetizer(e){return new qn("Error packetizing frame",Pn.Packetizer,{cause:e})}static encryption(e){return new qn("Error encrypting frame",Pn.Encryption,{cause:e})}}class Bi{constructor(e,t){this.trackSymbol=bd,this.isLocal=!0,this.typeSymbol=yd,this.handle=null,this.log=U,this.flushedFuture=new ye,this.isFlushed=!0,this.handleManagerReset=()=>{var n,s;(s=(n=this.flushedFuture).resolve)===null||s===void 0||s.call(n),this.manager.off("packetsFlushedChange",this.handleManagerPacketsFlushedChange),this.manager.off("reset",this.handleManagerReset)},this.handleManagerPacketsFlushedChange=n=>{var s,r;this.isFlushed=n.isFlushed,n.isFlushed&&((r=(s=this.flushedFuture).resolve)===null||r===void 0||r.call(s),this.flushedFuture=new ye)},this.options=e,this.manager=t,this.log=ke(ce.DataTracks),this.manager.on("packetsFlushedChange",this.handleManagerPacketsFlushedChange),this.manager.on("reset",this.handleManagerReset)}static withExplicitHandle(e,t,n){const s=new Bi(e,t);return s.handle=n,s}get info(){const e=this.descriptor;if(e?.type==="active")return e.info}get descriptor(){return this.handle?this.manager.getDescriptor(this.handle):null}publish(e){return m(this,void 0,void 0,function*(){try{this.handle=yield this.manager.publishRequest(this.options,e)}catch(t){throw t}})}isPublished(){var e;return((e=this.descriptor)===null||e===void 0?void 0:e.type)==="active"&&this.descriptor.publishState!=="unpublished"}tryPush(e){if(!this.handle)throw Tt.trackUnpublished();const t=vd.from(e);try{return this.manager.tryProcessAndSend(this.handle,t)}catch(n){throw n}}flush(){return m(this,void 0,void 0,function*(){if(!this.isFlushed)return this.flushedFuture.promise})}unpublish(){return m(this,void 0,void 0,function*(){if(!this.handle){U.warn('Data track "'.concat(this.options.name,'" is not published, so unpublishing has no effect.'));return}try{yield this.manager.unpublishRequest(this.handle)}catch(e){throw e}})}}class qi{constructor(e){this.e2eeManager=e.e2eeManager,this.packetizer=new Ir(e.info.pubHandle,qi.TRANSPORT_MTU_BYTES)}updateE2eeManager(e){this.e2eeManager=e}processFrame(e){return ac(this,arguments,function*(){const n=yield pt(this.encryptIfNeeded(e));try{yield pt(yield*Bu(xe(this.packetizer.packetize(n))))}catch(s){throw s instanceof Fi?qn.packetizer(s):s}})}encryptIfNeeded(e){return m(this,void 0,void 0,function*(){if(!this.e2eeManager)return e;let t;try{t=yield this.e2eeManager.encryptData(e.payload)}catch(n){throw qn.encryption(n)}return e.payload=t.payload,e.extensions.e2ee=new He(t.keyIndex,t.iv),e})}}qi.TRANSPORT_MTU_BYTES=16e3;const Oe=ke(ce.DataTracks),so={pending(){return{type:"pending",completionFuture:new ye}},active(i,e){return{type:"active",info:i,publishState:"published",pipeline:new qi({info:i,e2eeManager:e}),unpublishingFuture:new ye}}},ym=1e4;class Mr extends De.EventEmitter{constructor(e){var t;super(),this.handleAllocator=new np,this.descriptors=new Map,this.inFlightPacketCounter=new Map,this.e2eeManager=(t=e?.e2eeManager)!==null&&t!==void 0?t:null}static withDescriptors(e){const t=new Mr;return t.descriptors=e,t}updateE2eeManager(e){this.e2eeManager=e;for(const t of this.descriptors.values())t.type==="active"&&t.pipeline.updateE2eeManager(e)}
39getDescriptor(e){var t;return(t=this.descriptors.get(e))!==null&&t!==void 0?t:null}tryProcessAndSend(e,t){return m(this,void 0,void 0,function*(){var n,s,r,a,o;const d=this.getDescriptor(e);if(d?.type!=="active"||d.publishState==="unpublished")throw Tt.trackUnpublished();if(d.publishState==="republishing")throw Tt.dropped("Data track republishing");try{try{for(var c=!0,l=xe(d.pipeline.processFrame(t)),u;u=yield l.next(),n=u.done,!n;c=!0){a=u.value,c=!1;const h=a,p=(o=this.inFlightPacketCounter.get(e))!==null&&o!==void 0?o:0;this.inFlightPacketCounter.set(e,p+1),p===0&&this.emit("packetsFlushedChange",{handle:e,isFlushed:!1}),this.emit("packetAvailable",{handle:e,bytes:h.toBinary()})}}catch(h){s={error:h}}finally{try{!c&&!n&&(r=l.return)&&(yield r.call(l))}finally{if(s)throw s.error}}}catch(h){throw Tt.dropped(h)}})}handlePacketSendComplete(e){var t;let s=((t=this.inFlightPacketCounter.get(e))!==null&&t!==void 0?t:0)-1;s<0&&(Oe.warn("OutgoingDataTrackManager.handlePacketSendComplete: inFlightPacketCounter was decremented below 0 (got ".concat(this.inFlightPacketCounter," - resetting to 0. Were more packets send than were emitted?")),s=0),this.inFlightPacketCounter.set(e,s),s===0&&this.emit("packetsFlushedChange",{handle:e,isFlushed:!0})}publishRequest(e,t){return m(this,void 0,void 0,function*(){const n=this.handleAllocator.get();if(!n)throw he.limitReached();const s=fd(ym),r=t?md([t,s]):s;if(this.descriptors.has(n))throw new Error("Descriptor for handle already exists");const a=so.pending();this.descriptors.set(n,a);const o=()=>{var d,c;const l=this.descriptors.get(n);if(!l){Oe.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,s.aborted?he.timeout():he.cancelled()))};return r.aborted?(o(),a.completionFuture.promise.then(()=>n)):(r.addEventListener("abort",o),this.emit("sfuPublishRequest",{handle:n,name:e.name,usesE2ee:this.e2eeManager!==null}),yield a.completionFuture.promise,r.removeEventListener("abort",o),this.emit("trackPublished",{track:Bi.withExplicitHandle(e,this,n)}),n)})}queryPublished(){return Array.from(this.descriptors.values()).filter(t=>t.type==="active").map(t=>t.info)}unpublishRequest(e){return m(this,void 0,void 0,function*(){const t=this.descriptors.get(e);if(!t){Oe.warn("No descriptor for ".concat(e));return}if(t.type!=="active"){Oe.warn("Track ".concat(e," not active"));return}this.emit("sfuUnpublishRequest",{handle:e}),yield t.unpublishingFuture.promise,this.inFlightPacketCounter.delete(e),this.emit("trackUnpublished",{sid:t.info.sid})})}receivedSfuPublishResponse(e,t){var n,s,r,a;const o=this.descriptors.get(e);if(!o){Oe.warn("No descriptor for ".concat(e));return}switch(this.descriptors.delete(e),o.type){case"pending":{if(t.type==="ok"){const d=t.data;Oe.debug("SFU accepted publish request for handle ".concat(e),{sid:d.sid});const c=d.usesE2ee?this.e2eeManager:null;this.descriptors.set(d.pubHandle,so.active(d,c)),(s=(n=o.completionFuture).resolve)===null||s===void 0||s.call(n)}else Oe.debug("SFU rejected publish request for handle ".concat(e),{error:t.error}),(a=(r=o.completionFuture).reject)===null||a===void 0||a.call(r,t.error);return}case"active":{if(o.publishState!=="republishing"){Oe.warn("Track ".concat(e," already active"));return}if(t.type==="error"){Oe.warn("Republish failed for track ".concat(e));return}Oe.debug("Track ".concat(e," republished")),o.info.sid=t.data.sid,o.publishState="published",this.descriptors.set(o.info.pubHandle,o)}}}receivedSfuUnpublishResponse(e){var t,n;const s=this.descriptors.get(e);if(!s){Oe.warn("No descriptor for ".concat(e));return}if(this.descriptors.delete(e),s.type!=="active"){Oe.warn("Track ".concat(e," not active"));return}s.publishState="unpublished",(n=(t=s.unpublishingFuture).resolve)===null||n===void 0||n.call(t)}sfuWillRepublishTracks(){var e,t;for(const s of this.descriptors.entries()){var n=L(s,2);const r=n[0],a=n[1];switch(a.type){case"pending":this.descriptors.delete(r),(t=(e=a.completionFuture).reject)===null||t===void 0||t.call(e,he.disconnected());break;
39case"active":a.publishState="republishing",this.emit("sfuPublishRequest",{handle:a.info.pubHandle,name:a.info.name,usesE2ee:a.info.usesE2ee})}}}reset(){return m(this,void 0,void 0,function*(){var e,t,n,s;this.handleAllocator.reset();for(const r of this.descriptors.values())switch(r.type){case"pending":(t=(e=r.completionFuture).reject)===null||t===void 0||t.call(e,he.disconnected());break;case"active":(s=(n=r.unpublishingFuture).resolve)===null||s===void 0||s.call(n),yield this.unpublishRequest(r.info.pubHandle);break}this.descriptors.clear(),this.inFlightPacketCounter.clear(),this.emit("reset")})}}class z extends Error{constructor(e,t,n,s){super(t),this.code=e,this.message=ro(t,z.MAX_MESSAGE_BYTES),this.data=n?ro(n,z.MAX_DATA_BYTES):void 0,typeof s?.cause<"u"&&(this.cause=s?.cause)}static fromProto(e){return new z(e.code,e.message,e.data)}toProto(){return new Fo({code:this.code,message:this.message,data:this.data})}static builtIn(e,t,n){return new z(z.ErrorCode[e],z.ErrorMessage[e],t,n)}}z.MAX_MESSAGE_BYTES=256;z.MAX_DATA_BYTES=15360;z.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};z.ErrorMessage={APPLICATION_ERROR:"Application error in method handler",CONNECTION_TIMEOUT:"Connection timeout",RESPONSE_TIMEOUT:"Response timeout",RECIPIENT_DISCONNECTED:"Recipient disconnected",RESPONSE_PAYLOAD_TOO_LARGE:"Response payload too large",SEND_FAILED:"Failed to send",UNSUPPORTED_METHOD:"Method not supported at destination",RECIPIENT_NOT_FOUND:"Recipient not found",REQUEST_PAYLOAD_TOO_LARGE:"Request payload too large",UNSUPPORTED_SERVER:"RPC not supported by server",UNSUPPORTED_VERSION:"Unsupported RPC version"};const Td=15360,Sd="lk.rpc_request",Cd="lk.rpc_response";var be;(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="l
39k.rpc_request_version"})(be||(be={}));const km=1,Ed=2;function Dr(i){return new TextEncoder().encode(i).length}function ro(i,e){if(Dr(i)<=e)return i;let t=0,n=i.length;const s=new TextEncoder;for(;t<n;){const r=Math.floor((t+n+1)/2);s.encode(i.slice(0,r)).length<=e?t=r:n=r-1}return i.slice(0,t)}class Tm extends De.EventEmitter{constructor(e,t,n,s){super(),this.pendingAcks=new Map,this.pendingResponses=new Map,this.log=e,this.outgoingDataStreamManager=t,this.getRemoteParticipantClientProtocol=n,this.getServerVersion=s}performRpc(e){return m(this,arguments,void 0,function(t){var n=this;let s=t.destinationIdentity,r=t.method,a=t.payload,o=t.responseTimeout,d=o===void 0?15e3:o;return(function*(){const u=n.getRemoteParticipantClientProtocol(s);if(Dr(a)>Td&&u<Os)throw z.builtIn("REQUEST_PAYLOAD_TOO_LARGE");const p=n.getServerVersion();if(p&&nt(p,"1.8.0")<0)throw z.builtIn("UNSUPPORTED_SERVER");const f=Math.max(d,8e3),g=crypto.randomUUID(),k=new ye;let T=null;const S=setTimeout(()=>{var v;n.pendingAcks.delete(g),(v=k.reject)===null||v===void 0||v.call(k,z.builtIn("CONNECTION_TIMEOUT")),n.pendingResponses.delete(g),T!==null&&clearTimeout(T)},7e3);n.pendingAcks.set(g,{resolve:()=>{clearTimeout(S)},participantIdentity:s}),n.pendingResponses.set(g,{completionFuture:k,participantIdentity:s}),yield n.publishRpcRequest(s,g,r,a,f,u),T=setTimeout(()=>{var v;n.pendingResponses.delete(g),(v=k.reject)===null||v===void 0||v.call(k,z.builtIn("RESPONSE_TIMEOUT"))},d);const N=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,N]})()})}publishRpcRequest(e,t,n,s,r,a){return m(this,void 0,void 0,function*(){if(a>=Os){yield this.outgoingDataStreamManager.sendText(s,{topic:Sd,destinationIdentities:[e],attributes:{[be.RPC_REQUEST_ID]:t,[be.RPC_REQUEST_METHOD]:n,[be.RPC_REQUEST_RESPONSE_TIMEOUT_MS]:"".concat(r),[be.RPC_REQUEST_VERSION]:"".concat(Ed)}});return}this.emit("sendDataPacket",{packet:new Ee({destinationIdentities:[e],kind:Ct.RELIABLE,value:{case:"rpcRequest",value:new nr({id:t,method:n,payload:s,responseTimeoutMs:r,version:km})}})})})}handleIncomingDataStream(e,t,n){return m(this,void 0,void 0,function*(){const s=n[be.RPC_REQUEST_ID];if(!s){this.log.warn("RPC data stream malformed: ".concat(be.RPC_REQUEST_ID," not set."));return}const r=this.pendingResponses.get(s);if(r&&r.participantIdentity!==t){this.log.warn("RPC response stream for ".concat(s," arrived from unexpected sender ").concat(t,", expected ").concat(r.participantIdentity,". Ignoring."));return}let a;try{a=yield e.readAll()}catch(o){this.log.warn("Error reading RPC response payload: ".concat(o)),this.handleIncomingRpcResponseFailure(s,z.builtIn("APPLICATION_ERROR","Error reading RPC response payload",{cause:o}));return}this.handleIncomingRpcResponseSuccess(s,a)})}handleIncomingRpcResponseSuccess(e,t){var n,s;const r=this.pendingResponses.get(e);r?((s=(n=r.completionFuture).resolve)===null||s===void 0||s.call(n,t),this.pendingResponses.delete(e)):this.log.error("Response received for unexpected RPC request",e)}handleIncomingRpcResponseFailure(e,t){var n,s;const r=this.pendingResponses.get(e);r?((s=(n=r.completionFuture).reject)===null||s===void 0||s.call(n,t),this.pendingResponses.delete(e)):this.log.error("Response received for unexpected RPC request",e)}handleIncomingRpcAck(e){const t=this.pendingAcks.get(e);t?(t.resolve(),this.pendingAcks.delete(e)):this.log.error("Ack received for unexpected RPC request: ".concat(e))}handleParticipantDisconnected(e){var t;for(const a of this.pendingAcks){var n=L(a,2);const o=n[0];n[1].participantIdentity===e&&this.pendingAcks.delete(o)}for(const a of this.pendingResponses){var s=L(a,2);const o=s[0];var r=s[1];const d=r.participantIdentity,c=r.completionFuture;d===e&&((t=c.reject)===null||t===void 0||t.call(c,z.builtIn("RECIPIENT_DISCONNECTED")),this.pendingResponses.delete(o))}}}class Sm extends De.EventEmitter{constructor(e,t,n){super(),this.rpcHandlers=new Map,this.log=e,this.outgoingDataStreamManager=t,this.getRemoteParticipantClientProtocol=n}
39registerRpcMethod(e,t){if(this.rpcHandlers.has(e))throw Error("RPC handler already registered for method ".concat(e,", unregisterRpcMethod before trying to register again"));this.rpcHandlers.set(e,t)}unregisterRpcMethod(e){this.rpcHandlers.delete(e)}handleIncomingRpcRequest(e,t){return m(this,void 0,void 0,function*(){var n;if(this.publishRpcAck(e,t.id),t.version!==1){this.publishRpcResponsePacket(e,t.id,null,z.builtIn("UNSUPPORTED_VERSION"));return}const s=this.rpcHandlers.get(t.method);if(!s){this.publishRpcResponsePacket(e,t.id,null,z.builtIn("UNSUPPORTED_METHOD"));return}let r;try{r=yield s({requestId:t.id,callerIdentity:e,payload:t.payload,responseTimeout:t.responseTimeoutMs})}catch(a){let o;a instanceof z?o=a:(this.log.warn("Uncaught error returned by RPC handler for ".concat(t.method,". Returning APPLICATION_ERROR instead."),a),o=z.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,r??"")})}handleIncomingDataStream(e,t,n){return m(this,void 0,void 0,function*(){const s=n[be.RPC_REQUEST_ID],r=n[be.RPC_REQUEST_METHOD],a=parseInt(n[be.RPC_REQUEST_RESPONSE_TIMEOUT_MS],10),o=parseInt(n[be.RPC_REQUEST_VERSION],10);if(!s||!r||Number.isNaN(a)||Number.isNaN(o)){this.log.warn("RPC data stream malformed: ".concat(be.RPC_REQUEST_ID," / ").concat(be.RPC_REQUEST_METHOD," / ").concat(be.RPC_REQUEST_RESPONSE_TIMEOUT_MS," / ").concat(be.RPC_REQUEST_VERSION," not set.")),this.publishRpcResponsePacket(t,s,null,z.builtIn("APPLICATION_ERROR","RPC data stream malformed"));return}if(this.publishRpcAck(t,s),o!==Ed){this.publishRpcResponsePacket(t,s,null,z.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,s,null,z.builtIn("APPLICATION_ERROR","Error reading RPC request payload",{cause:u}));return}const c=this.rpcHandlers.get(r);if(!c){this.publishRpcResponsePacket(t,s,null,z.builtIn("UNSUPPORTED_METHOD"));return}let l;try{l=yield c({requestId:s,callerIdentity:t,payload:d,responseTimeout:a})}catch(u){let h;u instanceof z?h=u:(this.log.warn("Uncaught error returned by RPC handler for ".concat(r,". Returning APPLICATION_ERROR instead."),u),h=z.builtIn("APPLICATION_ERROR")),this.publishRpcResponsePacket(t,s,null,h);return}yield this.publishRpcResponse(t,s,l??"")})}publishRpcAck(e,t){this.emit("sendDataPacket",{packet:new Ee({destinationIdentities:[e],kind:Ct.RELIABLE,value:{case:"rpcAck",value:new Ri({requestId:t})}})})}publishRpcResponsePacket(e,t,n,s){this.emit("sendDataPacket",{packet:new Ee({destinationIdentities:[e],kind:Ct.RELIABLE,value:{case:"rpcResponse",value:new ir({requestId:t,value:s?{case:"error",value:s.toProto()}:{case:"payload",value:n??""}})}})})}publishRpcResponse(e,t,n){return m(this,void 0,void 0,function*(){if(this.getRemoteParticipantClientProtocol(e)>=Os){yield this.outgoingDataStreamManager.sendText(n,{topic:Cd,destinationIdentities:[e],attributes:{[be.RPC_REQUEST_ID]:t}});return}if(Dr(n)>Td){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,z.builtIn("RESPONSE_PAYLOAD_TOO_LARGE"));return}this.publishRpcResponsePacket(e,t,n,null)})}}class Cm extends Xc{constructor(e,t,n,s,r,a){super(e,t,C.Kind.Audio,n,a),this.monitorReceiver=()=>m(this,void 0,void 0,function*(){if(!this.receiver){this._currentBitrate=0;return}const o=yield this.getReceiverStats();o&&this.prevStats&&this.receiver&&(this._currentBitrate=Ni(o,this.prevStats)),this.prevStats=o}),this.audioContext=s,this.webAudioPluginNodes=[],r&&(this.sinkId=r.deviceId)}setVolume(e){var t;for(const n of this.attachedElements)this.audioContext?(t=this.gainNode)===null||t===void 0||t.gain.setTargetAtTime(e,0,.1):n.volume=e;Je()&&this._mediaStreamTrack._setVolume(e),this.elementVolume=e}getVolume(){if(this.elementVolume)return this.elementVolume;if(Je())return 1;let e=0;
vendor: 4,388 bytes, line 39
39return this.attachedElements.forEach(t=>{t.volume>e&&(e=t.volume)}),e}setSinkId(e){return m(this,void 0,void 0,function*(){this.sinkId=e,yield Promise.all(this.attachedElements.map(t=>{if(qs(t))return t.setSinkId(e)}))})}attach(e){const t=this.attachedElements.length===0;return e?super.attach(e):e=super.attach(),this.sinkId&&qs(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(s=>{n.connect(s),n=s}),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(s=>{this.emit(P.AudioPlaybackFailed,s)})}disconnectWebAudio(){var e,t;(e=this.gainNode)===null||e===void 0||e.disconnect(),(t=this.sourceNode)===null||t===void 0||t.disconnect(),this.gainNode=void 0,this.sourceNode=void 0}getReceiverStats(){return m(this,void 0,void 0,function*(){if(!this.receiver||!this.receiver.getStats)return;const e=yield this.receiver.getStats();let t;return e.forEach(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})}}class at extends De.EventEmitter{constructor(e,t,n,s){var r;super(),this.metadataMuted=!1,this.encryption=G.NONE,this.log=U,this.handleMuted=()=>{this.emit(P.Muted)},this.handleUnmuted=()=>{this.emit(P.Unmuted)},this.log=ke((r=s?.loggerName)!==null&&r!==void 0?r:ce.Publication),this.loggerContextCb=this.loggerContextCb,this.setMaxListeners(100),this.kind=e,this.trackSid=t,this.trackName=n,this.source=C.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)),V(this))}get isMuted(){return this.metadataMuted}get isEnabled(){return!0}get isSubscribed(){return this.track!==void 0}get isEncrypted(){return this.encryption!==G.NONE}get audioTrack(){if(tt(this.track))return this.track}get videoTrack(){if(mt(this.track))return this.track}updateInfo(e){this.trackSid=e.sid,this.trackName=e.name,this.source=C.sourceFromProto(e.source),this.mimeType=e.mimeType,this.kind===C.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={}))})(at||(at={}));class zs extends at{get isUpstreamPaused(){var e;return(e=this.track)===null||e===void 0?void 0:e.isUpstreamPaused}constructor(e,t,n,s){super(e,t.sid,t.name,s),this.track=void 0,this.handleTrackEnded=()=>
39{this.emit(P.Ended)},this.handleCpuConstrained=()=>{this.track&&mt(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 m(this,void 0,void 0,function*(){var e;return(e=this.track)===null||e===void 0?void 0:e.mute()})}unmute(){return m(this,void 0,void 0,function*(){var e;return(e=this.track)===null||e===void 0?void 0:e.unmute()})}pauseUpstream(){return m(this,void 0,void 0,function*(){var e;yield(e=this.track)===null||e===void 0?void 0:e.pauseUpstream()})}resumeUpstream(){return m(this,void 0,void 0,function*(){var e;yield(e=this.track)===null||e===void 0?void 0:e.resumeUpstream()})}getTrackFeatures(){var e;if(tt(this.track)){const t=this.track.getSourceTrackSettings(),n=new Set;return t.autoGainControl&&n.add(me.TF_AUTO_GAIN_CONTROL),t.echoCancellation&&n.add(me.TF_ECHO_CANCELLATION),t.noiseSuppression&&n.add(me.TF_NOISE_SUPPRESSION),t.channelCount&&t.channelCount>1&&n.add(me.TF_STEREO),!((e=this.options)===null||e===void 0)&&e.dtx||n.add(me.TF_NO_DTX),this.track.enhancedNoiseCancellation&&n.add(me.TF_ENHANCED_NOISE_CANCELLATION),Array.from(n.values())}else return[]}}function Vi(i,e){return m(this,void 0,void 0,function*(){i??(i={});let t=!1;const n=Gc(i),s=n.audioProcessor,r=n.videoProcessor,a=n.optionsWithoutProcessor;let o=a.audio,d=a.video;if(s&&typeof a.audio=="object"&&(a.audio.processor=s),r&&typeof a.video=="object"&&(a.video.processor=r),i.audio&&typeof a.audio=="object"&&typeof a.audio.deviceId=="string"){const h=a.audio.deviceId;a.audio.deviceId={exact:h},t=!0,o=Object.assign(Object.assign({},a.audio),{deviceId:{ideal:h}})}if(a.video&&typeof a.video=="object"&&typeof a.video.deviceId=="string"){const h=a.video.deviceId;a.video.deviceId={exact:h},t=!0,d=Object.assign(Object.assign({},a.video),{deviceId:{ideal:h}})}a.audio===!0?a.audio={deviceId:"default"}:typeof a.audio=="object"&&a.audio!==null&&(a.audio=Object.assign(Object.assign({},a.audio),{deviceId:a.audio.deviceId||"default"})),a.video===!0?a.video={deviceId:"default"}:typeof a.video=="object"&&!a.video.deviceId&&(a.video.deviceId="default");const c=jc(a,ed,td),l=vr(c),u=navigator.mediaDevices.getUserMedia(l);a.audio&&(fe.userMediaPromiseMap.set("audioinput",u),u.catch(()=>fe.userMediaPromiseMap.delete("audioinput"))),a.video&&(fe.userMediaPromiseMap.set("videoinput",u),u.catch(()=>fe.userMediaPromiseMap.delete("videoinput")));try{const h=yield u;return yield Promise.all(h.getTracks().map(p=>m(this,void 0,void 0,function*(){const f=p.kind==="audio";let g;const k=f?l.audio:l.video;typeof k!="boolean"&&(g=k);const T=p.getSettings().deviceId;g?.deviceId&&en(g.deviceId)!==T?g.deviceId=T:g||(g={deviceId:T});const S=xp(p,g,e);return S.kind===C.Kind.Video?S.source=C.Source.Camera:S.kind===C.Kind.Audio&&(S.source=C.Source.Microphone),S.mediaStream=h,tt(S)&&s?yield S.setProcessor(s):mt(S)&&r&&(yield S.setProcessor(r)),S})))}catch(h){if(!t)throw h;return Vi(Object.assign(Object.assign({},i),{audio:o,video:d}),e)}})}function Em(i){return m(this,void 0,void 0,function*(){return(yield Vi({audio:!1,video:!0}))[0]})}function _d(i){return m(this,void 0,void 0,function*(){return(yield Vi({audio:i??!0,video:!1}
39))[0]})}var bt;(function(i){i.Excellent="excellent",i.Good="good",i.Poor="poor",i.Lost="lost",i.Unknown="unknown"})(bt||(bt={}));function _m(i){switch(i){case yn.EXCELLENT:return bt.Excellent;case yn.GOOD:return bt.Good;case yn.POOR:return bt.Poor;case yn.LOST:return bt.Lost;default:return bt.Unknown}}class wd extends De.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===Mn.AGENT}get isActive(){var e;return((e=this.participantInfo)===null||e===void 0?void 0:e.state)===Qt.ACTIVE}get kind(){return this._kind}get attributes(){return Object.freeze(Object.assign({},this._attributes))}constructor(e,t,n,s,r,a){let o=arguments.length>6&&arguments[6]!==void 0?arguments[6]:Mn.STANDARD;var d;super(),this.audioLevel=0,this.isSpeaking=!1,this._connectionQuality=bt.Unknown,this.log=U,this.loggerOptions=a,this.log=ke((d=a?.loggerName)!==null&&d!==void 0?d:ce.Participant,()=>this.logContext),this.setMaxListeners(100),this.sid=e,this.identity=t,this.name=n,this.metadata=s,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this._kind=o,this._attributes=r??{}}getTrackPublications(){return Array.from(this.trackPublications.values())}getTrackPublication(e){for(const n of this.trackPublications){var t=L(n,2);const s=t[1];if(s.source===e)return s}}getTrackPublicationByName(e){for(const n of this.trackPublications){var t=L(n,2);const s=t[1];if(s.trackName===e)return s}}waitUntilActive(){return this.isActive?Promise.resolve():this.activeFuture?this.activeFuture.promise:(this.activeFuture=new ye,this.once(M.Active,()=>{var e,t;(t=(e=this.activeFuture)===null||e===void 0?void 0:e.resolve)===null||t===void 0||t.call(e),this.activeFuture=void 0}),this.activeFuture.promise)}get connectionQuality(){return this._connectionQuality}get isCameraEnabled(){var e;const t=this.getTrackPublication(C.Source.Camera);return!(!((e=t?.isMuted)!==null&&e!==void 0)||e)}get isMicrophoneEnabled(){var e;const t=this.getTrackPublication(C.Source.Microphone);return!(!((e=t?.isMuted)!==null&&e!==void 0)||e)}get isScreenShareEnabled(){return!!this.getTrackPublication(C.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===Qt.ACTIVE&&((t=this.participantInfo)===null||t===void 0?void 0:t.state)!==Qt.ACTIVE&&this.emit(M.Active),e.permission&&this.setPermissions(e.permission),this.participantInfo=e,!0)}_setMetadata(e){const t=this.metadata!==e,n=this.metadata;this.metadata=e,t&&this.emit(M.ParticipantMetadataChanged,n)}_setName(e){const t=this.name!==e;this.name=e,t&&this.emit(M.ParticipantNameChanged,e)}_setAttributes(e){const t=uh(this.attributes,e);this._attributes=e,Object.keys(t).length>0&&this.emit(M.AttributesChanged,t)}setPermissions(e){var t,n,s,r,a,o;const 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!==((s=this.permissions)===null||s===void 0?void 0:s.canPublishData)||e.hidden!==((r=this.permissions)===null||r===void 0?void 0:r.hidden)||e.recorder!==((a=this.permissions)===null||a===void 0?void 0:a.recorder)||e.canPublishSources.length!==this.permissions.canPublishSources.length||e.canPublishSources.some((l,u)=>{var h;return l!==((h=this.permissions)===null||h===void 0?void 0:h.canPublishSources[u])})||e.canSubscribeMetrics!==((o=this.permissions)===null||o===void 0?void 0:o.canSubscribeMetrics);
39return this.permissions=e,c&&this.emit(M.ParticipantPermissionsChanged,d),c}setIsSpeaking(e){e!==this.isSpeaking&&(this.isSpeaking=e,e&&(this.lastSpokeAt=new Date),this.emit(M.IsSpeakingChanged,e))}setConnectionQuality(e){const t=this._connectionQuality;this._connectionQuality=_m(e),t!==this._connectionQuality&&this.emit(M.ConnectionQualityChanged,this._connectionQuality)}setDisconnected(){var e,t;this.activeFuture&&((t=(e=this.activeFuture).reject)===null||t===void 0||t.call(e,new Error("Participant disconnected")),this.activeFuture=void 0)}setAudioContext(e){this.audioContext=e,this.audioTrackPublications.forEach(t=>tt(t.track)&&t.track.setAudioContext(e))}addTrackPublication(e){this.log.debug("adding track publication",{trackSid:e.trackSid,source:e.source,kind:e.kind}),e.on(P.Muted,()=>{this.emit(M.TrackMuted,e)}),e.on(P.Unmuted,()=>{this.emit(M.TrackUnmuted,e)});const t=e;switch(t.track&&(t.track.sid=e.trackSid),this.trackPublications.set(e.trackSid,e),e.kind){case C.Kind.Audio:this.audioTrackPublications.set(e.trackSid,e);break;case C.Kind.Video:this.videoTrackPublications.set(e.trackSid,e);break}}}function wm(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 ec({participantIdentity:(e=i.participantIdentity)!==null&&e!==void 0?e:"",participantSid:(t=i.participantSid)!==null&&t!==void 0?t:"",allTracks:(n=i.allowAll)!==null&&n!==void 0?n:!1,trackSids:i.allowedTrackSids||[]})}class Rm extends wd{constructor(e,t,n,s,r,a,o,d){super(e,t,void 0,void 0,void 0,{loggerName:s.loggerName,loggerContextCb:()=>this.engine.logContext}),this.pendingPublishing=new Set,this.pendingPublishPromises=new Map,this.participantTrackPermissions=[],this.allParticipantsAllowedToSubscribe=!0,this.encryptionType=G.NONE,this.e2eeStateMutex=new ge,this.enabledPublishVideoCodecs=[],this.handleReconnecting=()=>{this.reconnectFuture||(this.reconnectFuture=new ye)},this.handleReconnected=()=>{var c,l;(l=(c=this.reconnectFuture)===null||c===void 0?void 0:c.resolve)===null||l===void 0||l.call(c),this.reconnectFuture=void 0,this.updateTrackSubscriptionPermissions()},this.handleClosing=()=>{var c,l,u,h,p,f;this.reconnectFuture&&(this.reconnectFuture.promise.catch(g=>this.log.warn(g.message)),(l=(c=this.reconnectFuture)===null||c===void 0?void 0:c.reject)===null||l===void 0||l.call(c,new Error("Got disconnected during reconnection attempt")),this.reconnectFuture=void 0),this.signalConnectedFuture&&((h=(u=this.signalConnectedFuture).reject)===null||h===void 0||h.call(u,new Error("Got disconnected without signal connected")),this.signalConnectedFuture=void 0),(f=(p=this.activeAgentFuture)===null||p===void 0?void 0:p.reject)===null||f===void 0||f.call(p,new Error("Got disconnected without active agent present")),this.activeAgentFuture=void 0,this.firstActiveAgent=void 0},this.handleSignalConnected=c=>{var l,u;c.participant&&this.updateInfo(c.participant),this.signalConnectedFuture||(this.signalConnectedFuture=new ye),(u=(l=this.signalConnectedFuture).resolve)===null||u===void 0||u.call(l)},this.handleSignalRequestResponse=c=>{const l=c.requestId,u=c.reason,h=c.message,p=this.pendingSignalRequests.get(l);switch(p&&(u!==At.OK&&p.reject(new ua(h,u)),this.pendingSignalRequests.delete(l)),c.request.case){case"publishDataTrack":{let f;switch(c.reason){case At.NOT_ALLOWED:f=he.notAllowed(c.message);break;case At.DUPLICATE_NAME:f=he.duplicateName(c.message);break;case At.INVALID_NAME:f=he.invalidName(c.message);break;case At.LIMIT_EXCEEDED:f=he.limitReached(c.message);break;default:f=he.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=>wm(c)))},this.onTrackUnmuted=c=>{this.onTrackMuted(c,c.isUpstreamPaused)},this.onTrackMuted=(c,l)=>{if(l===void 0&&(l=!0),!c.sid){this.log.error("could not update mute status for unpublished track",V(c));return}this.engine.updateMuteStatus(c.sid,l)},this.onTrackUpstreamPaused=c=>{this.log.debug("upstream paused",V(c)),this.onTrackMuted(c,!0)},this.onTrackUpstreamResumed=c=>{this.log.debug("upstream resumed",V(c)),this.onTrackMuted(c,c.isMuted)},this.onTrackFeatureUpdate=c=>{const l=this.audioTrackPublications.get(c.sid);if(!l){this.log.warn("Could not update local audio track settings, missing publication for track ".concat(c.sid));return}this.engine.client.sendUpdateLocalAudioTrack(l.trackSid,l.getTrackFeatures())},this.onTrackCpuConstrained=(c,l)=>
39{this.log.debug("track cpu constrained",V(l)),this.emit(M.LocalTrackCpuConstrained,c,l)},this.handleSubscribedQualityUpdate=c=>m(this,void 0,void 0,function*(){var l,u,h,p,f;if(!(!((f=this.roomOptions)===null||f===void 0)&&f.dynacast))return;const g=this.videoTrackPublications.get(c.trackSid);if(!g){this.log.warn("received subscribed quality update for unknown track",{trackSid:c.trackSid});return}if(!g.videoTrack)return;const k=yield g.videoTrack.setPublishingCodecs(c.subscribedCodecs);try{for(var T=!0,S=xe(k),N;N=yield S.next(),l=N.done,!l;T=!0){p=N.value,T=!1;const v=p;ah(v)&&(this.log.debug("publish ".concat(v," for ").concat(g.videoTrack.sid),V(g)),yield this.publishAdditionalCodecForTrack(g.videoTrack,v,g.options))}}catch(v){u={error:v}}finally{try{!T&&!l&&(h=S.return)&&(yield h.call(S))}finally{if(u)throw u.error}}}),this.handleLocalTrackUnpublished=c=>{const l=this.trackPublications.get(c.trackSid);if(!l){this.log.warn("received unpublished event for unknown track",{trackSid:c.trackSid});return}this.unpublishTrack(l.track)},this.handleTrackEnded=c=>m(this,void 0,void 0,function*(){if(c.source===C.Source.ScreenShare||c.source===C.Source.ScreenShareAudio)this.log.debug("unpublishing local track due to TrackEnded",V(c)),this.unpublishTrack(c);else if(c.isUserProvided)yield c.mute();else if(st(c)||Qe(c))try{if(Me())try{const l=yield navigator?.permissions.query({name:c.source===C.Source.Camera?"camera":"microphone"});if(l&&l.state==="denied")throw this.log.warn("user has revoked access to ".concat(c.source),V(c)),l.onchange=()=>{l.state!=="denied"&&(c.isMuted||c.restartTrack(),l.onchange=null)},new Error("GetUserMedia Permission denied")}catch{}c.isMuted||(this.log.debug("track ended, attempting to use a different device",V(c)),st(c)?yield c.restartTrack({deviceId:"default"}):yield c.restartTrack())}catch{this.log.warn("could not restart track, muting instead",V(c)),yield c.mute()}}),this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this.engine=n,this.roomOptions=s,this.setupEngine(n),this.activeDeviceMap=new Map([["audioinput","default"],["videoinput","default"],["audiooutput","default"]]),this.pendingSignalRequests=new Map,this.roomOutgoingDataStreamManager=r,this.roomOutgoingDataTrackManager=a,this.rpcClientManager=o,this.rpcServerManager=d}get lastCameraError(){return this.cameraError}get lastMicrophoneError(){return this.microphoneError}get isE2EEEnabled(){return this.encryptionType!==G.NONE}getTrackPublication(e){const t=super.getTrackPublication(e);if(t)return t}getTrackPublicationByName(e){const t=super.getTrackPublicationByName(e);if(t)return t}setupEngine(e){var t;this.engine=e,this.engine.on(R.RemoteMute,(n,s)=>{const r=this.trackPublications.get(n);!r||!r.track||(s?r.mute():r.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 m(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({metadata:e})})}setName(e){return m(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({name:e})})}setAttributes(e){return m(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({attributes:e})})}requestMetadataUpdate(e){return m(this,arguments,void 0,function(t){var n=this;let s=t.metadata,r=t.name,a=t.attributes;return(function*(){return new _e((o,d)=>m(n,void 0,void 0,function*(){var c,l;try{let u=!1;const h=yield this.engine.client.sendUpdateLocalMetadata((c=s??this.metadata)!==null&&c!==void 0?c:"",(l=r??this.name)!==null&&l!==void 0?l:"",a),p=performance.now();for(this.pendingSignalRequests.set(h,{resolve:o,reject:f=>{d(f),u=!0},values:{name:r,metadata:s,attributes:a}});performance.now()-p<5e3&&!u;){if((!r||this.name===r)&&(!s||this.metadata===s)&&(!a||Object.entries(a).every(f=>{let g=L(f,2),k=g[0],T=g[1];return this.attributes[k]===T||T===""&&!this.attributes[k]}))){this.pendingSignalRequests.delete(h),o();return}yield Se(50)}d(new ua("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(C.Source.Camera,e,t,n)}setMicrophoneEnabled(e,t,n){return this.setTrackEnabled(C.Source.Microphone,e,t,n)}setScreenShareEnabled(e,t,n){return this.setTrackEnabled(C.Source.ScreenShare,e,t,n)}setE2EEEnabled(e){return m(this,void 0,void 0,function*(){const t=yield this.e2eeStateMutex.lock();try{if(this.encryptionType=e?G.GCM:G.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,s){return m(this,void 0,void 0,function*(){var r,a;this.log.debug("setTrackEnabled",{source:e,enabled:t}),this.republishPromise&&(yield this.republishPromise);let o=this.getTrackPublication(e);if(t)if(o)yield o.unmute();else{let u;if(this.pendingPublishing.has(e)){const h=yield this.waitForPendingPublicationOfSource(e);return h||this.log.info("waiting for pending publication promise timed out",{source:e}),yield h?.unmute(),h}this.pendingPublishing.add(e);try{switch(e){case C.Source.Camera:u=yield this.createTracks({video:(r=n)!==null&&r!==void 0?r:!0});break;case C.Source.Microphone:u=yield this.createTracks({audio:(a=n)!==null&&a!==void 0?a:!0});break;case C.Source.ScreenShare:u=yield this.createScreenTracks(Object.assign({},n));break;default:throw new lt(e)}}catch(h){throw u?.forEach(p=>{p.stop()}
39),h instanceof Error&&this.emit(M.MediaDevicesError,h,Us(e)),this.pendingPublishing.delete(e),h}for(const h of u){const p=Object.assign(Object.assign({},this.roomOptions.publishDefaults),n);e===C.Source.Microphone&&tt(h)&&p.preConnectBuffer&&(this.log.info("starting preconnect buffer for microphone"),h.startPreConnectBuffer())}try{const h=[];for(const f of u)this.log.info("publishing track",V(f)),h.push(this.publishTrack(f,s));const p=yield Promise.all(h);var d=L(p,1);o=d[0]}catch(h){throw u?.forEach(p=>{p.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===C.Source.ScreenShare){const u=[this.unpublishTrack(o.track)],h=this.getTrackPublication(C.Source.ScreenShareAudio);h&&h.track&&u.push(this.unpublishTrack(h.track));var c=yield Promise.all(u),l=L(c,1);o=l[0]}else yield o.mute();return o})}enableCameraAndMicrophone(){return m(this,void 0,void 0,function*(){if(!(this.pendingPublishing.has(C.Source.Camera)||this.pendingPublishing.has(C.Source.Microphone))){this.pendingPublishing.add(C.Source.Camera),this.pendingPublishing.add(C.Source.Microphone);try{const e=yield this.createTracks({audio:!0,video:!0});yield Promise.all(e.map(t=>this.publishTrack(t)))}finally{this.pendingPublishing.delete(C.Source.Camera),this.pendingPublishing.delete(C.Source.Microphone)}}})}createTracks(e){return m(this,void 0,void 0,function*(){var t,n;e??(e={});const s=jc(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 Vi(s,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext})).map(o=>(tt(o)&&(this.microphoneError=void 0,o.setAudioContext(this.audioContext),o.source=C.Source.Microphone,this.emit(M.AudioStreamAcquired)),mt(o)&&(this.cameraError=void 0,o.source=C.Source.Camera),o))}catch(r){throw r instanceof Error&&(e.audio&&(this.microphoneError=r),e.video&&(this.cameraError=r)),r}})}createScreenTracks(e){return m(this,void 0,void 0,function*(){if(e===void 0&&(e={}),navigator.mediaDevices.getDisplayMedia===void 0)throw new fr("getDisplayMedia not supported");e.resolution===void 0&&!Th()&&(e.resolution=gr.h1080fps30.resolution);const t=ch(e),n=yield navigator.mediaDevices.getDisplayMedia(t),s=n.getVideoTracks();if(s.length===0)throw new lt("no video track found");const r=new bi(s[0],void 0,!1,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});r.source=C.Source.ScreenShare,e.contentHint&&(r.mediaStreamTrack.contentHint=e.contentHint);const a=[r];if(n.getAudioTracks().length>0){this.emit(M.AudioStreamAcquired);const o=new gi(n.getAudioTracks()[0],void 0,!1,this.audioContext,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});o.source=C.Source.ScreenShareAudio,a.push(o)}return a})}publishTrack(e,t){return m(this,void 0,void 0,function*(){return this.publishOrRepublishTrack(e,t)})}waitForNextEngineRestart(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:15e3;return new Promise((t,n)=>{const s=()=>{clearTimeout(o),this.engine.off(R.Restarted,r),this.engine.off(R.Closing,a)},r=()=>{s(),t()},a=()=>{s(),n(new Error("engine closed before restart completed"))},o=setTimeout(()=>{s(),n(new Error("timed out waiting for engine restart"))},e);this.engine.once(R.Restarted,r),this.engine.once(R.Closing,a)})}publishOrRepublishTrack(e,t){return m(this,arguments,void 0,function(n,s){var r=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;st(n)&&n.setAudioContext(r.audioContext),yield(d=r.reconnectFuture)===null||d===void 0?void 0:d.promise,r.republishPromise&&!a&&(yield r.republishPromise),tn(n)&&r.pendingPublishPromises.has(n)&&(yield r.pendingPublishPromises.get(n));let h;if(n instanceof MediaStreamTrack)h=n.getConstraints();else{h=n.constraints;let S;switch(n.source){case C.Source.Microphone:S="audioinput";break;case C.Source.Camera:S="videoinput"}S&&r.activeDeviceMap.has(S)&&(h=Object.assign(Object.assign({},h),{deviceId:r.activeDeviceMap.get(S)}))}if(n instanceof MediaStreamTrack)switch(n.kind){case"audio":n=new gi(n,h,!0,r.audioContext,{loggerName:r.roomOptions.loggerName,loggerContextCb:()=>r.logContext});break;case"video":n=new bi(n,h,!0,{loggerName:r.roomOptions.loggerName,loggerContextCb:()=>r.logContext});break;default:throw new lt("unsupported MediaStreamTrack kind ".concat(n.kind))}else n.updateLoggerOptions({loggerName:r.roomOptions.loggerName,loggerContextCb:()=>r.logContext});let p;if(r.trackPublications.forEach(S=>{S.track&&S.track===n&&(p=S)}),p)return r.log.warn("track has already been published, skipping",V(p)),p;const f=Object.assign(Object.assign({},r.roomOptions.publishDefaults),s),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&&r.log.debug("Opus DTX will be disabled for stereo tracks by default. Enable them explicitly to make it work.",V(n)),f.red===void 0&&r.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)),!Ch()&&r.roomOptions.e2ee&&(r.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);const T=new Promise((S,N)=>m(r,void 0,void 0,function*(){try{if(this.engine.client.currentState!==$.CONNECTED){this.log.debug("deferring track publication until signal is connected",{track:V(n)});let v=!1;const y=setTimeout(()=>{v=!0,n.stop(),N(new la("publishing rejected as engine not connected within timeout",408))},15e3);if(yield this.waitUntilEngineConnected(),clearTimeout(y),v)return;const E=yield this.publish(n,f,k);S(E)}else try{const v=yield this.publish(n,f,k);S(v)}catch(v){N(v)}}catch(v){N(v)}}));r.pendingPublishPromises.set(n,T);try{return yield T}catch(S){if(!o&&S instanceof Bt)return r.log.warn("negotiation due to track publish failed, retrying after reconnect",{error:S}),r.pendingPublishPromises.delete(n),yield r.waitForNextEngineRestart(),yield r.publishOrRepublishTrack(n,s,a,!0);throw S}finally{r.pendingPublishPromises.delete(n)}})()})}waitUntilEngineConnected(){return this.signalConnectedFuture||(this.signalConnectedFuture=new ye),this.signalConnectedFuture.promise}hasPermissionsToPublish(e){if(!this.permissions)return this.log.warn("no permissions present for publishing track",V(e)),!1;const t=this.permissions,n=t.canPublish,s=t.canPublishSources;return n&&(s.length===0||s.map(r=>hh(r)).includes(e.source))?!0:(this.log.warn("insufficient permissions to publish",V(e)),!1)}publish(e,t,n){return m(this,void 0,void 0,function*(){var s,r,a,o,d,c,l,u,h,p;
39if(!this.hasPermissionsToPublish(e))throw new la("failed to publish track, insufficient permissions",403);Array.from(this.trackPublications.values()).find(D=>tn(e)&&D.source===e.source)&&e.source!==C.Source.Unknown&&this.log.info("publishing a second track with the same source: ".concat(e.source),V(e)),t.stopMicTrackOnMute&&tt(e)&&(e.stopOnMute=!0),e.source===C.Source.ScreenShare&&Wt()&&(t.simulcast=!1),t.videoCodec==="av1"&&!vh()&&(t.videoCodec=void 0),t.videoCodec==="vp9"&&!bh()&&(t.videoCodec=void 0),t.videoCodec===void 0&&(t.videoCodec=Hs),this.enabledPublishVideoCodecs.length>0&&(this.enabledPublishVideoCodecs.some(D=>t.videoCodec===Cn(D.mime))||(t.videoCodec=Cn(this.enabledPublishVideoCodecs[0].mime)));const 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);const k=[],T=!(!((s=t.dtx)!==null&&s!==void 0)||s),S=e.getSourceTrackSettings();S.autoGainControl&&k.push(me.TF_AUTO_GAIN_CONTROL),S.echoCancellation&&k.push(me.TF_ECHO_CANCELLATION),S.noiseSuppression&&k.push(me.TF_NOISE_SUPPRESSION),S.channelCount&&S.channelCount>1&&k.push(me.TF_STEREO),T&&k.push(me.TF_NO_DTX),st(e)&&e.hasPreConnectBuffer&&k.push(me.TF_PRECONNECT_BUFFER);const N=this.normalizeRequestedFrameMetadataOptions(e,t),v=new An({cid:e.mediaStreamTrack.id,name:t.name,type:C.kindToProto(e.kind),muted:e.isMuted,source:C.sourceToProto(e.source),disableDtx:T,encryption:this.encryptionType,stereo:n,disableRed:this.isE2EEEnabled||!(!((r=t.red)!==null&&r!==void 0)||r),stream:t?.stream,backupCodecPolicy:t?.backupCodecPolicy,audioFeatures:k,packetTrailerFeatures:N});let y;if(e.kind===C.Kind.Video){let D;try{D=yield e.waitForDimensions()}catch{const F=(o=(a=this.roomOptions.videoCaptureDefaults)===null||a===void 0?void 0:a.resolution)!==null&&o!==void 0?o:On.h720.resolution;D={width:F.width,height:F.height},this.log.error("could not determine track dimensions, using defaults",Object.assign(Object.assign({},V(e)),{dims:D}))}v.width=D.width,v.height=D.height,Qe(e)&&(Ze(g)&&(e.source===C.Source.ScreenShare&&(t.scalabilityMode="L1T3","contentHint"in e.mediaStreamTrack&&(e.mediaStreamTrack.contentHint="motion",this.log.debug("forcing contentHint to motion for screenshare with SVC codecs",V(e)))),t.scalabilityMode=(d=t.scalabilityMode)!==null&&d!==void 0?d:"L3T3_KEY"),v.simulcastCodecs=[new Cs({codec:g,cid:e.mediaStreamTrack.id})],t.backupCodec===!0&&(t.backupCodec={codec:Hs}),t.backupCodec&&g!==t.backupCodec.codec&&v.encryption===G.NONE&&(this.roomOptions.dynacast||(this.roomOptions.dynacast=!0),v.simulcastCodecs.push(new Cs({codec:t.backupCodec.codec,cid:""})))),y=vi(e.source===C.Source.ScreenShare,v.width,v.height,t),v.layers=Va(v.width,v.height,y,Ze(t.videoCodec))}else e.kind===C.Kind.Audio&&(y=[{maxBitrate:(c=t.audioPreset)===null||c===void 0?void 0:c.maxBitrate,priority:(u=(l=t.audioPreset)===null||l===void 0?void 0:l.priority)!==null&&u!==void 0?u:"high",networkPriority:(p=(h=t.audioPreset)===null||h===void 0?void 0:h.priority)!==null&&p!==void 0?p:"high"}]);if(!this.engine||this.engine.isClosed)throw new X("cannot publish track when not connected");const E=()=>m(this,void 0,void 0,function*(){var D,O,F,Y;if(!this.engine.pcManager)throw new X("pcManager is not ready");if(e.sender=yield this.engine.createSender(e,t,y),Qe(e)&&(e.publishOptions=t),this.emit(M.LocalSenderCreated,e.sender,e),Qe(e)&&((D=t.degradationPreference)!==null&&D!==void 0||(t.degradationPreference=Kp(e)),e.setDegradationPreference(t.degradationPreference)),y){if(Wt()&&e.kind===C.Kind.Audio){let te;for(const ve of this.engine.pcManager.publisher.getTransceivers())if(ve.sender===e.sender){te=ve;break}te&&this.engine.pcManager.publisher.setTrackCodecBitrate({transceiver:te,codec:"opus",maxbr:!((O=y[0])===null||O===void 0)&&O.maxBitrate?y[0].maxBitrate/1e3:0})}else if(e.codec&&Qc(e.codec)){const te=Ze(e.codec)?(Y=(F=y[0])===null||F===void 0?void 0:F.maxBitrate)!==null&&Y!==void 0?Y:0:y.reduce((ve,$e)=>{var gt;return ve+((gt=$e.maxBitrate)!==null&>!==void 0?gt:0)},0);te>0&&this.engine.pcManager.publisher.setTrackCodecBitrate({cid:v.cid,codec:e.codec,maxbr:te/1e3,isScreenShare:e.source===C.Source.ScreenShare})}}yield this.engine.negotiate()});let I;const A=new Promise((D,O)=>m(this,void 0,void 0,function*(){var F;try{I=yield this.engine.addTrack(v),D(I)}catch(Y){if(e.sender&&(!((F=this.engine.pcManager)===null||F===void 0)&&F.publisher)){try{this.engine.pcManager.publisher.removeTrack(e.sender)}catch(te){this.log.error(te)}yield this.engine.negotiate().catch(te=>
39{this.log.error("failed to negotiate after removing track due to failed add track request",Object.assign(Object.assign({},V(e)),{error:te}))})}O(Y)}}));if(this.enabledPublishVideoCodecs.length>0&&N.length===0)I=(yield Promise.all([A,E()]))[0];else{I=yield A;let D;if(I.codecs.forEach(O=>{D===void 0&&(D=O.mimeType)}),D&&e.kind===C.Kind.Video){const O=Cn(D);O!==g&&(this.log.debug("falling back to server selected codec",Object.assign(Object.assign({},V(e)),{codec:O})),t.videoCodec=O,y=vi(e.source===C.Source.ScreenShare,v.width,v.height,t))}yield E()}const B=new zs(e.kind,I,e,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});if(B.on(P.CpuConstrained,D=>this.onTrackCpuConstrained(D,B)),B.options=t,e.sid=I.sid,Qe(e)&&(e.publishOptions=t,v.width&&v.height&&(e.lastEncodedDimensions={width:v.width,height:v.height})),this.log.debug("publishing ".concat(e.kind," with encodings"),{encodings:y,trackInfo:I}),Qe(e)?e.startMonitor(this.engine.client):st(e)&&e.startMonitor(),this.addTrackPublication(B),this.emit(M.LocalTrackPublished,B),st(e)&&I.audioFeatures.includes(me.TF_PRECONNECT_BUFFER)){const D=e.getPreConnectBuffer(),O=e.getPreConnectBufferMimeType();this.on(M.LocalTrackSubscribed,F=>{if(F.trackSid===I.sid){if(!e.hasPreConnectBuffer){this.log.warn("subscribe event came to late, buffer already closed");return}this.log.debug("finished recording preconnect buffer",V(e)),e.stopPreConnectBuffer()}}),D&&new Promise((Y,te)=>m(this,void 0,void 0,function*(){var ve,$e,gt,pe,It,Wi;try{this.log.debug("waiting for agent",V(e));const Gi=setTimeout(()=>{te(new Error("agent not active within 10 seconds"))},1e4),xd=yield this.waitUntilActiveAgentPresent();clearTimeout(Gi),this.log.debug("sending preconnect buffer",V(e));const Lr=yield this.streamBytes({name:"preconnect-buffer",mimeType:O,topic:"lk.agent.pre-connect-audio-buffer",destinationIdentities:[xd.identity],attributes:{trackId:B.trackSid,sampleRate:String((It=S.sampleRate)!==null&&It!==void 0?It:"48000"),channels:String((Wi=S.channelCount)!==null&&Wi!==void 0?Wi:"1")}});try{for(var ji=!0,Hi=xe(D),Ki;Ki=yield Hi.next(),ve=Ki.done,!ve;ji=!0){pe=Ki.value,ji=!1;const zi=pe;yield Lr.write(zi)}}catch(zi){$e={error:zi}}finally{try{!ji&&!ve&&(gt=Hi.return)&&(yield gt.call(Hi))}finally{if($e)throw $e.error}}yield Lr.close(),Y()}catch(Gi){te(Gi)}})).then(()=>{this.log.debug("preconnect buffer sent successfully",V(e))}).catch(Y=>{this.log.error("error sending preconnect buffer",Object.assign(Object.assign({},V(e)),{error:Y}))})}return B})}canPublishFrameMetadata(){var e;return!!(this.roomOptions.e2ee||this.roomOptions.encryption||Un((e=this.roomOptions.frameMetadata)!==null&&e!==void 0?e:this.roomOptions.packetTrailer))}normalizeRequestedFrameMetadataOptions(e,t){var n;const s=(n=t.frameMetadata)!==null&&n!==void 0?n:t.packetTrailer;if(e.kind!==C.Kind.Video||!mi(s))return t.frameMetadata=void 0,t.packetTrailer=void 0,[];if(!this.canPublishFrameMetadata())return this.log.warn("frame metadata transform not supported; not advertising features",Object.assign(Object.assign({},this.logContext),V(e))),t.frameMetadata=void 0,t.packetTrailer=void 0,[];const r=Gh(s),a=zh(r);return t.frameMetadata=a,t.packetTrailer=a,r}get isLocal(){return!0}publishAdditionalCodecForTrack(e,t,n){return m(this,void 0,void 0,function*(){var s;if(this.encryptionType!==G.NONE)return;let r;if(this.trackPublications.forEach(f=>{f.track&&f.track===e&&(r=f)}),!r)throw new lt("track is not published");if(!Qe(e))throw new lt("track is not a video track");const a=Object.assign(Object.assign({},(s=this.roomOptions)===null||s===void 0?void 0:s.publishDefaults),n),o=sd(e,t,a);if(!o){this.log.info("backup codec has been disabled, ignoring request to add additional codec for track",V(e));return}const d=e.addSimulcastTrack(t,o);if(!d)return;const c=this.normalizeRequestedFrameMetadataOptions(e,a),l=new An({cid:d.mediaStreamTrack.id,type:C.kindToProto(e.kind),muted:e.isMuted,source:C.sourceToProto(e.source),sid:e.sid,packetTrailerFeatures:c,simulcastCodecs:[{codec:a.videoCodec,cid:d.mediaStreamTrack.id}]});if(l.layers=Va(l.width,l.height,o),!this.engine||this.engine.isClosed)throw new X("cannot publish track when not connected");const u=()=>m(this,void 0,void 0,function*(){yield this.engine.createSimulcastSender(e,d,a,o),yield this.engine.negotiate()}),p=(yield Promise.all([this.engine.addTrack(l),u()]))[0];this.log.debug("published ".concat(t," for track ").concat(e.sid),{encodings:o,trackInfo:p})})}unpublishTrack(e,t){return m(this,void 0,void 0,function*(){var n,s;if(tn(e)){const l=this.pendingPublishPromises.get(e);l&&(this.log.debug("awaiting publish promise before attempting to unpublish",V(e)),yield l)}const r=this.getPublicationForTrack(e),a=r?V(r):void 0;if(this.log.info("unpublishing track",a),!r||!r.track){this.log.warn("track was not unpublished because no publication was found",a);return}e=r.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=(s=(n=this.roomOptions)===null||n===void 0?void 0:n.stopLocalTrackOnUnpublish)!==null&&s!==void 0?s:!0),t?e.stop():e.stopMonitor();let o=!1;const d=e.sender;if(e.sender=void 0,this.engine.pcManager&&this.engine.pcManager.currentState<ne.FAILED&&d)try{for(const l of this.engine.pcManager.publisher.getTransceivers())l.sender===d&&(l.direction="inactive",o=!0);try{o=this.engine.removeTrack(d)}catch(l){this.log.warn(l),o=!0}
39if(Qe(e)){for(const l of e.simulcastCodecs){var c=L(l,2);const u=c[1];if(u.sender){try{o=this.engine.removeTrack(u.sender)}catch(h){this.log.warn(h),o=!0}u.sender=void 0}}e.simulcastCodecs.clear()}}catch(l){this.log.warn("failed to unpublish track",Object.assign(Object.assign({},a),{error:l}))}switch(this.trackPublications.delete(r.trackSid),r.kind){case C.Kind.Audio:this.audioTrackPublications.delete(r.trackSid);break;case C.Kind.Video:this.videoTrackPublications.delete(r.trackSid);break}return this.emit(M.LocalTrackUnpublished,r),r.setTrack(void 0),o&&(yield this.engine.negotiate()),r})}unpublishTracks(e){return m(this,void 0,void 0,function*(){return(yield Promise.all(e.map(n=>this.unpublishTrack(n)))).filter(n=>!!n)})}republishAllTracks(e){return m(this,arguments,void 0,function(t){var n=this;let s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return(function*(){n.republishPromise&&(yield n.republishPromise),n.republishPromise=new _e((r,a)=>m(n,void 0,void 0,function*(){try{const o=[];this.trackPublications.forEach(d=>{d.track&&(t&&(d.options=Object.assign(Object.assign({},d.options),t)),o.push(d))}),yield Promise.all(o.map(d=>m(this,void 0,void 0,function*(){const c=d.track;yield this.unpublishTrack(c,!1),s&&!c.isMuted&&c.source!==C.Source.ScreenShare&&c.source!==C.Source.ScreenShareAudio&&(st(c)||Qe(c))&&!c.isUserProvided&&(this.log.debug("restarting existing track",{track:d.trackSid}),yield c.restartTrack()),yield this.publishOrRepublishTrack(c,d.options,!0)}))),r()}catch(o){o instanceof Error?a(o):a(new Error(String(o)))}finally{this.republishPromise=void 0}})),yield n.republishPromise})()})}publishData(e){return m(this,arguments,void 0,function(t){var n=this;let s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return(function*(){const r=s.reliable?q.RELIABLE:q.LOSSY,a=s.reliable?Ct.RELIABLE:Ct.LOSSY,o=s.destinationIdentities,d=s.topic;let c=new tr({participantIdentity:n.identity,payload:t,destinationIdentities:o,topic:d});const l=new Ee({kind:a,value:{case:"user",value:c}});yield n.engine.sendDataPacket(l,r)})()})}publishDtmf(e,t){return m(this,void 0,void 0,function*(){const n=new Ee({kind:Ct.RELIABLE,value:{case:"sipDtmf",value:new Uo({code:e,digit:t})}});yield this.engine.sendDataPacket(n,q.RELIABLE)})}sendChatMessage(e,t){return m(this,void 0,void 0,function*(){const n={id:crypto.randomUUID(),message:e,timestamp:Date.now(),attachedFiles:t?.attachments},s=new Ee({value:{case:"chatMessage",value:new hi(Object.assign(Object.assign({},n),{timestamp:ee.parse(n.timestamp)}))}});return yield this.engine.sendDataPacket(s,q.RELIABLE),this.emit(M.ChatMessage,n),n})}editChatMessage(e,t){return m(this,void 0,void 0,function*(){const n=Object.assign(Object.assign({},t),{message:e,editTimestamp:Date.now()}),s=new Ee({value:{case:"chatMessage",value:new hi(Object.assign(Object.assign({},n),{timestamp:ee.parse(n.timestamp),editTimestamp:ee.parse(n.editTimestamp)}))}});return yield this.engine.sendDataPacket(s,q.RELIABLE),this.emit(M.ChatMessage,n),n})}sendText(e,t){return m(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.sendText(e,t)})}streamText(e){return m(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.streamText(e)})}sendFile(e,t){return m(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.sendFile(e,t)})}sendBytes(e,t){return m(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.sendBytes(e,t)})}streamBytes(e){return m(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.streamBytes(e)})}performRpc(e){return this.rpcClientManager.performRpc(e).then(t=>{let n=L(t,2);return n[0],n[1]})}
39registerRpcMethod(e,t){this.rpcServerManager.registerRpcMethod(e,t)}unregisterRpcMethod(e){this.rpcServerManager.unregisterRpcMethod(e)}setTrackSubscriptionPermissions(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:[];this.participantTrackPermissions=t,this.allParticipantsAllowedToSubscribe=e,this.engine.client.isDisconnected||this.updateTrackSubscriptionPermissions()}setEnabledPublishCodecs(e){this.enabledPublishVideoCodecs=e.filter(t=>t.mime.split("/")[0].toLowerCase()==="video")}updateInfo(e){return super.updateInfo(e)?(e.tracks.forEach(t=>{var n,s;const r=this.trackPublications.get(t.sid);if(r){const a=r.isMuted||((s=(n=r.track)===null||n===void 0?void 0:n.isUpstreamPaused)!==null&&s!==void 0?s:!1);a!==t.muted&&(this.log.debug("updating server mute state after reconcile",Object.assign(Object.assign({},V(r)),{mutedOnServer:a})),this.engine.client.sendMuteTrack(t.sid,a))}}),!0):!1}setActiveAgent(e){var t,n,s,r;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):(r=(s=this.activeAgentFuture)===null||s===void 0?void 0:s.reject)===null||r===void 0||r.call(s,new Error("Agent disconnected")),this.activeAgentFuture=void 0}waitUntilActiveAgentPresent(){return this.firstActiveAgent?Promise.resolve(this.firstActiveAgent):(this.activeAgentFuture||(this.activeAgentFuture=new ye),this.activeAgentFuture.promise)}getPublicationForTrack(e){let t;return this.trackPublications.forEach(n=>{const s=n.track;s&&(e instanceof MediaStreamTrack?(st(s)||Qe(s))&&s.mediaStreamTrack===e&&(t=n):e===s&&(t=n))}),t}waitForPendingPublicationOfSource(e){return m(this,void 0,void 0,function*(){const n=Date.now();for(;Date.now()<n+1e4;){const s=Array.from(this.pendingPublishPromises.entries()).find(r=>L(r,1)[0].source===e);if(s)return s[1];yield Se(20)}})}publishDataTrack(e){return m(this,void 0,void 0,function*(){const t=new Bi(e,this.roomOutgoingDataTrackManager);return yield t.publish(),t})}}class ao extends DOMException{constructor(e,t){super(e,"AbortError"),this.reason=t}}class Pm extends Map{constructor(){super(...arguments),this.pending=new Map}set(e,t){var n,s;super.set(e,t);const r=(n=this.pending)===null||n===void 0?void 0:n.get(e);if(r){for(const a of r)a.isResolved||(s=a.resolve)===null||s===void 0||s.call(a,t);this.pending.delete(e)}return this}get[Symbol.toStringTag](){return"DeferrableMap"}getDeferred(e,t){return m(this,void 0,void 0,function*(){const n=this.get(e);if(typeof n<"u")return n;if(t?.aborted)throw new ao("The operation was aborted.",t.reason);const s=new ye(void 0,()=>{const a=this.pending.get(e);if(!a)return;const o=a.indexOf(s);o!==-1&&a.splice(o,1),a.length===0&&this.pending.delete(e)}),r=this.pending.get(e);if(r?r.push(s):this.pending.set(e,[s]),t){const a=()=>{var o;s.isResolved||(o=s.reject)===null||o===void 0||o.call(s,new ao("The operation was aborted.",t.reason))};t.addEventListener("abort",a,{once:!0}),s.promise.finally(()=>{t.removeEventListener("abort",a)})}return s.promise})}}class Im extends at{constructor(e,t,n,s){super(e,t.sid,t.name,s),this.track=void 0,this.allowed=!0,this.requestedDisabled=void 0,this.visible=!0,this.handleEnded=r=>{this.setTrack(void 0),this.emit(P.Ended,r)},this.handleVisibilityChange=r=>{this.log.debug("adaptivestream video visibility ".concat(this.trackSid,", visible=").concat(r),this.logContext),this.visible=r,this.emitTrackUpdate()},this.handleVideoDimensionsChange=r=>{this.log.debug("adaptivestream video dimensions ".concat(r.width,"x").concat(r.height),this.logContext),this.videoDimensionsAdaptiveStream=r,this.emitTrackUpdate()},this.subscribed=n,this.updateInfo(t)}setSubscribed(e){const t=this.subscriptionStatus,n=this.permissionStatus;this.subscribed=e,e&&(this.allowed=!0);const s=new Di({trackSids:[this.trackSid],subscribe:this.subscribed,participantTracks:[new Bo({participantSid:"",trackSids:[this.trackSid]})]});this.emit(P.UpdateSubscription,s),this.emitSubscriptionUpdateIfChanged(t),this.emitPermissionUpdateIfChanged(n)}get subscriptionStatus(){return this.subscribed===!1?at.SubscriptionStatus.Unsubscribed:super.isSubscribed?at.SubscriptionStatus.Subscribed:at.SubscriptionStatus.Desired}get permissionStatus(){return this.allowed?at.PermissionStatus.Allowed:at.PermissionStatus.NotAllowed}get isSubscribed(){return this.subscribed===!1?!1:super.isSubscribed}get isDesired(){return this.subscribed!==!1}get isEnabled(){return this.requestedDisabled!==void 0?!this.requestedDisabled:this.isAdaptiveStream?this.visible:!0}get isLocal(){return!1}setEnabled(e){!this.isManualOperationAllowed()||this.requestedDisabled===!e||(this.requestedDisabled=!e,this.emitTrackUpdate())}setVideoQuality(e){!this.isManualOperationAllowed()||this.requestedMaxQuality===e||(this.requestedMaxQuality=e,this.requestedVideoDimensions=void 0,this.emitTrackUpdate())}setVideoDimensions(e){var t,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||(ss(this.track)&&(this.requestedVideoDimensions=e),this.requestedMaxQuality=void 0,this.emitTrackUpdate()))}setVideoFPS(e){this.isManualOperationAllowed()&&ss(this.track)&&this.fps!==e&&(this.fps=e,this.emitTrackUpdate())}get videoQuality(){var e;return(e=this.requestedMaxQuality)!==null&&e!==void 0?e:Ae.HIGH}setTrack(e){const t=this.subscriptionStatus,n=this.permissionStatus,s=this.track;s!==e&&(s&&(s.off(P.VideoDimensionsChanged,this.handleVideoDimensionsChange),s.off(P.VisibilityChanged,this.handleVisibilityChange),s.off(P.Ended,this.handleEnded),s.detach(),s.stopMonitor(),this.emit
39(P.Unsubscribed,s)),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){const 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);const 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){const 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 ss(this.track)&&this.track.isAdaptiveStream}emitTrackUpdate(){const e=new Qo({trackSids:[this.trackSid],disabled:!this.isEnabled,fps:this.fps});if(this.kind===C.Kind.Video){let t=this.requestedVideoDimensions;if(this.videoDimensionsAdaptiveStream!==void 0)if(t)pa(this.videoDimensionsAdaptiveStream,t)&&(this.log.debug("using adaptive stream dimensions instead of requested",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),t=this.videoDimensionsAdaptiveStream);else if(this.requestedMaxQuality!==void 0&&this.trackInfo){const n=ph(this.trackInfo,this.requestedMaxQuality);n&&pa(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:Ae.HIGH})),e.quality=Ae.HIGH)}this.emit(P.UpdateSettings,e)}}class Ti extends wd{static fromParticipantInfo(e,t,n,s){return new Ti(e,t.sid,t.identity,t.name,t.metadata,t.attributes,n,t.kind,t.dataTracks.map(r=>{const a=fi.from(r);return new kd(a,s,{publisherIdentity:t.identity})}),t.clientProtocol,t.capabilities)}get logContext(){return Object.assign(Object.assign({},super.logContext),{remoteParticipantID:this.sid,remoteParticipant:this.identity})}constructor(e,t,n,s,r,a,o){let d=arguments.length>7&&arguments[7]!==void 0?arguments[7]:Mn.STANDARD,c=arguments.length>8&&arguments[8]!==void 0?arguments[8]:[],l=arguments.length>9&&arguments[9]!==void 0?arguments[9]:qc,u=arguments.length>10&&arguments[10]!==void 0?arguments[10]:[];super(t,n||"",s,r,a,o,d),this.signalClient=e,this.trackPublications=new Map,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.dataTracks=new Pm(c.map(h=>[h.info.name,h])),this.volumeMap=new Map,this.clientProtocol=l,this.capabilities=u}addTrackPublication(e){super.addTrackPublication(e),e.on(P.UpdateSettings,t=>{this.log.debug("send update settings",Object.assign(Object.assign(Object.assign({},this.logContext),V(e)),{settings:t})),this.signalClient.sendUpdateTrackSettings(t)}),e.on(P.UpdateSubscription,t=>{t.participantTracks.forEach(n=>{n.participantSid=this.sid}),this.signalClient.sendUpdateSubscription(t)}),e.on(P.SubscriptionPermissionChanged,t=>{this.emit(M.TrackSubscriptionPermissionChanged,e,t)}),e.on(P.SubscriptionStatusChanged,t=>{this.emit(M.TrackSubscriptionStatusChanged,e,t)}),e.on(P.Subscribed,t=>
39{this.emit(M.TrackSubscribed,t,e)}),e.on(P.Unsubscribed,t=>{this.emit(M.TrackUnsubscribed,t,e)}),e.on(P.SubscriptionFailed,t=>{this.emit(M.TrackSubscriptionFailed,e.trackSid,t)})}getTrackPublication(e){const t=super.getTrackPublication(e);if(t)return t}getTrackPublicationByName(e){const t=super.getTrackPublicationByName(e);if(t)return t}setVolume(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:C.Source.Microphone;this.volumeMap.set(t,e);const n=this.getTrackPublication(t);n&&n.track&&n.track.setVolume(e)}getVolume(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:C.Source.Microphone;const t=this.getTrackPublication(e);return t&&t.track?t.track.getVolume():this.volumeMap.get(e)}addSubscribedMediaTrack(e,t,n,s,r,a){let o=this.getTrackPublicationBySid(t);if(o||t.startsWith("TR")||this.trackPublications.forEach(l=>{!o&&e.kind===l.kind.toString()&&(o=l)}),!o){if(a===0){this.log.error("could not find published track",Object.assign(Object.assign({},this.logContext),{trackSid:t})),this.emit(M.TrackSubscriptionFailed,t);return}a===void 0&&(a=20),setTimeout(()=>{this.addSubscribedMediaTrack(e,t,n,s,r,a-1)},150);return}if(e.readyState==="ended"){this.log.error("unable to subscribe because MediaStreamTrack is ended. Do not call MediaStreamTrack.stop()",Object.assign(Object.assign({},this.logContext),V(o))),this.emit(M.TrackSubscriptionFailed,t);return}const d=e.kind==="video";let c;return d?c=new Sr(e,t,s,r):c=new Cm(e,t,s,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)&&Ws(c)&&tt(c)&&c.setVolume(this.volumeMap.get(o.source)),o}get hasMetadata(){return!!this.participantInfo}getTrackPublicationBySid(e){return this.trackPublications.get(e)}updateInfo(e){if(!super.updateInfo(e))return!1;const t=new Map,n=new Map;return e.tracks.forEach(s=>{var r,a;let o=this.getTrackPublicationBySid(s.sid);if(o)o.updateInfo(s);else{const d=C.kindFromProto(s.type);if(!d)return;o=new Im(d,s,(r=this.signalClient.connectOptions)===null||r===void 0?void 0:r.autoSubscribe,{loggerContextCb:()=>this.logContext,loggerName:(a=this.loggerOptions)===null||a===void 0?void 0:a.loggerName}),o.updateInfo(s),n.set(s.sid,o);const c=Array.from(this.trackPublications.values()).find(l=>l.source===o?.source);c&&o.source!==C.Source.Unknown&&this.log.debug("received a second track publication for ".concat(this.identity," with the same source: ").concat(o.source),Object.assign(Object.assign({},this.logContext),{oldTrack:V(c),newTrack:V(o)})),this.addTrackPublication(o)}t.set(s.sid,o)}),this.trackPublications.forEach(s=>{t.has(s.trackSid)||(this.log.trace("detected removed track on remote participant, unpublishing",Object.assign(Object.assign({},this.logContext),V(s))),this.unpublishTrack(s.trackSid,!0))}),n.forEach(s=>{this.emit(M.TrackPublished,s)}),!0}unpublishTrack(e,t){const n=this.trackPublications.get(e);if(!n)return;const s=n.track;switch(s&&(s.stop(),n.setTrack(void 0)),this.trackPublications.delete(e),n.kind){case C.Kind.Audio:this.audioTrackPublications.delete(e);break;case C.Kind.Video:this.videoTrackPublications.delete(e);break}t&&this.emit(M.TrackUnpublished,n)}setAudioOutput(e){return m(this,void 0,void 0,function*(){this.audioOutput=e;const t=[];this.audioTrackPublications.forEach(n=>{var s;tt(n.track)&&Ws(n.track)&&t.push(n.track.setSinkId((s=e.deviceId)!==null&&s!==void 0?s:"default"))}),yield Promise.all(t)})}addRemoteDataTrack(e){this.dataTracks.set(e.info.name,e)}removeRemoteDataTrack(e){for(const n of this.dataTracks.entries()){var t=L(n,2);const s=t[0],r=t[1];e===r.info.sid&&this.dataTracks.delete(s)}}emit(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),s=1;s<t;s++)n[s-1]=arguments[s];return this.log.trace("participant event",Object.assign(Object.assign({},this.logContext),{event:e,args:n})),super.emit(e,...n)}}var K;(function(i){i.Disconnected="disconnected",i.Connecting="connecting",i.Connected="connected",i.Reconnecting="reconnecting",i.SignalReconnecting="signalReconnecting"})(K||(K={}));const Mm=4*1e3;class hn extends De.EventEmitter{get hasE2EESetup(){return this.e2eeManager!==void 0}constructor(e){var t,n,s,r,a,o,d;if(super(),t=this,this.state=K.Disconnected,this.activeSpeakers=[],this.isE2EEEnabled=!1,this.audioEnabled=!0,this.e2eeStateMutex=new ge,this.isVideoPlaybackBlocked=!1,this.log=U,this.bufferedEvents=[],this.isResuming=!1,this.connect=(c,l,u)=>m(this,void 0,void 0,function*(){var h;if(!yh())throw Je()?Error("WebRTC isn't detected, have you called registerGlobals?"):Error("LiveKit doesn't seem to be supported on this browser. Try to update your browser and make sure no browser extensions are disabling webRTC.");const p=yield this.disconnectLock.lock();if(this.state===K.Connected)return this.log.info("already connected to room ".concat(this.name)),p(),Promise.resolve();if(this.connectFuture)return p(),this.connectFuture.promise;this.setAndEmitConnectionState(K.Connecting),((h=this.regionUrlProvider)===null||h===void 0?void 0:h.getServerUrl().toString())!==Yc(c)&&(this.regionUrl=void 0,this.regionUrlProvider=void 0),dn(new URL(c))&&(this.regionUrlProvider===void 0?this.regionUrlProvider=new H(c,l):this.regionUrlProvider.updateToken(l),this.regionUrlProvider.fetchRegionSettings().then(k=>{var T;(T=this.regionUrlProvider)===null||T===void 0||T.setServerReportedRegions(k)}).catch(k=>{this.log.warn("could not fetch region settings",{error:k})}));const f=(k,T,S)=>m(this,void 0,void 0,function*(){var N,v;this.abortController&&this.abortController.abort();const y=new AbortController;this.abortController=y,p?.();try{if(yield nn.getInstance().getBackOffPromise(c),y.signal.aborted)throw x.cancelled("Connection attempt aborted");yield this.attemptConnection(S??c,l,u,y),this.abortController=void 0,k()}
39catch(E){if(this.regionUrlProvider&&E instanceof x&&E.reason!==Q.Cancelled&&E.reason!==Q.NotAllowed){let I=null;try{this.log.debug("Fetching next region"),I=yield this.regionUrlProvider.getNextBestRegionUrl((N=this.abortController)===null||N===void 0?void 0:N.signal)}catch(A){if(A instanceof x&&(A.status===401||A.reason===Q.Cancelled)){this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),T(A);return}}[Q.InternalError,Q.ServerUnreachable,Q.Timeout].includes(E.reason)&&(this.log.debug("Adding failed connection attempt to back off"),nn.getInstance().addFailedConnectionAttempt(c)),I&&!(!((v=this.abortController)===null||v===void 0)&&v.signal.aborted)?(this.log.info("Initial connection failed with ConnectionError: ".concat(E.message,". Retrying with another region: ").concat(I)),this.recreateEngine(!0),yield f(k,T,I)):(this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,ya(E)),T(E))}else{let I=Ke.UNKNOWN_REASON;E instanceof x&&(I=ya(E)),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,I),T(E)}}}),g=this.regionUrl;return this.regionUrl=void 0,this.connectFuture=new ye((k,T)=>{f(k,T,g)},()=>{this.clearConnectionFutures()}),this.connectFuture.promise}),this.connectSignal=(c,l,u,h,p,f)=>m(this,void 0,void 0,function*(){const g=yield u.join(c,l,{autoSubscribe:h.autoSubscribe,adaptiveStream:typeof p.adaptiveStream=="object"?!0:p.adaptiveStream,clientInfoCapabilities:this.getClientInfoCapabilities(p),maxRetries:h.maxRetries,e2eeEnabled:!!this.e2eeManager,websocketTimeout:h.websocketTimeout},f.signal,!p.singlePeerConnection),k=g.joinResponse,T=g.serverInfo;if(this.serverInfo=T,!T.version)throw new th("unknown server version");return T.version==="0.15.1"&&this.options.dynacast&&(this.log.debug("disabling dynacast due to server version"),p.dynacast=!1),k}),this.applyJoinResponse=c=>{const l=c.participant;if(this.localParticipant.sid=l.sid,this.localParticipant.identity=l.identity,this.localParticipant.setEnabledPublishCodecs(c.enabledPublishCodecs),this.e2eeManager)try{this.e2eeManager.setSifTrailer(c.sifTrailer)}catch(u){this.log.error(u instanceof Error?u.message:"Could not set SifTrailer",{error:u})}this.handleParticipantUpdates([l,...c.otherParticipants]),c.room&&this.handleRoomUpdate(c.room)},this.attemptConnection=(c,l,u,h)=>m(this,void 0,void 0,function*(){var p,f;this.state===K.Reconnecting||this.isResuming||!((p=this.engine)===null||p===void 0)&&p.pendingReconnect?(this.log.info("Reconnection attempt replaced by new connection attempt"),this.recreateEngine(!0)):this.maybeCreateEngine(),!((f=this.regionUrlProvider)===null||f===void 0)&&f.isCloud()&&this.engine.setRegionStrategy(this.createRegionStrategy()),this.acquireAudioContext(),this.connOptions=Object.assign(Object.assign({},Rr),u),this.connOptions.rtcConfig&&(this.engine.rtcConfig=this.connOptions.rtcConfig),this.connOptions.peerConnectionTimeout&&(this.engine.peerConnectionTimeout=this.connOptions.peerConnectionTimeout);try{const g=yield this.connectSignal(c,l,this.engine,this.connOptions,this.options,h);this.applyJoinResponse(g),this.setupLocalParticipantEvents(),this.emit(_.SignalConnected)}catch(g){yield this.engine.close(),this.recreateEngine();const k=h.signal.aborted?x.cancelled("Signal connection aborted"):x.serverUnreachable("could not establish signal connection");throw g instanceof Error&&(k.message="".concat(k.message,": ").concat(g.message)),g instanceof x&&(k.reason=g.reason,k.status=g.status),this.log.debug("error trying to establish signal connection",{error:g}),k}if(h.signal.aborted)throw yield this.engine.close(),this.recreateEngine(),x.cancelled("Connection attempt aborted");try{yield this.engine.waitForPCInitialConnection(this.connOptions.peerConnectionTimeout,h)}catch(g){throw yield this.engine.close(),this.recreateEngine(),g}Me()&&this.options.disconnectOnPageLeave&&(window.addEventListener("pagehide",this.onPageLeave),window.addEventListener("beforeunload",this.onPageLeave)),Me()&&window.addEventListener("freeze",this.onPageLeave),this.setAndEmitConnectionState(K.Connected),this.emit(_.Connected),nn.getInstance().resetFailedConnectionAttempts(c),this.registerConnectionReconcile(),this.regionUrlProvider&&this.regionUrlProvider.notifyConnected()}),this.disconnect=function(){for(var c=arguments.length,l=new Array(c),u=0;u<c;u++)l[u]=arguments[u];return m(t,[...l],void 0,function(){var h=this;let p=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return(function*(){var f,g,k;const T=yield h.disconnectLock.lock();try{if(h.state===K.Disconnected){h.log.debug("already disconnected");return}if(h.log.info("disconnect from room"),h.state===K.Connecting||h.state===K.Reconnecting||h.isResuming){const S="Abort connection attempt due to user initiated disconnect";h.log.warn(S),(f=h.abortController)===null||f===void 0||f.abort(S),(k=(g=h.connectFuture)===null||g===void 0?void 0:g.reject)===null||k===void 0||k.call(g,x.cancelled("Client initiated disconnect")),h.connectFuture=void 0}h.engine&&(h.engine.client.isDisconnected||(yield h.engine.client.sendLeave()),yield h.engine.close()),h.handleDisconnect(p,Ke.CLIENT_INITIATED),h.engine=void 0}finally{T()}})()})},this.onPageLeave=()=>m(this,void 0,void 0,function*(){this.log.info("Page leave detected, disconnecting"),yield this.disconnect()}),this.startAudio=()=>m(this,void 0,void 0,function*(){const c=[],l=we();if(l&&l.os==="iOS"){const u="livekit-dummy-audio-el";let h=document.getElementById(u);if(!h){h=document.createElement("audio"),h.id=u,h.autoplay=!0,h.hidden=!0;const p=is();p.enabled=!0;const f=new MediaStream([p]);h.srcObject=f,document.addEventListener("visibilitychange",()=>{h&&(h.srcObject=document.hidden?null:f,document.hidden||(this.log.debug("page visible again, triggering startAudio to resume playback and update playback status"),this.startAudio()))}),document.body.append(h),this.once(_.Disconnected,()=>{h?.remove(),h=null})}c.push(h)}
39this.remoteParticipants.forEach(u=>{u.audioTrackPublications.forEach(h=>{h.track&&h.track.attachedElements.forEach(p=>{c.push(p)})})});try{yield Promise.all([this.acquireAudioContext(),...c.map(u=>(this.options.webAudioMix||(u.muted=!1),u.play()))]),this.handleAudioPlaybackStarted()}catch(u){throw this.handleAudioPlaybackFailed(u),u}}),this.startVideo=()=>m(this,void 0,void 0,function*(){const c=[];for(const l of this.remoteParticipants.values())l.videoTrackPublications.forEach(u=>{var h;(h=u.track)===null||h===void 0||h.attachedElements.forEach(p=>{c.includes(p)||c.push(p)})});yield Promise.all(c.map(l=>l.play())).then(()=>{this.handleVideoPlaybackStarted()}).catch(l=>{l.name==="NotAllowedError"?this.handleVideoPlaybackFailed():this.log.warn("Resuming video playback failed, make sure you call `startVideo` directly in a user gesture handler")})}),this.handleRestarting=()=>{this.clearConnectionReconcile(),this.isResuming=!1;for(const c of this.remoteParticipants.values())this.handleParticipantDisconnected(c.identity,c);this.setAndEmitConnectionState(K.Reconnecting)&&this.emit(_.Reconnecting)},this.handleRestarted=()=>{this.outgoingDataTrackManager.sfuWillRepublishTracks(),this.incomingDataTrackManager.resendSubscriptionUpdates()},this.handleSignalRestarted=c=>m(this,void 0,void 0,function*(){this.log.debug("signal reconnected to server, region ".concat(c.serverRegion),{region:c.serverRegion}),this.bufferedEvents=[],this.applyJoinResponse(c);try{yield this.localParticipant.republishAllTracks(void 0,!0)}catch(l){this.log.error("error trying to re-publish tracks after reconnection",{error:l})}try{yield this.engine.waitForRestarted(),this.log.debug("fully reconnected to server",{region:c.serverRegion})}catch{return}this.setAndEmitConnectionState(K.Connected),this.emit(_.Reconnected),this.registerConnectionReconcile(),this.emitBufferedEvents()}),this.handleParticipantUpdates=c=>{var l;for(const h of c){if(h.identity===this.localParticipant.identity){this.localParticipant.updateInfo(h);continue}h.identity===""&&(h.identity=(l=this.sidToIdentity.get(h.sid))!==null&&l!==void 0?l:"");let p=this.remoteParticipants.get(h.identity);h.state===Qt.DISCONNECTED?this.handleParticipantDisconnected(h.identity,p):this.getOrCreateParticipant(h.identity,h)}const u=new Map(c.filter(h=>h.identity!==this.localParticipant.identity).map(h=>[h.identity,h.dataTracks.map(p=>fi.from(p))]));this.incomingDataTrackManager.receiveSfuPublicationUpdates(u)},this.handleActiveSpeakersUpdate=c=>{const l=[],u={};
39c.forEach(h=>{if(u[h.sid]=!0,h.sid===this.localParticipant.sid)this.localParticipant.audioLevel=h.level,this.localParticipant.setIsSpeaking(!0),l.push(this.localParticipant);else{const p=this.getRemoteParticipantBySid(h.sid);p&&(p.audioLevel=h.level,p.setIsSpeaking(!0),l.push(p))}}),u[this.localParticipant.sid]||(this.localParticipant.audioLevel=0,this.localParticipant.setIsSpeaking(!1)),this.remoteParticipants.forEach(h=>{u[h.sid]||(h.audioLevel=0,h.setIsSpeaking(!1))}),this.activeSpeakers=l,this.emitWhenConnected(_.ActiveSpeakersChanged,l)},this.handleSpeakersChanged=c=>{const l=new Map;this.activeSpeakers.forEach(h=>{const p=this.remoteParticipants.get(h.identity);p&&p.sid!==h.sid||l.set(h.sid,h)}),c.forEach(h=>{let p=this.getRemoteParticipantBySid(h.sid);h.sid===this.localParticipant.sid&&(p=this.localParticipant),p&&(p.audioLevel=h.level,p.setIsSpeaking(h.active),h.active?l.set(h.sid,p):l.delete(h.sid))});const u=Array.from(l.values());u.sort((h,p)=>p.audioLevel-h.audioLevel),this.activeSpeakers=u,this.emitWhenConnected(_.ActiveSpeakersChanged,u)},this.handleStreamStateUpdate=c=>{c.streamStates.forEach(l=>{const u=this.getRemoteParticipantBySid(l.participantSid);if(!u)return;const h=u.getTrackPublicationBySid(l.trackSid);if(!h||!h.track)return;const p=C.streamStateFromProto(l.state);h.track.setStreamState(p),p!==h.track.streamState&&(u.emit(M.TrackStreamStateChanged,h,h.track.streamState),this.emitWhenConnected(_.TrackStreamStateChanged,h,h.track.streamState,u))})},this.handleSubscriptionPermissionUpdate=c=>{const l=this.getRemoteParticipantBySid(c.participantSid);if(!l)return;const u=l.getTrackPublicationBySid(c.trackSid);u&&u.setAllowed(c.allowed)},this.handleSubscriptionError=c=>{const l=Array.from(this.remoteParticipants.values()).find(h=>h.trackPublications.has(c.trackSid));if(!l)return;const u=l.getTrackPublicationBySid(c.trackSid);u&&u.setSubscriptionError(c.err)},this.handleDataPacket=(c,l)=>{const u=this.remoteParticipants.get(c.participantIdentity);if(c.value.case==="user")this.handleUserPacket(u,c.value.value,c.kind,l);else if(c.value.case==="transcription")this.handleTranscription(u,c.value.value);else if(c.value.case==="sipDtmf")this.handleSipDtmf(u,c.value.value);else if(c.value.case==="chatMessage")this.handleChatMessage(u,c.value.value);else if(c.value.case==="metrics")this.handleMetrics(c.value.value,u);else if(c.value.case==="streamHeader"||c.value.case==="streamChunk"||c.value.case==="streamTrailer")this.handleDataStream(c,l);else if(c.value.case==="rpcRequest"){const h=c.value.value;this.rpcServerManager.handleIncomingRpcRequest(c.participantIdentity,h)}else if(c.value.case==="rpcResponse"){const h=c.value.value;switch(h.value.case){case"payload":this.rpcClientManager.handleIncomingRpcResponseSuccess(h.requestId,h.value.value);break;case"error":this.rpcClientManager.handleIncomingRpcResponseFailure(h.requestId,z.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(_.DataReceived,l.payload,c,u,l.topic,h),c?.emit(M.DataReceived,l.payload,u,h)},this.handleSipDtmf=(c,l)=>{this.emit(_.SipDTMFReceived,l,c),c?.emit(M.SipDTMFReceived,l)},this.handleTranscription=(c,l)=>{const u=l.transcribedParticipantIdentity===this.localParticipant.identity?this.localParticipant:this.getParticipantByIdentity(l.transcribedParticipantIdentity),h=u?.trackPublications.get(l.trackId),p=Ph(l,this.transcriptionReceivedTimes);h?.emit(P.TranscriptionReceived,p),u?.emit(M.TranscriptionReceived,p,h),this.emit(_.TranscriptionReceived,p,u,h)},this.handleChatMessage=(c,l)=>{const u=Ih(l);this.emit(_.ChatMessage,u,c)},this.handleMetrics=(c,l)=>{this.emit(_.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(_.AudioPlaybackStatusChanged,!0))},this.handleAudioPlaybackFailed=c=>{this.log.warn("could not playback audio",{error:c}
39),this.canPlaybackAudio&&(this.audioEnabled=!1,this.emit(_.AudioPlaybackStatusChanged,!1))},this.handleVideoPlaybackStarted=()=>{this.isVideoPlaybackBlocked&&(this.isVideoPlaybackBlocked=!1,this.emit(_.VideoPlaybackStatusChanged,!0))},this.handleVideoPlaybackFailed=()=>{this.isVideoPlaybackBlocked||(this.isVideoPlaybackBlocked=!0,this.emit(_.VideoPlaybackStatusChanged,!1))},this.handleDeviceChange=()=>m(this,void 0,void 0,function*(){var c;((c=we())===null||c===void 0?void 0:c.os)!=="iOS"&&(yield this.selectDefaultDevices()),this.emit(_.MediaDevicesChanged)}),this.handleRoomUpdate=c=>{const l=this.roomInfo;this.roomInfo=c,l&&l.metadata!==c.metadata&&this.emitWhenConnected(_.RoomMetadataChanged,c.metadata),l?.activeRecording!==c.activeRecording&&this.emitWhenConnected(_.RecordingStatusChanged,c.activeRecording)},this.handleConnectionQualityUpdate=c=>{c.updates.forEach(l=>{if(l.participantSid===this.localParticipant.sid){this.localParticipant.setConnectionQuality(l.quality);return}const u=this.getRemoteParticipantBySid(l.participantSid);u&&u.setConnectionQuality(l.quality)})},this.getRemoteParticipantClientProtocol=c=>{var l,u;return(u=(l=this.remoteParticipants.get(c))===null||l===void 0?void 0:l.clientProtocol)!==null&&u!==void 0?u:qc},this.getRemoteParticipantCapabilities=c=>{var l,u;return(u=(l=this.remoteParticipants.get(c))===null||l===void 0?void 0:l.capabilities)!==null&&u!==void 0?u:[]},this.getAllRemoteParticipantIdentities=()=>Array.from(this.remoteParticipants.keys()),this.onLocalParticipantMetadataChanged=c=>{this.emit(_.ParticipantMetadataChanged,c,this.localParticipant)},this.onLocalParticipantNameChanged=c=>{this.emit(_.ParticipantNameChanged,c,this.localParticipant)},this.onLocalAttributesChanged=c=>{this.emit(_.ParticipantAttributesChanged,c,this.localParticipant)},this.onLocalTrackMuted=c=>{this.emit(_.TrackMuted,c,this.localParticipant)},this.onLocalTrackUnmuted=c=>{this.emit(_.TrackUnmuted,c,this.localParticipant)},this.onTrackProcessorUpdate=c=>{var l;(l=c?.onPublish)===null||l===void 0||l.call(c,this)},this.onLocalTrackPublished=c=>m(this,void 0,void 0,function*(){var l,u,h,p,f,g;(l=c.track)===null||l===void 0||l.on(P.TrackProcessorUpdate,this.onTrackProcessorUpdate),(u=c.track)===null||u===void 0||u.on(P.Restarted,this.onLocalTrackRestarted),(f=(p=(h=c.track)===null||h===void 0?void 0:h.getProcessor())===null||p===void 0?void 0:p.onPublish)===null||f===void 0||f.call(p,this),this.emit(_.LocalTrackPublished,c,this.localParticipant),st(c.track)&&(yield c.track.checkForSilence())&&this.emit(_.LocalAudioSilenceDetected,c);const k=yield(g=c.track)===null||g===void 0?void 0:g.getDeviceId(!1),T=Us(c.source);T&&k&&k!==this.localParticipant.activeDeviceMap.get(T)&&(this.localParticipant.activeDeviceMap.set(T,k),this.emit(_.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(_.LocalTrackUnpublished,c,this.localParticipant)},this.onLocalTrackRestarted=c=>m(this,void 0,void 0,function*(){const l=yield c.getDeviceId(!1),u=Us(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(_.ActiveDeviceChanged,u,l))}),this.onLocalConnectionQualityChanged=c=>{this.emit(_.ConnectionQualityChanged,c,this.localParticipant)},this.onMediaDevicesError=(c,l)=>{this.emit(_.MediaDevicesError,c,l)},this.onLocalParticipantPermissionsChanged=c=>{this.emit(_.ParticipantPermissionsChanged,c,this.localParticipant)},this.onLocalChatMessageSent=c=>{this.emit(_.ChatMessage,c,this.localParticipant)},this.setMaxListeners(100),this.remoteParticipants=new Map,this.sidToIdentity=new Map,this.options=Object.assign(Object.assign({},Tp),e),this.log=ke((n=this.options.loggerName)!==null&&n!==void 0?n:ce.Room,()=>this.logContext),this.transcriptionReceivedTimes=new Map,this.options.audioCaptureDefaults=Object.assign(Object.assign({},ed),e?.audioCaptureDefaults),this.options.videoCaptureDefaults=Object.assign(Object.assign({},td),e?.videoCaptureDefaults),this.options.publishDefaults=Object.assign(Object.assign({},kp),e?.publishDefaults),this.maybeCreateEngine(),this.incomingDataStreamManager=new tm,this.outgoingDataStreamManager=new dm(this.engine,this.log,this.getRemoteParticipantClientProtocol,this.getRemoteParticipantCapabilities,this.getAllRemoteParticipantIdentities),this.incomingDataTrackManager=new bm({e2eeManager:this.e2eeManager}),this.incomingDataTrackManager.on("sfuUpdateSubscription",c=>{this.engine.client.sendUpdateDataSubscription(c.sid,c.subscribe)}).on("trackPublished",c=>{var l;c.track.publisherIdentity!==this.localParticipant.identity&&(this.emit
39(_.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(_.DataTrackUnpublished,c.sid),(l=this.remoteParticipants.get(c.publisherIdentity))===null||l===void 0||l.removeRemoteDataTrack(c.sid))}),this.outgoingDataTrackManager=new Mr({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(_.LocalDataTrackPublished,c.track)}).on("trackUnpublished",c=>{this.emit(_.LocalDataTrackUnpublished,c.sid)}).on("packetAvailable",c=>{let l=c.handle,u=c.bytes;this.engine.sendDataTrackFrame(u).finally(()=>this.outgoingDataTrackManager.handlePacketSendComplete(l))}),this.registerRpcDataStreamHandler(),this.rpcClientManager=new Tm(this.log,this.outgoingDataStreamManager,this.getRemoteParticipantClientProtocol,()=>{var c,l;return(l=(c=this.engine.latestJoinResponse)===null||c===void 0?void 0:c.serverInfo)===null||l===void 0?void 0:l.version}),this.rpcClientManager.on("sendDataPacket",c=>{let l=c.packet;var u;(u=this.engine)===null||u===void 0||u.sendDataPacket(l,q.RELIABLE)}),this.rpcServerManager=new Sm(this.log,this.outgoingDataStreamManager,this.getRemoteParticipantClientProtocol),this.rpcServerManager.on("sendDataPacket",c=>{let l=c.packet;var u;(u=this.engine)===null||u===void 0||u.sendDataPacket(l,q.RELIABLE)}),this.disconnectLock=new ge,this.localParticipant=new Rm("","",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((s=this.e2eeManager)!==null&&s!==void 0?s:null),this.outgoingDataTrackManager.updateE2eeManager((r=this.e2eeManager)!==null&&r!==void 0?r:null),this.options.videoCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("videoinput",en(this.options.videoCaptureDefaults.deviceId)),this.options.audioCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("audioinput",en(this.options.audioCaptureDefaults.deviceId)),!((a=this.options.audioOutput)===null||a===void 0)&&a.deviceId&&this.switchActiveDevice("audiooutput",en(this.options.audioOutput.deviceId)).catch(c=>this.log.warn("Could not set audio output: ".concat(c.message))),Me()){const c=new AbortController;let l;if(hn.cleanupRegistry){const u=new WeakRef(this);l=()=>{const h=u.deref();h&&h.handleDeviceChange()},hn.cleanupRegistry.register(this,()=>{c.abort()})}else l=this.handleDeviceChange;(d=(o=navigator.mediaDevices)===null||o===void 0?void 0:o.addEventListener)===null||d===void 0||d.call(o,"devicechange",l,{signal:c.signal})}}registerTextStreamHandler(e,t){return this.incomingDataStreamManager.registerTextStreamHandler(e,t)}unregisterTextStreamHandler(e){return this.incomingDataStreamManager.unregisterTextStreamHandler(e)}registerByteStreamHandler(e,t){return this.incomingDataStreamManager.registerByteStreamHandler(e,t)}unregisterByteStreamHandler(e){return this.incomingDataStreamManager.unregisterByteStreamHandler(e)}
39registerRpcMethod(e,t){this.rpcServerManager.registerRpcMethod(e,t)}unregisterRpcMethod(e){this.rpcServerManager.unregisterRpcMethod(e)}setE2EEEnabled(e){return m(this,void 0,void 0,function*(){const t=yield this.e2eeStateMutex.lock();try{if(this.e2eeManager)this.isE2EEEnabled!==e&&(yield this.localParticipant.setE2EEEnabled(e),this.localParticipant.identity!==""&&this.e2eeManager.setParticipantCryptorEnabled(e,this.localParticipant.identity));else throw Error("e2ee not configured, please set e2ee settings within the room options")}finally{t()}})}setupE2EE(){var e,t;const n=!!this.options.encryption,s=this.options.encryption||this.options.e2ee;s&&("e2eeManager"in s?(this.e2eeManager=s.e2eeManager,this.e2eeManager.isDataChannelEncryptionEnabled=n):this.e2eeManager=new $h(s,n),this.e2eeManager.on(yt.ParticipantEncryptionStatusChanged,(r,a)=>{Dh(a)&&(this.isE2EEEnabled=r),this.emit(_.ParticipantEncryptionStatusChanged,r,a)}),this.e2eeManager.on(yt.EncryptionError,(r,a)=>{const o=a?this.getParticipantByIdentity(a):void 0;this.emit(_.EncryptionError,r,o)}),(e=this.e2eeManager)===null||e===void 0||e.setup(this),(t=this.e2eeManager)===null||t===void 0||t.setupEngine(this.engine))}setupFrameMetadata(){var e;const t=(e=this.options.frameMetadata)!==null&&e!==void 0?e:this.options.packetTrailer;this.frameMetadataManager=new Xh(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===K.Disconnected?_e.resolve(""):this.roomInfo&&this.roomInfo.sid!==""?_e.resolve(this.roomInfo.sid):new _e((e,t)=>{const n=s=>{s.sid!==""&&(this.engine.off(R.RoomUpdate,n),e(s.sid))};this.engine.on(R.RoomUpdate,n),this.once(_.Disconnected,()=>{this.engine.off(R.RoomUpdate,n),t(new X("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 Yp(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(K.SignalReconnecting)&&this.emit(_.SignalReconnecting)}).on(R.Resumed,()=>{this.registerConnectionReconcile(),this.isResuming=!1,this.log.debug("Resumed signal connection"),this.updateSubscriptions(),this.setAndEmitConnectionState(K.Connected)&&this.emit(_.Reconnected),this.emitBufferedEvents()}).on(R.SignalResumed,()=>{this.bufferedEvents=[],(this.state===K.Reconnecting||this.isResuming)&&this.sendSyncState()}).on(R.Restarting,this.handleRestarting).on(R.Restarted,this.handleRestarted).on(R.SignalRestarted,this.handleSignalRestarted).on(R.Offline,()=>
39{this.setAndEmitConnectionState(K.Reconnecting)&&this.emit(_.Reconnecting)}).on(R.DCBufferStatusChanged,(e,t)=>{this.emit(_.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(_.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!==G.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=>{const t=new Map(Object.entries(e.subHandles).map(n=>{let s=L(n,2),r=s[0],a=s[1];return[parseInt(r,10),a.trackSid]}));this.incomingDataTrackManager.receivedSfuSubscriberHandles(t)}).on(R.DataTrackPacketReceived,e=>{try{this.incomingDataTrackManager.packetReceived(e)}catch(t){throw t}}).on(R.Joined,e=>{const t=new Map(e.otherParticipants.map(n=>[n.identity,n.dataTracks.map(s=>fi.from(s))]));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:Gs})}),this.localParticipant&&this.localParticipant.setupEngine(this.engine),this.e2eeManager&&this.e2eeManager.setupEngine(this.engine),this.outgoingDataStreamManager&&this.outgoingDataStreamManager.setupEngine(this.engine))}createRegionStrategy(){return{getNextUrl:e=>m(this,void 0,void 0,function*(){return this.regionUrlProvider?this.regionUrlProvider.getNextBestRegionUrl(e):null}),resetAttempts:()=>{var e;return(e=this.regionUrlProvider)===null||e===void 0?void 0:e.resetAttempts()}}}static getLocalDevices(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return fe.getInstance().getDevices(e,t)}prepareConnection(e,t){return m(this,void 0,void 0,function*(){if(this.state===K.Disconnected){this.log.debug("prepareConnection to ".concat(e));try{if(dn(new URL(e))&&t){this.regionUrlProvider=new H(e,t);const n=yield this.regionUrlProvider.getNextBestRegionUrl();n&&this.state===K.Disconnected&&(this.regionUrl=n,yield fetch(Ln(n),{method:"HEAD"}),this.log.debug("prepared connection to ".concat(n)))}else yield fetch(Ln(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 m(this,void 0,void 0,function*(){let n=()=>m(this,void 0,void 0,function*(){}),s;switch(e){case"signal-reconnect":yield this.engine.client.handleOnClose("simulate disconnect");break;case"fail-on-v1-path":this.engine.failNextV1Path();break;case"speaker":s=new Ye({scenario:{case:"speakerUpdate",value:3}});break;case"node-failure":s=new Ye({scenario:{case:"nodeFailure",value:!0}});break;case"server-leave":s=new Ye({scenario:{case:"serverLeave",value:!0}});break;case"migration":s=new Ye({scenario:{case:"migration",value:!0}});break;case"resume-reconnect":this.engine.failNext(),yield this.engine.client.handleOnClose("simulate resume-disconnect");break;case"disconnect-signal-on-resume":n=()=>m(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),s=new Ye({scenario:{case:"disconnectSignalOnResume",value:!0}});break;case"disconnect-signal-on-resume-no-messages":n=()=>m(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),s=new Ye({scenario:{case:"disconnectSignalOnResumeNoMessages",value:!0}});break;case"full-reconnect":this.engine.fullReconnectOnNext=!0,yield this.engine.client.handleOnClose("simulate full-reconnect");break;case"force-tcp":case"force-tls":s=new Ye({scenario:{case:"switchCandidateProtocol",value:e==="force-tls"?2:1}}),n=()=>m(this,void 0,void 0,function*(){const r=this.engine.client.onLeave;r&&r(new Ai({reason:Ke.CLIENT_INITIATED,action:Yt.RECONNECT}))});break;case"subscriber-bandwidth":if(t===void 0||typeof t!="number")throw new Error("subscriber-bandwidth requires a number as argument");s=new Ye({scenario:{case:"subscriberBandwidth",value:ze(t)}});break;case"leave-full-reconnect":s=new Ye({scenario:{case:"leaveRequestFullReconnect",value:!0}})}s&&(yield this.engine.client.sendSimulateScenario(s),yield n())})}get canPlaybackAudio(){return this.audioEnabled}get canPlaybackVideo(){return!this.isVideoPlaybackBlocked}getActiveDevice(e){return this.localParticipant.activeDeviceMap.get(e)}switchActiveDevice(e,t){return m(this,arguments,void 0,function(n,s){var r=this;let a=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0;return(function*(){var o,d,c,l,u,h,p;let f=!0,g=!1;const k=a?{exact:s}:s;if(n==="audioinput"){g=r.localParticipant.audioTrackPublications.size===0;const T=(o=r.getActiveDevice(n))!==null&&o!==void 0?o:r.options.audioCaptureDefaults.deviceId;r.options.audioCaptureDefaults.deviceId=k;const S=Array.from(r.localParticipant.audioTrackPublications.values()).filter(v=>v.source===C.Source.Microphone);
39try{f=(yield Promise.all(S.map(v=>{var y;return(y=v.audioTrack)===null||y===void 0?void 0:y.setDeviceId(k)}))).every(v=>v===!0)}catch(v){throw r.options.audioCaptureDefaults.deviceId=T,v}const N=S.some(v=>{var y,E;return(E=(y=v.track)===null||y===void 0?void 0:y.isMuted)!==null&&E!==void 0?E:!1});f&&N&&(g=!0)}else if(n==="videoinput"){g=r.localParticipant.videoTrackPublications.size===0;const T=(d=r.getActiveDevice(n))!==null&&d!==void 0?d:r.options.videoCaptureDefaults.deviceId;r.options.videoCaptureDefaults.deviceId=k;const S=Array.from(r.localParticipant.videoTrackPublications.values()).filter(v=>v.source===C.Source.Camera);try{f=(yield Promise.all(S.map(v=>{var y;return(y=v.videoTrack)===null||y===void 0?void 0:y.setDeviceId(k)}))).every(v=>v===!0)}catch(v){throw r.options.videoCaptureDefaults.deviceId=T,v}const N=S.some(v=>{var y,E;return(E=(y=v.track)===null||y===void 0?void 0:y.isMuted)!==null&&E!==void 0?E:!1});f&&N&&(g=!0)}else if(n==="audiooutput"){if(g=!0,!qs()&&!r.options.webAudioMix||r.options.webAudioMix&&r.audioContext&&!("setSinkId"in r.audioContext))throw new Error("cannot switch audio output, the current browser does not support it");r.options.webAudioMix&&(s=(c=yield fe.getInstance().normalizeDeviceId("audiooutput",s))!==null&&c!==void 0?c:""),(l=(p=r.options).audioOutput)!==null&&l!==void 0||(p.audioOutput={});const T=(u=r.getActiveDevice(n))!==null&&u!==void 0?u:r.options.audioOutput.deviceId;r.options.audioOutput.deviceId=s;try{r.options.webAudioMix&&((h=r.audioContext)===null||h===void 0||h.setSinkId(s)),yield Promise.all(Array.from(r.remoteParticipants.values()).map(S=>S.setAudioOutput({deviceId:s})))}catch(S){throw r.options.audioOutput.deviceId=T,S}}return g&&(r.localParticipant.activeDeviceMap.set(n,s),r.emit(_.ActiveDeviceChanged,n,s)),f})()})}setupLocalParticipantEvents(){this.localParticipant.on(M.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).on(M.ParticipantNameChanged,this.onLocalParticipantNameChanged).on(M.AttributesChanged,this.onLocalAttributesChanged).on(M.TrackMuted,this.onLocalTrackMuted).on(M.TrackUnmuted,this.onLocalTrackUnmuted).on(M.LocalTrackPublished,this.onLocalTrackPublished).on(M.LocalTrackUnpublished,this.onLocalTrackUnpublished).on(M.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).on(M.MediaDevicesError,this.onMediaDevicesError).on(M.AudioStreamAcquired,this.startAudio).on(M.ChatMessage,this.onLocalChatMessageSent).on(M.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged)}recreateEngine(e){const t=this.engine;e&&t&&!t.client.isDisconnected?t.client.sendLeave().finally(()=>t.close()):t?.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===K.Connecting||this.state===K.Reconnecting){const u=()=>{this.log.debug("deferring on track for later",{mediaTrackId:e.id,mediaStreamId:t.id,tracksInStream:t.getTracks().map(p=>p.id)}),this.onTrackAdded(e,t,n),h()},h=()=>{this.off(_.Reconnected,u),this.off(_.Connected,u),this.off(_.Disconnected,h)};this.once(_.Reconnected,u),this.once(_.Connected,u),this.once(_.Disconnected,h);return}if(this.state===K.Disconnected){this.log.warn("skipping incoming track after Room disconnected");return}if(e.readyState==="ended"){this.log.debug("skipping incoming track as it already ended");return}const s=gh(t.id),r=s[0];let a=s[1],o=e.id;if(a&&a.startsWith("TR")&&(o=a),r===this.localParticipant.sid){this.log.warn("tried to create RemoteParticipant for local participant");return}const d=Array.from(this.remoteParticipants.values()).find(u=>u.sid===r);if(!d){r.startsWith("PA")&&this.log.error("Tried to add a track for a participant, that's not present. Sid: ".concat(r));return}if(!o.startsWith("TR")){const 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(r));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(r,", streamId: ").concat(a,", trackId: ").concat(o),{remoteParticipantID:r,streamId:a,trackId:o});let c;this.options.adaptiveStream&&(typeof this.options.adaptiveStream=="object"?c=this.options.adaptiveStream:c={});const l=d.addSubscribedMediaTrack(e,o,t,n,c);
39l?.isEncrypted&&!this.e2eeManager&&this.emit(_.EncryptionError,new Error("Encrypted ".concat(l.source," track received from participant ").concat(d.sid,", but room does not have encryption enabled!")))}handleLocalTrackSubscribed(e){const 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});const s=1e4;let r;const a=d=>{d.trackSid===e&&(o(),this.emitLocalTrackSubscribed(d))},o=()=>{clearTimeout(r),this.localParticipant.off(M.LocalTrackPublished,a),this.off(_.Disconnected,o)};this.localParticipant.on(M.LocalTrackPublished,a),this.once(_.Disconnected,o),r=setTimeout(()=>{o();const d=t();d?this.emitLocalTrackSubscribed(d):this.log.warn("could not find local track publication for LocalTrackSubscribed event after timeout",{subscribedSid:e})},s)}emitLocalTrackSubscribed(e){this.localParticipant.emit(M.LocalTrackSubscribed,e),this.emitWhenConnected(_.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,s;if(this.clearConnectionReconcile(),this.isResuming=!1,this.bufferedEvents=[],this.transcriptionReceivedTimes.clear(),this.incomingDataStreamManager.clearControllers(),this.incomingDataTrackManager.reset(),this.outgoingDataTrackManager.reset(),this.state!==K.Disconnected){this.regionUrl=void 0,this.regionUrlProvider&&this.regionUrlProvider.notifyDisconnected();
39try{this.remoteParticipants.forEach(r=>{r.trackPublications.forEach(a=>{r.unpublishTrack(a.trackSid)})}),this.localParticipant.trackPublications.forEach(r=>{var a,o,d;r.track&&this.localParticipant.unpublishTrack(r.track,e),e?((a=r.track)===null||a===void 0||a.detach(),(o=r.track)===null||o===void 0||o.stop()):(d=r.track)===null||d===void 0||d.stopMonitor()}),this.localParticipant.off(M.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).off(M.ParticipantNameChanged,this.onLocalParticipantNameChanged).off(M.AttributesChanged,this.onLocalAttributesChanged).off(M.TrackMuted,this.onLocalTrackMuted).off(M.TrackUnmuted,this.onLocalTrackUnmuted).off(M.LocalTrackPublished,this.onLocalTrackPublished).off(M.LocalTrackUnpublished,this.onLocalTrackUnpublished).off(M.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).off(M.MediaDevicesError,this.onMediaDevicesError).off(M.AudioStreamAcquired,this.startAudio).off(M.ChatMessage,this.onLocalChatMessageSent).off(M.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged),this.localParticipant.trackPublications.clear(),this.localParticipant.videoTrackPublications.clear(),this.localParticipant.audioTrackPublications.clear(),this.remoteParticipants.clear(),this.sidToIdentity.clear(),this.activeSpeakers=[],this.audioContext&&typeof this.options.webAudioMix=="boolean"&&(this.audioContext.close(),this.audioContext=void 0),Me()&&(window.removeEventListener("beforeunload",this.onPageLeave),window.removeEventListener("pagehide",this.onPageLeave),window.removeEventListener("freeze",this.onPageLeave),(s=(n=navigator.mediaDevices)===null||n===void 0?void 0:n.removeEventListener)===null||s===void 0||s.call(n,"devicechange",this.handleDeviceChange))}finally{this.setAndEmitConnectionState(K.Disconnected),this.emit(_.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(_.ParticipantDisconnected,t),t.setDisconnected(),this.rpcClientManager.handleParticipantDisconnected(t.identity))}selectDefaultDevices(){return m(this,void 0,void 0,function*(){var e,t,n;const s=fe.getInstance().previousDevices,r=yield fe.getInstance().getDevices(void 0,!1),a=we();if(a?.name==="Chrome"&&a.os!=="iOS")for(let d of r){const c=s.find(l=>l.deviceId===d.deviceId);c&&c.label!==""&&c.kind===d.kind&&c.label!==d.label&&this.getActiveDevice(d.kind)==="default"&&this.emit(_.ActiveDeviceChanged,d.kind,d.deviceId)}const o=["audiooutput","audioinput","videoinput"];for(let d of o){const c=oh(d),l=this.localParticipant.getTrackPublication(c);if(l&&(!((e=l.track)===null||e===void 0)&&e.isUserProvided))continue;const u=r.filter(p=>p.kind===d),h=this.getActiveDevice(d);if(h===((t=s.filter(p=>p.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"&&!Nn()||d==="videoinput"||u.length>0&&!u.find(p=>p.deviceId===this.getActiveDevice(d))&&(d!=="audiooutput"||!Nn())&&(yield this.switchActiveDevice(d,u[0].deviceId))}})}acquireAudioContext(){return m(this,void 0,void 0,function*(){var e,t;if(typeof this.options.webAudioMix!="boolean"&&this.options.webAudioMix.audioContext?this.audioContext=this.options.webAudioMix.audioContext:(!this.audioContext||this.audioContext.state==="closed")&&(this.audioContext=(e=Kc())!==null&&e!==void 0?e:void 0),this.options.webAudioMix&&this.remoteParticipants.forEac
39h(s=>s.setAudioContext(this.audioContext)),this.localParticipant.setAudioContext(this.audioContext),this.audioContext&&this.audioContext.state==="suspended")try{yield Promise.race([this.audioContext.resume(),Se(200)])}catch(s){this.log.warn("Could not resume audio context",{error:s})}const n=((t=this.audioContext)===null||t===void 0?void 0:t.state)==="running";n!==this.canPlaybackAudio&&(this.audioEnabled=n,this.emit(_.AudioPlaybackStatusChanged,n))})}createParticipant(e,t){var n;let s;return t?s=Ti.fromParticipantInfo(this.engine.client,t,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName},this.incomingDataTrackManager):s=new Ti(this.engine.client,"",e,void 0,void 0,void 0,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}),this.options.webAudioMix&&s.setAudioContext(this.audioContext),!((n=this.options.audioOutput)===null||n===void 0)&&n.deviceId&&s.setAudioOutput(this.options.audioOutput).catch(r=>this.log.warn("Could not set audio output: ".concat(r.message))),s}getOrCreateParticipant(e,t){if(this.remoteParticipants.has(e)){const s=this.remoteParticipants.get(e);return t&&s.updateInfo(t)&&this.sidToIdentity.set(t.sid,t.identity),s}const n=this.createParticipant(e,t);return this.remoteParticipants.set(e,n),this.sidToIdentity.set(t.sid,t.identity),this.emitWhenConnected(_.ParticipantConnected,n),n.on(M.TrackPublished,s=>{this.emitWhenConnected(_.TrackPublished,s,n)}).on(M.TrackSubscribed,(s,r)=>{s.kind===C.Kind.Audio?(s.on(P.AudioPlaybackStarted,this.handleAudioPlaybackStarted),s.on(P.AudioPlaybackFailed,this.handleAudioPlaybackFailed)):s.kind===C.Kind.Video&&(s.on(P.VideoPlaybackFailed,this.handleVideoPlaybackFailed),s.on(P.VideoPlaybackStarted,this.handleVideoPlaybackStarted)),this.emitWhenConnected(_.TrackSubscribed,s,r,n)}).on(M.TrackUnpublished,s=>{this.emit(_.TrackUnpublished,s,n)}).on(M.TrackUnsubscribed,(s,r)=>{this.emit(_.TrackUnsubscribed,s,r,n)}).on(M.TrackMuted,s=>{this.emitWhenConnected(_.TrackMuted,s,n)}).on(M.TrackUnmuted,s=>{this.emitWhenConnected(_.TrackUnmuted,s,n)}).on(M.ParticipantMetadataChanged,s=>{this.emitWhenConnected(_.ParticipantMetadataChanged,s,n)}).on(M.ParticipantNameChanged,s=>{this.emitWhenConnected(_.ParticipantNameChanged,s,n)}).on(M.AttributesChanged,s=>{this.emitWhenConnected(_.ParticipantAttributesChanged,s,n)}).on(M.ConnectionQualityChanged,s=>{this.emitWhenConnected(_.ConnectionQualityChanged,s,n)}).on(M.ParticipantPermissionsChanged,s=>{this.emitWhenConnected(_.ParticipantPermissionsChanged,s,n)}).on(M.TrackSubscriptionStatusChanged,(s,r)=>{this.emitWhenConnected(_.TrackSubscriptionStatusChanged,s,r,n)}).on(M.TrackSubscriptionFailed,(s,r)=>{this.emit(_.TrackSubscriptionFailed,s,n,r)}).on(M.TrackSubscriptionPermissionChanged,(s,r)=>{this.emitWhenConnected(_.TrackSubscriptionPermissionChanged,s,r,n)}).on(M.Active,()=>{this.emitWhenConnected(_.ParticipantActive,n),n.kind===Mn.AGENT&&this.localParticipant.setActiveAgent(n)}),t&&n.updateInfo(t),n}sendSyncState(){const e=Array.from(this.remoteParticipants.values()).reduce((s,r)=>(s.push(...r.getTrackPublications()),s),[]),t=this.localParticipant.getTrackPublications(),n=this.outgoingDataTrackManager.queryPublished();this.engine.sendSyncState(e,t,n)}updateSubscriptions(){for(const e of this.remoteParticipants.values())for(const t of e.videoTrackPublications.values())t.isSubscribed&&Mh(t)&&t.emitTrackUpdate()}getRemoteParticipantBySid(e){const t=this.sidToIdentity.get(e);if(t)return this.remoteParticipants.get(t)}getClientInfoCapabilities(e){var t;const n=[];return(Un((t=e.frameMetadata)!==null&&t!==void 0?t:e.packetTrailer)||this.e2eeManager)&&n.push(Dn.CAP_PACKET_TRAILER),Et()&&n.push(Dn.CAP_COMPRESSION_DEFLATE_RAW),n}registerRpcDataStreamHandler(){this.incomingDataStreamManager.registerTextStreamHandler(Sd,(e,t)=>m(this,[e,t],void 0,function(n,s){var r=this;let a=s.identity;return(function*(){var o;const d=(o=n.info.attributes)!==null&&o!==void 0?o:{};yield r.rpcServerManager.handleIncomingDataStream(n,a,d)})()})),this.incomingDataStreamManager.registerTextStreamHandler(Cd,(e,t)=>m(this,[e,t],void 0,function(n,s){var r=this;let a=s.identity;return(function*(){var o;const d=(o=n.info.attributes)!==null&&o!==void 0?o:{};yield r.rpcClientManager.handleIncomingDataStream(n,a,d)})()}))}registerConnectionReconcile(){this.clearConnectionReconcile();let e=0;this.connectionReconcileInterval=ae.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,Ke.STATE_MISMATCH))):e=0},Mm)}clearConnectionReconcile(){this.connectionReconcileInterval&&ae.clearInterval(this.connectionReconcileInterval)}setAndEmitConnectionState(e){return e===this.state?!1:(this.log.info("connection state changed: ".concat(this.state," -> ").concat(e)),this.state=e,this.incomingDataStreamManager.setConnected(e===K.Connected),this.emit
vendor: 11,112 bytes, line 39
39(_.ConnectionStateChanged,this.state),!0)}emitBufferedEvents(){this.bufferedEvents.forEach(e=>{let t=L(e,2),n=t[0],s=t[1];this.emit(n,...s)}),this.bufferedEvents=[]}emitWhenConnected(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),s=1;s<t;s++)n[s-1]=arguments[s];if(this.state===K.Reconnecting||this.isResuming||!this.engine||this.engine.pendingReconnect)this.bufferedEvents.push([e,n]);else if(this.state===K.Connected)return this.emit(e,...n);return!1}simulateParticipants(e){return m(this,void 0,void 0,function*(){var t,n,s,r;const a=Object.assign({audio:!0,video:!0,useRealTracks:!1},e.publish),o=Object.assign({count:9,audio:!1,video:!0,aspectRatios:[1.66,1.7,1.3]},e.participants);if(this.handleDisconnect(),this.roomInfo=new _i({sid:"RM_SIMULATED",name:"simulated-room",emptyTimeout:0,maxParticipants:0,creationTime:ee.parse(new Date().getTime()),metadata:"",numParticipants:1,numPublishers:1,turnPassword:"",enabledCodecs:[],activeRecording:!1}),this.localParticipant.updateInfo(new Vt({identity:"simulated-local",name:"local-name"})),this.setupLocalParticipantEvents(),this.emit(_.SignalConnected),this.emit(_.Connected),this.setAndEmitConnectionState(K.Connected),a.video){const d=new zs(C.Kind.Video,new zt({source:le.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:Ve.AUDIO,name:"video-dummy"}),new bi(a.useRealTracks&&(!((t=window.navigator.mediaDevices)===null||t===void 0)&&t.getUserMedia)?(yield window.navigator.mediaDevices.getUserMedia({video:!0})).getVideoTracks()[0]:ba(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(M.LocalTrackPublished,d)}if(a.audio){const d=new zs(C.Kind.Audio,new zt({source:le.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:Ve.AUDIO}),new gi(a.useRealTracks&&(!((s=navigator.mediaDevices)===null||s===void 0)&&s.getUserMedia)?(yield navigator.mediaDevices.getUserMedia({audio:!0})).getAudioTracks()[0]:is(),void 0,!1,this.audioContext,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(d),this.localParticipant.emit(M.LocalTrackPublished,d)}for(let d=0;d<o.count-1;d+=1){let c=new Vt({sid:Math.floor(Math.random()*1e4).toString(),identity:"simulated-".concat(d),state:Qt.ACTIVE,tracks:[],joinedAt:ee.parse(Date.now())});const l=this.getOrCreateParticipant(c.identity,c);if(o.video){const u=ba(160*((r=o.aspectRatios[d%o.aspectRatios.length])!==null&&r!==void 0?r:1),160,!1,!0),h=new zt({source:le.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:Ve.AUDIO});l.addSubscribedMediaTrack(u,h.sid,new MediaStream([u]),new RTCRtpReceiver),c.tracks=[...c.tracks,h]}if(o.audio){const u=is(),h=new zt({source:le.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:Ve.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),s=1;s<t;s++)n[s-1]=arguments[s];if(e!==_.ActiveSpeakersChanged&&e!==_.TranscriptionReceived){const r=Rd(n).filter(a=>a!==void 0);(e===_.TrackSubscribed||e===_.TrackUnsubscribed)&&this.log.trace("subscribe trace: ".concat(e),{event:e,args:r}),this.log.debug("room event ".concat(e),{event:e,args:r})}return super.emit(e,...n)}}hn.cleanupRegistry=typeof FinalizationRegistry<"u"&&typeof WeakRef<"u"&&new FinalizationRegistry(i=>{i()});function Rd(i){return i.map(e=>{if(e)return Array.isArray(e)?Rd(e):typeof e=="object"?"logContext"in e?e.logContext:void 0:e})}var qe;(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"})(qe||(qe={}));class Pt extends De.EventEmitter{constructor(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.status=qe.IDLE,this.logs=[],this.options={},this.url=e,this.token=t,this.name=this.constructor.name,this.room=new hn(n.roomOptions),this.connectOptions=n.connectOptions,this.options=n}run(e){return m(this,void 0,void 0,function*(){if(this.status!==qe.IDLE)throw Error("check is running already");this.setStatus(qe.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!==qe.SKIPPED&&this.setStatus(this.isSuccess()?qe.SUCCESS:qe.FAILED),e&&e(),this.getInfo()})}isSuccess(){return!this.logs.some(e=>e.level==="error")}connect(e){return m(this,void 0,void 0,function*(){return this.room.state===K.Connected?this.room:(e||(e=this.url),yield this.room.connect(e,this.token,this.connectOptions),this.room)})}disconnect(){return m(this,void 0,void 0,function*(){this.room&&this.room.state!==K.Disconnected&&(yield this.room.disconnect(),yield new Promise(e=>setTimeout(e,500)))})}skip(){this.setStatus(qe.SKIPPED)}switchProtocol(e){return m(this,void 0,void 0,function*(){let t=!1,n=!1;if(this.room.on(_.Reconnecting,()=>{t=!0}),this.room.once(_.Reconnected,()=>{n=!0}),this.room.simulateScenario("force-".concat(e)),yield new Promise(r=>setTimeout(r,1e3)),!t)return;const s=Date.now()+1e4;for(;Date.now()<s;){if(n)return;yield Se(100)}throw new Error("Could not reconnect using ".concat(e," protocol after 10 seconds"))})}appendMessage(e){this.logs.push({level:"info",message:e}),this.emit("update",this.getInfo())}appendWarning(e){this.logs.push({level:"warning",message:e}),this.emit("update",this.getInfo())}appendError(e){this.logs.push({level:"error",message:e}),this.emit("update",this.getInfo())}setStatus(e){this.status=e,this.emit("update",this.getInfo())}get engine(){var e;return(e=this.room)===null||e===void 0?void 0:e.engine}getInfo(){return{logs:this.logs,name:this.name,status:this.status,description:this.description}}}class Dm extends Pt{get description(){return"Cloud regions"}perform(){return m(this,void 0,void 0,function*(){const e=new H(this.url,this.token);if(!e.isCloud()){this.skip();return}const t=[],n=new Set;for(let r=0;r<3;r++){const a=yield e.getNextBestRegionUrl();if(!a)break;if(n.has(a))continue;n.add(a);const o=yield this.checkCloudRegion(a);this.appendMessage("".concat(o.region," RTT: ").concat(o.rtt,"ms, duration: ").concat(o.duration,"ms")),t.push(o)}t.sort((r,a)=>(r.duration-a.duration)*.5+(r.rtt-a.rtt)*.5);const s=t[0];this.bestStats=s,this.appendMessage("best Cloud region: ".concat(s.region))})}getInfo(){const e=super.getInfo();return e.data=this.bestStats,e}checkCloudRegion(e){return m(this,void 0,void 0,function*(){var t,n;yield this.connect(e),this.options.protocol==="tcp"&&(yield this.switchProtocol("tcp"));const s=(t=this.room.serverInfo)===null||t===void 0?void 0:t.region;if(!s)throw new Error("Region not found");const r=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 r.write(c);yield r.close();const u=Date.now(),h=yield(n=this.room.engine.pcManager)===null||n===void 0?void 0:n.publisher.getStats(),p={region:s,rtt:1e4,duration:u-l};return h?.forEach(f=>{f.type==="candidate-pair"&&f.nominated&&(p.rtt=f.currentRoundTripTime*1e3)}),yield this.disconnect(),p})}}const ys=1e4;class Am extends Pt{get description(){return"Connection via UDP vs TCP"}perform(){return m(this,void 0,void 0,function*(){const e=yield this.checkConnectionProtocol("udp"),t=yield this.checkConnectionProtocol("tcp");this.bestStats=e,e.qualityLimitationDurations.bandwidth-t.qualityLimitationDurations.bandwidth>.5||(e.packetsLost-t.packetsLost)/e.packetsSent>.01?(this.appendMessage("best connection quality via tcp"),this.bestStats=t):this.appendMessage("best connection quality via udp");const 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/(ys/1e3)*100).toFixed(2),"%")),n.qualityLimitationDurations.cpu>0&&this.appendWarning("cpu limited ".concat((n.qualityLimitationDurations.cpu/(ys/1e3)*100).toFixed(2),"%"))})}getInfo(){const e=super.getInfo();return e.data=this.bestStats,e}checkConnectionProtocol(e){return m(this,void 0,void 0,function*(){yield this.connect(),e==="tcp"?yield this.switchProtocol("tcp"):yield this.switchProtocol("udp");const t=document.createElement("canvas");t.width=1280,t.height=720;const n=t.getContext("2d");if(!n)throw new Error("Could not get canvas context");let s=0;const r=()=>{s=(s+1)%360,n.fillStyle="hsl(".concat(s,", 100%, 50%)"),n.fillRect(0,0,t.width,t.height),requestAnimationFrame(r)};r();const o=t.captureStream(30).getVideoTracks()[0],c=(yield this.room.localParticipant.publishTrack(o,{simulcast:!1,degradationPreference:"maintain-resolution",videoEncoding:{maxBitrate:2e6}})).track,l={protocol:e,packetsLost:0,packetsSent:0,qualityLimitationDurations:{},rttTotal:0,jitterTotal:0,bitrateTotal:0,count:0},u=setInterval(()=>m(this,void 0,void 0,function*(){const h=yield c.getRTCStatsReport();h?.forEach(p=>{p.type==="outbound-rtp"?(l.packetsSent=p.packetsSent,l.qualityLimitationDurations=p.qualityLimitationDurations,l.bitrateTotal+=p.targetBitrate,l.count++):p.type==="remote-inbound-rtp"&&(l.packetsLost=p.packetsLost,l.rttTotal+=p.roundTripTime,l.jitterTotal+=p.jitter)})}),1e3);return yield new Promise(h=>setTimeout(h,ys)),clearInterval(u),o.stop(),t.remove(),yield this.disconnect(),l})}}class Om extends Pt{get description(){return"Can publish audio"}perform(){return m(this,void 0,void 0,function*(){var e;const t=yield this.connect(),n=yield _d();if(yield Hc(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));const r=yield(e=n.sender)===null||e===void 0?void 0:e.getStats();if(!r)throw new Error("Could not get RTCStats");let a=0;if(r.forEach(o=>{o.type==="outbound-rtp"&&(o.kind==="audio"||!o.kind&&o.mediaType==="audio")&&(a=o.packetsSent)}),a===0)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(a," audio packets"))})}}class Nm extends Pt{get description(){return"Can publish video"}perform(){return m(this,void 0,void 0,function*(){var e;const t=yield this.connect(),n=yield Em();yield this.checkForVideo(n.mediaStreamTrack),t.localParticipant.publishTrack(n),yield new Promise(a=>setTimeout(a,5e3));const s=yield(e=n.sender)===null||e===void 0?void 0:e.getStats();if(!s)throw new Error("Could not get RTCStats");let r=0;if(s.forEach(a=>
39{a.type==="outbound-rtp"&&(a.kind==="video"||!a.kind&&a.mediaType==="video")&&(r+=a.packetsSent)}),r===0)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(r," video packets"))})}checkForVideo(e){return m(this,void 0,void 0,function*(){const t=new MediaStream;t.addTrack(e.clone());const 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(s=>{n.onplay=()=>{setTimeout(()=>{var r,a,o,d;const c=document.createElement("canvas"),l=e.getSettings(),u=(a=(r=l.width)!==null&&r!==void 0?r: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;const p=c.getContext("2d");p.drawImage(n,0,0);const g=p.getImageData(0,0,c.width,c.height).data;let k=!0;for(let T=0;T<g.length;T+=4)if(g[T]!==0||g[T+1]!==0||g[T+2]!==0){k=!1;break}k?this.appendError("camera appears to be producing only black frames"):this.appendMessage("received video frames"),s()},1e3)},n.play()}),t.getTracks().forEach(s=>s.stop()),n.remove()})}}class Lm extends Pt{get description(){return"Resuming connection after interruption"}perform(){return m(this,void 0,void 0,function*(){var e;const t=yield this.connect();let n=!1,s=!1,r;const a=new Promise(c=>{setTimeout(c,5e3),r=c}),o=()=>{n=!0};t.on(_.SignalReconnecting,o).on(_.Reconnecting,o).on(_.Reconnected,()=>{s=!0,r(!0)}),(e=t.engine.client.ws)===null||e===void 0||e.close();const d=t.engine.client.onClose;if(d&&d(""),yield a,n){if(!s||t.state!==K.Connected)throw this.appendWarning("reconnection is only possible in Redis-based configurations"),new Error("Not able to reconnect")}else throw new Error("Did not attempt to reconnect")})}}class xm extends Pt{get description(){return"Can connect via TURN"}perform(){return m(this,void 0,void 0,function*(){var e,t,n;dn(new URL(this.url))&&(this.appendMessage("Using region specific url"),this.url=(e=yield new H(this.url,this.token).getNextBestRegionUrl())!==null&&e!==void 0?e:this.url);const s=new _r,r=yield s.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3},void 0,!0);let a=!1,o=!1,d=!1;for(let c of r.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 s.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)))})}}class Um extends Pt{get description(){return"Establishing WebRTC connection"}perform(){return m(this,void 0,void 0,function*(){let e=!1,t=!1;this.room.on(_.SignalConnected,()=>{var n;const s=this.room.engine.client.onTrickle;this.room.engine.client.onTrickle=(r,a)=>{if(r.candidate){const o=new RTCIceCandidate(r);let d="".concat(o.protocol," ").concat(o.address,":").concat(o.port," ").concat(o.type);o.address&&(Fm(o.address)?d+=" (private)":o.protocol==="tcp"&&o.tcpType==="passive"?(e=!0,d+=" (passive)"):o.protocol==="udp"&&(t=!0)),this.appendMessage(d)}s&&s(r,a)},!((n=this.room.engine.pcManager)===null||n===void 0)&&n.subscriber&&(this.room.engine.pcManager.subscriber.onIceCandidateError=r=>{r instanceof RTCPeerConnectionIceErrorEvent&&this.appendWarning("error with ICE candidate: ".concat(r.errorCode," ").concat(r.errorText," ").concat(r.url))})});try{yield this.connect(),U.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 Fm(i){const e=i.split(".");if(e.length===4){if(e[0]==="10")return!0;
39if(e[0]==="192"&&e[1]==="168")return!0;if(e[0]==="172"){const t=parseInt(e[1],10);if(t>=16&&t<=31)return!0}}return!1}class Bm extends Pt{get description(){return"Connecting to signal connection via WebSocket"}perform(){return m(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 s=new _r,r;try{r=yield s.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3},void 0,!0)}catch(a){if(dn(new URL(this.url))){this.appendMessage("Initial connection failed with error ".concat(a.message,". Retrying with region fallback"));const d=yield new H(this.url,this.token).getNextBestRegionUrl();d&&(r=yield s.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"))}}r?(this.appendMessage("Connected to server, version ".concat(r.serverVersion,".")),((e=r.serverInfo)===null||e===void 0?void 0:e.edition)===Vo.Cloud&&(!((t=r.serverInfo)===null||t===void 0)&&t.region)&&this.appendMessage("LiveKit Cloud: ".concat((n=r.serverInfo)===null||n===void 0?void 0:n.region))):this.appendError("Websocket connection could not be established"),yield s.close()})}}class cf extends De.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(){const e=this.checkResults.size;return this.checkResults.set(e,{logs:[],status:qe.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!==qe.FAILED)}getResults(){return Array.from(this.checkResults.values())}createAndRunCheck(e){return m(this,void 0,void 0,function*(){const t=this.getNextCheckId(),n=new e(this.url,this.token,this.options),s=a=>{this.updateCheck(t,a)};n.on("update",s);const r=yield n.run();return n.off("update",s),r})}checkWebsocket(){return m(this,void 0,void 0,function*(){return this.createAndRunCheck(Bm)})}checkWebRTC(){return m(this,void 0,void 0,function*(){return this.createAndRunCheck(Um)})}checkTURN(){return m(this,void 0,void 0,function*(){return this.createAndRunCheck(xm)})}checkReconnect(){return m(this,void 0,void 0,function*(){return this.createAndRunCheck(Lm)})}checkPublishAudio(){return m(this,void 0,void 0,function*(){return this.createAndRunCheck(Om)})}checkPublishVideo(){return m(this,void 0,void 0,function*(){return this.createAndRunCheck(Nm)})}checkConnectionProtocol(){return m(this,void 0,void 0,function*(){const e=yield this.createAndRunCheck(Am);if(e.data&&"protocol"in e.data){const t=e.data;this.options.protocol=t.protocol}return e})}checkCloudRegion(){return m(this,void 0,void 0,function*(){return this.createAndRunCheck(Dm)}
39)}}new TextEncoder;new TextDecoder;class Re extends Error{constructor(e,t){var n;super(e,t),j(this,"code","ERR_JOSE_GENERIC"),this.name=this.constructor.name,(n=Error.captureStackTrace)===null||n===void 0||n.call(Error,this,this.constructor)}}j(Re,"code","ERR_JOSE_GENERIC");class qm extends Re{constructor(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:"unspecified",s=arguments.length>3&&arguments[3]!==void 0?arguments[3]:"unspecified";super(e,{cause:{claim:n,reason:s,payload:t}}),j(this,"code","ERR_JWT_CLAIM_VALIDATION_FAILED"),j(this,"claim",void 0),j(this,"reason",void 0),j(this,"payload",void 0),this.claim=n,this.reason=s,this.payload=t}}j(qm,"code","ERR_JWT_CLAIM_VALIDATION_FAILED");class Vm extends Re{constructor(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:"unspecified",s=arguments.length>3&&arguments[3]!==void 0?arguments[3]:"unspecified";super(e,{cause:{claim:n,reason:s,payload:t}}),j(this,"code","ERR_JWT_EXPIRED"),j(this,"claim",void 0),j(this,"reason",void 0),j(this,"payload",void 0),this.claim=n,this.reason=s,this.payload=t}}j(Vm,"code","ERR_JWT_EXPIRED");class Wm extends Re{constructor(){super(...arguments),j(this,"code","ERR_JOSE_ALG_NOT_ALLOWED")}}j(Wm,"code","ERR_JOSE_ALG_NOT_ALLOWED");class jm extends Re{constructor(){super(...arguments),j(this,"code","ERR_JOSE_NOT_SUPPORTED")}}j(jm,"code","ERR_JOSE_NOT_SUPPORTED");class Hm extends Re{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"decryption operation failed",t=arguments.length>1?arguments[1]:void 0;super(e,t),j(this,"code","ERR_JWE_DECRYPTION_FAILED")}}
39j(Hm,"code","ERR_JWE_DECRYPTION_FAILED");class Km extends Re{constructor(){super(...arguments),j(this,"code","ERR_JWE_INVALID")}}j(Km,"code","ERR_JWE_INVALID");class Gm extends Re{constructor(){super(...arguments),j(this,"code","ERR_JWS_INVALID")}}j(Gm,"code","ERR_JWS_INVALID");class zm extends Re{constructor(){super(...arguments),j(this,"code","ERR_JWT_INVALID")}}j(zm,"code","ERR_JWT_INVALID");class Jm extends Re{constructor(){super(...arguments),j(this,"code","ERR_JWK_INVALID")}}j(Jm,"code","ERR_JWK_INVALID");class $m extends Re{constructor(){super(...arguments),j(this,"code","ERR_JWKS_INVALID")}}j($m,"code","ERR_JWKS_INVALID");class Qm extends Re{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"no applicable key found in the JSON Web Key Set",t=arguments.length>1?arguments[1]:void 0;super(e,t),j(this,"code","ERR_JWKS_NO_MATCHING_KEY")}}j(Qm,"code","ERR_JWKS_NO_MATCHING_KEY");class Ym extends Re{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"multiple matching keys found in the JSON Web Key Set",t=arguments.length>1?arguments[1]:void 0;super(e,t),j(this,Symbol.asyncIterator,void 0),j(this,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS")}}j(Ym,"code","ERR_JWKS_MULTIPLE_MATCHING_KEYS");class Xm extends Re{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"request timed out",t=arguments.length>1?arguments[1]:void 0;super(e,t),j(this,"code","ERR_JWKS_TIMEOUT")}}j(Xm,"code","ERR_JWKS_TIMEOUT");class Zm extends Re{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"signature verification failed",t=arguments.length>1?arguments[1]:void 0;super(e,t),j(this,"code","ERR_JWS_SIGNATURE_VERIFICATION_FAILED")}}
39j(Zm,"code","ERR_JWS_SIGNATURE_VERIFICATION_FAILED");function ut(){return ut=Object.assign?Object.assign.bind():function(i){for(var e=1;e<arguments.length;e++){var t=arguments[e];for(var n in t)({}).hasOwnProperty.call(t,n)&&(i[n]=t[n])}return i},ut.apply(null,arguments)}const oo=new Uint8Array(0);class Vn{static getFullOptions(e){return ut({clientTools:{},onConnect:()=>{},onDebug:()=>{},onDisconnect:()=>{},onError:()=>{},onMessage:()=>{},onAudio:()=>{},onModeChange:()=>{},onStatusChange:()=>{},onCanSendFeedbackChange:()=>{},onInterruption:()=>{}},e)}constructor(e,t){var n=this;this.options=void 0,this.connection=void 0,this.lastInterruptTimestamp=0,this.mode="listening",this.status="connecting",this.volume=1,this.currentEventId=1,this.lastFeedbackEventId=0,this.canSendFeedback=!1,this.endSessionWithDetails=async function(s){n.status!=="connected"&&n.status!=="connecting"||(n.updateStatus("disconnecting"),await n.handleEndSession(),n.updateStatus("disconnected"),n.options.onDisconnect&&n.options.onDisconnect(s))},this.onMessage=async function(s){switch(s.type){case"interruption":return void n.handleInterruption(s);case"agent_response":return void n.handleAgentResponse(s);case"user_transcript":return void n.handleUserTranscript(s);case"internal_tentative_agent_response":return void n.handleTentativeAgentResponse(s);case"client_tool_call":try{await n.handleClientToolCall(s)}catch(r){n.onError(`Unexpected error in client tool call handling: ${r instanceof Error?r.message:String(r)}`,{clientToolName:s.client_tool_call.tool_name,toolCallId:s.client_tool_call.tool_call_id})}return;case"audio":return void n.handleAudio(s);case"vad_score":return void n.handleVadScore(s);case"ping":return void n.connection.sendMessage({type:"pong",event_id:s.ping_event.event_id});case"mcp_tool_call":return void n.handleMCPToolCall(s);case"mcp_connection_status":return void n.handleMCPConnectionStatus(s);case"agent_tool_request":return void n.handleAgentToolRequest(s);case"agent_tool_response":return void n.handleAgentToolResponse(s);case"conversation_initiation_metadata":return void n.handleConversationMetadata(s);case"asr_initiation_metadata":return void n.handleAsrInitiationMetadata(s);case"agent_chat_response_part":return void n.handleAgentChatResponsePart(s);case"error":return void n.handleErrorEvent(s);default:return void(n.options.onDebug&&n.options.onDebug(s))}},this.setVolume=({volume:s})=>{this.volume=s},this.options=e,this.connection=t,this.options.onConnect&&this.options.onConnect({conversationId:t.conversationId}),this.connection.onMessage(this.onMessage),this.connection.onDisconnect(this.endSessionWithDetails),this.connection.onModeChange(s=>this.updateMode(s)),this.updateStatus("connected")}endSession(){return this.endSessionWithDetails({reason:"user"})}async handleEndSession(){this.connection.close()}updateMode(e){e!==this.mode&&(this.mode=e,this.options.onModeChange&&this.options.onModeChange({mode:e}))}updateStatus(e){e!==this.status&&(this.status=e,this.options.onStatusChange&&this.options.onStatusChange({status:e}))}updateCanSendFeedback(){const e=this.currentEventId!==this.lastFeedbackEventId;this.canSendFeedback!==e&&(this.canSendFeedback=e,this.options.onCanSendFeedbackChange&&this.options.onCanSendFeedbackChange({canSendFeedback:e}))}handleInterruption(e){e.interruption_event&&(this.lastInterruptTimestamp=e.interruption_event.event_id,this.options.onInterruption&&this.options.onInterruption({event_id:e.interruption_event.event_id}))}handleAgentResponse(e){this.options.onMessage&&this.options.onMessage({source:"ai",role:"agent",message:e.agent_response_event.agent_response})}handleUserTranscript(e){this.options.onMessage&&this.options.onMessage({source:"user",role:"user",message:e.user_transcription_event.user_transcript})}handleTentativeAgentResponse(e){this.options.onDebug&&this.options.onDebug({type:"tentative_agent_response",response:e.tentative_agent_response_internal_event.tentative_agent_response})}handleVadScore(e){this.options.onVadScore&&this.options.onVadScore({vadScore:e.vad_score_event.vad_score})}async handleClientToolCall(e){if(Object.prototype.hasOwnProperty.call(this.options.clientTools,e.client_tool_call.tool_name))try{var t;const n=(t=await this.options.clientTools[e.client_tool_call.tool_name](e.client_tool_call.parameters))!=null?t:"Client tool execution successful.",s=typeof n=="object"?JSON.stringify(n):String(n);this.connection.sendMessage({type:"client_tool_result",tool_call_id:e.client_tool_call.tool_call_id,result:s,is_error:!1})}catch(n){this.onError(`Client tool execution failed with following error: ${n?.message}`,{clientToolName:e.client_tool_call.tool_name}),this.connection.sendMessage({type:"client_tool_result",tool_call_id:e.client_tool_call.tool_call_id,result:`Client tool execution failed: ${n?.message}`,is_error:!0})}else{if(this.options.onUnhandledClientToolCall)return void this.options.onUnhandledClientToolCall(e.client_tool_call);this.onError(`Client tool with name ${e.client_tool_call.tool_name} is not defined on client`,{clientToolName:e.client_tool_call.tool_name}),this.connection.sendMessage({type:"client_tool_result",tool_call_id:e.client_tool_call.tool_call_id,result:`Client tool with name ${e.client_tool_call.tool_name} is not defined on client`,is_error:!0})}}handleAudio(e){}handleMCPToolCall(e){this.options.onMCPToolCall&&this.options.onMCPToolCall(e.mcp_tool_call)}
39handleMCPConnectionStatus(e){this.options.onMCPConnectionStatus&&this.options.onMCPConnectionStatus(e.mcp_connection_status)}handleAgentToolRequest(e){this.options.onAgentToolRequest&&this.options.onAgentToolRequest(e.agent_tool_request)}handleAgentToolResponse(e){e.agent_tool_response.tool_name==="end_call"&&this.endSessionWithDetails({reason:"agent",context:new CloseEvent("end_call",{reason:"Agent ended the call"})}),this.options.onAgentToolResponse&&this.options.onAgentToolResponse(e.agent_tool_response)}handleConversationMetadata(e){this.options.onConversationMetadata&&this.options.onConversationMetadata(e.conversation_initiation_metadata_event)}handleAsrInitiationMetadata(e){this.options.onAsrInitiationMetadata&&this.options.onAsrInitiationMetadata(e.asr_initiation_metadata_event)}handleAgentChatResponsePart(e){this.options.onAgentChatResponsePart&&this.options.onAgentChatResponsePart(e.text_response_part)}handleErrorEvent(e){const t=e.error_event.error_type,n=e.error_event.message||e.error_event.reason||"Unknown error";t!=="max_duration_exceeded"?this.onError(`Server error: ${n}`,{errorType:t,code:e.error_event.code,debugMessage:e.error_event.debug_message,details:e.error_event.details}):this.endSessionWithDetails({reason:"error",message:n,context:new Event("max_duration_exceeded")})}onError(e,t){console.error(e,t),this.options.onError&&this.options.onError(e,t)}getId(){return this.connection.conversationId}isOpen(){return this.status==="connected"}setMicMuted(e){this.connection.setMicMuted(e)}getInputByteFrequencyData(){return oo}getOutputByteFrequencyData(){return oo}getInputVolume(){return 0}getOutputVolume(){return 0}sendFeedback(e){this.canSendFeedback?(this.connection.sendMessage({type:"feedback",score:e?"like":"dislike",event_id:this.currentEventId}),this.lastFeedbackEventId=this.currentEventId,this.updateCanSendFeedback()):console.warn(this.lastFeedbackEventId===0?"Cannot send feedback: the conversation has not started yet.":"Cannot send feedback: feedback has already been sent for the current response.")}sendContextualUpdate(e){this.connection.sendMessage({type:"contextual_update",text:e})}sendUserMessage(e){this.connection.sendMessage({type:"user_message",text:e})}sendUserActivity(){this.connection.sendMessage({type:"user_activity"})}sendMCPToolApprovalResult(e,t){this.connection.sendMessage({type:"mcp_tool_approval_result",tool_call_id:e,is_approved:t})}}class Pd{constructor(e={}){this.queue=[],this.disconnectionDetails=null,this.onDisconnectCallback=null,this.onMessageCallback=null,this.onModeChangeCallback=null,this.onDebug=void 0,this.onDebug=e.onDebug}debug(e){this.onDebug&&this.onDebug(e)}onMessage(e){this.onMessageCallback=e;const t=this.queue;this.queue=[],t.length>0&&queueMicrotask(()=>{t.forEach(e)})}onDisconnect(e){this.onDisconnectCallback=e;const t=this.disconnectionDetails;t&&queueMicrotask(()=>{e(t)})}onModeChange(e){this.onModeChangeCallback=e}updateMode(e){var t;(t=this.onModeChangeCallback)==null||t.call(this,e)}disconnect(e){var t;this.disconnectionDetails||(this.disconnectionDetails=e,(t=this.onDisconnectCallback)==null||t.call(this,e))}handleMessage(e){this.onMessageCallback?this.onMessageCallback(e):this.queue.push(e)}}function Si(i){const[e,t]=i.split("_");if(!["pcm","ulaw"].includes(e))throw new Error(`Invalid format: ${i}`);const n=Number.parseInt(t);if(Number.isNaN(n))throw new Error(`Invalid sample rate: ${t}`);return{format:e,sampleRate:n}}const Id="0.12.2";function Js(i){return!!i.type}const Md="conversation_initiation_client_data";function Dd(i){var e;const t={type:Md};var n,s,r,a,o,d;return i.overrides&&(t.conversation_config_override={agent:{prompt:(n=i.overrides.agent)==null?void 0:n.prompt,first_message:(s=i.overrides.agent)==null?void 0:s.firstMessage,language:(r=i.overrides.agent)==null?void 0:r.language},tts:{voice_id:(a=i.overrides.tts)==null?void 0:a.voiceId,speed:(o=i.overrides.tts)==null?void 0:o.speed},conversation:{text_only:(d=i.overrides.conversation)==null?void 0:d.textOnly}}),i.customLlmExtraBody&&(t.custom_llm_extra_body=i.customLlmExtraBody),i.dynamicVariables&&(t.dynamic_variables=i.dynamicVariables),i.userId&&(t.user_id=i.userId),(e=i.overrides)!=null&&e.client&&(t.source_info={source:i.overrides.client.source,version:i.overrides.client.version}),t}class Wn extends Pd{constructor(e,t,n,s){super(),this.socket=void 0,this.conversationId=void 0,this.inputFormat=void 0,this.outputFormat=void 0,this.socket=e,this.conversationId=t,this.inputFormat=n,this.outputFormat=s,this.socket.addEventListener("error",r=>{setTimeout(()=>this.disconnect({reason:"error",message:"The connection was closed due to a socket error.",context:r}),0)}),this.socket.addEventListener("close",r=>{this.disconnect(r.code===1e3?{reason:"agent",context:r}:{reason:"error",message:r.reason||"The connection was closed by the server.",context:r})}),this.socket.addEventListener("message",r=>{try{const a=JSON.parse(r.data);if(!Js(a))return void this.debug({type:"invalid_event",message:"Received invali
39d socket event",data:r.data});this.handleMessage(a)}catch(a){this.debug({type:"parsing_error",message:"Failed to parse socket message",error:a instanceof Error?a.message:String(a),data:r.data})}})}static async create(e){let t=null;try{var n,s,r;const o=(n=e.origin)!=null?n:"wss://api.elevenlabs.io";let d;const c=((s=e.overrides)==null||(s=s.client)==null?void 0:s.version)||Id,l=((r=e.overrides)==null||(r=r.client)==null?void 0:r.source)||"js_sdk";if(e.signedUrl){const S=e.signedUrl.includes("?")?"&":"?";d=`${e.signedUrl}${S}source=${l}&version=${c}`}else d=`${o}/v1/convai/conversation?agent_id=${e.agentId}&source=${l}&version=${c}`;const u=["convai"];e.authorization&&u.push(`bearer.${e.authorization}`),t=new WebSocket(d,u);const h=await new Promise((S,N)=>{t.addEventListener("open",()=>{var v;const y=Dd(e);(v=t)==null||v.send(JSON.stringify(y))},{once:!0}),t.addEventListener("error",v=>{setTimeout(()=>N(v),0)}),t.addEventListener("close",N),t.addEventListener("message",v=>{const y=JSON.parse(v.data);Js(y)&&(y.type==="conversation_initiation_metadata"?S(y.conversation_initiation_metadata_event):console.warn("First received message is not conversation metadata."))},{once:!0})}),{conversation_id:p,agent_output_audio_format:f,user_input_audio_format:g}=h,k=Si(g??"pcm_16000"),T=Si(f);return new Wn(t,p,k,T)}catch(o){var a;throw(a=t)==null||a.close(),o}}close(){this.socket.close(1e3,"User ended conversation")}sendMessage(e){this.socket.send(JSON.stringify(e))}async setMicMuted(e){console.warn(`WebSocket connection setMicMuted called with ${e}, but this is handled by VoiceConversation`)}}function Ad(i){const e=new Uint8Array(i);return window.btoa(String.fromCharCode(...e))}function ef(i){const e=window.atob(i),t=e.length,n=new Uint8Array(t);for(let s=0;s<t;s++)n[s]=e.charCodeAt(s);return n.buffer}const $n=new Map;function Ar(i,e){return async(t,n)=>{const s=$n.get(i);if(s)return t.addModule(s);if(n)try{return await t.addModule(n),void $n.set(i,n)}catch(o){throw new Error(`Failed to load the ${i} worklet module from path: ${n}. Error: ${o}`)}const r=new Blob([e],{type:"application/javascript"}),a=URL.createObjectURL(r);try{return await t.addModule(a),void $n.set(i,a)}catch{URL.revokeObjectURL(a)}try{const o=`data:application/javascript;base64,${btoa(e)}`;await t.addModule(o),$n.set(i,o)}catch{throw new Error(`Failed to load the ${i} worklet module. Make sure the browser supports AudioWorklets. If you are using a strict CSP, you may need to self-host the worklet files.`)}}}const Od=Ar("rawAudioProcessor",`/* 40 * ulaw encoding logic taken from the wavefile library 41 * https://github.com/rochars/wavefile/blob/master/lib/codecs/mulaw.js 42 * USED BY @elevenlabs/client 43 */ 44 45const BIAS = 0x84; 46const CLIP = 32635; 47const encodeTable = [ 48 0,0,1,1,2,2,2,2,3,3,3,3,3,3,3,3, 49 4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4, 50 5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5, 51 5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5, 52 6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6, 53 6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6, 54 6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6, 55 6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6, 56 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, 57 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, 58 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, 59 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, 60 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, 61 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, 62 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, 63 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7 64]; 65 66function encodeSample(sample) { 67 let sign; 68 let exponent; 69 let mantissa; 70 let muLawSample; 71 sign = (sample >> 8) & 0x80; 72 if (sign !== 0) sample = -sample; 73 sample = sample + BIAS; 74 if (sample > CLIP) sample = CLIP; 75 exponent = encodeTable[(sample>>7) & 0xFF]; 76 mantissa = (sample >> (exponent+3)) & 0x0F; 77 muLawSample = ~(sign | (exponent << 4) | mantissa); 78 79 return muLawSample; 80} 81 82class RawAudioProcessor extends AudioWorkletProcessor { 83 constructor() { 84 super(); 85 86 this.port.onmessage = ({ data }) => { 87 switch (data.type) { 88 case "setFormat": 89 this.isMuted = false; 90 this.buffer = []; // Initialize an empty buffer 91 this.bufferSize = data.sampleRate / 4; 92 this.format = data.format; 93 94 if (globalThis.LibSampleRate && sampleRate !== data.sampleRate) { 95 globalThis.LibSampleRate.create(1, sampleRate, data.sampleRate).then(resampler => { 96 this.resampler = resampler; 97 }); 98 } 99 break; 100 case "setMuted": 101 this.isMuted = data.isMuted; 102 break; 103 } 104 }; 105 } 106 process(inputs) { 107 if (!this.buffer) { 108 return true; 109 } 110 111 const input = inputs[0]; // Get the first input node 112 if (input.length > 0) { 113 let channelData = input[0]; // Get the first channel's data 114 115 // Resample the audio if necessary 116 if (this.resampler) { 117 channelData = this.resampler.full(channelData); 118 } 119 120 // Add channel data to the buffer 121 this.buffer.push(...channelData); 122 // Get max volume 123 let sum = 0.0; 124 for (let i = 0; i < channelData.length; i++) { 125 sum += channelData[i] * channelData[i]; 126 } 127 const maxVolume = Math.sqrt(sum / channelData.length); 128 // Check if buffer size has reached or exceeded the threshold 129 if (this.buffer.length >= this.bufferSize) { 130 const float32Array = this.isMuted 131 ? new Float32Array(this.buffer.length) 132 : new Float32Array(this.buffer); 133 134 let encodedArray = this.format === "ulaw" 135 ? new Uint8Array(float32Array.length) 136 : new Int16Array(float32Array.length); 137 138 // Iterate through the Float32Array and convert each sample to PCM16 139 for (let i = 0; i < float32Array.length; i++) { 140 // Clamp the value to the range [-1, 1] 141 let sample = Math.max(-1, Math.min(1, float32Array[i])); 142 143 // Scale the sample to the range [-32768, 32767] 144 let value = sample < 0 ? sample * 32768 : sample * 32767; 145 if (this.format === "ulaw") { 146 value = encodeSample(Math.round(value)); 147 } 148 149 encodedArray[i] = value; 150 } 151 152 // Send the buffered data to the main script 153 this.port.postMessage([encodedArray, maxVolume]); 154 155 // Clear the buffer after sending 156 this.buffer = []; 157 } 158 } 159 return true; // Continue processing 160 } 161} 162registerProcessor("rawAudioProcessor", RawAudioProcessor); 163`);class ot extends Pd{constructor(e,t,n,s,r={}){super(r),this.conversationId=void 0,this.inputFormat=void 0,this.outputFormat=void 0,this.room=void 0,this.isConnected=!1,this.audioEventId=1,this.audioCaptureContext=null,this.audioElements=[],this.outputDeviceId=null,this.outputAnalyser=null,this.outputFrequencyData=null,this.room=e,this.conversationId=t,this.inputFormat=n,this.outputFormat=s,this.setupRoomEventListeners()}static async create(e){let t;if("conversationToken"in e&&e.conversationToken)t=e.conversationToken;else{if(!("agentId"in e)||!e.agentId)throw new Error("Either conversationToken or agentId is required for WebRTC connection");try{var n,s,r;const c=((n=e.overrides)==null||(n=n.client)==null?void 0:n.version)||Id,l=((s=e.overrides)==null||(s=s.client)==null?void 0:s.source)||"js_s
163dk",u=`${a=(r=e.origin)!=null?r:"https://api.elevenlabs.io",a.replace(/^wss:\/\//,"https://")}/v1/convai/conversation/token?agent_id=${e.agentId}&source=${l}&version=${c}`,h=await fetch(u);if(!h.ok)throw new Error(`ElevenLabs API returned ${h.status} ${h.statusText}`);if(t=(await h.json()).token,!t)throw new Error("No conversation token received from API")}catch(c){let l=c instanceof Error?c.message:String(c);throw c instanceof Error&&c.message.includes("401")&&(l="Your agent has authentication enabled, but no signed URL or conversation token was provided."),new Error(`Failed to fetch conversation token for agent ${e.agentId}: ${l}`)}}var a;const o=new hn;try{const c=`room_${Date.now()}`,l=Si("pcm_48000"),u=Si("pcm_48000"),h=new ot(o,c,l,u,e),p=e.livekitUrl||"wss://livekit.rtc.elevenlabs.io";var d;await o.connect(p,t),await new Promise(g=>{if(h.isConnected)g();else{const k=()=>{o.off(_.Connected,k),g()};o.on(_.Connected,k)}}),o.name&&(h.conversationId=((d=o.name.match(/(conv_[a-zA-Z0-9]+)/))==null?void 0:d[0])||o.name),await o.localParticipant.setMicrophoneEnabled(!0);const f=Dd(e);return h.debug({type:Md,message:f}),await h.sendMessage(f),h}catch(c){throw await o.disconnect(),c}}setupRoomEventListeners(){var e=this;this.room.on(_.Connected,async function(){e.isConnected=!0,console.info("WebRTC room connected")}),this.room.on(_.Disconnected,t=>{this.isConnected=!1,this.disconnect({reason:"agent",context:new CloseEvent("close",{reason:t?.toString()})})}),this.room.on(_.ConnectionStateChanged,t=>{t===K.Disconnected&&(this.isConnected=!1,this.disconnect({reason:"error",message:`LiveKit connection state changed to ${t}`,context:new Event("connection_state_changed")}))}),this.room.on(_.DataReceived,(t,n)=>{try{const s=JSON.parse(new TextDecoder().decode(t));if(s.type==="audio")return;Js(s)?this.handleMessage(s):console.warn("Invalid socket event received:",s)}catch(s){console.warn("Failed to parse incoming data message:",s),console.warn("Raw payload:",new TextDecoder().decode(t))}}),this.room.on(_.TrackSubscribed,async function(t,n,s){if(t.kind===C.Kind.Audio&&s.identity.includes("agent")){const r=t,a=r.attach();if(a.autoplay=!0,a.controls=!1,e.outputDeviceId&&a.setSinkId)try{await a.setSinkId(e.outputDeviceId)}catch(o){console.warn("Failed to set output device for new audio element:",o)}a.style.display="none",document.body.appendChild(a),e.audioElements.push(a),e.audioElements.length===1&&(e.onDebug==null||e.onDebug({type:"audio_element_ready"})),await e.setupAudioCapture(r)}}),this.room.on(_.ActiveSpeakersChanged,async function(t){e.updateMode(t.length>0&&t[0].identity.startsWith("agent")?"speaking":"listening")}),this.room.on(_.ParticipantDisconnected,t=>{var n;(n=t.identity)!=null&&n.startsWith("agent")&&this.disconnect({reason:"agent",context:new CloseEvent("close",{reason:"agent disconnected"})})})}close(){if(this.isConnected){try{this.room.localParticipant.audioTrackPublications.forEach(e=>{e.track&&e.track.stop()})}catch(e){console.warn("Error stopping local tracks:",e)}this.audioCaptureContext&&(this.audioCaptureContext.close().catch(e=>{console.warn("Error closing audio capture context:",e)}),this.audioCaptureContext=null),this.audioElements.forEach(e=>{e.parentNode&&e.parentNode.removeChild(e)}),this.audioElements=[],this.room.disconnect()}}async sendMessage(e){if(this.isConnected&&this.room.localParticipant){if(!("user_audio_chunk"in e))try{const t=new TextEncoder().encode(JSON.stringify(e));await this.room.localParticipant.publishData(t,{reliable:!0})}catch(t){this.debug({type:"send_message_error",message:{message:e,error:t}}),console.error("Failed to send message via WebRTC:",t)}}else console.warn("Cannot send message: room not connected or no local participant")}getRoom(){return this.room}async setMicMuted(e){if(!this.isConnected||!this.room.localParticipant)return void console.warn("Cannot set microphone muted: room not connected or no local participant");const t=this.room.localParticipant.getTrackPublication(C.Source.Microphone);if(t!=null&&t.track)try{e?await t.track.mute():await t.track.unmute()}catch{await this.room.localParticipant.setMicrophoneEnabled(!e)}else await this.room.localParticipant.setMicrophoneEnabled(!e)}async setupAudioCapture(e){try{const t=new AudioContext;this.audioCaptureContext=t,this.outputAnalyser=t.createAnalyser(),this.outputAnalyser.fftSize=2048,this.outputAnalyser.smoothingTimeConstant=.8;const n=new MediaStream([e.mediaStreamTrack]),s=t.createMediaStreamSource(n);s.connect(this.outputAnalyser),await Od(t.audioWorklet);const r=new AudioWorkletNode(t,"rawAudioProcessor");this.outputAnalyser.connect(r),r.port.postMessage({type:"setFormat",format:this.outputFormat.format,sampleRate:this.outputFormat.sampleRate}),r.port.onmessage=a=>{const[o,d]=a.data;if(d>.01){const c=Ad(o.buffer),l=this.audioEventId++;this.handleMessage({type:"audio",audio_event:{audio_base_64:c,event_id:l}})}},s.connect(r)}catch(t){console.warn("Failed to set up audio capture:",t)}}
163setAudioVolume(e){this.audioElements.forEach(t=>{t.volume=e})}async setAudioOutputDevice(e){if(!("setSinkId"in HTMLAudioElement.prototype))throw new Error("setSinkId is not supported in this browser");const t=this.audioElements.map(async function(n){try{await n.setSinkId(e)}catch(s){throw console.error("Failed to set sink ID for audio element:",s),s}});await Promise.all(t),this.outputDeviceId=e}async setAudioInputDevice(e){if(!this.isConnected||!this.room.localParticipant)throw new Error("Cannot change input device: room not connected or no local participant");try{const t=this.room.localParticipant.getTrackPublication(C.Source.Microphone);t!=null&&t.track&&(await t.track.stop(),await this.room.localParticipant.unpublishTrack(t.track));const n={deviceId:{exact:e},echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,channelCount:{ideal:1}},s=await _d(n);await this.room.localParticipant.publishTrack(s,{name:"microphone",source:C.Source.Microphone})}catch(t){console.error("Failed to change input device:",t);try{await this.room.localParticipant.setMicrophoneEnabled(!0)}catch(n){console.error("Failed to recover microphone after device switch error:",n)}throw t}}getOutputByteFrequencyData(){return this.outputAnalyser?(this.outputFrequencyData!=null||(this.outputFrequencyData=new Uint8Array(this.outputAnalyser.frequencyBinCount)),this.outputAnalyser.getByteFrequencyData(this.outputFrequencyData),this.outputFrequencyData):null}}async function Nd(i){const e=(function(t){return t.connectionType?t.connectionType:"conversationToken"in t&&t.conversationToken?"webrtc":"websocket"})(i);switch(e){case"websocket":return Wn.create(i);case"webrtc":return ot.create(i);default:throw new Error(`Unknown connection type: ${e}`)}}function $s(){return["iPad Simulator","iPhone Simulator","iPod Simulator","iPad","iPhone","iPod"].includes(navigator.platform)||navigator.userAgent.includes("Mac")&&"ontouchend"in document}async function Ld(i={default:0,android:3e3}){let e=i.default;var t;if(/android/i.test(navigator.userAgent))e=(t=i.android)!=null?t:e;else if($s()){var n;e=(n=i.ios)!=null?n:e}e>0&&await new Promise(s=>setTimeout(s,e))}class Or extends Vn{static async startSession(e){const t=Vn.getFullOptions(e);t.onStatusChange&&t.onStatusChange({status:"connecting"}),t.onCanSendFeedbackChange&&t.onCanSendFeedbackChange({canSendFeedback:!1}),t.onModeChange&&t.onModeChange({mode:"listening"}),t.onCanSendFeedbackChange&&t.onCanSendFeedbackChange({canSendFeedback:!1});let n=null;try{return await Ld(t.connectionDelay),n=await Nd(e),new Or(t,n)}catch(r){var s;throw t.onStatusChange&&t.onStatusChange({status:"disconnected"}),(s=n)==null||s.close(),r}}}const co={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,channelCount:{ideal:1}};class an{static async create({sampleRate:e,format:t,preferHeadphonesForIosDevices:n,inputDeviceId:s,workletPaths:r,libsampleratePath:a}){let o=null,d=null;try{const u=ut({sampleRate:{ideal:e}},co);if($s()&&n){const T=(await window.navigator.mediaDevices.enumerateDevices()).find(S=>S.kind==="audioinput"&&["airpod","headphone","earphone"].find(N=>S.label.toLowerCase().includes(N)));T&&(u.deviceId={ideal:T.deviceId})}s&&(u.deviceId=an.getDeviceIdConstraint(s));const h=navigator.mediaDevices.getSupportedConstraints().sampleRate;o=new window.AudioContext(h?{sampleRate:e}:{});const p=o.createAnalyser();if(!h){const T=a||"https://cdn.jsdelivr.net/npm/@alexanderolsen/[email protected]/dist/libsamplerate.worklet.js";await o.audioWorklet.addModule(T)}await Od(o.audioWorklet,r?.rawAudioProcessor);const f=ut({voiceIsolation:!0},u);d=await navigator.mediaDevices.getUserMedia({audio:f});const g=o.createMediaStreamSource(d),k=new AudioWorkletNode(o,"rawAudioProcessor");return k.port.postMessage({type:"setFormat",format:t,sampleRate:e}),g.connect(p),p.connect(k),await o.resume(),new an(o,p,k,d,g)}catch(u){var c,l;throw(c=d)==null||c.getTracks().forEach(h=>{h.stop()}),(l=o)==null||l.close(),u}}static getDeviceIdConstraint(e){if(e)return $s()?{ideal:e}:{exact:e}}constructor(e,t,n,s,r){this.context=void 0,this.analyser=void 0,this.worklet=void 0,this.inputStream=void 0,this.mediaStreamSource=void 0,this.context=e,this.analyser=t,this.worklet=n,this.inputStream=s,this.mediaStreamSource=r}
163async close(){this.inputStream.getTracks().forEach(e=>{e.stop()}),this.mediaStreamSource.disconnect(),await this.context.close()}setMuted(e){this.worklet.port.postMessage({type:"setMuted",isMuted:e})}async setInputDevice(e){try{const t=ut({},co);e&&(t.deviceId=an.getDeviceIdConstraint(e));const n=ut({voiceIsolation:!0},t),s=await navigator.mediaDevices.getUserMedia({audio:n});this.inputStream.getTracks().forEach(r=>{r.stop()}),this.mediaStreamSource.disconnect(),this.inputStream=s,this.mediaStreamSource=this.context.createMediaStreamSource(s),this.mediaStreamSource.connect(this.analyser)}catch(t){throw console.error("Failed to switch input device:",t),t}}}const tf=Ar("audioConcatProcessor",`/* 164 * ulaw decoding logic taken from the wavefile library 165 * https://github.com/rochars/wavefile/blob/master/lib/codecs/mulaw.js 166 * USED BY @elevenlabs/client 167 */ 168 169const decodeTable = [0,132,396,924,1980,4092,8316,16764]; 170 171function decodeSample(muLawSample) { 172 let sign; 173 let exponent; 174 let mantissa; 175 let sample; 176 muLawSample = ~muLawSample; 177 sign = (muLawSample & 0x80); 178 exponent = (muLawSample >> 4) & 0x07; 179 mantissa = muLawSample & 0x0F; 180 sample = decodeTable[exponent] + (mantissa << (exponent+3)); 181 if (sign !== 0) sample = -sample; 182 183 return sample; 184} 185 186class AudioConcatProcessor extends AudioWorkletProcessor { 187 constructor() { 188 super(); 189 this.buffers = []; // Initialize an empty buffer 190 this.cursor = 0; 191 this.currentBuffer = null; 192 this.wasInterrupted = false; 193 this.finished = false; 194 195 this.port.onmessage = ({ data }) => { 196 switch (data.type) { 197 case "setFormat": 198 this.format = data.format; 199 break; 200 case "buffer": 201 this.wasInterrupted = false; 202 this.buffers.push( 203 this.format === "ulaw" 204 ? new Uint8Array(data.buffer) 205 : new Int16Array(data.buffer) 206 ); 207 break; 208 case "interrupt": 209 this.wasInterrupted = true; 210 break; 211 case "clearInterrupted": 212 if (this.wasInterrupted) { 213 this.wasInterrupted = false; 214 this.buffers = []; 215 this.currentBuffer = null; 216 } 217 } 218 }; 219 } 220 process(_, outputs) { 221 let finished = false; 222 const output = outputs[0][0]; 223 for (let i = 0; i < output.length; i++) { 224 if (!this.currentBuffer) { 225 if (this.buffers.length === 0) { 226 finished = true; 227 break; 228 } 229 this.currentBuffer = this.buffers.shift(); 230 this.cursor = 0; 231 } 232 233 let value = this.currentBuffer[this.cursor]; 234 if (this.format === "ulaw") { 235 value = decodeSample(value); 236 } 237 output[i] = value / 32768; 238 this.cursor++; 239 240 if (this.cursor >= this.currentBuffer.length) { 241 this.currentBuffer = null; 242 } 243 } 244 245 if (this.finished !== finished) { 246 this.finished = finished; 247 this.port.postMessage({ type: "process", finished }); 248 } 249 250 return true; // Continue processing 251 } 252} 253 254registerProcessor("audioConcatProcessor", AudioConcatProcessor); 255`);class Ci{static async create({sampleRate:e,format:t,outputDeviceId:n,workletPaths:s}){let r=null,a=null;try{r=new AudioContext({sampleRate:e});const c=r.createAnalyser(),l=r.createGain();a=new Audio,a.src="",a.load(),a.autoplay=!0,a.style.display="none",document.body.appendChild(a);const u=r.createMediaStreamDestination();a.srcObject=u.stream,l.connect(c),c.connect(u),await tf(r.audioWorklet,s?.audioConcatProcessor);const h=new AudioWorkletNode(r,"audioConcatProcessor");return h.port.postMessage({type:"setFormat",format:t}),h.connect(l),await r.resume(),n&&a.setSinkId&&await a.setSinkId(n),new Ci(r,c,l,h,a)}catch(c){var o,d;throw(o=a)!=null&&o.parentNode&&a.parentNode.removeChild(a),(d=a)==null||d.pause(),r&&r.state!=="closed"&&await r.close(),c}}constructor(e,t,n,s,r){this.context=void 0,this.analyser=void 0,this.gain=void 0,this.worklet=void 0,this.audioElement=void 0,this.context=e,this.analyser=t,this.gain=n,this.worklet=s,this.audioElement=r}async setOutputDevice(e){if(!("setSinkId"in HTMLAudioElement.prototype))throw new Error("setSinkId is not supported in this browser");await this.audioElement.setSinkId(e||"")}async close(){this.audioElement.parentNode&&this.audioElement.parentNode.removeChild(this.audioElement),this.audioElement.pause(),await this.context.close()}}class Nr extends Vn{static async startSession(e){var t;const n=Vn.getFullOptions(e);
255n.onStatusChange&&n.onStatusChange({status:"connecting"}),n.onCanSendFeedbackChange&&n.onCanSendFeedbackChange({canSendFeedback:!1});let s=null,r=null,a=null,o=null,d=null;if((t=e.useWakeLock)==null||t)try{d=await navigator.wakeLock.request("screen")}catch{}try{var c;return o=await navigator.mediaDevices.getUserMedia({audio:!0}),await Ld(n.connectionDelay),r=await Nd(e),[s,a]=await Promise.all([an.create(ut({},r.inputFormat,{preferHeadphonesForIosDevices:e.preferHeadphonesForIosDevices,inputDeviceId:e.inputDeviceId,workletPaths:e.workletPaths,libsampleratePath:e.libsampleratePath})),Ci.create(ut({},r.outputFormat,{outputDeviceId:e.outputDeviceId,workletPaths:e.workletPaths}))]),(c=o)==null||c.getTracks().forEach(g=>{g.stop()}),o=null,new Nr(n,r,s,a,d)}catch(g){var l,u,h,p;n.onStatusChange&&n.onStatusChange({status:"disconnected"}),(l=o)==null||l.getTracks().forEach(k=>{k.stop()}),(u=r)==null||u.close(),await((h=s)==null?void 0:h.close()),await((p=a)==null?void 0:p.close());try{var f;await((f=d)==null?void 0:f.release()),d=null}catch{}throw g}}constructor(e,t,n,s,r){super(e,t),this.input=void 0,this.output=void 0,this.wakeLock=void 0,this.inputFrequencyData=void 0,this.outputFrequencyData=void 0,this.onInputWorkletMessage=a=>{this.status==="connected"&&this.connection.sendMessage({user_audio_chunk:Ad(a.data[0].buffer)})},this.onOutputWorkletMessage=({data:a})=>{a.type==="process"&&this.updateMode(a.finished?"listening":"speaking")},this.addAudioBase64Chunk=a=>{this.output.gain.gain.cancelScheduledValues(this.output.context.currentTime),this.output.gain.gain.value=this.volume,this.output.worklet.port.postMessage({type:"clearInterrupted"}),this.output.worklet.port.postMessage({type:"buffer",buffer:ef(a)})},this.fadeOutAudio=()=>{this.updateMode("listening"),this.output.worklet.port.postMessage({type:"interrupt"}),this.output.gain.gain.exponentialRampToValueAtTime(1e-4,this.output.context.currentTime+2),setTimeout(()=>{this.output.gain.gain.value=this.volume,this.output.worklet.port.postMessage({type:"clearInterrupted"})},2e3)},this.calculateVolume=a=>{if(a.length===0)return 0;let o=0;for(let d=0;d<a.length;d++)o+=a[d]/255;return o/=a.length,o<0?0:o>1?1:o},this.setVolume=({volume:a})=>{const o=Number.isFinite(a)?Math.min(1,Math.max(0,a)):1;this.volume=o,this.connection instanceof ot?this.connection.setAudioVolume(o):this.output.gain.gain.value=o},this.input=n,this.output=s,this.wakeLock=r,this.input.worklet.port.onmessage=this.onInputWorkletMessage,this.output.worklet.port.onmessage=this.onOutputWorkletMessage}async handleEndSession(){await super.handleEndSession();try{var e;await((e=this.wakeLock)==null?void 0:e.release()),this.wakeLock=null}catch{}await this.input.close(),await this.output.close()}handleInterruption(e){super.handleInterruption(e),this.fadeOutAudio()}handleAudio(e){var t,n;this.lastInterruptTimestamp<=e.audio_event.event_id&&((t=(n=this.options).onAudio)==null||t.call(n,e.audio_event.audio_base_64),this.connection instanceof ot||this.addAudioBase64Chunk(e.audio_event.audio_base_64),this.currentEventId=e.audio_event.event_id,this.updateCanSendFeedback(),this.updateMode("speaking"))}setMicMuted(e){this.connection instanceof ot?this.connection.setMicMuted(e):this.input.setMuted(e)}getInputByteFrequencyData(){return this.inputFrequencyData!=null||(this.inputFrequencyData=new Uint8Array(this.input.analyser.frequencyBinCount)),this.input.analyser.getByteFrequencyData(this.inputFrequencyData),this.inputFrequencyData}getOutputByteFrequencyData(){return this.connection instanceof ot?this.connection.getOutputByteFrequencyData()||new Uint8Array(1024):(this.outputFrequencyData!=null||(this.outputFrequencyData=new Uint8Array(this.output.analyser.frequencyBinCount)),this.output.analyser.getByteFrequencyData(this.outputFrequencyData),this.outputFrequencyData)}getInputVolume(){return this.calculateVolume(this.getInputByteFrequencyData())}getOutputVolume(){return this.calculateVolume(this.getOutputByteFrequencyData())}async changeInputDevice({sampleRate:e,format:t,preferHeadphonesForIosDevices:n,inputDeviceId:s}){try{if(this.connection instanceof Wn)try{return await this.input.setInputDevice(s),this.input}catch(a){console.warn("Failed to change device on existing input, recreating:",a)}this.connection instanceof ot&&await this.connection.setAudioInputDevice(s||""),await this.input.close();const r=await an.create({sampleRate:e??this.connection.inputFormat.sampleRate,format:t??this.connection.inputFormat.format,preferHeadphonesForIosDevices:n,inputDeviceId:s,workletPaths:this.options.workletPaths,libsampleratePath:this.options.libsampleratePath});return this.input=r,this.input.worklet.port.onmessage=this.onInputWorkletMessage,this.input}catch(r){throw console.error("Error changing input device",r),r}}async changeOutputDevice({sampleRate:e,format:t,outputDeviceId:n}){try{if(this.connection instanceof Wn)try{return await this.output.setOutputDevice(n),this.output}catch(r){console.warn("Failed to change device on existing output, recreating:",r)}this.connection instanceof ot&&await this.connection.setAudioOutputDevice(n||""),await this.output.close();const s=await Ci.create({sampleRate:e??this.connection.outputFormat.sampleRate,format:t??this.connection.outputFormat.format,outputDeviceId:n,workletPaths:this.options.workletPaths});return this.output=s,this.output}catch(s){throw console.error("Error changing output device",s),s}}}function df(i,e,t="https://api.elevenlabs.io"){const n={};return typeof e=="boolean"?n.feedback=e?"like":"dislike":(n.rating=e.rating,n.comment=e.comment),fetch(`${t}/v1/convai/conversations/${i}/feedback`,{method:"POST",body:JSON.stringify(n),headers:{"Content-Type":"application/json"}})}class nf{constructor(){this.listeners=new Map}on(e,t){this.listeners.has(e)||this.listeners.set(e,new Set);const n=this.listeners.get(e);n&&n.add(t)}off(e,t){const n=this.listeners.get(e);n&&n.delete(t)}emit(e,...t){const n=this.listeners.get(e);
255n&&n.forEach(s=>{s(...t)})}}var W;(function(i){i.SESSION_STARTED="session_started",i.PARTIAL_TRANSCRIPT="partial_transcript",i.COMMITTED_TRANSCRIPT="committed_transcript",i.COMMITTED_TRANSCRIPT_WITH_TIMESTAMPS="committed_transcript_with_timestamps",i.AUTH_ERROR="auth_error",i.ERROR="error",i.OPEN="open",i.CLOSE="close",i.QUOTA_EXCEEDED="quota_exceeded",i.COMMIT_THROTTLED="commit_throttled",i.TRANSCRIBER_ERROR="transcriber_error",i.UNACCEPTED_TERMS="unaccepted_terms",i.RATE_LIMITED="rate_limited",i.INPUT_ERROR="input_error",i.QUEUE_OVERFLOW="queue_overflow",i.RESOURCE_EXHAUSTED="resource_exhausted",i.SESSION_TIME_LIMIT_EXCEEDED="session_time_limit_exceeded",i.CHUNK_SIZE_EXCEEDED="chunk_size_exceeded",i.INSUFFICIENT_AUDIO_ACTIVITY="insufficient_audio_activity"})(W||(W={}));class sf{constructor(e){this.websocket=null,this.eventEmitter=new nf,this.currentSampleRate=16e3,this._audioCleanup=void 0,this.currentSampleRate=e}setWebSocket(e){this.websocket=e,this.websocket.readyState===WebSocket.OPEN?this.eventEmitter.emit(W.OPEN):this.websocket.addEventListener("open",()=>{this.eventEmitter.emit(W.OPEN)}),this.websocket.addEventListener("message",t=>{try{const n=JSON.parse(t.data);switch(n.message_type){case"session_started":this.eventEmitter.emit(W.SESSION_STARTED,n);break;case"partial_transcript":this.eventEmitter.emit(W.PARTIAL_TRANSCRIPT,n);break;case"committed_transcript":this.eventEmitter.emit(W.COMMITTED_TRANSCRIPT,n);break;case"committed_transcript_with_timestamps":this.eventEmitter.emit(W.COMMITTED_TRANSCRIPT_WITH_TIMESTAMPS,n);break;case"auth_error":this.eventEmitter.emit(W.AUTH_ERROR,n),this.eventEmitter.emit(W.ERROR,n);break;case"quota_exceeded":this.eventEmitter.emit(W.QUOTA_EXCEEDED,n),this.eventEmitter.emit(W.ERROR,n);break;case"commit_throttled":this.eventEmitter.emit(W.COMMIT_THROTTLED,n),this.eventEmitter.emit(W.ERROR,n);break;case"transcriber_error":this.eventEmitter.emit(W.TRANSCRIBER_ERROR,n),this.eventEmitter.emit(W.ERROR,n);break;case"unaccepted_terms":this.eventEmitter.emit(W.UNACCEPTED_TERMS,n),this.eventEmitter.emit(W.ERROR,n);break;case"rate_limited":this.eventEmitter.emit(W.RATE_LIMITED,n),this.eventEmitter.emit(W.ERROR,n);break;case"input_error":this.eventEmitter.emit(W.INPUT_ERROR,n),this.eventEmitter.emit(W.ERROR,n);break;case"queue_overflow":this.eventEmitter.emit(W.QUEUE_OVERFLOW,n),this.eventEmitter.emit(W.ERROR,n);break;case"resource_exhausted":this.eventEmitter.emit(W.RESOURCE_EXHAUSTED,n),this.eventEmitter.emit(W.ERROR,n);break;case"session_time_limit_exceeded":this.eventEmitter.emit(W.SESSION_TIME_LIMIT_EXCEEDED,n),this.eventEmitter.emit(W.ERROR,n);break;case"chunk_size_exceeded":this.eventEmitter.emit(W.CHUNK_SIZE_EXCEEDED,n),this.eventEmitter.emit(W.ERROR,n);break;case"insufficient_audio_activity":this.eventEmitter.emit(W.INSUFFICIENT_AUDIO_ACTIVITY,n),this.eventEmitter.emit(W.ERROR,n);break;case"error":this.eventEmitter.emit(W.ERROR,n);break;default:console.warn("Unknown message type:",n)}}catch(n){console.error("Failed to parse WebSocket message:",n,t.data),this.eventEmitter.emit(W.ERROR,new Error(`Failed to parse message: ${n}`))}}),this.websocket.addEventListener("error",t=>{console.error("WebSocket error:",t),this.eventEmitter.emit(W.ERROR,t)}),this.websocket.addEventListener("close",t=>{if(console.log(`WebSocket closed: code=${t.code}, reason="${t.reason}", wasClean=${t.wasClean}`),!t.wasClean||t.code!==1e3&&t.code!==1005){const n=`WebSocket closed unexpectedly: ${t.code} - ${t.reason||"No reason provided"}`;console.error(n),this.eventEmitter.emit(W.ERROR,new Error(n))}this.eventEmitter.emit(W.CLOSE,t)})}on(e,t){this.eventEmitter.on(e,t)}off(e,t){this.eventEmitter.off(e,t)}send(e){var t,n;if(!this.websocket||this.websocket.readyState!==WebSocket.OPEN)throw new Error("WebSocket is not connected");const s={message_type:"input_audio_chunk",audio_base_64:e.audioBase64,commit:(t=e.commit)!=null&&t,sample_rate:(n=e.sampleRate)!=null?n:this.currentSampleRate,previous_text:e.previousText};this.websocket.send(JSON.stringify(s))}commit(){if(!this.websocket||this.websocket.readyState!==WebSocket.OPEN)throw new Error("WebSocket is not connected");this.websocket.send(JSON.stringify({message_type:"input_audio_chunk",audio_base_64:"",commit:!0,sample_rate:this.currentSampleRate}))}close(){this._audioCleanup&&this._audioCleanup(),this.websocket&&this.websocket.close(1e3,"User ended session")}}const rf=Ar("scribeAudioProcessor",`/* 256 * Scribe Audio Processor for converting microphone audio to PCM16 format 257 * USED BY @elevenlabs/client 258 */ 259 260class ScribeAudioProcessor extends AudioWorkletProcessor { 261 constructor() { 262 super(); 263 this.buffer = []; 264 this.bufferSize = 4096; // Buffer size for optimal chunk transmission 265 } 266 267 process(inputs) { 268 const input = inputs[0]; 269 if (input.length > 0) { 270 const channelData = input[0]; // Get first channel (mono) 271 272 // Add incoming audio to buffer 273 this.buffer.push(...channelData); 274 275 // When buffer reaches threshold, convert and send 276 if (this.buffer.length >= this.bufferSize) { 277 const float32Array = new Float32Array(this.buffer); 278 const int16Array = new Int16Array(float32Array.length); 279 280 // Convert Float32 [-1, 1] to Int16 [-32768, 32767] 281 for (let i = 0; i < float32Array.length; i++) { 282 // Clamp the value to prevent overflow 283 const sample = Math.max(-1, Math.min(1, float32Array[i])); 284 // Scale to PCM16 range 285 int16Array[i] = sample < 0 ? sample * 32768 : sample * 32767; 286 } 287 288 // Send to main thread as transferable ArrayBuffer 289 this.port.postMessage( 290 { 291 audioData: int16Array.buffer 292 }, 293 [int16Array.buffer] 294 ); 295 296 // Clear buffer 297 this.buffer = []; 298 } 299 } 300 301 return true; // Continue processing 302 } 303} 304 305registerProcessor("scribeAudioProcessor", ScribeAudioProcessor); 306 307`);var lo,uo;(function(i){i.PCM_8000="pcm_8000",i.PCM_16000="pcm_16000",i.PCM_22050="pcm_22050",i.PCM_24000="pcm_24000",i.PCM_44100="pcm_44100",i.PCM_48000="pcm_48
307000",i.ULAW_8000="ulaw_8000"})(lo||(lo={})),(function(i){i.MANUAL="manual",i.VAD="vad"})(uo||(uo={}));class $t{static getWebSocketUri(e=$t.DEFAULT_BASE_URI){return`${e}/v1/speech-to-text/realtime`}static buildWebSocketUri(e){const t=$t.getWebSocketUri(e.baseUri),n=new URLSearchParams;if(n.append("model_id",e.modelId),n.append("token",e.token),e.commitStrategy!==void 0&&n.append("commit_strategy",e.commitStrategy),e.audioFormat!==void 0&&n.append("audio_format",e.audioFormat),e.vadSilenceThresholdSecs!==void 0){if(e.vadSilenceThresholdSecs<=.3||e.vadSilenceThresholdSecs>3)throw new Error("vadSilenceThresholdSecs must be between 0.3 and 3.0");n.append("vad_silence_threshold_secs",e.vadSilenceThresholdSecs.toString())}if(e.vadThreshold!==void 0){if(e.vadThreshold<.1||e.vadThreshold>.9)throw new Error("vadThreshold must be between 0.1 and 0.9");n.append("vad_threshold",e.vadThreshold.toString())}if(e.minSpeechDurationMs!==void 0){if(e.minSpeechDurationMs<=50||e.minSpeechDurationMs>2e3)throw new Error("minSpeechDurationMs must be between 50 and 2000");n.append("min_speech_duration_ms",e.minSpeechDurationMs.toString())}if(e.minSilenceDurationMs!==void 0){if(e.minSilenceDurationMs<=50||e.minSilenceDurationMs>2e3)throw new Error("minSilenceDurationMs must be between 50 and 2000");n.append("min_silence_duration_ms",e.minSilenceDurationMs.toString())}e.languageCode!==void 0&&n.append("language_code",e.languageCode),e.includeTimestamps!==void 0&&n.append("include_timestamps",e.includeTimestamps?"true":"false");const s=n.toString();return s?`${t}?${s}`:t}static connect(e){if(!e.modelId)throw new Error("modelId is required");const t=new sf("microphone"in e&&e.microphone?16e3:e.sampleRate),n=$t.buildWebSocketUri(e),s=new WebSocket(n);return"microphone"in e&&e.microphone&&s.addEventListener("open",()=>{$t.streamFromMicrophone(e,t)}),t.setWebSocket(s),t}static async streamFromMicrophone(e,t){try{var n,s,r,a,o,d,c,l,u;const h=await navigator.mediaDevices.getUserMedia({audio:{deviceId:(n=e.microphone)==null?void 0:n.deviceId,echoCancellation:(s=(r=e.microphone)==null?void 0:r.echoCancellation)==null||s,noiseSuppression:(a=(o=e.microphone)==null?void 0:o.noiseSuppression)==null||a,autoGainControl:(d=(c=e.microphone)==null?void 0:c.autoGainControl)==null||d,channelCount:(l=(u=e.microphone)==null?void 0:u.channelCount)!=null?l:1,sampleRate:{ideal:16e3}}}),p=new AudioContext({sampleRate:16e3});await rf(p.audioWorklet);const f=p.createMediaStreamSource(h),g=new AudioWorkletNode(p,"scribeAudioProcessor");g.port.onmessage=k=>{const{audioData:T}=k.data,S=new Uint8Array(T);let N="";for(let y=0;y<S.length;y++)N+=String.fromCharCode(S[y]);const v=btoa(N);t.send({audioBase64:v})},f.connect(g),p.state==="suspended"&&await p.resume(),t._audioCleanup=()=>{h.getTracks().forEach(k=>{k.stop()}),f.disconnect(),g.disconnect(),p.close()}}catch(h){throw console.error("Failed to start microphone streaming:",h),h}}}$t.DEFAULT_BASE_URI="wss://api.elevenlabs.io";class lf extends Vn{static startSession(e){return e.textOnly?Or.startSession(e):Nr.startSession(e)}}export{lo as AudioFormat,uo as CommitStrategy,lf as Conversation,an as Input,Ci as Output,sf as RealtimeConnection,W as RealtimeEvents,$t as Scribe,Or as TextConversation,Nr as VoiceConversation,ot as WebRTCConnection,Wn as WebSocketConnection,Nd as createConnection,df as postOverallFeedback};
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.