hanc-webrtc-widgets 2.6.12 → 2.6.13
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
|
@@ -44,8 +44,8 @@
|
|
|
44
44
|
* @license
|
|
45
45
|
* Copyright 2020 Google LLC
|
|
46
46
|
* SPDX-License-Identifier: BSD-3-Clause
|
|
47
|
-
*/const ga=()=>new Tg;let Tg=class{};const jo=new WeakMap,va=vg(class extends xg{render(i){return Nt}update(i,[e]){var n;const t=e!==this.Y;return t&&this.Y!==void 0&&this.rt(void 0),(t||this.lt!==this.ct)&&(this.Y=e,this.ht=(n=i.options)==null?void 0:n.host,this.rt(this.ct=i.element)),Nt}rt(i){if(this.isConnected||(i=void 0),typeof this.Y=="function"){const e=this.ht??globalThis;let t=jo.get(e);t===void 0&&(t=new WeakMap,jo.set(e,t)),t.get(this.Y)!==void 0&&this.Y.call(this.ht,void 0),t.set(this.Y,i),i!==void 0&&this.Y.call(this.ht,i)}else this.Y.value=i}get lt(){var i,e;return typeof this.Y=="function"?(i=jo.get(this.ht??globalThis))==null?void 0:i.get(this.Y):(e=this.Y)==null?void 0:e.value}disconnected(){this.lt===this.ct&&this.rt(void 0)}reconnected(){this.rt(this.ct)}});function Cg(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 Eg=Object.defineProperty,Mg=(i,e,t)=>e in i?Eg(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,bu=(i,e,t)=>Mg(i,typeof e!="symbol"?e+"":e,t);class an{constructor(){bu(this,"_locking"),bu(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 Rt(i,e){if(!i)throw new Error(e)}const wg=34028234663852886e22,Ag=-34028234663852886e22,Rg=4294967295,Pg=2147483647,kg=-2147483648;function ba(i){if(typeof i!="number")throw new Error("invalid int 32: "+typeof i);if(!Number.isInteger(i)||i>Pg||i<kg)throw new Error("invalid int 32: "+i)}function Xo(i){if(typeof i!="number")throw new Error("invalid uint 32: "+typeof i);if(!Number.isInteger(i)||i>Rg||i<0)throw new Error("invalid uint 32: "+i)}function yu(i){if(typeof i!="number")throw new Error("invalid float 32: "+typeof i);if(Number.isFinite(i)&&(i>wg||i<Ag))throw new Error("invalid float 32: "+i)}const _u=Symbol("@bufbuild/protobuf/enum-type");function Ig(i){const e=i[_u];return Rt(e,"missing enum type on enum object"),e}function Su(i,e,t,n){i[_u]=xu(e,t.map(s=>({no:s.no,name:s.name,localName:i[s.no]})))}function xu(i,e,t){const n=Object.create(null),s=Object.create(null),r=[];for(const a of e){const o=Tu(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 Dg(i,e,t){const n={};for(const s of e){const r=Tu(s);n[r.localName]=r.no,n[r.no]=r.localName}return Su(n,i,e),n}function Tu(i){return"localName"in i?i:Object.assign(Object.assign({},i),{localName:i.name})}class Yo{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==null?void 0:e.prettySpaces)!==null&&t!==void 0?t:0)}toJSON(){return this.toJson({emitDefaultValues:!0})}getType(){return Object.getPrototypeOf(this).constructor}}function Lg(i,e,t,n){var s;const r=(s=n==null?void 0: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 Yo),Object.assign(a,{runtime:i,typeName:e,fields:i.util.newFieldList(t),fromBinary(o,c){return new a().fromBinary(o,c)},fromJson(o,c){return new a().fromJson(o,c)},fromJsonString(o,c){return new a().fromJsonString(o,c)},equals(o,c){return i.util.equals(a,o,c)}}),a}function Ug(){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 Ko(i,e,t){for(let r=0;r<28;r=r+7){const a=i>>>r,o=!(!(a>>>7)&&e==0),c=(o?a|128:a)&255;if(t.push(c),!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),c=(o?a|128:a)&255;if(t.push(c),!o)return}t.push(e>>>31&1)}}const ya=4294967296;function Cu(i){const e=i[0]==="-";e&&(i=i.slice(1));const t=1e6;let n=0,s=0;function r(a,o){const c=Number(i.slice(a,o));s*=t,n=n*t+c,n>=ya&&(s=s+(n/ya|0),n=n%ya)}return r(-24,-18),r(-18,-12),r(-12,-6),r(-6),e?Mu(n,s):Jo(n,s)}function Ng(i,e){let t=Jo(i,e);const n=t.hi&2147483648;n&&(t=Mu(t.lo,t.hi));const s=Eu(t.lo,t.hi);return n?"-"+s:s}function Eu(i,e){if({lo:i,hi:e}=Og(i,e),e<=2097151)return String(ya*e+i);const t=i&16777215,n=(i>>>24|e<<8)&16777215,s=e>>16&65535;let r=t+n*6777216+s*6710656,a=n+s*8147497,o=s*2;const c=1e7;return r>=c&&(a+=Math.floor(r/c),r%=c),a>=c&&(o+=Math.floor(a/c),a%=c),o.toString()+wu(a)+wu(r)}function Og(i,e){return{lo:i>>>0,hi:e>>>0}}function Jo(i,e){return{lo:i|0,hi:e|0}}function Mu(i,e){return e=~e,i?i=~i+1:e+=1,Jo(i,e)}const wu=i=>{const e=String(i);return"0000000".slice(e.length)+e};function Au(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 Fg(){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 Bg(){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 process.env!="object"||process.env.BUF_BIGINT_DISABLE!=="1")){const s=BigInt("-9223372036854775808"),r=BigInt("9223372036854775807"),a=BigInt("0"),o=BigInt("18446744073709551615");return{zero:BigInt(0),supported:!0,parse(c){const l=typeof c=="bigint"?c:BigInt(c);if(l>r||l<s)throw new Error("int64 invalid: ".concat(c));return l},uParse(c){const l=typeof c=="bigint"?c:BigInt(c);if(l>o||l<a)throw new Error("uint64 invalid: ".concat(c));return l},enc(c){return i.setBigInt64(0,this.parse(c),!0),{lo:i.getInt32(0,!0),hi:i.getInt32(4,!0)}},uEnc(c){return i.setBigInt64(0,this.uParse(c),!0),{lo:i.getInt32(0,!0),hi:i.getInt32(4,!0)}},dec(c,l){return i.setInt32(0,c,!0),i.setInt32(4,l,!0),i.getBigInt64(0,!0)},uDec(c,l){return i.setInt32(0,c,!0),i.setInt32(4,l,!0),i.getBigUint64(0,!0)}}}const t=s=>Rt(/^-?[0-9]+$/.test(s),"int64 invalid: ".concat(s)),n=s=>Rt(/^[0-9]+$/.test(s),"uint64 invalid: ".concat(s));return{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),Cu(s)},uEnc(s){return typeof s!="string"&&(s=s.toString()),n(s),Cu(s)},dec(s,r){return Ng(s,r)},uDec(s,r){return Eu(s,r)}}}const At=Bg();var Z;(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"})(Z||(Z={}));var Ni;(function(i){i[i.BIGINT=0]="BIGINT",i[i.STRING=1]="STRING"})(Ni||(Ni={}));function Oi(i,e,t){if(e===t)return!0;if(i==Z.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 Z.UINT64:case Z.FIXED64:case Z.INT64:case Z.SFIXED64:case Z.SINT64:return e==t}return!1}function Ps(i,e){switch(i){case Z.BOOL:return!1;case Z.UINT64:case Z.FIXED64:case Z.INT64:case Z.SFIXED64:case Z.SINT64:return e==0?At.zero:"0";case Z.DOUBLE:case Z.FLOAT:return 0;case Z.BYTES:return new Uint8Array(0);case Z.STRING:return"";default:return 0}}function Ru(i,e){switch(i){case Z.BOOL:return e===!1;case Z.STRING:return e==="";case Z.BYTES:return e instanceof Uint8Array&&!e.byteLength;default:return e==0}}var Lt;(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"})(Lt||(Lt={}));class zg{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;s++)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(Xo(e);e>127;)this.buf.push(e&127|128),e=e>>>7;return this.buf.push(e),this}int32(e){return ba(e),Au(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){yu(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){Xo(e);let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!0),this.raw(t)}sfixed32(e){ba(e);let t=new Uint8Array(4);return new DataView(t.buffer).setInt32(0,e,!0),this.raw(t)}sint32(e){return ba(e),e=(e<<1^e>>31)>>>0,Au(e,this.buf),this}sfixed64(e){let t=new Uint8Array(8),n=new DataView(t.buffer),s=At.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=At.uEnc(e);return n.setInt32(0,s.lo,!0),n.setInt32(4,s.hi,!0),this.raw(t)}int64(e){let t=At.enc(e);return Ko(t.lo,t.hi,this.buf),this}sint64(e){let t=At.enc(e),n=t.hi>>31,s=t.lo<<1^n,r=(t.hi<<1|t.lo>>>31)^n;return Ko(s,r,this.buf),this}uint64(e){let t=At.uEnc(e);return Ko(t.lo,t.hi,this.buf),this}}class Vg{constructor(e,t){this.varint64=Ug,this.uint32=Fg,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 Lt.Varint:for(;this.buf[this.pos++]&128;);break;case Lt.Bit64:this.pos+=4;case Lt.Bit32:this.pos+=4;break;case Lt.LengthDelimited:let s=this.uint32();this.pos+=s;break;case Lt.StartGroup:for(;;){const[r,a]=this.tag();if(a===Lt.EndGroup){if(t!==void 0&&r!==t)throw new Error("invalid end group tag");break}this.skip(a,r)}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 At.dec(...this.varint64())}uint64(){return At.uDec(...this.varint64())}sint64(){let[e,t]=this.varint64(),n=-(e&1);return e=(e>>>1|(t&1)<<31)^n,t=t>>>1^n,At.dec(e,t)}bool(){let[e,t]=this.varint64();return e!==0||t!==0}fixed32(){return this.view.getUint32((this.pos+=4)-4,!0)}sfixed32(){return this.view.getInt32((this.pos+=4)-4,!0)}fixed64(){return At.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return At.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 Gg(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 Pu(i){const e=i.field.localName,t=Object.create(null);return t[e]=Hg(i),[t,()=>t[e]]}function Hg(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 Ps(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 Wg(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 ui="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),_a=[];for(let i=0;i<ui.length;i++)_a[ui[i].charCodeAt(0)]=i;_a[45]=ui.indexOf("+"),_a[95]=ui.indexOf("/");const ku={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=_a[i.charCodeAt(o)],r===void 0)switch(i[o]){case"=":s=0;case`
|
|
48
|
-
`: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+=ui[n>>2],s=(n&3)<<4,t=1;break;case 1:e+=ui[s|n>>4],s=(n&15)<<2,t=2;break;case 2:e+=ui[s|n>>6],e+=ui[n&63],t=0;break}return t&&(e+=ui[s],e+="=",t==1&&(e+="=")),e}};function qg(i,e,t){Du(e,i);const n=e.runtime.bin.makeReadOptions(t),s=Wg(i.getType().runtime.bin.listUnknownFields(i),e.field),[r,a]=Pu(e);for(const o of s)e.runtime.bin.readField(r,n.readerFactory(o.data),e.field,o.wireType,n);return a()}function $g(i,e,t,n){Du(e,i);const s=e.runtime.bin.makeReadOptions(n),r=e.runtime.bin.makeWriteOptions(n);if(Iu(i,e)){const l=i.getType().runtime.bin.listUnknownFields(i).filter(d=>d.no!=e.field.no);i.getType().runtime.bin.discardUnknownFields(i);for(const d of l)i.getType().runtime.bin.onUnknownField(i,d.no,d.wireType,d.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 c=s.readerFactory(a.finish());for(;c.pos<c.len;){const[l,d]=c.tag(),u=c.skip(d,l);i.getType().runtime.bin.onUnknownField(i,l,d,u)}}function Iu(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 Du(i,e){Rt(i.extendee.typeName==e.getType().typeName,"extension ".concat(i.typeName," can only be applied to message ").concat(i.extendee.typeName))}function Lu(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:!Ru(i.T,e[t]);case"message":return e[t]!==void 0;case"map":return Object.keys(e[t]).length>0}}function Uu(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?Ps(i.T,i.L):void 0;break;case"message":e[t]=void 0;break}}function hi(i,e){if(i===null||typeof i!="object"||!Object.getOwnPropertyNames(Yo.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 Nu(i,e){return hi(e)||!i.fieldWrapper?e:i.fieldWrapper.wrapField(e)}Z.DOUBLE,Z.FLOAT,Z.INT64,Z.UINT64,Z.INT32,Z.UINT32,Z.BOOL,Z.STRING,Z.BYTES;const Ou={ignoreUnknownFields:!1},Fu={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0};function jg(i){return i?Object.assign(Object.assign({},Ou),i):Ou}function Xg(i){return i?Object.assign(Object.assign({},Fu),i):Fu}const Sa=Symbol(),xa=Symbol();function Yg(){return{makeReadOptions:jg,makeWriteOptions:Xg,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($n(e)));n=n??new i;const s=new Map,r=t.typeRegistry;for(const[a,o]of Object.entries(e)){const c=i.fields.findJsonName(a);if(c){if(c.oneof){if(o===null&&c.kind=="scalar")continue;const l=s.get(c.oneof);if(l!==void 0)throw new Error("cannot decode message ".concat(i.typeName,' from JSON: multiple keys for oneof "').concat(c.oneof.name,'" present: "').concat(l,'", "').concat(a,'"'));s.set(c.oneof,a)}Bu(n,o,c,t,i)}else{let l=!1;if(r!=null&&r.findExtension&&a.startsWith("[")&&a.endsWith("]")){const d=r.findExtension(a.substring(1,a.length-1));if(d&&d.extendee.typeName==i.typeName){l=!0;const[u,h]=Pu(d);Bu(u,o,d.field,t,d),$g(n,d,h(),t)}}if(!l&&!t.ignoreUnknownFields)throw new Error("cannot decode message ".concat(i.typeName,' from JSON: key "').concat(a,'" is unknown'))}}return n},writeMessage(i,e){const t=i.getType(),n={};let s;try{for(s of t.fields.byNumber()){if(!Lu(s,i)){if(s.req)throw"required field not set";if(!e.emitDefaultValues||!Jg(s))continue}const a=s.oneof?i[s.oneof.localName].value:i[s.localName],o=zu(s,a,e);o!==void 0&&(n[e.useProtoFieldName?s.name:s.jsonName]=o)}const r=e.typeRegistry;if(r!=null&&r.findExtensionFor)for(const a of t.runtime.bin.listUnknownFields(i)){const o=r.findExtensionFor(t.typeName,a.no);if(o&&Iu(i,o)){const c=qg(i,o,e),l=zu(o.field,c,e);l!==void 0&&(n[o.field.jsonName]=l)}}}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},readScalar(i,e,t){return wr(i,e,t??Ni.BIGINT,!0)},writeScalar(i,e,t){if(e!==void 0&&(t||Ru(i,e)))return Ta(i,e)},debug:$n}}function $n(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 Bu(i,e,t,n,s){let r=t.localName;if(t.repeated){if(Rt(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($n(e)));const a=i[r];for(const o of e){if(o===null)throw new Error("cannot decode field ".concat(s.typeName,".").concat(t.name," from JSON: ").concat($n(o)));switch(t.kind){case"message":a.push(t.T.fromJson(o,n));break;case"enum":const c=Zo(t.T,o,n.ignoreUnknownFields,!0);c!==xa&&a.push(c);break;case"scalar":try{a.push(wr(t.T,o,t.L,!0))}catch(l){let d="cannot decode field ".concat(s.typeName,".").concat(t.name," from JSON: ").concat($n(o));throw l instanceof Error&&l.message.length>0&&(d+=": ".concat(l.message)),new Error(d)}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($n(e)));const a=i[r];for(const[o,c]of Object.entries(e)){if(c===null)throw new Error("cannot decode field ".concat(s.typeName,".").concat(t.name," from JSON: map value null"));let l;try{l=Kg(t.K,o)}catch(d){let u="cannot decode map key for field ".concat(s.typeName,".").concat(t.name," from JSON: ").concat($n(e));throw d instanceof Error&&d.message.length>0&&(u+=": ".concat(d.message)),new Error(u)}switch(t.V.kind){case"message":a[l]=t.V.T.fromJson(c,n);break;case"enum":const d=Zo(t.V.T,c,n.ignoreUnknownFields,!0);d!==xa&&(a[l]=d);break;case"scalar":try{a[l]=wr(t.V.T,c,Ni.BIGINT,!0)}catch(u){let h="cannot decode map value for field ".concat(s.typeName,".").concat(t.name," from JSON: ").concat($n(e));throw u instanceof Error&&u.message.length>0&&(h+=": ".concat(u.message)),new Error(h)}break}}}else switch(t.oneof&&(i=i[t.oneof.localName]={case:r},r="value"),t.kind){case"message":const a=t.T;if(e===null&&a.typeName!="google.protobuf.Value")return;let o=i[r];hi(o)?o.fromJson(e,n):(i[r]=o=a.fromJson(e,n),a.fieldWrapper&&!t.oneof&&(i[r]=a.fieldWrapper.unwrapField(o)));break;case"enum":const c=Zo(t.T,e,n.ignoreUnknownFields,!1);switch(c){case Sa:Uu(t,i);break;case xa:break;default:i[r]=c;break}break;case"scalar":try{const l=wr(t.T,e,t.L,!1);switch(l){case Sa:Uu(t,i);break;default:i[r]=l;break}}catch(l){let d="cannot decode field ".concat(s.typeName,".").concat(t.name," from JSON: ").concat($n(e));throw l instanceof Error&&l.message.length>0&&(d+=": ".concat(l.message)),new Error(d)}break}}function Kg(i,e){if(i===Z.BOOL)switch(e){case"true":e=!0;break;case"false":e=!1;break}return wr(i,e,Ni.BIGINT,!0).toString()}function wr(i,e,t,n){if(e===null)return n?Ps(i,t):Sa;switch(i){case Z.DOUBLE:case Z.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==Z.FLOAT&&yu(s),s;case Z.INT32:case Z.FIXED32:case Z.SFIXED32:case Z.SINT32:case Z.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==Z.UINT32||i==Z.FIXED32?Xo(r):ba(r),r;case Z.INT64:case Z.SFIXED64:case Z.SINT64:if(typeof e!="number"&&typeof e!="string")break;const a=At.parse(e);return t?a.toString():a;case Z.FIXED64:case Z.UINT64:if(typeof e!="number"&&typeof e!="string")break;const o=At.uParse(e);return t?o.toString():o;case Z.BOOL:if(typeof e!="boolean")break;return e;case Z.STRING:if(typeof e!="string")break;try{encodeURIComponent(e)}catch{throw new Error("invalid UTF8")}return e;case Z.BYTES:if(e==="")return new Uint8Array(0);if(typeof e!="string")break;return ku.dec(e)}throw new Error}function Zo(i,e,t,n){if(e===null)return i.typeName=="google.protobuf.NullValue"?0:n?i.values[0].no:Sa;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 xa;break}throw new Error("cannot decode enum ".concat(i.typeName," from JSON: ").concat($n(e)))}function Jg(i){return i.repeated||i.kind=="map"?!0:!(i.oneof||i.kind=="message"||i.opt||i.req)}function zu(i,e,t){if(i.kind=="map"){Rt(typeof e=="object"&&e!=null);const n={},s=Object.entries(e);switch(i.V.kind){case"scalar":for(const[a,o]of s)n[a.toString()]=Ta(i.V.T,o);break;case"message":for(const[a,o]of s)n[a.toString()]=o.toJson(t);break;case"enum":const r=i.V.T;for(const[a,o]of s)n[a.toString()]=Qo(r,o,t.enumAsInteger);break}return t.emitDefaultValues||s.length>0?n:void 0}if(i.repeated){Rt(Array.isArray(e));const n=[];switch(i.kind){case"scalar":for(let s=0;s<e.length;s++)n.push(Ta(i.T,e[s]));break;case"enum":for(let s=0;s<e.length;s++)n.push(Qo(i.T,e[s],t.enumAsInteger));break;case"message":for(let s=0;s<e.length;s++)n.push(e[s].toJson(t));break}return t.emitDefaultValues||n.length>0?n:void 0}switch(i.kind){case"scalar":return Ta(i.T,e);case"enum":return Qo(i.T,e,t.enumAsInteger);case"message":return Nu(i.T,e).toJson(t)}}function Qo(i,e,t){var n;if(Rt(typeof e=="number"),i.typeName=="google.protobuf.NullValue")return null;if(t)return e;const s=i.findNumber(e);return(n=s==null?void 0:s.name)!==null&&n!==void 0?n:e}function Ta(i,e){switch(i){case Z.INT32:case Z.SFIXED32:case Z.SINT32:case Z.FIXED32:case Z.UINT32:return Rt(typeof e=="number"),e;case Z.FLOAT:case Z.DOUBLE:return Rt(typeof e=="number"),Number.isNaN(e)?"NaN":e===Number.POSITIVE_INFINITY?"Infinity":e===Number.NEGATIVE_INFINITY?"-Infinity":e;case Z.STRING:return Rt(typeof e=="string"),e;case Z.BOOL:return Rt(typeof e=="boolean"),e;case Z.UINT64:case Z.FIXED64:case Z.INT64:case Z.SFIXED64:case Z.SINT64:return Rt(typeof e=="bigint"||typeof e=="string"||typeof e=="number"),e.toString();case Z.BYTES:return Rt(e instanceof Uint8Array),ku.enc(e)}}const ks=Symbol("@bufbuild/protobuf/unknown-fields"),Vu={readUnknownFields:!0,readerFactory:i=>new Vg(i)},Gu={writeUnknownFields:!0,writerFactory:()=>new zg};function Zg(i){return i?Object.assign(Object.assign({},Vu),i):Vu}function Qg(i){return i?Object.assign(Object.assign({},Gu),i):Gu}function ev(){return{makeReadOptions:Zg,makeWriteOptions:Qg,listUnknownFields(i){var e;return(e=i[ks])!==null&&e!==void 0?e:[]},discardUnknownFields(i){delete i[ks]},writeUnknownFields(i,e){const n=i[ks];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[ks])||(s[ks]=[]),s[ks].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,c;for(;e.pos<a&&([o,c]=e.tag(),!(s===!0&&c==Lt.EndGroup));){const l=r.fields.find(o);if(!l){const d=e.skip(c,o);n.readUnknownFields&&this.onUnknownField(i,o,c,d);continue}Hu(i,e,l,c,n)}if(s&&(c!=Lt.EndGroup||o!==t))throw new Error("invalid end group tag")},readField:Hu,writeMessage(i,e,t){const n=i.getType();for(const s of n.fields.byNumber()){if(!Lu(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];Wu(s,r,e,t)}return t.writeUnknownFields&&this.writeUnknownFields(i,e),e},writeField(i,e,t,n){e!==void 0&&Wu(i,e,t,n)}}}function Hu(i,e,t,n,s){let{repeated:r,localName:a}=t;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"?Z.INT32:t.T;let c=Ea;if(t.kind=="scalar"&&t.L>0&&(c=nv),r){let h=i[a];if(n==Lt.LengthDelimited&&o!=Z.STRING&&o!=Z.BYTES){let g=e.uint32()+e.pos;for(;e.pos<g;)h.push(c(e,o))}else h.push(c(e,o))}else i[a]=c(e,o);break;case"message":const l=t.T;r?i[a].push(Ca(e,new l,s,t)):hi(i[a])?Ca(e,i[a],s,t):(i[a]=Ca(e,new l,s,t),l.fieldWrapper&&!t.oneof&&!t.repeated&&(i[a]=l.fieldWrapper.unwrapField(i[a])));break;case"map":let[d,u]=tv(t,e,s);i[a][d]=u;break}}function Ca(i,e,t,n){const s=e.getType().runtime.bin,r=n==null?void 0:n.delimited;return s.readMessage(e,i,r?n.no:i.uint32(),t,r),e}function tv(i,e,t){const n=e.uint32(),s=e.pos+n;let r,a;for(;e.pos<s;){const[o]=e.tag();switch(o){case 1:r=Ea(e,i.K);break;case 2:switch(i.V.kind){case"scalar":a=Ea(e,i.V.T);break;case"enum":a=e.int32();break;case"message":a=Ca(e,new i.V.T,t,void 0);break}break}}if(r===void 0&&(r=Ps(i.K,Ni.BIGINT)),typeof r!="string"&&typeof r!="number"&&(r=r.toString()),a===void 0)switch(i.V.kind){case"scalar":a=Ps(i.V.T,Ni.BIGINT);break;case"enum":a=i.V.T.values[0].no;break;case"message":a=new i.V.T;break}return[r,a]}function nv(i,e){const t=Ea(i,e);return typeof t=="bigint"?t.toString():t}function Ea(i,e){switch(e){case Z.STRING:return i.string();case Z.BOOL:return i.bool();case Z.DOUBLE:return i.double();case Z.FLOAT:return i.float();case Z.INT32:return i.int32();case Z.INT64:return i.int64();case Z.UINT64:return i.uint64();case Z.FIXED64:return i.fixed64();case Z.BYTES:return i.bytes();case Z.FIXED32:return i.fixed32();case Z.SFIXED32:return i.sfixed32();case Z.SFIXED64:return i.sfixed64();case Z.SINT64:return i.sint64();case Z.UINT32:return i.uint32();case Z.SINT32:return i.sint32()}}function Wu(i,e,t,n){Rt(e!==void 0);const s=i.repeated;switch(i.kind){case"scalar":case"enum":let r=i.kind=="enum"?Z.INT32:i.T;if(s)if(Rt(Array.isArray(e)),i.packed)sv(t,r,i.no,e);else for(const a of e)Ar(t,r,i.no,a);else Ar(t,r,i.no,e);break;case"message":if(s){Rt(Array.isArray(e));for(const a of e)qu(t,n,i,a)}else qu(t,n,i,e);break;case"map":Rt(typeof e=="object"&&e!=null);for(const[a,o]of Object.entries(e))iv(t,n,i,a,o);break}}function iv(i,e,t,n,s){i.tag(t.no,Lt.LengthDelimited),i.fork();let r=n;switch(t.K){case Z.INT32:case Z.FIXED32:case Z.UINT32:case Z.SFIXED32:case Z.SINT32:r=Number.parseInt(n);break;case Z.BOOL:Rt(n=="true"||n=="false"),r=n=="true";break}switch(Ar(i,t.K,1,r),t.V.kind){case"scalar":Ar(i,t.V.T,2,s);break;case"enum":Ar(i,Z.INT32,2,s);break;case"message":Rt(s!==void 0),i.tag(2,Lt.LengthDelimited).bytes(s.toBinary(e));break}i.join()}function qu(i,e,t,n){const s=Nu(t.T,n);t.delimited?i.tag(t.no,Lt.StartGroup).raw(s.toBinary(e)).tag(t.no,Lt.EndGroup):i.tag(t.no,Lt.LengthDelimited).bytes(s.toBinary(e))}function Ar(i,e,t,n){Rt(n!==void 0);let[s,r]=$u(e);i.tag(t,s)[r](n)}function sv(i,e,t,n){if(!n.length)return;i.tag(t,Lt.LengthDelimited).fork();let[,s]=$u(e);for(let r=0;r<n.length;r++)i[s](n[r]);i.join()}function $u(i){let e=Lt.Varint;switch(i){case Z.BYTES:case Z.STRING:e=Lt.LengthDelimited;break;case Z.DOUBLE:case Z.FIXED64:case Z.SFIXED64:e=Lt.Bit64;break;case Z.FIXED32:case Z.SFIXED32:case Z.FLOAT:e=Lt.Bit32;break}const t=Z[i].toLowerCase();return[e,t]}function rv(){return{setEnumType:Su,initPartial(i,e){if(i===void 0)return;const t=e.getType();for(const n of t.fields.byMember()){const s=n.localName,r=e,a=i;if(a[s]!=null)switch(n.kind){case"oneof":const o=a[s].case;if(o===void 0)continue;const c=n.findField(o);let l=a[s].value;c&&c.kind=="message"&&!hi(l,c.T)?l=new c.T(l):c&&c.kind==="scalar"&&c.T===Z.BYTES&&(l=Rr(l)),r[s]={case:o,value:l};break;case"scalar":case"enum":let d=a[s];n.T===Z.BYTES&&(d=n.repeated?d.map(Rr):Rr(d)),r[s]=d;break;case"map":switch(n.V.kind){case"scalar":case"enum":if(n.V.T===Z.BYTES)for(const[f,g]of Object.entries(a[s]))r[s][f]=Rr(g);else Object.assign(r[s],a[s]);break;case"message":const h=n.V.T;for(const f of Object.keys(a[s])){let g=a[s][f];h.fieldWrapper||(g=new h(g)),r[s][f]=g}break}break;case"message":const u=n.T;if(n.repeated)r[s]=a[s].map(h=>hi(h,u)?h:new u(h));else{const h=a[s];u.fieldWrapper?u.typeName==="google.protobuf.BytesValue"?r[s]=Rr(h):r[s]=h:r[s]=hi(h,u)?h:new u(h)}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)=>Oi(n.T,a,r[o]));case"enum":return s.every((a,o)=>Oi(Z.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&&!hi(a)&&(a=n.T.fieldWrapper.wrapField(a)),o!==void 0&&!hi(o)&&(o=n.T.fieldWrapper.wrapField(o))),n.T.equals(a,o);case"enum":return Oi(Z.INT32,s,r);case"scalar":return Oi(n.T,s,r);case"oneof":if(s.case!==r.case)return!1;const c=n.findField(s.case);if(c===void 0)return!0;switch(c.kind){case"message":return c.T.equals(s.value,r.value);case"enum":return Oi(Z.INT32,s.value,r.value);case"scalar":return Oi(c.T,s.value,r.value)}throw new Error("oneof cannot contain ".concat(c.kind));case"map":const l=Object.keys(s).concat(Object.keys(r));switch(n.V.kind){case"message":const d=n.V.T;return l.every(h=>d.equals(s[h],r[h]));case"enum":return l.every(h=>Oi(Z.INT32,s[h],r[h]));case"scalar":const u=n.V.T;return l.every(h=>Oi(u,s[h],r[h]))}break}})},clone(i){const e=i.getType(),t=new e,n=t;for(const s of e.fields.byMember()){const r=i[s.localName];let a;if(s.repeated)a=r.map(Ma);else if(s.kind=="map"){a=n[s.localName];for(const[o,c]of Object.entries(r))a[o]=Ma(c)}else s.kind=="oneof"?a=s.findField(r.case)?{case:r.case,value:Ma(r.value)}:{case:void 0}:a=Ma(r);n[s.localName]=a}for(const s of e.runtime.bin.listUnknownFields(i))e.runtime.bin.onUnknownField(n,s.no,s.wireType,s.data);return t}}}function Ma(i){if(i===void 0)return i;if(hi(i))return i.clone();if(i instanceof Uint8Array){const e=new Uint8Array(i.byteLength);return e.set(i),e}return i}function Rr(i){return i instanceof Uint8Array?i:new Uint8Array(i)}function av(i,e,t){return{syntax:i,json:Yg(),bin:ev(),util:Object.assign(Object.assign({},rv()),{newFieldList:e,initFields:t}),makeMessageType(n,s,r){return Lg(this,n,s,r)},makeEnum:Dg,makeEnumType:xu,getEnumType:Ig,makeExtension(n,s,r){return Gg(this,n,s,r)}}}class ov{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 ju(i,e){const t=Xu(i);return e?t:fv(hv(t))}function cv(i){return ju(i,!1)}const lv=Xu;function Xu(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 dv=new Set(["constructor","toString","toJSON","valueOf"]),uv=new Set(["getType","clone","equals","fromBinary","fromJson","fromJsonString","toBinary","toJson","toJsonString","toObject"]),Yu=i=>"".concat(i,"$"),hv=i=>uv.has(i)?Yu(i):i,fv=i=>dv.has(i)?Yu(i):i;class pv{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=cv(e)}addField(e){Rt(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 mv(i,e){var t,n,s,r,a,o;const c=[];let l;for(const d of typeof i=="function"?i():i){const u=d;if(u.localName=ju(d.name,d.oneof!==void 0),u.jsonName=(t=d.jsonName)!==null&&t!==void 0?t:lv(d.name),u.repeated=(n=d.repeated)!==null&&n!==void 0?n:!1,d.kind=="scalar"&&(u.L=(s=d.L)!==null&&s!==void 0?s:Ni.BIGINT),u.delimited=(r=d.delimited)!==null&&r!==void 0?r:!1,u.req=(a=d.req)!==null&&a!==void 0?a:!1,u.opt=(o=d.opt)!==null&&o!==void 0?o:!1,d.packed===void 0&&(u.packed=d.kind=="enum"||d.kind=="scalar"&&d.T!=Z.BYTES&&d.T!=Z.STRING),d.oneof!==void 0){const h=typeof d.oneof=="string"?d.oneof:d.oneof.name;(!l||l.name!=h)&&(l=new pv(h)),u.oneof=l,l.addField(u)}c.push(u)}return c}const G=av("proto3",i=>new ov(i,e=>mv(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]=Ps(e.T,e.L);break}}});class on extends Yo{constructor(e){super(),this.seconds=At.zero,this.nanos=0,G.util.initPartial(e,this)}fromJson(e,t){if(typeof e!="string")throw new Error("cannot decode google.protobuf.Timestamp from JSON: ".concat(G.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=At.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 on.fromDate(new Date)}static fromDate(e){const t=e.getTime();return new on({seconds:At.parse(Math.floor(t/1e3)),nanos:t%1e3*1e6})}static fromBinary(e,t){return new on().fromBinary(e,t)}static fromJson(e,t){return new on().fromJson(e,t)}static fromJsonString(e,t){return new on().fromJsonString(e,t)}static equals(e,t){return G.util.equals(on,e,t)}}on.runtime=G,on.typeName="google.protobuf.Timestamp",on.fields=G.util.newFieldList(()=>[{no:1,name:"seconds",kind:"scalar",T:3},{no:2,name:"nanos",kind:"scalar",T:5}]);const gv=G.makeMessageType("livekit.MetricsBatch",()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:on},{no:3,name:"str_data",kind:"scalar",T:9,repeated:!0},{no:4,name:"time_series",kind:"message",T:vv,repeated:!0},{no:5,name:"events",kind:"message",T:yv,repeated:!0}]),vv=G.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:bv,repeated:!0},{no:5,name:"rid",kind:"scalar",T:13}]),bv=G.makeMessageType("livekit.MetricSample",()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:on},{no:3,name:"value",kind:"scalar",T:2}]),yv=G.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:on},{no:7,name:"normalized_end_timestamp",kind:"message",T:on,opt:!0},{no:8,name:"metadata",kind:"scalar",T:9},{no:9,name:"rid",kind:"scalar",T:13}]),Ku=G.makeEnum("livekit.BackupCodecPolicy",[{no:0,name:"PREFER_REGRESSION"},{no:1,name:"SIMULCAST"},{no:2,name:"REGRESSION"}]),kn=G.makeEnum("livekit.TrackType",[{no:0,name:"AUDIO"},{no:1,name:"VIDEO"},{no:2,name:"DATA"}]),Ot=G.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"}]),ec=G.makeEnum("livekit.VideoQuality",[{no:0,name:"LOW"},{no:1,name:"MEDIUM"},{no:2,name:"HIGH"},{no:3,name:"OFF"}]),Pr=G.makeEnum("livekit.ConnectionQuality",[{no:0,name:"POOR"},{no:1,name:"GOOD"},{no:2,name:"EXCELLENT"},{no:3,name:"LOST"}]),kr=G.makeEnum("livekit.ClientConfigSetting",[{no:0,name:"UNSET"},{no:1,name:"DISABLED"},{no:2,name:"ENABLED"}]),In=G.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"}]),Is=G.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"}]),_v=G.makeEnum("livekit.SubscriptionError",[{no:0,name:"SE_UNKNOWN"},{no:1,name:"SE_CODEC_UNSUPPORTED"},{no:2,name:"SE_TRACK_NOTFOUND"}]),qt=G.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"}]),wa=G.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:Aa,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:dh}]),Aa=G.makeMessageType("livekit.Codec",()=>[{no:1,name:"mime",kind:"scalar",T:9},{no:2,name:"fmtp_line",kind:"scalar",T:9}]),Sv=G.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:G.getEnumType(Ot),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}]),ss=G.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:G.getEnumType(Ds)},{no:4,name:"tracks",kind:"message",T:Ls,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:Sv},{no:12,name:"region",kind:"scalar",T:9},{no:13,name:"is_publisher",kind:"scalar",T:8},{no:14,name:"kind",kind:"enum",T:G.getEnumType(Ir)},{no:15,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:16,name:"disconnect_reason",kind:"enum",T:G.getEnumType(In)},{no:18,name:"kind_details",kind:"enum",T:G.getEnumType(xv),repeated:!0}]),Ds=G.makeEnum("livekit.ParticipantInfo.State",[{no:0,name:"JOINING"},{no:1,name:"JOINED"},{no:2,name:"ACTIVE"},{no:3,name:"DISCONNECTED"}]),Ir=G.makeEnum("livekit.ParticipantInfo.Kind",[{no:0,name:"STANDARD"},{no:1,name:"INGRESS"},{no:2,name:"EGRESS"},{no:3,name:"SIP"},{no:4,name:"AGENT"}]),xv=G.makeEnum("livekit.ParticipantInfo.KindDetail",[{no:0,name:"CLOUD_AGENT"},{no:1,name:"FORWARDED"}]),vn=G.makeEnum("livekit.Encryption.Type",[{no:0,name:"NONE"},{no:1,name:"GCM"},{no:2,name:"CUSTOM"}]),Tv=G.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:rs,repeated:!0}]),Ls=G.makeMessageType("livekit.TrackInfo",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"type",kind:"enum",T:G.getEnumType(kn)},{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:G.getEnumType(Ot)},{no:10,name:"layers",kind:"message",T:rs,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:Tv,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:G.getEnumType(vn)},{no:17,name:"stream",kind:"scalar",T:9},{no:18,name:"version",kind:"message",T:dh},{no:19,name:"audio_features",kind:"enum",T:G.getEnumType(qt),repeated:!0},{no:20,name:"backup_codec_policy",kind:"enum",T:G.getEnumType(Ku)}]),rs=G.makeMessageType("livekit.VideoLayer",()=>[{no:1,name:"quality",kind:"enum",T:G.getEnumType(ec)},{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}]),cn=G.makeMessageType("livekit.DataPacket",()=>[{no:1,name:"kind",kind:"enum",T:G.getEnumType(We)},{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:Zu,oneof:"value"},{no:3,name:"speaker",kind:"message",T:Cv,oneof:"value"},{no:6,name:"sip_dtmf",kind:"message",T:Qu,oneof:"value"},{no:7,name:"transcription",kind:"message",T:Ev,oneof:"value"},{no:8,name:"metrics",kind:"message",T:gv,oneof:"value"},{no:9,name:"chat_message",kind:"message",T:tc,oneof:"value"},{no:10,name:"rpc_request",kind:"message",T:eh,oneof:"value"},{no:11,name:"rpc_ack",kind:"message",T:th,oneof:"value"},{no:12,name:"rpc_response",kind:"message",T:nh,oneof:"value"},{no:13,name:"stream_header",kind:"message",T:ic,oneof:"value"},{no:14,name:"stream_chunk",kind:"message",T:sc,oneof:"value"},{no:15,name:"stream_trailer",kind:"message",T:rc,oneof:"value"},{no:16,name:"sequence",kind:"scalar",T:13},{no:17,name:"participant_sid",kind:"scalar",T:9}]),We=G.makeEnum("livekit.DataPacket.Kind",[{no:0,name:"RELIABLE"},{no:1,name:"LOSSY"}]),Cv=G.makeMessageType("livekit.ActiveSpeakerUpdate",()=>[{no:1,name:"speakers",kind:"message",T:Ju,repeated:!0}]),Ju=G.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}]),Zu=G.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}]),Qu=G.makeMessageType("livekit.SipDTMF",()=>[{no:3,name:"code",kind:"scalar",T:13},{no:4,name:"digit",kind:"scalar",T:9}]),Ev=G.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:Mv,repeated:!0}]),Mv=G.makeMessageType("livekit.TranscriptionSegment",()=>[{no:1,name:"id",kind:"scalar",T:9},{no:2,name:"text",kind:"scalar",T:9},{no:3,name:"start_time",kind:"scalar",T:4},{no:4,name:"end_time",kind:"scalar",T:4},{no:5,name:"final",kind:"scalar",T:8},{no:6,name:"language",kind:"scalar",T:9}]),tc=G.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}]),eh=G.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}]),th=G.makeMessageType("livekit.RpcAck",()=>[{no:1,name:"request_id",kind:"scalar",T:9}]),nh=G.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:ih,oneof:"value"}]),ih=G.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}]),sh=G.makeMessageType("livekit.ParticipantTracks",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"track_sids",kind:"scalar",T:9,repeated:!0}]),rh=G.makeMessageType("livekit.ServerInfo",()=>[{no:1,name:"edition",kind:"enum",T:G.getEnumType(ah)},{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}]),ah=G.makeEnum("livekit.ServerInfo.Edition",[{no:0,name:"Standard"},{no:1,name:"Cloud"}]),wv=G.makeMessageType("livekit.ClientInfo",()=>[{no:1,name:"sdk",kind:"enum",T:G.getEnumType(oh)},{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}]),oh=G.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"}]),ch=G.makeMessageType("livekit.ClientConfiguration",()=>[{no:1,name:"video",kind:"message",T:lh},{no:2,name:"screen",kind:"message",T:lh},{no:3,name:"resume_connection",kind:"enum",T:G.getEnumType(kr)},{no:4,name:"disabled_codecs",kind:"message",T:Av},{no:5,name:"force_relay",kind:"enum",T:G.getEnumType(kr)}]),lh=G.makeMessageType("livekit.VideoConfiguration",()=>[{no:1,name:"hardware_encoder",kind:"enum",T:G.getEnumType(kr)}]),Av=G.makeMessageType("livekit.DisabledCodecs",()=>[{no:1,name:"codecs",kind:"message",T:Aa,repeated:!0},{no:2,name:"publish",kind:"message",T:Aa,repeated:!0}]),dh=G.makeMessageType("livekit.TimedVersion",()=>[{no:1,name:"unix_micro",kind:"scalar",T:3},{no:2,name:"ticks",kind:"scalar",T:5}]),nc=G.makeEnum("livekit.DataStream.OperationType",[{no:0,name:"CREATE"},{no:1,name:"UPDATE"},{no:2,name:"DELETE"},{no:3,name:"REACTION"}]),uh=G.makeMessageType("livekit.DataStream.TextHeader",()=>[{no:1,name:"operation_type",kind:"enum",T:G.getEnumType(nc)},{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"}),hh=G.makeMessageType("livekit.DataStream.ByteHeader",()=>[{no:1,name:"name",kind:"scalar",T:9}],{localName:"DataStream_ByteHeader"}),ic=G.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:G.getEnumType(vn)},{no:8,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:9,name:"text_header",kind:"message",T:uh,oneof:"content_header"},{no:10,name:"byte_header",kind:"message",T:hh,oneof:"content_header"}],{localName:"DataStream_Header"}),sc=G.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"}),rc=G.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"}),Dn=G.makeEnum("livekit.SignalTarget",[{no:0,name:"PUBLISHER"},{no:1,name:"SUBSCRIBER"}]),ac=G.makeEnum("livekit.StreamState",[{no:0,name:"ACTIVE"},{no:1,name:"PAUSED"}]),Rv=G.makeEnum("livekit.CandidateProtocol",[{no:0,name:"UDP"},{no:1,name:"TCP"},{no:2,name:"TLS"}]),Pv=G.makeMessageType("livekit.SignalRequest",()=>[{no:1,name:"offer",kind:"message",T:as,oneof:"message"},{no:2,name:"answer",kind:"message",T:as,oneof:"message"},{no:3,name:"trickle",kind:"message",T:lc,oneof:"message"},{no:4,name:"add_track",kind:"message",T:cc,oneof:"message"},{no:5,name:"mute",kind:"message",T:dc,oneof:"message"},{no:6,name:"subscription",kind:"message",T:Ra,oneof:"message"},{no:7,name:"track_setting",kind:"message",T:ph,oneof:"message"},{no:8,name:"leave",kind:"message",T:Pa,oneof:"message"},{no:10,name:"update_layers",kind:"message",T:gh,oneof:"message"},{no:11,name:"subscription_permission",kind:"message",T:_h,oneof:"message"},{no:12,name:"sync_state",kind:"message",T:Sh,oneof:"message"},{no:13,name:"simulate",kind:"message",T:jn,oneof:"message"},{no:14,name:"ping",kind:"scalar",T:3,oneof:"message"},{no:15,name:"update_metadata",kind:"message",T:vh,oneof:"message"},{no:16,name:"ping_req",kind:"message",T:Ch,oneof:"message"},{no:17,name:"update_audio_track",kind:"message",T:mh,oneof:"message"},{no:18,name:"update_video_track",kind:"message",T:Uv,oneof:"message"}]),fh=G.makeMessageType("livekit.SignalResponse",()=>[{no:1,name:"join",kind:"message",T:kv,oneof:"message"},{no:2,name:"answer",kind:"message",T:as,oneof:"message"},{no:3,name:"offer",kind:"message",T:as,oneof:"message"},{no:4,name:"trickle",kind:"message",T:lc,oneof:"message"},{no:5,name:"update",kind:"message",T:Lv,oneof:"message"},{no:6,name:"track_published",kind:"message",T:uc,oneof:"message"},{no:8,name:"leave",kind:"message",T:Pa,oneof:"message"},{no:9,name:"mute",kind:"message",T:dc,oneof:"message"},{no:10,name:"speakers_changed",kind:"message",T:Nv,oneof:"message"},{no:11,name:"room_update",kind:"message",T:Ov,oneof:"message"},{no:12,name:"connection_quality",kind:"message",T:Bv,oneof:"message"},{no:13,name:"stream_state_update",kind:"message",T:Vv,oneof:"message"},{no:14,name:"subscribed_quality_update",kind:"message",T:Hv,oneof:"message"},{no:15,name:"subscription_permission_update",kind:"message",T:Wv,oneof:"message"},{no:16,name:"refresh_token",kind:"scalar",T:9,oneof:"message"},{no:17,name:"track_unpublished",kind:"message",T:Dv,oneof:"message"},{no:18,name:"pong",kind:"scalar",T:3,oneof:"message"},{no:19,name:"reconnect",kind:"message",T:Iv,oneof:"message"},{no:20,name:"pong_resp",kind:"message",T:$v,oneof:"message"},{no:21,name:"subscription_response",kind:"message",T:Yv,oneof:"message"},{no:22,name:"request_response",kind:"message",T:Kv,oneof:"message"},{no:23,name:"track_subscribed",kind:"message",T:Jv,oneof:"message"},{no:24,name:"room_moved",kind:"message",T:qv,oneof:"message"}]),oc=G.makeMessageType("livekit.SimulcastCodec",()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"cid",kind:"scalar",T:9}]),cc=G.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:G.getEnumType(kn)},{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:G.getEnumType(Ot)},{no:9,name:"layers",kind:"message",T:rs,repeated:!0},{no:10,name:"simulcast_codecs",kind:"message",T:oc,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:G.getEnumType(vn)},{no:15,name:"stream",kind:"scalar",T:9},{no:16,name:"backup_codec_policy",kind:"enum",T:G.getEnumType(Ku)},{no:17,name:"audio_features",kind:"enum",T:G.getEnumType(qt),repeated:!0}]),lc=G.makeMessageType("livekit.TrickleRequest",()=>[{no:1,name:"candidateInit",kind:"scalar",T:9},{no:2,name:"target",kind:"enum",T:G.getEnumType(Dn)},{no:3,name:"final",kind:"scalar",T:8}]),dc=G.makeMessageType("livekit.MuteTrackRequest",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"muted",kind:"scalar",T:8}]),kv=G.makeMessageType("livekit.JoinResponse",()=>[{no:1,name:"room",kind:"message",T:wa},{no:2,name:"participant",kind:"message",T:ss},{no:3,name:"other_participants",kind:"message",T:ss,repeated:!0},{no:4,name:"server_version",kind:"scalar",T:9},{no:5,name:"ice_servers",kind:"message",T:bh,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:ch},{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:rh},{no:13,name:"sif_trailer",kind:"scalar",T:12},{no:14,name:"enabled_publish_codecs",kind:"message",T:Aa,repeated:!0},{no:15,name:"fast_publish",kind:"scalar",T:8}]),Iv=G.makeMessageType("livekit.ReconnectResponse",()=>[{no:1,name:"ice_servers",kind:"message",T:bh,repeated:!0},{no:2,name:"client_configuration",kind:"message",T:ch},{no:3,name:"server_info",kind:"message",T:rh},{no:4,name:"last_message_seq",kind:"scalar",T:13}]),uc=G.makeMessageType("livekit.TrackPublishedResponse",()=>[{no:1,name:"cid",kind:"scalar",T:9},{no:2,name:"track",kind:"message",T:Ls}]),Dv=G.makeMessageType("livekit.TrackUnpublishedResponse",()=>[{no:1,name:"track_sid",kind:"scalar",T:9}]),as=G.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}]),Lv=G.makeMessageType("livekit.ParticipantUpdate",()=>[{no:1,name:"participants",kind:"message",T:ss,repeated:!0}]),Ra=G.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:sh,repeated:!0}]),ph=G.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:G.getEnumType(ec)},{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}]),mh=G.makeMessageType("livekit.UpdateLocalAudioTrack",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"features",kind:"enum",T:G.getEnumType(qt),repeated:!0}]),Uv=G.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}]),Pa=G.makeMessageType("livekit.LeaveRequest",()=>[{no:1,name:"can_reconnect",kind:"scalar",T:8},{no:2,name:"reason",kind:"enum",T:G.getEnumType(In)},{no:3,name:"action",kind:"enum",T:G.getEnumType(Us)},{no:4,name:"regions",kind:"message",T:jv}]),Us=G.makeEnum("livekit.LeaveRequest.Action",[{no:0,name:"DISCONNECT"},{no:1,name:"RESUME"},{no:2,name:"RECONNECT"}]),gh=G.makeMessageType("livekit.UpdateVideoLayers",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"layers",kind:"message",T:rs,repeated:!0}]),vh=G.makeMessageType("livekit.UpdateParticipantMetadata",()=>[{no:1,name:"metadata",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",T:9},{no:3,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:4,name:"request_id",kind:"scalar",T:13}]),bh=G.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}]),Nv=G.makeMessageType("livekit.SpeakersChanged",()=>[{no:1,name:"speakers",kind:"message",T:Ju,repeated:!0}]),Ov=G.makeMessageType("livekit.RoomUpdate",()=>[{no:1,name:"room",kind:"message",T:wa}]),Fv=G.makeMessageType("livekit.ConnectionQualityInfo",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"quality",kind:"enum",T:G.getEnumType(Pr)},{no:3,name:"score",kind:"scalar",T:2}]),Bv=G.makeMessageType("livekit.ConnectionQualityUpdate",()=>[{no:1,name:"updates",kind:"message",T:Fv,repeated:!0}]),zv=G.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:G.getEnumType(ac)}]),Vv=G.makeMessageType("livekit.StreamStateUpdate",()=>[{no:1,name:"stream_states",kind:"message",T:zv,repeated:!0}]),hc=G.makeMessageType("livekit.SubscribedQuality",()=>[{no:1,name:"quality",kind:"enum",T:G.getEnumType(ec)},{no:2,name:"enabled",kind:"scalar",T:8}]),Gv=G.makeMessageType("livekit.SubscribedCodec",()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"qualities",kind:"message",T:hc,repeated:!0}]),Hv=G.makeMessageType("livekit.SubscribedQualityUpdate",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribed_qualities",kind:"message",T:hc,repeated:!0},{no:3,name:"subscribed_codecs",kind:"message",T:Gv,repeated:!0}]),yh=G.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}]),_h=G.makeMessageType("livekit.SubscriptionPermission",()=>[{no:1,name:"all_participants",kind:"scalar",T:8},{no:2,name:"track_permissions",kind:"message",T:yh,repeated:!0}]),Wv=G.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}]),qv=G.makeMessageType("livekit.RoomMovedResponse",()=>[{no:1,name:"room",kind:"message",T:wa},{no:2,name:"token",kind:"scalar",T:9},{no:3,name:"participant",kind:"message",T:ss},{no:4,name:"other_participants",kind:"message",T:ss,repeated:!0}]),Sh=G.makeMessageType("livekit.SyncState",()=>[{no:1,name:"answer",kind:"message",T:as},{no:2,name:"subscription",kind:"message",T:Ra},{no:3,name:"publish_tracks",kind:"message",T:uc,repeated:!0},{no:4,name:"data_channels",kind:"message",T:Th,repeated:!0},{no:5,name:"offer",kind:"message",T:as},{no:6,name:"track_sids_disabled",kind:"scalar",T:9,repeated:!0},{no:7,name:"datachannel_receive_states",kind:"message",T:xh,repeated:!0}]),xh=G.makeMessageType("livekit.DataChannelReceiveState",()=>[{no:1,name:"publisher_sid",kind:"scalar",T:9},{no:2,name:"last_seq",kind:"scalar",T:13}]),Th=G.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:G.getEnumType(Dn)}]),jn=G.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:G.getEnumType(Rv),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"}]),Ch=G.makeMessageType("livekit.Ping",()=>[{no:1,name:"timestamp",kind:"scalar",T:3},{no:2,name:"rtt",kind:"scalar",T:3}]),$v=G.makeMessageType("livekit.Pong",()=>[{no:1,name:"last_ping_timestamp",kind:"scalar",T:3},{no:2,name:"timestamp",kind:"scalar",T:3}]),jv=G.makeMessageType("livekit.RegionSettings",()=>[{no:1,name:"regions",kind:"message",T:Xv,repeated:!0}]),Xv=G.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}]),Yv=G.makeMessageType("livekit.SubscriptionResponse",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"err",kind:"enum",T:G.getEnumType(_v)}]),Kv=G.makeMessageType("livekit.RequestResponse",()=>[{no:1,name:"request_id",kind:"scalar",T:13},{no:2,name:"reason",kind:"enum",T:G.getEnumType(fc)},{no:3,name:"message",kind:"scalar",T:9}]),fc=G.makeEnum("livekit.RequestResponse.Reason",[{no:0,name:"OK"},{no:1,name:"NOT_FOUND"},{no:2,name:"NOT_ALLOWED"},{no:3,name:"LIMIT_EXCEEDED"}]),Jv=G.makeMessageType("livekit.TrackSubscribed",()=>[{no:1,name:"track_sid",kind:"scalar",T:9}]);function Zv(i){return i&&i.__esModule&&Object.prototype.hasOwnProperty.call(i,"default")?i.default:i}var ka={exports:{}},Qv=ka.exports,Eh;function e0(){return Eh||(Eh=1,function(i){(function(e,t){i.exports?i.exports=t():e.log=t()})(Qv,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(v,m){var p=v[m];if(typeof p.bind=="function")return p.bind(v);try{return Function.prototype.bind.call(p,v)}catch{return function(){return Function.prototype.apply.apply(p,[v,arguments])}}}function c(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function l(v){return v==="debug"&&(v="log"),typeof console===t?!1:v==="trace"&&n?c:console[v]!==void 0?o(console,v):console.log!==void 0?o(console,"log"):e}function d(){for(var v=this.getLevel(),m=0;m<s.length;m++){var p=s[m];this[p]=m<v?e:this.methodFactory(p,v,this.name)}if(this.log=this.debug,typeof console===t&&v<this.levels.SILENT)return"No console available for logging"}function u(v){return function(){typeof console!==t&&(d.call(this),this[v].apply(this,arguments))}}function h(v,m,p){return l(v)||u.apply(this,arguments)}function f(v,m){var p=this,x,C,b,S="loglevel";typeof v=="string"?S+=":"+v:typeof v=="symbol"&&(S=void 0);function M(R){var O=(s[R]||"silent").toUpperCase();if(!(typeof window===t||!S)){try{window.localStorage[S]=O;return}catch{}try{window.document.cookie=encodeURIComponent(S)+"="+O+";"}catch{}}}function A(){var R;if(!(typeof window===t||!S)){try{R=window.localStorage[S]}catch{}if(typeof R===t)try{var O=window.document.cookie,z=encodeURIComponent(S),$=O.indexOf(z+"=");$!==-1&&(R=/^([^;]+)/.exec(O.slice($+z.length+1))[1])}catch{}return p.levels[R]===void 0&&(R=void 0),R}}function k(){if(!(typeof window===t||!S)){try{window.localStorage.removeItem(S)}catch{}try{window.document.cookie=encodeURIComponent(S)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}function _(R){var O=R;if(typeof O=="string"&&p.levels[O.toUpperCase()]!==void 0&&(O=p.levels[O.toUpperCase()]),typeof O=="number"&&O>=0&&O<=p.levels.SILENT)return O;throw new TypeError("log.setLevel() called with invalid level: "+R)}p.name=v,p.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},p.methodFactory=m||h,p.getLevel=function(){return b??C??x},p.setLevel=function(R,O){return b=_(R),O!==!1&&M(b),d.call(p)},p.setDefaultLevel=function(R){C=_(R),A()||p.setLevel(R,!1)},p.resetLevel=function(){b=null,k(),d.call(p)},p.enableAll=function(R){p.setLevel(p.levels.TRACE,R)},p.disableAll=function(R){p.setLevel(p.levels.SILENT,R)},p.rebuild=function(){if(a!==p&&(x=_(a.getLevel())),d.call(p),a===p)for(var R in r)r[R].rebuild()},x=_(a?a.getLevel():"WARN");var T=A();T!=null&&(b=_(T)),d.call(p)}a=new f,a.getLogger=function(m){if(typeof m!="symbol"&&typeof m!="string"||m==="")throw new TypeError("You must supply a name when creating a logger.");var p=r[m];return p||(p=r[m]=new f(m,a.methodFactory)),p};var g=typeof window!==t?window.log:void 0;return a.noConflict=function(){return typeof window!==t&&window.log===a&&(window.log=g),a},a.getLoggers=function(){return r},a.default=a,a})}(ka)),ka.exports}var Ia=e0(),pc;(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"})(pc||(pc={}));var Ln;(function(i){i.Default="livekit",i.Room="livekit-room",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"})(Ln||(Ln={}));let Ke=Ia.getLogger("livekit");Object.values(Ln).map(i=>Ia.getLogger(i)),Ke.setDefaultLevel(pc.info);function fi(i){const e=Ia.getLogger(i);return e.setDefaultLevel(Ke.getLevel()),e}const t0=Ia.getLogger("lk-e2ee"),Dr=7e3,n0=[0,300,2*2*300,3*3*300,4*4*300,Dr,Dr,Dr,Dr,Dr];class i0{constructor(e){this._retryDelays=e!==void 0?[...e]:n0}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 s0(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 P(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(d){try{l(n.next(d))}catch(u){a(u)}}function c(d){try{l(n.throw(d))}catch(u){a(u)}}function l(d){d.done?r(d.value):s(d.value).then(o,c)}l((n=n.apply(i,e||[])).next())})}function Mh(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 pi(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 Mh=="function"?Mh(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,c){a=i[r](a),s(o,c,a.done,a.value)})}}function s(r,a,o,c){Promise.resolve(c).then(function(l){r({value:l,done:o})},a)}}typeof SuppressedError=="function"&&SuppressedError;var Da={exports:{}},wh;function r0(){if(wh)return Da.exports;wh=1;var i=typeof Reflect=="object"?Reflect:null,e=i&&typeof i.apply=="function"?i.apply:function(S,M,A){return Function.prototype.apply.call(S,M,A)},t;i&&typeof i.ownKeys=="function"?t=i.ownKeys:Object.getOwnPropertySymbols?t=function(S){return Object.getOwnPropertyNames(S).concat(Object.getOwnPropertySymbols(S))}:t=function(S){return Object.getOwnPropertyNames(S)};function n(b){console&&console.warn&&console.warn(b)}var s=Number.isNaN||function(S){return S!==S};function r(){r.init.call(this)}Da.exports=r,Da.exports.once=p,r.EventEmitter=r,r.prototype._events=void 0,r.prototype._eventsCount=0,r.prototype._maxListeners=void 0;var a=10;function o(b){if(typeof b!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof b)}Object.defineProperty(r,"defaultMaxListeners",{enumerable:!0,get:function(){return a},set:function(b){if(typeof b!="number"||b<0||s(b))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+b+".");a=b}}),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(S){if(typeof S!="number"||S<0||s(S))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+S+".");return this._maxListeners=S,this};function c(b){return b._maxListeners===void 0?r.defaultMaxListeners:b._maxListeners}r.prototype.getMaxListeners=function(){return c(this)},r.prototype.emit=function(S){for(var M=[],A=1;A<arguments.length;A++)M.push(arguments[A]);var k=S==="error",_=this._events;if(_!==void 0)k=k&&_.error===void 0;else if(!k)return!1;if(k){var T;if(M.length>0&&(T=M[0]),T instanceof Error)throw T;var R=new Error("Unhandled error."+(T?" ("+T.message+")":""));throw R.context=T,R}var O=_[S];if(O===void 0)return!1;if(typeof O=="function")e(O,this,M);else for(var z=O.length,$=g(O,z),A=0;A<z;++A)e($[A],this,M);return!0};function l(b,S,M,A){var k,_,T;if(o(M),_=b._events,_===void 0?(_=b._events=Object.create(null),b._eventsCount=0):(_.newListener!==void 0&&(b.emit("newListener",S,M.listener?M.listener:M),_=b._events),T=_[S]),T===void 0)T=_[S]=M,++b._eventsCount;else if(typeof T=="function"?T=_[S]=A?[M,T]:[T,M]:A?T.unshift(M):T.push(M),k=c(b),k>0&&T.length>k&&!T.warned){T.warned=!0;var R=new Error("Possible EventEmitter memory leak detected. "+T.length+" "+String(S)+" listeners added. Use emitter.setMaxListeners() to increase limit");R.name="MaxListenersExceededWarning",R.emitter=b,R.type=S,R.count=T.length,n(R)}return b}r.prototype.addListener=function(S,M){return l(this,S,M,!1)},r.prototype.on=r.prototype.addListener,r.prototype.prependListener=function(S,M){return l(this,S,M,!0)};function d(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function u(b,S,M){var A={fired:!1,wrapFn:void 0,target:b,type:S,listener:M},k=d.bind(A);return k.listener=M,A.wrapFn=k,k}r.prototype.once=function(S,M){return o(M),this.on(S,u(this,S,M)),this},r.prototype.prependOnceListener=function(S,M){return o(M),this.prependListener(S,u(this,S,M)),this},r.prototype.removeListener=function(S,M){var A,k,_,T,R;if(o(M),k=this._events,k===void 0)return this;if(A=k[S],A===void 0)return this;if(A===M||A.listener===M)--this._eventsCount===0?this._events=Object.create(null):(delete k[S],k.removeListener&&this.emit("removeListener",S,A.listener||M));else if(typeof A!="function"){for(_=-1,T=A.length-1;T>=0;T--)if(A[T]===M||A[T].listener===M){R=A[T].listener,_=T;break}if(_<0)return this;_===0?A.shift():v(A,_),A.length===1&&(k[S]=A[0]),k.removeListener!==void 0&&this.emit("removeListener",S,R||M)}return this},r.prototype.off=r.prototype.removeListener,r.prototype.removeAllListeners=function(S){var M,A,k;if(A=this._events,A===void 0)return this;if(A.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):A[S]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete A[S]),this;if(arguments.length===0){var _=Object.keys(A),T;for(k=0;k<_.length;++k)T=_[k],T!=="removeListener"&&this.removeAllListeners(T);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(M=A[S],typeof M=="function")this.removeListener(S,M);else if(M!==void 0)for(k=M.length-1;k>=0;k--)this.removeListener(S,M[k]);return this};function h(b,S,M){var A=b._events;if(A===void 0)return[];var k=A[S];return k===void 0?[]:typeof k=="function"?M?[k.listener||k]:[k]:M?m(k):g(k,k.length)}r.prototype.listeners=function(S){return h(this,S,!0)},r.prototype.rawListeners=function(S){return h(this,S,!1)},r.listenerCount=function(b,S){return typeof b.listenerCount=="function"?b.listenerCount(S):f.call(b,S)},r.prototype.listenerCount=f;function f(b){var S=this._events;if(S!==void 0){var M=S[b];if(typeof M=="function")return 1;if(M!==void 0)return M.length}return 0}r.prototype.eventNames=function(){return this._eventsCount>0?t(this._events):[]};function g(b,S){for(var M=new Array(S),A=0;A<S;++A)M[A]=b[A];return M}function v(b,S){for(;S+1<b.length;S++)b[S]=b[S+1];b.pop()}function m(b){for(var S=new Array(b.length),M=0;M<S.length;++M)S[M]=b[M].listener||b[M];return S}function p(b,S){return new Promise(function(M,A){function k(T){b.removeListener(S,_),A(T)}function _(){typeof b.removeListener=="function"&&b.removeListener("error",k),M([].slice.call(arguments))}C(b,S,_,{once:!0}),S!=="error"&&x(b,k,{once:!0})})}function x(b,S,M){typeof b.on=="function"&&C(b,"error",S,M)}function C(b,S,M,A){if(typeof b.on=="function")A.once?b.once(S,M):b.on(S,M);else if(typeof b.addEventListener=="function")b.addEventListener(S,function k(_){A.once&&b.removeEventListener(S,k),M(_)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof b)}return Da.exports}var Xn=r0();let Ah=!0,Rh=!0;function Lr(i,e,t){const n=i.match(e);return n&&n.length>=t&&parseFloat(n[t],10)}function os(i,e,t){if(!i.RTCPeerConnection)return;const n=i.RTCPeerConnection.prototype,s=n.addEventListener;n.addEventListener=function(a,o){if(a!==e)return s.apply(this,arguments);const c=l=>{const d=t(l);d&&(o.handleEvent?o.handleEvent(d):o(d))};return this._eventMap=this._eventMap||{},this._eventMap[e]||(this._eventMap[e]=new Map),this._eventMap[e].set(o,c),s.apply(this,[a,c])};const r=n.removeEventListener;n.removeEventListener=function(a,o){if(a!==e||!this._eventMap||!this._eventMap[e])return r.apply(this,arguments);if(!this._eventMap[e].has(o))return r.apply(this,arguments);const c=this._eventMap[e].get(o);return this._eventMap[e].delete(o),this._eventMap[e].size===0&&delete this._eventMap[e],Object.keys(this._eventMap).length===0&&delete this._eventMap,r.apply(this,[a,c])},Object.defineProperty(n,"on"+e,{get(){return this["_on"+e]},set(a){this["_on"+e]&&(this.removeEventListener(e,this["_on"+e]),delete this["_on"+e]),a&&this.addEventListener(e,this["_on"+e]=a)},enumerable:!0,configurable:!0})}function a0(i){return typeof i!="boolean"?new Error("Argument type: "+typeof i+". Please use a boolean."):(Ah=i,i?"adapter.js logging disabled":"adapter.js logging enabled")}function o0(i){return typeof i!="boolean"?new Error("Argument type: "+typeof i+". Please use a boolean."):(Rh=!i,"adapter.js deprecation warnings "+(i?"disabled":"enabled"))}function Ph(){if(typeof window=="object"){if(Ah)return;typeof console<"u"&&typeof console.log=="function"&&console.log.apply(console,arguments)}}function mc(i,e){Rh&&console.warn(i+" is deprecated, please use "+e+" instead.")}function c0(i){const e={browser:null,version:null};if(typeof i>"u"||!i.navigator||!i.navigator.userAgent)return e.browser="Not a browser.",e;const{navigator:t}=i;if(t.userAgentData&&t.userAgentData.brands){const n=t.userAgentData.brands.find(s=>s.brand==="Chromium");if(n)return{browser:"chrome",version:parseInt(n.version,10)}}if(t.mozGetUserMedia)e.browser="firefox",e.version=parseInt(Lr(t.userAgent,/Firefox\/(\d+)\./,1));else if(t.webkitGetUserMedia||i.isSecureContext===!1&&i.webkitRTCPeerConnection)e.browser="chrome",e.version=parseInt(Lr(t.userAgent,/Chrom(e|ium)\/(\d+)\./,2));else if(i.RTCPeerConnection&&t.userAgent.match(/AppleWebKit\/(\d+)\./))e.browser="safari",e.version=parseInt(Lr(t.userAgent,/AppleWebKit\/(\d+)\./,1)),e.supportsUnifiedPlan=i.RTCRtpTransceiver&&"currentDirection"in i.RTCRtpTransceiver.prototype,e._safariVersion=Lr(t.userAgent,/Version\/(\d+(\.?\d+))/,1);else return e.browser="Not a supported browser.",e;return e}function kh(i){return Object.prototype.toString.call(i)==="[object Object]"}function Ih(i){return kh(i)?Object.keys(i).reduce(function(e,t){const n=kh(i[t]),s=n?Ih(i[t]):i[t],r=n&&!Object.keys(s).length;return s===void 0||r?e:Object.assign(e,{[t]:s})},{}):i}function gc(i,e,t){!e||t.has(e.id)||(t.set(e.id,e),Object.keys(e).forEach(n=>{n.endsWith("Id")?gc(i,i.get(e[n]),t):n.endsWith("Ids")&&e[n].forEach(s=>{gc(i,i.get(s),t)})}))}function Dh(i,e,t){const n=t?"outbound-rtp":"inbound-rtp",s=new Map;if(e===null)return s;const r=[];return 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&&gc(i,o,s)})}),s}const Lh=Ph;function Uh(i,e){const t=i&&i.navigator;if(!t.mediaDevices)return;const n=function(o){if(typeof o!="object"||o.mandatory||o.optional)return o;const c={};return Object.keys(o).forEach(l=>{if(l==="require"||l==="advanced"||l==="mediaSource")return;const d=typeof o[l]=="object"?o[l]:{ideal:o[l]};d.exact!==void 0&&typeof d.exact=="number"&&(d.min=d.max=d.exact);const u=function(h,f){return h?h+f.charAt(0).toUpperCase()+f.slice(1):f==="deviceId"?"sourceId":f};if(d.ideal!==void 0){c.optional=c.optional||[];let h={};typeof d.ideal=="number"?(h[u("min",l)]=d.ideal,c.optional.push(h),h={},h[u("max",l)]=d.ideal,c.optional.push(h)):(h[u("",l)]=d.ideal,c.optional.push(h))}d.exact!==void 0&&typeof d.exact!="number"?(c.mandatory=c.mandatory||{},c.mandatory[u("",l)]=d.exact):["min","max"].forEach(h=>{d[h]!==void 0&&(c.mandatory=c.mandatory||{},c.mandatory[u(h,l)]=d[h])})}),o.advanced&&(c.optional=(c.optional||[]).concat(o.advanced)),c},s=function(o,c){if(e.version>=61)return c(o);if(o=JSON.parse(JSON.stringify(o)),o&&typeof o.audio=="object"){const l=function(d,u,h){u in d&&!(h in d)&&(d[h]=d[u],delete d[u])};o=JSON.parse(JSON.stringify(o)),l(o.audio,"autoGainControl","googAutoGainControl"),l(o.audio,"noiseSuppression","googNoiseSuppression"),o.audio=n(o.audio)}if(o&&typeof o.video=="object"){let l=o.video.facingMode;l=l&&(typeof l=="object"?l:{ideal:l});const d=e.version<66;if(l&&(l.exact==="user"||l.exact==="environment"||l.ideal==="user"||l.ideal==="environment")&&!(t.mediaDevices.getSupportedConstraints&&t.mediaDevices.getSupportedConstraints().facingMode&&!d)){delete o.video.facingMode;let u;if(l.exact==="environment"||l.ideal==="environment"?u=["back","rear"]:(l.exact==="user"||l.ideal==="user")&&(u=["front"]),u)return t.mediaDevices.enumerateDevices().then(h=>{h=h.filter(g=>g.kind==="videoinput");let f=h.find(g=>u.some(v=>g.label.toLowerCase().includes(v)));return!f&&h.length&&u.includes("back")&&(f=h[h.length-1]),f&&(o.video.deviceId=l.exact?{exact:f.deviceId}:{ideal:f.deviceId}),o.video=n(o.video),Lh("chrome: "+JSON.stringify(o)),c(o)})}o.video=n(o.video)}return Lh("chrome: "+JSON.stringify(o)),c(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,c,l){s(o,d=>{t.webkitGetUserMedia(d,c,u=>{l&&l(r(u))})})};if(t.getUserMedia=a.bind(t),t.mediaDevices.getUserMedia){const o=t.mediaDevices.getUserMedia.bind(t.mediaDevices);t.mediaDevices.getUserMedia=function(c){return s(c,l=>o(l).then(d=>{if(l.audio&&!d.getAudioTracks().length||l.video&&!d.getVideoTracks().length)throw d.getTracks().forEach(u=>{u.stop()}),new DOMException("","NotFoundError");return d},d=>Promise.reject(r(d))))}}}function Nh(i){i.MediaStream=i.MediaStream||i.webkitMediaStream}function Oh(i){if(typeof i=="object"&&i.RTCPeerConnection&&!("ontrack"in i.RTCPeerConnection.prototype)){Object.defineProperty(i.RTCPeerConnection.prototype,"ontrack",{get(){return this._ontrack},set(t){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=t)},enumerable:!0,configurable:!0});const e=i.RTCPeerConnection.prototype.setRemoteDescription;i.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=n=>{n.stream.addEventListener("addtrack",s=>{let r;i.RTCPeerConnection.prototype.getReceivers?r=this.getReceivers().find(o=>o.track&&o.track.id===s.track.id):r={track:s.track};const a=new Event("track");a.track=s.track,a.receiver=r,a.transceiver={receiver:r},a.streams=[n.stream],this.dispatchEvent(a)}),n.stream.getTracks().forEach(s=>{let r;i.RTCPeerConnection.prototype.getReceivers?r=this.getReceivers().find(o=>o.track&&o.track.id===s.id):r={track:s};const a=new Event("track");a.track=s,a.receiver=r,a.transceiver={receiver:r},a.streams=[n.stream],this.dispatchEvent(a)})},this.addEventListener("addstream",this._ontrackpoly)),e.apply(this,arguments)}}else os(i,"track",e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e))}function Fh(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,c){let l=s.apply(this,arguments);return l||(l=e(this,o),this._senders.push(l)),l};const r=i.RTCPeerConnection.prototype.removeTrack;i.RTCPeerConnection.prototype.removeTrack=function(o){r.apply(this,arguments);const c=this._senders.indexOf(o);c!==-1&&this._senders.splice(c,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(c=>c.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 Bh(i){if(!(typeof i=="object"&&i.RTCPeerConnection&&i.RTCRtpSender&&i.RTCRtpReceiver))return;if(!("getStats"in i.RTCRtpSender.prototype)){const t=i.RTCPeerConnection.prototype.getSenders;t&&(i.RTCPeerConnection.prototype.getSenders=function(){const r=t.apply(this,[]);return r.forEach(a=>a._pc=this),r});const n=i.RTCPeerConnection.prototype.addTrack;n&&(i.RTCPeerConnection.prototype.addTrack=function(){const r=n.apply(this,arguments);return r._pc=this,r}),i.RTCRtpSender.prototype.getStats=function(){const r=this;return this._pc.getStats().then(a=>Dh(a,r.track,!0))}}if(!("getStats"in i.RTCRtpReceiver.prototype)){const t=i.RTCPeerConnection.prototype.getReceivers;t&&(i.RTCPeerConnection.prototype.getReceivers=function(){const s=t.apply(this,[]);return s.forEach(r=>r._pc=this),s}),os(i,"track",n=>(n.receiver._pc=n.srcElement,n)),i.RTCRtpReceiver.prototype.getStats=function(){const s=this;return this._pc.getStats().then(r=>Dh(r,s.track,!1))}}if(!("getStats"in i.RTCRtpSender.prototype&&"getStats"in i.RTCRtpReceiver.prototype))return;const e=i.RTCPeerConnection.prototype.getStats;i.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof i.MediaStreamTrack){const n=arguments[0];let s,r,a;return this.getSenders().forEach(o=>{o.track===n&&(s?a=!0:s=o)}),this.getReceivers().forEach(o=>(o.track===n&&(r?a=!0:r=o),o.track===n)),a||s&&r?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):s?s.getStats():r?r.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return e.apply(this,arguments)}}function zh(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 c=e.apply(this,arguments);return this._shimmedLocalStreams[o.id]?this._shimmedLocalStreams[o.id].indexOf(c)===-1&&this._shimmedLocalStreams[o.id].push(c):this._shimmedLocalStreams[o.id]=[o,c],c};const t=i.RTCPeerConnection.prototype.addStream;i.RTCPeerConnection.prototype.addStream=function(a){this._shimmedLocalStreams=this._shimmedLocalStreams||{},a.getTracks().forEach(l=>{if(this.getSenders().find(u=>u.track===l))throw new DOMException("Track already exists.","InvalidAccessError")});const o=this.getSenders();t.apply(this,arguments);const c=this.getSenders().filter(l=>o.indexOf(l)===-1);this._shimmedLocalStreams[a.id]=[a].concat(c)};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 c=this._shimmedLocalStreams[o].indexOf(a);c!==-1&&this._shimmedLocalStreams[o].splice(c,1),this._shimmedLocalStreams[o].length===1&&delete this._shimmedLocalStreams[o]}),s.apply(this,arguments)}}function Vh(i,e){if(!i.RTCPeerConnection)return;if(i.RTCPeerConnection.prototype.addTrack&&e.version>=65)return zh(i);const t=i.RTCPeerConnection.prototype.getLocalStreams;i.RTCPeerConnection.prototype.getLocalStreams=function(){const d=t.apply(this);return this._reverseStreams=this._reverseStreams||{},d.map(u=>this._reverseStreams[u.id])};const n=i.RTCPeerConnection.prototype.addStream;i.RTCPeerConnection.prototype.addStream=function(d){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},d.getTracks().forEach(u=>{if(this.getSenders().find(f=>f.track===u))throw new DOMException("Track already exists.","InvalidAccessError")}),!this._reverseStreams[d.id]){const u=new i.MediaStream(d.getTracks());this._streams[d.id]=u,this._reverseStreams[u.id]=d,d=u}n.apply(this,[d])};const s=i.RTCPeerConnection.prototype.removeStream;i.RTCPeerConnection.prototype.removeStream=function(d){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},s.apply(this,[this._streams[d.id]||d]),delete this._reverseStreams[this._streams[d.id]?this._streams[d.id].id:d.id],delete this._streams[d.id]},i.RTCPeerConnection.prototype.addTrack=function(d,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(v=>v===d))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(v=>v.track===d))throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};const g=this._streams[u.id];if(g)g.addTrack(d),Promise.resolve().then(()=>{this.dispatchEvent(new Event("negotiationneeded"))});else{const v=new i.MediaStream([d]);this._streams[u.id]=v,this._reverseStreams[v.id]=u,this.addStream(v)}return this.getSenders().find(v=>v.track===d)};function r(l,d){let u=d.sdp;return Object.keys(l._reverseStreams||[]).forEach(h=>{const f=l._reverseStreams[h],g=l._streams[f.id];u=u.replace(new RegExp(g.id,"g"),f.id)}),new RTCSessionDescription({type:d.type,sdp:u})}function a(l,d){let u=d.sdp;return Object.keys(l._reverseStreams||[]).forEach(h=>{const f=l._reverseStreams[h],g=l._streams[f.id];u=u.replace(new RegExp(f.id,"g"),g.id)}),new RTCSessionDescription({type:d.type,sdp:u})}["createOffer","createAnswer"].forEach(function(l){const d=i.RTCPeerConnection.prototype[l],u={[l](){const h=arguments;return arguments.length&&typeof arguments[0]=="function"?d.apply(this,[g=>{const v=r(this,g);h[0].apply(null,[v])},g=>{h[1]&&h[1].apply(null,g)},arguments[2]]):d.apply(this,arguments).then(g=>r(this,g))}};i.RTCPeerConnection.prototype[l]=u[l]});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 c=Object.getOwnPropertyDescriptor(i.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(i.RTCPeerConnection.prototype,"localDescription",{get(){const l=c.get.apply(this);return l.type===""?l:r(this,l)}}),i.RTCPeerConnection.prototype.removeTrack=function(d){if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!d._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(!(d._pc===this))throw new DOMException("Sender was not created by this connection.","InvalidAccessError");this._streams=this._streams||{};let h;Object.keys(this._streams).forEach(f=>{this._streams[f].getTracks().find(v=>d.track===v)&&(h=this._streams[f])}),h&&(h.getTracks().length===1?this.removeStream(this._reverseStreams[h.id]):h.removeTrack(d.track),this.dispatchEvent(new Event("negotiationneeded")))}}function vc(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 Gh(i,e){os(i,"negotiationneeded",t=>{const n=t.target;if(!((e.version<72||n.getConfiguration&&n.getConfiguration().sdpSemantics==="plan-b")&&n.signalingState!=="stable"))return t})}var Hh=Object.freeze({__proto__:null,fixNegotiationNeeded:Gh,shimAddTrackRemoveTrack:Vh,shimAddTrackRemoveTrackWithNative:zh,shimGetSendersWithDtmf:Fh,shimGetUserMedia:Uh,shimMediaStream:Nh,shimOnTrack:Oh,shimPeerConnection:vc,shimSenderReceiverGetStats:Bh});function Wh(i,e){const t=i&&i.navigator,n=i&&i.MediaStreamTrack;if(t.getUserMedia=function(s,r,a){mc("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,c){o in a&&!(c in a)&&(a[c]=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 l0(i,e){i.navigator.mediaDevices&&"getDisplayMedia"in i.navigator.mediaDevices||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 qh(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 bc(i,e){if(typeof i!="object"||!(i.RTCPeerConnection||i.mozRTCPeerConnection))return;!i.RTCPeerConnection&&i.mozRTCPeerConnection&&(i.RTCPeerConnection=i.mozRTCPeerConnection),e.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(s){const r=i.RTCPeerConnection.prototype[s],a={[s](){return arguments[0]=new(s==="addIceCandidate"?i.RTCIceCandidate:i.RTCSessionDescription)(arguments[0]),r.apply(this,arguments)}};i.RTCPeerConnection.prototype[s]=a[s]});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,a,o]=arguments;return n.apply(this,[r||null]).then(c=>{if(e.version<53&&!a)try{c.forEach(l=>{l.type=t[l.type]||l.type})}catch(l){if(l.name!=="TypeError")throw l;c.forEach((d,u)=>{c.set(u,Object.assign({},d,{type:t[d.type]||d.type}))})}return c}).then(a,o)}}function $h(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 jh(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}),os(i,"track",t=>(t.receiver._pc=t.srcElement,t)),i.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function Xh(i){!i.RTCPeerConnection||"removeStream"in i.RTCPeerConnection.prototype||(i.RTCPeerConnection.prototype.removeStream=function(t){mc("removeStream","removeTrack"),this.getSenders().forEach(n=>{n.track&&t.getTracks().includes(n.track)&&this.removeTrack(n)})})}function Yh(i){i.DataChannel&&!i.RTCDataChannel&&(i.RTCDataChannel=i.DataChannel)}function Kh(i){if(!(typeof i=="object"&&i.RTCPeerConnection))return;const e=i.RTCPeerConnection.prototype.addTransceiver;e&&(i.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let n=arguments[1]&&arguments[1].sendEncodings;n===void 0&&(n=[]),n=[...n];const s=n.length>0;s&&n.forEach(a=>{if("rid"in a&&!/^[a-z0-9]{0,16}$/i.test(a.rid))throw new TypeError("Invalid RID value provided.");if("scaleResolutionDownBy"in a&&!(parseFloat(a.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in a&&!(parseFloat(a.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")});const r=e.apply(this,arguments);if(s){const{sender:a}=r,o=a.getParameters();(!("encodings"in o)||o.encodings.length===1&&Object.keys(o.encodings[0]).length===0)&&(o.encodings=n,a.sendEncodings=n,this.setParametersPromises.push(a.setParameters(o).then(()=>{delete a.sendEncodings}).catch(()=>{delete a.sendEncodings})))}return r})}function Jh(i){if(!(typeof i=="object"&&i.RTCRtpSender))return;const e=i.RTCRtpSender.prototype.getParameters;e&&(i.RTCRtpSender.prototype.getParameters=function(){const n=e.apply(this,arguments);return"encodings"in n||(n.encodings=[].concat(this.sendEncodings||[{}])),n})}function Zh(i){if(!(typeof i=="object"&&i.RTCPeerConnection))return;const e=i.RTCPeerConnection.prototype.createOffer;i.RTCPeerConnection.prototype.createOffer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>e.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):e.apply(this,arguments)}}function Qh(i){if(!(typeof i=="object"&&i.RTCPeerConnection))return;const e=i.RTCPeerConnection.prototype.createAnswer;i.RTCPeerConnection.prototype.createAnswer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>e.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):e.apply(this,arguments)}}var ef=Object.freeze({__proto__:null,shimAddTransceiver:Kh,shimCreateAnswer:Qh,shimCreateOffer:Zh,shimGetDisplayMedia:l0,shimGetParameters:Jh,shimGetUserMedia:Wh,shimOnTrack:qh,shimPeerConnection:bc,shimRTCDataChannel:Yh,shimReceiverGetStats:jh,shimRemoveStream:Xh,shimSenderGetStats:$h});function tf(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 nf(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 sf(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(l,d){const u=arguments.length>=2?arguments[2]:arguments[0],h=t.apply(this,[u]);return d?(h.then(l,d),Promise.resolve()):h},e.createAnswer=function(l,d){const u=arguments.length>=2?arguments[2]:arguments[0],h=n.apply(this,[u]);return d?(h.then(l,d),Promise.resolve()):h};let o=function(c,l,d){const u=s.apply(this,[c]);return d?(u.then(l,d),Promise.resolve()):u};e.setLocalDescription=o,o=function(c,l,d){const u=r.apply(this,[c]);return d?(u.then(l,d),Promise.resolve()):u},e.setRemoteDescription=o,o=function(c,l,d){const u=a.apply(this,[c]);return d?(u.then(l,d),Promise.resolve()):u},e.addIceCandidate=o}function rf(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(af(s))}!e.getUserMedia&&e.mediaDevices&&e.mediaDevices.getUserMedia&&(e.getUserMedia=(function(n,s,r){e.mediaDevices.getUserMedia(n).then(s,r)}).bind(e))}function af(i){return i&&i.video!==void 0?Object.assign({},i,{video:Ih(i.video)}):i}function of(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?(mc("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 cf(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 lf(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 df(i){typeof i!="object"||i.AudioContext||(i.AudioContext=i.webkitAudioContext)}var uf=Object.freeze({__proto__:null,shimAudioContext:df,shimCallbacksAPI:sf,shimConstraints:af,shimCreateOfferLegacy:lf,shimGetUserMedia:rf,shimLocalStreamsAPI:tf,shimRTCIceServerUrls:of,shimRemoteStreamsAPI:nf,shimTrackEventTransceiver:cf}),yc={exports:{}},hf;function d0(){return hf||(hf=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(`
|
|
47
|
+
*/const ga=()=>new Tg;let Tg=class{};const jo=new WeakMap,va=vg(class extends xg{render(i){return Nt}update(i,[e]){var n;const t=e!==this.Y;return t&&this.Y!==void 0&&this.rt(void 0),(t||this.lt!==this.ct)&&(this.Y=e,this.ht=(n=i.options)==null?void 0:n.host,this.rt(this.ct=i.element)),Nt}rt(i){if(this.isConnected||(i=void 0),typeof this.Y=="function"){const e=this.ht??globalThis;let t=jo.get(e);t===void 0&&(t=new WeakMap,jo.set(e,t)),t.get(this.Y)!==void 0&&this.Y.call(this.ht,void 0),t.set(this.Y,i),i!==void 0&&this.Y.call(this.ht,i)}else this.Y.value=i}get lt(){var i,e;return typeof this.Y=="function"?(i=jo.get(this.ht??globalThis))==null?void 0:i.get(this.Y):(e=this.Y)==null?void 0:e.value}disconnected(){this.lt===this.ct&&this.rt(void 0)}reconnected(){this.rt(this.ct)}});function Cg(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 Eg=Object.defineProperty,Mg=(i,e,t)=>e in i?Eg(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,bu=(i,e,t)=>Mg(i,typeof e!="symbol"?e+"":e,t);class cn{constructor(){bu(this,"_locking"),bu(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 Rt(i,e){if(!i)throw new Error(e)}const wg=34028234663852886e22,Ag=-34028234663852886e22,Rg=4294967295,Pg=2147483647,kg=-2147483648;function ba(i){if(typeof i!="number")throw new Error("invalid int 32: "+typeof i);if(!Number.isInteger(i)||i>Pg||i<kg)throw new Error("invalid int 32: "+i)}function Xo(i){if(typeof i!="number")throw new Error("invalid uint 32: "+typeof i);if(!Number.isInteger(i)||i>Rg||i<0)throw new Error("invalid uint 32: "+i)}function yu(i){if(typeof i!="number")throw new Error("invalid float 32: "+typeof i);if(Number.isFinite(i)&&(i>wg||i<Ag))throw new Error("invalid float 32: "+i)}const _u=Symbol("@bufbuild/protobuf/enum-type");function Ig(i){const e=i[_u];return Rt(e,"missing enum type on enum object"),e}function Su(i,e,t,n){i[_u]=xu(e,t.map(s=>({no:s.no,name:s.name,localName:i[s.no]})))}function xu(i,e,t){const n=Object.create(null),s=Object.create(null),r=[];for(const a of e){const o=Tu(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 Dg(i,e,t){const n={};for(const s of e){const r=Tu(s);n[r.localName]=r.no,n[r.no]=r.localName}return Su(n,i,e),n}function Tu(i){return"localName"in i?i:Object.assign(Object.assign({},i),{localName:i.name})}class Yo{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==null?void 0:e.prettySpaces)!==null&&t!==void 0?t:0)}toJSON(){return this.toJson({emitDefaultValues:!0})}getType(){return Object.getPrototypeOf(this).constructor}}function Lg(i,e,t,n){var s;const r=(s=n==null?void 0: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 Yo),Object.assign(a,{runtime:i,typeName:e,fields:i.util.newFieldList(t),fromBinary(o,c){return new a().fromBinary(o,c)},fromJson(o,c){return new a().fromJson(o,c)},fromJsonString(o,c){return new a().fromJsonString(o,c)},equals(o,c){return i.util.equals(a,o,c)}}),a}function Ug(){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 Ko(i,e,t){for(let r=0;r<28;r=r+7){const a=i>>>r,o=!(!(a>>>7)&&e==0),c=(o?a|128:a)&255;if(t.push(c),!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),c=(o?a|128:a)&255;if(t.push(c),!o)return}t.push(e>>>31&1)}}const ya=4294967296;function Cu(i){const e=i[0]==="-";e&&(i=i.slice(1));const t=1e6;let n=0,s=0;function r(a,o){const c=Number(i.slice(a,o));s*=t,n=n*t+c,n>=ya&&(s=s+(n/ya|0),n=n%ya)}return r(-24,-18),r(-18,-12),r(-12,-6),r(-6),e?Mu(n,s):Jo(n,s)}function Ng(i,e){let t=Jo(i,e);const n=t.hi&2147483648;n&&(t=Mu(t.lo,t.hi));const s=Eu(t.lo,t.hi);return n?"-"+s:s}function Eu(i,e){if({lo:i,hi:e}=Og(i,e),e<=2097151)return String(ya*e+i);const t=i&16777215,n=(i>>>24|e<<8)&16777215,s=e>>16&65535;let r=t+n*6777216+s*6710656,a=n+s*8147497,o=s*2;const c=1e7;return r>=c&&(a+=Math.floor(r/c),r%=c),a>=c&&(o+=Math.floor(a/c),a%=c),o.toString()+wu(a)+wu(r)}function Og(i,e){return{lo:i>>>0,hi:e>>>0}}function Jo(i,e){return{lo:i|0,hi:e|0}}function Mu(i,e){return e=~e,i?i=~i+1:e+=1,Jo(i,e)}const wu=i=>{const e=String(i);return"0000000".slice(e.length)+e};function Au(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 Fg(){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 Bg(){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 process.env!="object"||process.env.BUF_BIGINT_DISABLE!=="1")){const s=BigInt("-9223372036854775808"),r=BigInt("9223372036854775807"),a=BigInt("0"),o=BigInt("18446744073709551615");return{zero:BigInt(0),supported:!0,parse(c){const l=typeof c=="bigint"?c:BigInt(c);if(l>r||l<s)throw new Error("int64 invalid: ".concat(c));return l},uParse(c){const l=typeof c=="bigint"?c:BigInt(c);if(l>o||l<a)throw new Error("uint64 invalid: ".concat(c));return l},enc(c){return i.setBigInt64(0,this.parse(c),!0),{lo:i.getInt32(0,!0),hi:i.getInt32(4,!0)}},uEnc(c){return i.setBigInt64(0,this.uParse(c),!0),{lo:i.getInt32(0,!0),hi:i.getInt32(4,!0)}},dec(c,l){return i.setInt32(0,c,!0),i.setInt32(4,l,!0),i.getBigInt64(0,!0)},uDec(c,l){return i.setInt32(0,c,!0),i.setInt32(4,l,!0),i.getBigUint64(0,!0)}}}const t=s=>Rt(/^-?[0-9]+$/.test(s),"int64 invalid: ".concat(s)),n=s=>Rt(/^[0-9]+$/.test(s),"uint64 invalid: ".concat(s));return{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),Cu(s)},uEnc(s){return typeof s!="string"&&(s=s.toString()),n(s),Cu(s)},dec(s,r){return Ng(s,r)},uDec(s,r){return Eu(s,r)}}}const At=Bg();var Z;(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"})(Z||(Z={}));var Ni;(function(i){i[i.BIGINT=0]="BIGINT",i[i.STRING=1]="STRING"})(Ni||(Ni={}));function Oi(i,e,t){if(e===t)return!0;if(i==Z.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 Z.UINT64:case Z.FIXED64:case Z.INT64:case Z.SFIXED64:case Z.SINT64:return e==t}return!1}function Ps(i,e){switch(i){case Z.BOOL:return!1;case Z.UINT64:case Z.FIXED64:case Z.INT64:case Z.SFIXED64:case Z.SINT64:return e==0?At.zero:"0";case Z.DOUBLE:case Z.FLOAT:return 0;case Z.BYTES:return new Uint8Array(0);case Z.STRING:return"";default:return 0}}function Ru(i,e){switch(i){case Z.BOOL:return e===!1;case Z.STRING:return e==="";case Z.BYTES:return e instanceof Uint8Array&&!e.byteLength;default:return e==0}}var Lt;(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"})(Lt||(Lt={}));class zg{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;s++)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(Xo(e);e>127;)this.buf.push(e&127|128),e=e>>>7;return this.buf.push(e),this}int32(e){return ba(e),Au(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){yu(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){Xo(e);let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!0),this.raw(t)}sfixed32(e){ba(e);let t=new Uint8Array(4);return new DataView(t.buffer).setInt32(0,e,!0),this.raw(t)}sint32(e){return ba(e),e=(e<<1^e>>31)>>>0,Au(e,this.buf),this}sfixed64(e){let t=new Uint8Array(8),n=new DataView(t.buffer),s=At.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=At.uEnc(e);return n.setInt32(0,s.lo,!0),n.setInt32(4,s.hi,!0),this.raw(t)}int64(e){let t=At.enc(e);return Ko(t.lo,t.hi,this.buf),this}sint64(e){let t=At.enc(e),n=t.hi>>31,s=t.lo<<1^n,r=(t.hi<<1|t.lo>>>31)^n;return Ko(s,r,this.buf),this}uint64(e){let t=At.uEnc(e);return Ko(t.lo,t.hi,this.buf),this}}class Vg{constructor(e,t){this.varint64=Ug,this.uint32=Fg,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 Lt.Varint:for(;this.buf[this.pos++]&128;);break;case Lt.Bit64:this.pos+=4;case Lt.Bit32:this.pos+=4;break;case Lt.LengthDelimited:let s=this.uint32();this.pos+=s;break;case Lt.StartGroup:for(;;){const[r,a]=this.tag();if(a===Lt.EndGroup){if(t!==void 0&&r!==t)throw new Error("invalid end group tag");break}this.skip(a,r)}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 At.dec(...this.varint64())}uint64(){return At.uDec(...this.varint64())}sint64(){let[e,t]=this.varint64(),n=-(e&1);return e=(e>>>1|(t&1)<<31)^n,t=t>>>1^n,At.dec(e,t)}bool(){let[e,t]=this.varint64();return e!==0||t!==0}fixed32(){return this.view.getUint32((this.pos+=4)-4,!0)}sfixed32(){return this.view.getInt32((this.pos+=4)-4,!0)}fixed64(){return At.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return At.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 Gg(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 Pu(i){const e=i.field.localName,t=Object.create(null);return t[e]=Hg(i),[t,()=>t[e]]}function Hg(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 Ps(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 Wg(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 ui="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),_a=[];for(let i=0;i<ui.length;i++)_a[ui[i].charCodeAt(0)]=i;_a[45]=ui.indexOf("+"),_a[95]=ui.indexOf("/");const ku={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=_a[i.charCodeAt(o)],r===void 0)switch(i[o]){case"=":s=0;case`
|
|
48
|
+
`: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+=ui[n>>2],s=(n&3)<<4,t=1;break;case 1:e+=ui[s|n>>4],s=(n&15)<<2,t=2;break;case 2:e+=ui[s|n>>6],e+=ui[n&63],t=0;break}return t&&(e+=ui[s],e+="=",t==1&&(e+="=")),e}};function qg(i,e,t){Du(e,i);const n=e.runtime.bin.makeReadOptions(t),s=Wg(i.getType().runtime.bin.listUnknownFields(i),e.field),[r,a]=Pu(e);for(const o of s)e.runtime.bin.readField(r,n.readerFactory(o.data),e.field,o.wireType,n);return a()}function $g(i,e,t,n){Du(e,i);const s=e.runtime.bin.makeReadOptions(n),r=e.runtime.bin.makeWriteOptions(n);if(Iu(i,e)){const l=i.getType().runtime.bin.listUnknownFields(i).filter(d=>d.no!=e.field.no);i.getType().runtime.bin.discardUnknownFields(i);for(const d of l)i.getType().runtime.bin.onUnknownField(i,d.no,d.wireType,d.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 c=s.readerFactory(a.finish());for(;c.pos<c.len;){const[l,d]=c.tag(),u=c.skip(d,l);i.getType().runtime.bin.onUnknownField(i,l,d,u)}}function Iu(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 Du(i,e){Rt(i.extendee.typeName==e.getType().typeName,"extension ".concat(i.typeName," can only be applied to message ").concat(i.extendee.typeName))}function Lu(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:!Ru(i.T,e[t]);case"message":return e[t]!==void 0;case"map":return Object.keys(e[t]).length>0}}function Uu(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?Ps(i.T,i.L):void 0;break;case"message":e[t]=void 0;break}}function hi(i,e){if(i===null||typeof i!="object"||!Object.getOwnPropertyNames(Yo.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 Nu(i,e){return hi(e)||!i.fieldWrapper?e:i.fieldWrapper.wrapField(e)}Z.DOUBLE,Z.FLOAT,Z.INT64,Z.UINT64,Z.INT32,Z.UINT32,Z.BOOL,Z.STRING,Z.BYTES;const Ou={ignoreUnknownFields:!1},Fu={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0};function jg(i){return i?Object.assign(Object.assign({},Ou),i):Ou}function Xg(i){return i?Object.assign(Object.assign({},Fu),i):Fu}const Sa=Symbol(),xa=Symbol();function Yg(){return{makeReadOptions:jg,makeWriteOptions:Xg,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($n(e)));n=n??new i;const s=new Map,r=t.typeRegistry;for(const[a,o]of Object.entries(e)){const c=i.fields.findJsonName(a);if(c){if(c.oneof){if(o===null&&c.kind=="scalar")continue;const l=s.get(c.oneof);if(l!==void 0)throw new Error("cannot decode message ".concat(i.typeName,' from JSON: multiple keys for oneof "').concat(c.oneof.name,'" present: "').concat(l,'", "').concat(a,'"'));s.set(c.oneof,a)}Bu(n,o,c,t,i)}else{let l=!1;if(r!=null&&r.findExtension&&a.startsWith("[")&&a.endsWith("]")){const d=r.findExtension(a.substring(1,a.length-1));if(d&&d.extendee.typeName==i.typeName){l=!0;const[u,h]=Pu(d);Bu(u,o,d.field,t,d),$g(n,d,h(),t)}}if(!l&&!t.ignoreUnknownFields)throw new Error("cannot decode message ".concat(i.typeName,' from JSON: key "').concat(a,'" is unknown'))}}return n},writeMessage(i,e){const t=i.getType(),n={};let s;try{for(s of t.fields.byNumber()){if(!Lu(s,i)){if(s.req)throw"required field not set";if(!e.emitDefaultValues||!Jg(s))continue}const a=s.oneof?i[s.oneof.localName].value:i[s.localName],o=zu(s,a,e);o!==void 0&&(n[e.useProtoFieldName?s.name:s.jsonName]=o)}const r=e.typeRegistry;if(r!=null&&r.findExtensionFor)for(const a of t.runtime.bin.listUnknownFields(i)){const o=r.findExtensionFor(t.typeName,a.no);if(o&&Iu(i,o)){const c=qg(i,o,e),l=zu(o.field,c,e);l!==void 0&&(n[o.field.jsonName]=l)}}}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},readScalar(i,e,t){return wr(i,e,t??Ni.BIGINT,!0)},writeScalar(i,e,t){if(e!==void 0&&(t||Ru(i,e)))return Ta(i,e)},debug:$n}}function $n(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 Bu(i,e,t,n,s){let r=t.localName;if(t.repeated){if(Rt(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($n(e)));const a=i[r];for(const o of e){if(o===null)throw new Error("cannot decode field ".concat(s.typeName,".").concat(t.name," from JSON: ").concat($n(o)));switch(t.kind){case"message":a.push(t.T.fromJson(o,n));break;case"enum":const c=Zo(t.T,o,n.ignoreUnknownFields,!0);c!==xa&&a.push(c);break;case"scalar":try{a.push(wr(t.T,o,t.L,!0))}catch(l){let d="cannot decode field ".concat(s.typeName,".").concat(t.name," from JSON: ").concat($n(o));throw l instanceof Error&&l.message.length>0&&(d+=": ".concat(l.message)),new Error(d)}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($n(e)));const a=i[r];for(const[o,c]of Object.entries(e)){if(c===null)throw new Error("cannot decode field ".concat(s.typeName,".").concat(t.name," from JSON: map value null"));let l;try{l=Kg(t.K,o)}catch(d){let u="cannot decode map key for field ".concat(s.typeName,".").concat(t.name," from JSON: ").concat($n(e));throw d instanceof Error&&d.message.length>0&&(u+=": ".concat(d.message)),new Error(u)}switch(t.V.kind){case"message":a[l]=t.V.T.fromJson(c,n);break;case"enum":const d=Zo(t.V.T,c,n.ignoreUnknownFields,!0);d!==xa&&(a[l]=d);break;case"scalar":try{a[l]=wr(t.V.T,c,Ni.BIGINT,!0)}catch(u){let h="cannot decode map value for field ".concat(s.typeName,".").concat(t.name," from JSON: ").concat($n(e));throw u instanceof Error&&u.message.length>0&&(h+=": ".concat(u.message)),new Error(h)}break}}}else switch(t.oneof&&(i=i[t.oneof.localName]={case:r},r="value"),t.kind){case"message":const a=t.T;if(e===null&&a.typeName!="google.protobuf.Value")return;let o=i[r];hi(o)?o.fromJson(e,n):(i[r]=o=a.fromJson(e,n),a.fieldWrapper&&!t.oneof&&(i[r]=a.fieldWrapper.unwrapField(o)));break;case"enum":const c=Zo(t.T,e,n.ignoreUnknownFields,!1);switch(c){case Sa:Uu(t,i);break;case xa:break;default:i[r]=c;break}break;case"scalar":try{const l=wr(t.T,e,t.L,!1);switch(l){case Sa:Uu(t,i);break;default:i[r]=l;break}}catch(l){let d="cannot decode field ".concat(s.typeName,".").concat(t.name," from JSON: ").concat($n(e));throw l instanceof Error&&l.message.length>0&&(d+=": ".concat(l.message)),new Error(d)}break}}function Kg(i,e){if(i===Z.BOOL)switch(e){case"true":e=!0;break;case"false":e=!1;break}return wr(i,e,Ni.BIGINT,!0).toString()}function wr(i,e,t,n){if(e===null)return n?Ps(i,t):Sa;switch(i){case Z.DOUBLE:case Z.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==Z.FLOAT&&yu(s),s;case Z.INT32:case Z.FIXED32:case Z.SFIXED32:case Z.SINT32:case Z.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==Z.UINT32||i==Z.FIXED32?Xo(r):ba(r),r;case Z.INT64:case Z.SFIXED64:case Z.SINT64:if(typeof e!="number"&&typeof e!="string")break;const a=At.parse(e);return t?a.toString():a;case Z.FIXED64:case Z.UINT64:if(typeof e!="number"&&typeof e!="string")break;const o=At.uParse(e);return t?o.toString():o;case Z.BOOL:if(typeof e!="boolean")break;return e;case Z.STRING:if(typeof e!="string")break;try{encodeURIComponent(e)}catch{throw new Error("invalid UTF8")}return e;case Z.BYTES:if(e==="")return new Uint8Array(0);if(typeof e!="string")break;return ku.dec(e)}throw new Error}function Zo(i,e,t,n){if(e===null)return i.typeName=="google.protobuf.NullValue"?0:n?i.values[0].no:Sa;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 xa;break}throw new Error("cannot decode enum ".concat(i.typeName," from JSON: ").concat($n(e)))}function Jg(i){return i.repeated||i.kind=="map"?!0:!(i.oneof||i.kind=="message"||i.opt||i.req)}function zu(i,e,t){if(i.kind=="map"){Rt(typeof e=="object"&&e!=null);const n={},s=Object.entries(e);switch(i.V.kind){case"scalar":for(const[a,o]of s)n[a.toString()]=Ta(i.V.T,o);break;case"message":for(const[a,o]of s)n[a.toString()]=o.toJson(t);break;case"enum":const r=i.V.T;for(const[a,o]of s)n[a.toString()]=Qo(r,o,t.enumAsInteger);break}return t.emitDefaultValues||s.length>0?n:void 0}if(i.repeated){Rt(Array.isArray(e));const n=[];switch(i.kind){case"scalar":for(let s=0;s<e.length;s++)n.push(Ta(i.T,e[s]));break;case"enum":for(let s=0;s<e.length;s++)n.push(Qo(i.T,e[s],t.enumAsInteger));break;case"message":for(let s=0;s<e.length;s++)n.push(e[s].toJson(t));break}return t.emitDefaultValues||n.length>0?n:void 0}switch(i.kind){case"scalar":return Ta(i.T,e);case"enum":return Qo(i.T,e,t.enumAsInteger);case"message":return Nu(i.T,e).toJson(t)}}function Qo(i,e,t){var n;if(Rt(typeof e=="number"),i.typeName=="google.protobuf.NullValue")return null;if(t)return e;const s=i.findNumber(e);return(n=s==null?void 0:s.name)!==null&&n!==void 0?n:e}function Ta(i,e){switch(i){case Z.INT32:case Z.SFIXED32:case Z.SINT32:case Z.FIXED32:case Z.UINT32:return Rt(typeof e=="number"),e;case Z.FLOAT:case Z.DOUBLE:return Rt(typeof e=="number"),Number.isNaN(e)?"NaN":e===Number.POSITIVE_INFINITY?"Infinity":e===Number.NEGATIVE_INFINITY?"-Infinity":e;case Z.STRING:return Rt(typeof e=="string"),e;case Z.BOOL:return Rt(typeof e=="boolean"),e;case Z.UINT64:case Z.FIXED64:case Z.INT64:case Z.SFIXED64:case Z.SINT64:return Rt(typeof e=="bigint"||typeof e=="string"||typeof e=="number"),e.toString();case Z.BYTES:return Rt(e instanceof Uint8Array),ku.enc(e)}}const ks=Symbol("@bufbuild/protobuf/unknown-fields"),Vu={readUnknownFields:!0,readerFactory:i=>new Vg(i)},Gu={writeUnknownFields:!0,writerFactory:()=>new zg};function Zg(i){return i?Object.assign(Object.assign({},Vu),i):Vu}function Qg(i){return i?Object.assign(Object.assign({},Gu),i):Gu}function ev(){return{makeReadOptions:Zg,makeWriteOptions:Qg,listUnknownFields(i){var e;return(e=i[ks])!==null&&e!==void 0?e:[]},discardUnknownFields(i){delete i[ks]},writeUnknownFields(i,e){const n=i[ks];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[ks])||(s[ks]=[]),s[ks].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,c;for(;e.pos<a&&([o,c]=e.tag(),!(s===!0&&c==Lt.EndGroup));){const l=r.fields.find(o);if(!l){const d=e.skip(c,o);n.readUnknownFields&&this.onUnknownField(i,o,c,d);continue}Hu(i,e,l,c,n)}if(s&&(c!=Lt.EndGroup||o!==t))throw new Error("invalid end group tag")},readField:Hu,writeMessage(i,e,t){const n=i.getType();for(const s of n.fields.byNumber()){if(!Lu(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];Wu(s,r,e,t)}return t.writeUnknownFields&&this.writeUnknownFields(i,e),e},writeField(i,e,t,n){e!==void 0&&Wu(i,e,t,n)}}}function Hu(i,e,t,n,s){let{repeated:r,localName:a}=t;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"?Z.INT32:t.T;let c=Ea;if(t.kind=="scalar"&&t.L>0&&(c=nv),r){let h=i[a];if(n==Lt.LengthDelimited&&o!=Z.STRING&&o!=Z.BYTES){let g=e.uint32()+e.pos;for(;e.pos<g;)h.push(c(e,o))}else h.push(c(e,o))}else i[a]=c(e,o);break;case"message":const l=t.T;r?i[a].push(Ca(e,new l,s,t)):hi(i[a])?Ca(e,i[a],s,t):(i[a]=Ca(e,new l,s,t),l.fieldWrapper&&!t.oneof&&!t.repeated&&(i[a]=l.fieldWrapper.unwrapField(i[a])));break;case"map":let[d,u]=tv(t,e,s);i[a][d]=u;break}}function Ca(i,e,t,n){const s=e.getType().runtime.bin,r=n==null?void 0:n.delimited;return s.readMessage(e,i,r?n.no:i.uint32(),t,r),e}function tv(i,e,t){const n=e.uint32(),s=e.pos+n;let r,a;for(;e.pos<s;){const[o]=e.tag();switch(o){case 1:r=Ea(e,i.K);break;case 2:switch(i.V.kind){case"scalar":a=Ea(e,i.V.T);break;case"enum":a=e.int32();break;case"message":a=Ca(e,new i.V.T,t,void 0);break}break}}if(r===void 0&&(r=Ps(i.K,Ni.BIGINT)),typeof r!="string"&&typeof r!="number"&&(r=r.toString()),a===void 0)switch(i.V.kind){case"scalar":a=Ps(i.V.T,Ni.BIGINT);break;case"enum":a=i.V.T.values[0].no;break;case"message":a=new i.V.T;break}return[r,a]}function nv(i,e){const t=Ea(i,e);return typeof t=="bigint"?t.toString():t}function Ea(i,e){switch(e){case Z.STRING:return i.string();case Z.BOOL:return i.bool();case Z.DOUBLE:return i.double();case Z.FLOAT:return i.float();case Z.INT32:return i.int32();case Z.INT64:return i.int64();case Z.UINT64:return i.uint64();case Z.FIXED64:return i.fixed64();case Z.BYTES:return i.bytes();case Z.FIXED32:return i.fixed32();case Z.SFIXED32:return i.sfixed32();case Z.SFIXED64:return i.sfixed64();case Z.SINT64:return i.sint64();case Z.UINT32:return i.uint32();case Z.SINT32:return i.sint32()}}function Wu(i,e,t,n){Rt(e!==void 0);const s=i.repeated;switch(i.kind){case"scalar":case"enum":let r=i.kind=="enum"?Z.INT32:i.T;if(s)if(Rt(Array.isArray(e)),i.packed)sv(t,r,i.no,e);else for(const a of e)Ar(t,r,i.no,a);else Ar(t,r,i.no,e);break;case"message":if(s){Rt(Array.isArray(e));for(const a of e)qu(t,n,i,a)}else qu(t,n,i,e);break;case"map":Rt(typeof e=="object"&&e!=null);for(const[a,o]of Object.entries(e))iv(t,n,i,a,o);break}}function iv(i,e,t,n,s){i.tag(t.no,Lt.LengthDelimited),i.fork();let r=n;switch(t.K){case Z.INT32:case Z.FIXED32:case Z.UINT32:case Z.SFIXED32:case Z.SINT32:r=Number.parseInt(n);break;case Z.BOOL:Rt(n=="true"||n=="false"),r=n=="true";break}switch(Ar(i,t.K,1,r),t.V.kind){case"scalar":Ar(i,t.V.T,2,s);break;case"enum":Ar(i,Z.INT32,2,s);break;case"message":Rt(s!==void 0),i.tag(2,Lt.LengthDelimited).bytes(s.toBinary(e));break}i.join()}function qu(i,e,t,n){const s=Nu(t.T,n);t.delimited?i.tag(t.no,Lt.StartGroup).raw(s.toBinary(e)).tag(t.no,Lt.EndGroup):i.tag(t.no,Lt.LengthDelimited).bytes(s.toBinary(e))}function Ar(i,e,t,n){Rt(n!==void 0);let[s,r]=$u(e);i.tag(t,s)[r](n)}function sv(i,e,t,n){if(!n.length)return;i.tag(t,Lt.LengthDelimited).fork();let[,s]=$u(e);for(let r=0;r<n.length;r++)i[s](n[r]);i.join()}function $u(i){let e=Lt.Varint;switch(i){case Z.BYTES:case Z.STRING:e=Lt.LengthDelimited;break;case Z.DOUBLE:case Z.FIXED64:case Z.SFIXED64:e=Lt.Bit64;break;case Z.FIXED32:case Z.SFIXED32:case Z.FLOAT:e=Lt.Bit32;break}const t=Z[i].toLowerCase();return[e,t]}function rv(){return{setEnumType:Su,initPartial(i,e){if(i===void 0)return;const t=e.getType();for(const n of t.fields.byMember()){const s=n.localName,r=e,a=i;if(a[s]!=null)switch(n.kind){case"oneof":const o=a[s].case;if(o===void 0)continue;const c=n.findField(o);let l=a[s].value;c&&c.kind=="message"&&!hi(l,c.T)?l=new c.T(l):c&&c.kind==="scalar"&&c.T===Z.BYTES&&(l=Rr(l)),r[s]={case:o,value:l};break;case"scalar":case"enum":let d=a[s];n.T===Z.BYTES&&(d=n.repeated?d.map(Rr):Rr(d)),r[s]=d;break;case"map":switch(n.V.kind){case"scalar":case"enum":if(n.V.T===Z.BYTES)for(const[f,g]of Object.entries(a[s]))r[s][f]=Rr(g);else Object.assign(r[s],a[s]);break;case"message":const h=n.V.T;for(const f of Object.keys(a[s])){let g=a[s][f];h.fieldWrapper||(g=new h(g)),r[s][f]=g}break}break;case"message":const u=n.T;if(n.repeated)r[s]=a[s].map(h=>hi(h,u)?h:new u(h));else{const h=a[s];u.fieldWrapper?u.typeName==="google.protobuf.BytesValue"?r[s]=Rr(h):r[s]=h:r[s]=hi(h,u)?h:new u(h)}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)=>Oi(n.T,a,r[o]));case"enum":return s.every((a,o)=>Oi(Z.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&&!hi(a)&&(a=n.T.fieldWrapper.wrapField(a)),o!==void 0&&!hi(o)&&(o=n.T.fieldWrapper.wrapField(o))),n.T.equals(a,o);case"enum":return Oi(Z.INT32,s,r);case"scalar":return Oi(n.T,s,r);case"oneof":if(s.case!==r.case)return!1;const c=n.findField(s.case);if(c===void 0)return!0;switch(c.kind){case"message":return c.T.equals(s.value,r.value);case"enum":return Oi(Z.INT32,s.value,r.value);case"scalar":return Oi(c.T,s.value,r.value)}throw new Error("oneof cannot contain ".concat(c.kind));case"map":const l=Object.keys(s).concat(Object.keys(r));switch(n.V.kind){case"message":const d=n.V.T;return l.every(h=>d.equals(s[h],r[h]));case"enum":return l.every(h=>Oi(Z.INT32,s[h],r[h]));case"scalar":const u=n.V.T;return l.every(h=>Oi(u,s[h],r[h]))}break}})},clone(i){const e=i.getType(),t=new e,n=t;for(const s of e.fields.byMember()){const r=i[s.localName];let a;if(s.repeated)a=r.map(Ma);else if(s.kind=="map"){a=n[s.localName];for(const[o,c]of Object.entries(r))a[o]=Ma(c)}else s.kind=="oneof"?a=s.findField(r.case)?{case:r.case,value:Ma(r.value)}:{case:void 0}:a=Ma(r);n[s.localName]=a}for(const s of e.runtime.bin.listUnknownFields(i))e.runtime.bin.onUnknownField(n,s.no,s.wireType,s.data);return t}}}function Ma(i){if(i===void 0)return i;if(hi(i))return i.clone();if(i instanceof Uint8Array){const e=new Uint8Array(i.byteLength);return e.set(i),e}return i}function Rr(i){return i instanceof Uint8Array?i:new Uint8Array(i)}function av(i,e,t){return{syntax:i,json:Yg(),bin:ev(),util:Object.assign(Object.assign({},rv()),{newFieldList:e,initFields:t}),makeMessageType(n,s,r){return Lg(this,n,s,r)},makeEnum:Dg,makeEnumType:xu,getEnumType:Ig,makeExtension(n,s,r){return Gg(this,n,s,r)}}}class ov{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 ju(i,e){const t=Xu(i);return e?t:fv(hv(t))}function cv(i){return ju(i,!1)}const lv=Xu;function Xu(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 dv=new Set(["constructor","toString","toJSON","valueOf"]),uv=new Set(["getType","clone","equals","fromBinary","fromJson","fromJsonString","toBinary","toJson","toJsonString","toObject"]),Yu=i=>"".concat(i,"$"),hv=i=>uv.has(i)?Yu(i):i,fv=i=>dv.has(i)?Yu(i):i;class pv{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=cv(e)}addField(e){Rt(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 mv(i,e){var t,n,s,r,a,o;const c=[];let l;for(const d of typeof i=="function"?i():i){const u=d;if(u.localName=ju(d.name,d.oneof!==void 0),u.jsonName=(t=d.jsonName)!==null&&t!==void 0?t:lv(d.name),u.repeated=(n=d.repeated)!==null&&n!==void 0?n:!1,d.kind=="scalar"&&(u.L=(s=d.L)!==null&&s!==void 0?s:Ni.BIGINT),u.delimited=(r=d.delimited)!==null&&r!==void 0?r:!1,u.req=(a=d.req)!==null&&a!==void 0?a:!1,u.opt=(o=d.opt)!==null&&o!==void 0?o:!1,d.packed===void 0&&(u.packed=d.kind=="enum"||d.kind=="scalar"&&d.T!=Z.BYTES&&d.T!=Z.STRING),d.oneof!==void 0){const h=typeof d.oneof=="string"?d.oneof:d.oneof.name;(!l||l.name!=h)&&(l=new pv(h)),u.oneof=l,l.addField(u)}c.push(u)}return c}const G=av("proto3",i=>new ov(i,e=>mv(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]=Ps(e.T,e.L);break}}});class ln extends Yo{constructor(e){super(),this.seconds=At.zero,this.nanos=0,G.util.initPartial(e,this)}fromJson(e,t){if(typeof e!="string")throw new Error("cannot decode google.protobuf.Timestamp from JSON: ".concat(G.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=At.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 ln.fromDate(new Date)}static fromDate(e){const t=e.getTime();return new ln({seconds:At.parse(Math.floor(t/1e3)),nanos:t%1e3*1e6})}static fromBinary(e,t){return new ln().fromBinary(e,t)}static fromJson(e,t){return new ln().fromJson(e,t)}static fromJsonString(e,t){return new ln().fromJsonString(e,t)}static equals(e,t){return G.util.equals(ln,e,t)}}ln.runtime=G,ln.typeName="google.protobuf.Timestamp",ln.fields=G.util.newFieldList(()=>[{no:1,name:"seconds",kind:"scalar",T:3},{no:2,name:"nanos",kind:"scalar",T:5}]);const gv=G.makeMessageType("livekit.MetricsBatch",()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:ln},{no:3,name:"str_data",kind:"scalar",T:9,repeated:!0},{no:4,name:"time_series",kind:"message",T:vv,repeated:!0},{no:5,name:"events",kind:"message",T:yv,repeated:!0}]),vv=G.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:bv,repeated:!0},{no:5,name:"rid",kind:"scalar",T:13}]),bv=G.makeMessageType("livekit.MetricSample",()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:ln},{no:3,name:"value",kind:"scalar",T:2}]),yv=G.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:ln},{no:7,name:"normalized_end_timestamp",kind:"message",T:ln,opt:!0},{no:8,name:"metadata",kind:"scalar",T:9},{no:9,name:"rid",kind:"scalar",T:13}]),Ku=G.makeEnum("livekit.BackupCodecPolicy",[{no:0,name:"PREFER_REGRESSION"},{no:1,name:"SIMULCAST"},{no:2,name:"REGRESSION"}]),kn=G.makeEnum("livekit.TrackType",[{no:0,name:"AUDIO"},{no:1,name:"VIDEO"},{no:2,name:"DATA"}]),Ot=G.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"}]),ec=G.makeEnum("livekit.VideoQuality",[{no:0,name:"LOW"},{no:1,name:"MEDIUM"},{no:2,name:"HIGH"},{no:3,name:"OFF"}]),Pr=G.makeEnum("livekit.ConnectionQuality",[{no:0,name:"POOR"},{no:1,name:"GOOD"},{no:2,name:"EXCELLENT"},{no:3,name:"LOST"}]),kr=G.makeEnum("livekit.ClientConfigSetting",[{no:0,name:"UNSET"},{no:1,name:"DISABLED"},{no:2,name:"ENABLED"}]),In=G.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"}]),Is=G.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"}]),_v=G.makeEnum("livekit.SubscriptionError",[{no:0,name:"SE_UNKNOWN"},{no:1,name:"SE_CODEC_UNSUPPORTED"},{no:2,name:"SE_TRACK_NOTFOUND"}]),qt=G.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"}]),wa=G.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:Aa,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:dh}]),Aa=G.makeMessageType("livekit.Codec",()=>[{no:1,name:"mime",kind:"scalar",T:9},{no:2,name:"fmtp_line",kind:"scalar",T:9}]),Sv=G.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:G.getEnumType(Ot),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}]),ss=G.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:G.getEnumType(Ds)},{no:4,name:"tracks",kind:"message",T:Ls,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:Sv},{no:12,name:"region",kind:"scalar",T:9},{no:13,name:"is_publisher",kind:"scalar",T:8},{no:14,name:"kind",kind:"enum",T:G.getEnumType(Ir)},{no:15,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:16,name:"disconnect_reason",kind:"enum",T:G.getEnumType(In)},{no:18,name:"kind_details",kind:"enum",T:G.getEnumType(xv),repeated:!0}]),Ds=G.makeEnum("livekit.ParticipantInfo.State",[{no:0,name:"JOINING"},{no:1,name:"JOINED"},{no:2,name:"ACTIVE"},{no:3,name:"DISCONNECTED"}]),Ir=G.makeEnum("livekit.ParticipantInfo.Kind",[{no:0,name:"STANDARD"},{no:1,name:"INGRESS"},{no:2,name:"EGRESS"},{no:3,name:"SIP"},{no:4,name:"AGENT"}]),xv=G.makeEnum("livekit.ParticipantInfo.KindDetail",[{no:0,name:"CLOUD_AGENT"},{no:1,name:"FORWARDED"}]),vn=G.makeEnum("livekit.Encryption.Type",[{no:0,name:"NONE"},{no:1,name:"GCM"},{no:2,name:"CUSTOM"}]),Tv=G.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:rs,repeated:!0}]),Ls=G.makeMessageType("livekit.TrackInfo",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"type",kind:"enum",T:G.getEnumType(kn)},{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:G.getEnumType(Ot)},{no:10,name:"layers",kind:"message",T:rs,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:Tv,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:G.getEnumType(vn)},{no:17,name:"stream",kind:"scalar",T:9},{no:18,name:"version",kind:"message",T:dh},{no:19,name:"audio_features",kind:"enum",T:G.getEnumType(qt),repeated:!0},{no:20,name:"backup_codec_policy",kind:"enum",T:G.getEnumType(Ku)}]),rs=G.makeMessageType("livekit.VideoLayer",()=>[{no:1,name:"quality",kind:"enum",T:G.getEnumType(ec)},{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}]),dn=G.makeMessageType("livekit.DataPacket",()=>[{no:1,name:"kind",kind:"enum",T:G.getEnumType(We)},{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:Zu,oneof:"value"},{no:3,name:"speaker",kind:"message",T:Cv,oneof:"value"},{no:6,name:"sip_dtmf",kind:"message",T:Qu,oneof:"value"},{no:7,name:"transcription",kind:"message",T:Ev,oneof:"value"},{no:8,name:"metrics",kind:"message",T:gv,oneof:"value"},{no:9,name:"chat_message",kind:"message",T:tc,oneof:"value"},{no:10,name:"rpc_request",kind:"message",T:eh,oneof:"value"},{no:11,name:"rpc_ack",kind:"message",T:th,oneof:"value"},{no:12,name:"rpc_response",kind:"message",T:nh,oneof:"value"},{no:13,name:"stream_header",kind:"message",T:ic,oneof:"value"},{no:14,name:"stream_chunk",kind:"message",T:sc,oneof:"value"},{no:15,name:"stream_trailer",kind:"message",T:rc,oneof:"value"},{no:16,name:"sequence",kind:"scalar",T:13},{no:17,name:"participant_sid",kind:"scalar",T:9}]),We=G.makeEnum("livekit.DataPacket.Kind",[{no:0,name:"RELIABLE"},{no:1,name:"LOSSY"}]),Cv=G.makeMessageType("livekit.ActiveSpeakerUpdate",()=>[{no:1,name:"speakers",kind:"message",T:Ju,repeated:!0}]),Ju=G.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}]),Zu=G.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}]),Qu=G.makeMessageType("livekit.SipDTMF",()=>[{no:3,name:"code",kind:"scalar",T:13},{no:4,name:"digit",kind:"scalar",T:9}]),Ev=G.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:Mv,repeated:!0}]),Mv=G.makeMessageType("livekit.TranscriptionSegment",()=>[{no:1,name:"id",kind:"scalar",T:9},{no:2,name:"text",kind:"scalar",T:9},{no:3,name:"start_time",kind:"scalar",T:4},{no:4,name:"end_time",kind:"scalar",T:4},{no:5,name:"final",kind:"scalar",T:8},{no:6,name:"language",kind:"scalar",T:9}]),tc=G.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}]),eh=G.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}]),th=G.makeMessageType("livekit.RpcAck",()=>[{no:1,name:"request_id",kind:"scalar",T:9}]),nh=G.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:ih,oneof:"value"}]),ih=G.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}]),sh=G.makeMessageType("livekit.ParticipantTracks",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"track_sids",kind:"scalar",T:9,repeated:!0}]),rh=G.makeMessageType("livekit.ServerInfo",()=>[{no:1,name:"edition",kind:"enum",T:G.getEnumType(ah)},{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}]),ah=G.makeEnum("livekit.ServerInfo.Edition",[{no:0,name:"Standard"},{no:1,name:"Cloud"}]),wv=G.makeMessageType("livekit.ClientInfo",()=>[{no:1,name:"sdk",kind:"enum",T:G.getEnumType(oh)},{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}]),oh=G.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"}]),ch=G.makeMessageType("livekit.ClientConfiguration",()=>[{no:1,name:"video",kind:"message",T:lh},{no:2,name:"screen",kind:"message",T:lh},{no:3,name:"resume_connection",kind:"enum",T:G.getEnumType(kr)},{no:4,name:"disabled_codecs",kind:"message",T:Av},{no:5,name:"force_relay",kind:"enum",T:G.getEnumType(kr)}]),lh=G.makeMessageType("livekit.VideoConfiguration",()=>[{no:1,name:"hardware_encoder",kind:"enum",T:G.getEnumType(kr)}]),Av=G.makeMessageType("livekit.DisabledCodecs",()=>[{no:1,name:"codecs",kind:"message",T:Aa,repeated:!0},{no:2,name:"publish",kind:"message",T:Aa,repeated:!0}]),dh=G.makeMessageType("livekit.TimedVersion",()=>[{no:1,name:"unix_micro",kind:"scalar",T:3},{no:2,name:"ticks",kind:"scalar",T:5}]),nc=G.makeEnum("livekit.DataStream.OperationType",[{no:0,name:"CREATE"},{no:1,name:"UPDATE"},{no:2,name:"DELETE"},{no:3,name:"REACTION"}]),uh=G.makeMessageType("livekit.DataStream.TextHeader",()=>[{no:1,name:"operation_type",kind:"enum",T:G.getEnumType(nc)},{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"}),hh=G.makeMessageType("livekit.DataStream.ByteHeader",()=>[{no:1,name:"name",kind:"scalar",T:9}],{localName:"DataStream_ByteHeader"}),ic=G.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:G.getEnumType(vn)},{no:8,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:9,name:"text_header",kind:"message",T:uh,oneof:"content_header"},{no:10,name:"byte_header",kind:"message",T:hh,oneof:"content_header"}],{localName:"DataStream_Header"}),sc=G.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"}),rc=G.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"}),Dn=G.makeEnum("livekit.SignalTarget",[{no:0,name:"PUBLISHER"},{no:1,name:"SUBSCRIBER"}]),ac=G.makeEnum("livekit.StreamState",[{no:0,name:"ACTIVE"},{no:1,name:"PAUSED"}]),Rv=G.makeEnum("livekit.CandidateProtocol",[{no:0,name:"UDP"},{no:1,name:"TCP"},{no:2,name:"TLS"}]),Pv=G.makeMessageType("livekit.SignalRequest",()=>[{no:1,name:"offer",kind:"message",T:as,oneof:"message"},{no:2,name:"answer",kind:"message",T:as,oneof:"message"},{no:3,name:"trickle",kind:"message",T:lc,oneof:"message"},{no:4,name:"add_track",kind:"message",T:cc,oneof:"message"},{no:5,name:"mute",kind:"message",T:dc,oneof:"message"},{no:6,name:"subscription",kind:"message",T:Ra,oneof:"message"},{no:7,name:"track_setting",kind:"message",T:ph,oneof:"message"},{no:8,name:"leave",kind:"message",T:Pa,oneof:"message"},{no:10,name:"update_layers",kind:"message",T:gh,oneof:"message"},{no:11,name:"subscription_permission",kind:"message",T:_h,oneof:"message"},{no:12,name:"sync_state",kind:"message",T:Sh,oneof:"message"},{no:13,name:"simulate",kind:"message",T:jn,oneof:"message"},{no:14,name:"ping",kind:"scalar",T:3,oneof:"message"},{no:15,name:"update_metadata",kind:"message",T:vh,oneof:"message"},{no:16,name:"ping_req",kind:"message",T:Ch,oneof:"message"},{no:17,name:"update_audio_track",kind:"message",T:mh,oneof:"message"},{no:18,name:"update_video_track",kind:"message",T:Uv,oneof:"message"}]),fh=G.makeMessageType("livekit.SignalResponse",()=>[{no:1,name:"join",kind:"message",T:kv,oneof:"message"},{no:2,name:"answer",kind:"message",T:as,oneof:"message"},{no:3,name:"offer",kind:"message",T:as,oneof:"message"},{no:4,name:"trickle",kind:"message",T:lc,oneof:"message"},{no:5,name:"update",kind:"message",T:Lv,oneof:"message"},{no:6,name:"track_published",kind:"message",T:uc,oneof:"message"},{no:8,name:"leave",kind:"message",T:Pa,oneof:"message"},{no:9,name:"mute",kind:"message",T:dc,oneof:"message"},{no:10,name:"speakers_changed",kind:"message",T:Nv,oneof:"message"},{no:11,name:"room_update",kind:"message",T:Ov,oneof:"message"},{no:12,name:"connection_quality",kind:"message",T:Bv,oneof:"message"},{no:13,name:"stream_state_update",kind:"message",T:Vv,oneof:"message"},{no:14,name:"subscribed_quality_update",kind:"message",T:Hv,oneof:"message"},{no:15,name:"subscription_permission_update",kind:"message",T:Wv,oneof:"message"},{no:16,name:"refresh_token",kind:"scalar",T:9,oneof:"message"},{no:17,name:"track_unpublished",kind:"message",T:Dv,oneof:"message"},{no:18,name:"pong",kind:"scalar",T:3,oneof:"message"},{no:19,name:"reconnect",kind:"message",T:Iv,oneof:"message"},{no:20,name:"pong_resp",kind:"message",T:$v,oneof:"message"},{no:21,name:"subscription_response",kind:"message",T:Yv,oneof:"message"},{no:22,name:"request_response",kind:"message",T:Kv,oneof:"message"},{no:23,name:"track_subscribed",kind:"message",T:Jv,oneof:"message"},{no:24,name:"room_moved",kind:"message",T:qv,oneof:"message"}]),oc=G.makeMessageType("livekit.SimulcastCodec",()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"cid",kind:"scalar",T:9}]),cc=G.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:G.getEnumType(kn)},{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:G.getEnumType(Ot)},{no:9,name:"layers",kind:"message",T:rs,repeated:!0},{no:10,name:"simulcast_codecs",kind:"message",T:oc,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:G.getEnumType(vn)},{no:15,name:"stream",kind:"scalar",T:9},{no:16,name:"backup_codec_policy",kind:"enum",T:G.getEnumType(Ku)},{no:17,name:"audio_features",kind:"enum",T:G.getEnumType(qt),repeated:!0}]),lc=G.makeMessageType("livekit.TrickleRequest",()=>[{no:1,name:"candidateInit",kind:"scalar",T:9},{no:2,name:"target",kind:"enum",T:G.getEnumType(Dn)},{no:3,name:"final",kind:"scalar",T:8}]),dc=G.makeMessageType("livekit.MuteTrackRequest",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"muted",kind:"scalar",T:8}]),kv=G.makeMessageType("livekit.JoinResponse",()=>[{no:1,name:"room",kind:"message",T:wa},{no:2,name:"participant",kind:"message",T:ss},{no:3,name:"other_participants",kind:"message",T:ss,repeated:!0},{no:4,name:"server_version",kind:"scalar",T:9},{no:5,name:"ice_servers",kind:"message",T:bh,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:ch},{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:rh},{no:13,name:"sif_trailer",kind:"scalar",T:12},{no:14,name:"enabled_publish_codecs",kind:"message",T:Aa,repeated:!0},{no:15,name:"fast_publish",kind:"scalar",T:8}]),Iv=G.makeMessageType("livekit.ReconnectResponse",()=>[{no:1,name:"ice_servers",kind:"message",T:bh,repeated:!0},{no:2,name:"client_configuration",kind:"message",T:ch},{no:3,name:"server_info",kind:"message",T:rh},{no:4,name:"last_message_seq",kind:"scalar",T:13}]),uc=G.makeMessageType("livekit.TrackPublishedResponse",()=>[{no:1,name:"cid",kind:"scalar",T:9},{no:2,name:"track",kind:"message",T:Ls}]),Dv=G.makeMessageType("livekit.TrackUnpublishedResponse",()=>[{no:1,name:"track_sid",kind:"scalar",T:9}]),as=G.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}]),Lv=G.makeMessageType("livekit.ParticipantUpdate",()=>[{no:1,name:"participants",kind:"message",T:ss,repeated:!0}]),Ra=G.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:sh,repeated:!0}]),ph=G.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:G.getEnumType(ec)},{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}]),mh=G.makeMessageType("livekit.UpdateLocalAudioTrack",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"features",kind:"enum",T:G.getEnumType(qt),repeated:!0}]),Uv=G.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}]),Pa=G.makeMessageType("livekit.LeaveRequest",()=>[{no:1,name:"can_reconnect",kind:"scalar",T:8},{no:2,name:"reason",kind:"enum",T:G.getEnumType(In)},{no:3,name:"action",kind:"enum",T:G.getEnumType(Us)},{no:4,name:"regions",kind:"message",T:jv}]),Us=G.makeEnum("livekit.LeaveRequest.Action",[{no:0,name:"DISCONNECT"},{no:1,name:"RESUME"},{no:2,name:"RECONNECT"}]),gh=G.makeMessageType("livekit.UpdateVideoLayers",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"layers",kind:"message",T:rs,repeated:!0}]),vh=G.makeMessageType("livekit.UpdateParticipantMetadata",()=>[{no:1,name:"metadata",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",T:9},{no:3,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:4,name:"request_id",kind:"scalar",T:13}]),bh=G.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}]),Nv=G.makeMessageType("livekit.SpeakersChanged",()=>[{no:1,name:"speakers",kind:"message",T:Ju,repeated:!0}]),Ov=G.makeMessageType("livekit.RoomUpdate",()=>[{no:1,name:"room",kind:"message",T:wa}]),Fv=G.makeMessageType("livekit.ConnectionQualityInfo",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"quality",kind:"enum",T:G.getEnumType(Pr)},{no:3,name:"score",kind:"scalar",T:2}]),Bv=G.makeMessageType("livekit.ConnectionQualityUpdate",()=>[{no:1,name:"updates",kind:"message",T:Fv,repeated:!0}]),zv=G.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:G.getEnumType(ac)}]),Vv=G.makeMessageType("livekit.StreamStateUpdate",()=>[{no:1,name:"stream_states",kind:"message",T:zv,repeated:!0}]),hc=G.makeMessageType("livekit.SubscribedQuality",()=>[{no:1,name:"quality",kind:"enum",T:G.getEnumType(ec)},{no:2,name:"enabled",kind:"scalar",T:8}]),Gv=G.makeMessageType("livekit.SubscribedCodec",()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"qualities",kind:"message",T:hc,repeated:!0}]),Hv=G.makeMessageType("livekit.SubscribedQualityUpdate",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribed_qualities",kind:"message",T:hc,repeated:!0},{no:3,name:"subscribed_codecs",kind:"message",T:Gv,repeated:!0}]),yh=G.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}]),_h=G.makeMessageType("livekit.SubscriptionPermission",()=>[{no:1,name:"all_participants",kind:"scalar",T:8},{no:2,name:"track_permissions",kind:"message",T:yh,repeated:!0}]),Wv=G.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}]),qv=G.makeMessageType("livekit.RoomMovedResponse",()=>[{no:1,name:"room",kind:"message",T:wa},{no:2,name:"token",kind:"scalar",T:9},{no:3,name:"participant",kind:"message",T:ss},{no:4,name:"other_participants",kind:"message",T:ss,repeated:!0}]),Sh=G.makeMessageType("livekit.SyncState",()=>[{no:1,name:"answer",kind:"message",T:as},{no:2,name:"subscription",kind:"message",T:Ra},{no:3,name:"publish_tracks",kind:"message",T:uc,repeated:!0},{no:4,name:"data_channels",kind:"message",T:Th,repeated:!0},{no:5,name:"offer",kind:"message",T:as},{no:6,name:"track_sids_disabled",kind:"scalar",T:9,repeated:!0},{no:7,name:"datachannel_receive_states",kind:"message",T:xh,repeated:!0}]),xh=G.makeMessageType("livekit.DataChannelReceiveState",()=>[{no:1,name:"publisher_sid",kind:"scalar",T:9},{no:2,name:"last_seq",kind:"scalar",T:13}]),Th=G.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:G.getEnumType(Dn)}]),jn=G.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:G.getEnumType(Rv),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"}]),Ch=G.makeMessageType("livekit.Ping",()=>[{no:1,name:"timestamp",kind:"scalar",T:3},{no:2,name:"rtt",kind:"scalar",T:3}]),$v=G.makeMessageType("livekit.Pong",()=>[{no:1,name:"last_ping_timestamp",kind:"scalar",T:3},{no:2,name:"timestamp",kind:"scalar",T:3}]),jv=G.makeMessageType("livekit.RegionSettings",()=>[{no:1,name:"regions",kind:"message",T:Xv,repeated:!0}]),Xv=G.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}]),Yv=G.makeMessageType("livekit.SubscriptionResponse",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"err",kind:"enum",T:G.getEnumType(_v)}]),Kv=G.makeMessageType("livekit.RequestResponse",()=>[{no:1,name:"request_id",kind:"scalar",T:13},{no:2,name:"reason",kind:"enum",T:G.getEnumType(fc)},{no:3,name:"message",kind:"scalar",T:9}]),fc=G.makeEnum("livekit.RequestResponse.Reason",[{no:0,name:"OK"},{no:1,name:"NOT_FOUND"},{no:2,name:"NOT_ALLOWED"},{no:3,name:"LIMIT_EXCEEDED"}]),Jv=G.makeMessageType("livekit.TrackSubscribed",()=>[{no:1,name:"track_sid",kind:"scalar",T:9}]);function Zv(i){return i&&i.__esModule&&Object.prototype.hasOwnProperty.call(i,"default")?i.default:i}var ka={exports:{}},Qv=ka.exports,Eh;function e0(){return Eh||(Eh=1,function(i){(function(e,t){i.exports?i.exports=t():e.log=t()})(Qv,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(v,m){var p=v[m];if(typeof p.bind=="function")return p.bind(v);try{return Function.prototype.bind.call(p,v)}catch{return function(){return Function.prototype.apply.apply(p,[v,arguments])}}}function c(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function l(v){return v==="debug"&&(v="log"),typeof console===t?!1:v==="trace"&&n?c:console[v]!==void 0?o(console,v):console.log!==void 0?o(console,"log"):e}function d(){for(var v=this.getLevel(),m=0;m<s.length;m++){var p=s[m];this[p]=m<v?e:this.methodFactory(p,v,this.name)}if(this.log=this.debug,typeof console===t&&v<this.levels.SILENT)return"No console available for logging"}function u(v){return function(){typeof console!==t&&(d.call(this),this[v].apply(this,arguments))}}function h(v,m,p){return l(v)||u.apply(this,arguments)}function f(v,m){var p=this,x,C,b,S="loglevel";typeof v=="string"?S+=":"+v:typeof v=="symbol"&&(S=void 0);function M(R){var O=(s[R]||"silent").toUpperCase();if(!(typeof window===t||!S)){try{window.localStorage[S]=O;return}catch{}try{window.document.cookie=encodeURIComponent(S)+"="+O+";"}catch{}}}function A(){var R;if(!(typeof window===t||!S)){try{R=window.localStorage[S]}catch{}if(typeof R===t)try{var O=window.document.cookie,z=encodeURIComponent(S),$=O.indexOf(z+"=");$!==-1&&(R=/^([^;]+)/.exec(O.slice($+z.length+1))[1])}catch{}return p.levels[R]===void 0&&(R=void 0),R}}function k(){if(!(typeof window===t||!S)){try{window.localStorage.removeItem(S)}catch{}try{window.document.cookie=encodeURIComponent(S)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}function _(R){var O=R;if(typeof O=="string"&&p.levels[O.toUpperCase()]!==void 0&&(O=p.levels[O.toUpperCase()]),typeof O=="number"&&O>=0&&O<=p.levels.SILENT)return O;throw new TypeError("log.setLevel() called with invalid level: "+R)}p.name=v,p.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},p.methodFactory=m||h,p.getLevel=function(){return b??C??x},p.setLevel=function(R,O){return b=_(R),O!==!1&&M(b),d.call(p)},p.setDefaultLevel=function(R){C=_(R),A()||p.setLevel(R,!1)},p.resetLevel=function(){b=null,k(),d.call(p)},p.enableAll=function(R){p.setLevel(p.levels.TRACE,R)},p.disableAll=function(R){p.setLevel(p.levels.SILENT,R)},p.rebuild=function(){if(a!==p&&(x=_(a.getLevel())),d.call(p),a===p)for(var R in r)r[R].rebuild()},x=_(a?a.getLevel():"WARN");var T=A();T!=null&&(b=_(T)),d.call(p)}a=new f,a.getLogger=function(m){if(typeof m!="symbol"&&typeof m!="string"||m==="")throw new TypeError("You must supply a name when creating a logger.");var p=r[m];return p||(p=r[m]=new f(m,a.methodFactory)),p};var g=typeof window!==t?window.log:void 0;return a.noConflict=function(){return typeof window!==t&&window.log===a&&(window.log=g),a},a.getLoggers=function(){return r},a.default=a,a})}(ka)),ka.exports}var Ia=e0(),pc;(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"})(pc||(pc={}));var Ln;(function(i){i.Default="livekit",i.Room="livekit-room",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"})(Ln||(Ln={}));let Ke=Ia.getLogger("livekit");Object.values(Ln).map(i=>Ia.getLogger(i)),Ke.setDefaultLevel(pc.info);function fi(i){const e=Ia.getLogger(i);return e.setDefaultLevel(Ke.getLevel()),e}const t0=Ia.getLogger("lk-e2ee"),Dr=7e3,n0=[0,300,2*2*300,3*3*300,4*4*300,Dr,Dr,Dr,Dr,Dr];class i0{constructor(e){this._retryDelays=e!==void 0?[...e]:n0}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 s0(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 P(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(d){try{l(n.next(d))}catch(u){a(u)}}function c(d){try{l(n.throw(d))}catch(u){a(u)}}function l(d){d.done?r(d.value):s(d.value).then(o,c)}l((n=n.apply(i,e||[])).next())})}function Mh(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 pi(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 Mh=="function"?Mh(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,c){a=i[r](a),s(o,c,a.done,a.value)})}}function s(r,a,o,c){Promise.resolve(c).then(function(l){r({value:l,done:o})},a)}}typeof SuppressedError=="function"&&SuppressedError;var Da={exports:{}},wh;function r0(){if(wh)return Da.exports;wh=1;var i=typeof Reflect=="object"?Reflect:null,e=i&&typeof i.apply=="function"?i.apply:function(S,M,A){return Function.prototype.apply.call(S,M,A)},t;i&&typeof i.ownKeys=="function"?t=i.ownKeys:Object.getOwnPropertySymbols?t=function(S){return Object.getOwnPropertyNames(S).concat(Object.getOwnPropertySymbols(S))}:t=function(S){return Object.getOwnPropertyNames(S)};function n(b){console&&console.warn&&console.warn(b)}var s=Number.isNaN||function(S){return S!==S};function r(){r.init.call(this)}Da.exports=r,Da.exports.once=p,r.EventEmitter=r,r.prototype._events=void 0,r.prototype._eventsCount=0,r.prototype._maxListeners=void 0;var a=10;function o(b){if(typeof b!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof b)}Object.defineProperty(r,"defaultMaxListeners",{enumerable:!0,get:function(){return a},set:function(b){if(typeof b!="number"||b<0||s(b))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+b+".");a=b}}),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(S){if(typeof S!="number"||S<0||s(S))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+S+".");return this._maxListeners=S,this};function c(b){return b._maxListeners===void 0?r.defaultMaxListeners:b._maxListeners}r.prototype.getMaxListeners=function(){return c(this)},r.prototype.emit=function(S){for(var M=[],A=1;A<arguments.length;A++)M.push(arguments[A]);var k=S==="error",_=this._events;if(_!==void 0)k=k&&_.error===void 0;else if(!k)return!1;if(k){var T;if(M.length>0&&(T=M[0]),T instanceof Error)throw T;var R=new Error("Unhandled error."+(T?" ("+T.message+")":""));throw R.context=T,R}var O=_[S];if(O===void 0)return!1;if(typeof O=="function")e(O,this,M);else for(var z=O.length,$=g(O,z),A=0;A<z;++A)e($[A],this,M);return!0};function l(b,S,M,A){var k,_,T;if(o(M),_=b._events,_===void 0?(_=b._events=Object.create(null),b._eventsCount=0):(_.newListener!==void 0&&(b.emit("newListener",S,M.listener?M.listener:M),_=b._events),T=_[S]),T===void 0)T=_[S]=M,++b._eventsCount;else if(typeof T=="function"?T=_[S]=A?[M,T]:[T,M]:A?T.unshift(M):T.push(M),k=c(b),k>0&&T.length>k&&!T.warned){T.warned=!0;var R=new Error("Possible EventEmitter memory leak detected. "+T.length+" "+String(S)+" listeners added. Use emitter.setMaxListeners() to increase limit");R.name="MaxListenersExceededWarning",R.emitter=b,R.type=S,R.count=T.length,n(R)}return b}r.prototype.addListener=function(S,M){return l(this,S,M,!1)},r.prototype.on=r.prototype.addListener,r.prototype.prependListener=function(S,M){return l(this,S,M,!0)};function d(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function u(b,S,M){var A={fired:!1,wrapFn:void 0,target:b,type:S,listener:M},k=d.bind(A);return k.listener=M,A.wrapFn=k,k}r.prototype.once=function(S,M){return o(M),this.on(S,u(this,S,M)),this},r.prototype.prependOnceListener=function(S,M){return o(M),this.prependListener(S,u(this,S,M)),this},r.prototype.removeListener=function(S,M){var A,k,_,T,R;if(o(M),k=this._events,k===void 0)return this;if(A=k[S],A===void 0)return this;if(A===M||A.listener===M)--this._eventsCount===0?this._events=Object.create(null):(delete k[S],k.removeListener&&this.emit("removeListener",S,A.listener||M));else if(typeof A!="function"){for(_=-1,T=A.length-1;T>=0;T--)if(A[T]===M||A[T].listener===M){R=A[T].listener,_=T;break}if(_<0)return this;_===0?A.shift():v(A,_),A.length===1&&(k[S]=A[0]),k.removeListener!==void 0&&this.emit("removeListener",S,R||M)}return this},r.prototype.off=r.prototype.removeListener,r.prototype.removeAllListeners=function(S){var M,A,k;if(A=this._events,A===void 0)return this;if(A.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):A[S]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete A[S]),this;if(arguments.length===0){var _=Object.keys(A),T;for(k=0;k<_.length;++k)T=_[k],T!=="removeListener"&&this.removeAllListeners(T);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(M=A[S],typeof M=="function")this.removeListener(S,M);else if(M!==void 0)for(k=M.length-1;k>=0;k--)this.removeListener(S,M[k]);return this};function h(b,S,M){var A=b._events;if(A===void 0)return[];var k=A[S];return k===void 0?[]:typeof k=="function"?M?[k.listener||k]:[k]:M?m(k):g(k,k.length)}r.prototype.listeners=function(S){return h(this,S,!0)},r.prototype.rawListeners=function(S){return h(this,S,!1)},r.listenerCount=function(b,S){return typeof b.listenerCount=="function"?b.listenerCount(S):f.call(b,S)},r.prototype.listenerCount=f;function f(b){var S=this._events;if(S!==void 0){var M=S[b];if(typeof M=="function")return 1;if(M!==void 0)return M.length}return 0}r.prototype.eventNames=function(){return this._eventsCount>0?t(this._events):[]};function g(b,S){for(var M=new Array(S),A=0;A<S;++A)M[A]=b[A];return M}function v(b,S){for(;S+1<b.length;S++)b[S]=b[S+1];b.pop()}function m(b){for(var S=new Array(b.length),M=0;M<S.length;++M)S[M]=b[M].listener||b[M];return S}function p(b,S){return new Promise(function(M,A){function k(T){b.removeListener(S,_),A(T)}function _(){typeof b.removeListener=="function"&&b.removeListener("error",k),M([].slice.call(arguments))}C(b,S,_,{once:!0}),S!=="error"&&x(b,k,{once:!0})})}function x(b,S,M){typeof b.on=="function"&&C(b,"error",S,M)}function C(b,S,M,A){if(typeof b.on=="function")A.once?b.once(S,M):b.on(S,M);else if(typeof b.addEventListener=="function")b.addEventListener(S,function k(_){A.once&&b.removeEventListener(S,k),M(_)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof b)}return Da.exports}var Xn=r0();let Ah=!0,Rh=!0;function Lr(i,e,t){const n=i.match(e);return n&&n.length>=t&&parseFloat(n[t],10)}function os(i,e,t){if(!i.RTCPeerConnection)return;const n=i.RTCPeerConnection.prototype,s=n.addEventListener;n.addEventListener=function(a,o){if(a!==e)return s.apply(this,arguments);const c=l=>{const d=t(l);d&&(o.handleEvent?o.handleEvent(d):o(d))};return this._eventMap=this._eventMap||{},this._eventMap[e]||(this._eventMap[e]=new Map),this._eventMap[e].set(o,c),s.apply(this,[a,c])};const r=n.removeEventListener;n.removeEventListener=function(a,o){if(a!==e||!this._eventMap||!this._eventMap[e])return r.apply(this,arguments);if(!this._eventMap[e].has(o))return r.apply(this,arguments);const c=this._eventMap[e].get(o);return this._eventMap[e].delete(o),this._eventMap[e].size===0&&delete this._eventMap[e],Object.keys(this._eventMap).length===0&&delete this._eventMap,r.apply(this,[a,c])},Object.defineProperty(n,"on"+e,{get(){return this["_on"+e]},set(a){this["_on"+e]&&(this.removeEventListener(e,this["_on"+e]),delete this["_on"+e]),a&&this.addEventListener(e,this["_on"+e]=a)},enumerable:!0,configurable:!0})}function a0(i){return typeof i!="boolean"?new Error("Argument type: "+typeof i+". Please use a boolean."):(Ah=i,i?"adapter.js logging disabled":"adapter.js logging enabled")}function o0(i){return typeof i!="boolean"?new Error("Argument type: "+typeof i+". Please use a boolean."):(Rh=!i,"adapter.js deprecation warnings "+(i?"disabled":"enabled"))}function Ph(){if(typeof window=="object"){if(Ah)return;typeof console<"u"&&typeof console.log=="function"&&console.log.apply(console,arguments)}}function mc(i,e){Rh&&console.warn(i+" is deprecated, please use "+e+" instead.")}function c0(i){const e={browser:null,version:null};if(typeof i>"u"||!i.navigator||!i.navigator.userAgent)return e.browser="Not a browser.",e;const{navigator:t}=i;if(t.userAgentData&&t.userAgentData.brands){const n=t.userAgentData.brands.find(s=>s.brand==="Chromium");if(n)return{browser:"chrome",version:parseInt(n.version,10)}}if(t.mozGetUserMedia)e.browser="firefox",e.version=parseInt(Lr(t.userAgent,/Firefox\/(\d+)\./,1));else if(t.webkitGetUserMedia||i.isSecureContext===!1&&i.webkitRTCPeerConnection)e.browser="chrome",e.version=parseInt(Lr(t.userAgent,/Chrom(e|ium)\/(\d+)\./,2));else if(i.RTCPeerConnection&&t.userAgent.match(/AppleWebKit\/(\d+)\./))e.browser="safari",e.version=parseInt(Lr(t.userAgent,/AppleWebKit\/(\d+)\./,1)),e.supportsUnifiedPlan=i.RTCRtpTransceiver&&"currentDirection"in i.RTCRtpTransceiver.prototype,e._safariVersion=Lr(t.userAgent,/Version\/(\d+(\.?\d+))/,1);else return e.browser="Not a supported browser.",e;return e}function kh(i){return Object.prototype.toString.call(i)==="[object Object]"}function Ih(i){return kh(i)?Object.keys(i).reduce(function(e,t){const n=kh(i[t]),s=n?Ih(i[t]):i[t],r=n&&!Object.keys(s).length;return s===void 0||r?e:Object.assign(e,{[t]:s})},{}):i}function gc(i,e,t){!e||t.has(e.id)||(t.set(e.id,e),Object.keys(e).forEach(n=>{n.endsWith("Id")?gc(i,i.get(e[n]),t):n.endsWith("Ids")&&e[n].forEach(s=>{gc(i,i.get(s),t)})}))}function Dh(i,e,t){const n=t?"outbound-rtp":"inbound-rtp",s=new Map;if(e===null)return s;const r=[];return 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&&gc(i,o,s)})}),s}const Lh=Ph;function Uh(i,e){const t=i&&i.navigator;if(!t.mediaDevices)return;const n=function(o){if(typeof o!="object"||o.mandatory||o.optional)return o;const c={};return Object.keys(o).forEach(l=>{if(l==="require"||l==="advanced"||l==="mediaSource")return;const d=typeof o[l]=="object"?o[l]:{ideal:o[l]};d.exact!==void 0&&typeof d.exact=="number"&&(d.min=d.max=d.exact);const u=function(h,f){return h?h+f.charAt(0).toUpperCase()+f.slice(1):f==="deviceId"?"sourceId":f};if(d.ideal!==void 0){c.optional=c.optional||[];let h={};typeof d.ideal=="number"?(h[u("min",l)]=d.ideal,c.optional.push(h),h={},h[u("max",l)]=d.ideal,c.optional.push(h)):(h[u("",l)]=d.ideal,c.optional.push(h))}d.exact!==void 0&&typeof d.exact!="number"?(c.mandatory=c.mandatory||{},c.mandatory[u("",l)]=d.exact):["min","max"].forEach(h=>{d[h]!==void 0&&(c.mandatory=c.mandatory||{},c.mandatory[u(h,l)]=d[h])})}),o.advanced&&(c.optional=(c.optional||[]).concat(o.advanced)),c},s=function(o,c){if(e.version>=61)return c(o);if(o=JSON.parse(JSON.stringify(o)),o&&typeof o.audio=="object"){const l=function(d,u,h){u in d&&!(h in d)&&(d[h]=d[u],delete d[u])};o=JSON.parse(JSON.stringify(o)),l(o.audio,"autoGainControl","googAutoGainControl"),l(o.audio,"noiseSuppression","googNoiseSuppression"),o.audio=n(o.audio)}if(o&&typeof o.video=="object"){let l=o.video.facingMode;l=l&&(typeof l=="object"?l:{ideal:l});const d=e.version<66;if(l&&(l.exact==="user"||l.exact==="environment"||l.ideal==="user"||l.ideal==="environment")&&!(t.mediaDevices.getSupportedConstraints&&t.mediaDevices.getSupportedConstraints().facingMode&&!d)){delete o.video.facingMode;let u;if(l.exact==="environment"||l.ideal==="environment"?u=["back","rear"]:(l.exact==="user"||l.ideal==="user")&&(u=["front"]),u)return t.mediaDevices.enumerateDevices().then(h=>{h=h.filter(g=>g.kind==="videoinput");let f=h.find(g=>u.some(v=>g.label.toLowerCase().includes(v)));return!f&&h.length&&u.includes("back")&&(f=h[h.length-1]),f&&(o.video.deviceId=l.exact?{exact:f.deviceId}:{ideal:f.deviceId}),o.video=n(o.video),Lh("chrome: "+JSON.stringify(o)),c(o)})}o.video=n(o.video)}return Lh("chrome: "+JSON.stringify(o)),c(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,c,l){s(o,d=>{t.webkitGetUserMedia(d,c,u=>{l&&l(r(u))})})};if(t.getUserMedia=a.bind(t),t.mediaDevices.getUserMedia){const o=t.mediaDevices.getUserMedia.bind(t.mediaDevices);t.mediaDevices.getUserMedia=function(c){return s(c,l=>o(l).then(d=>{if(l.audio&&!d.getAudioTracks().length||l.video&&!d.getVideoTracks().length)throw d.getTracks().forEach(u=>{u.stop()}),new DOMException("","NotFoundError");return d},d=>Promise.reject(r(d))))}}}function Nh(i){i.MediaStream=i.MediaStream||i.webkitMediaStream}function Oh(i){if(typeof i=="object"&&i.RTCPeerConnection&&!("ontrack"in i.RTCPeerConnection.prototype)){Object.defineProperty(i.RTCPeerConnection.prototype,"ontrack",{get(){return this._ontrack},set(t){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=t)},enumerable:!0,configurable:!0});const e=i.RTCPeerConnection.prototype.setRemoteDescription;i.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=n=>{n.stream.addEventListener("addtrack",s=>{let r;i.RTCPeerConnection.prototype.getReceivers?r=this.getReceivers().find(o=>o.track&&o.track.id===s.track.id):r={track:s.track};const a=new Event("track");a.track=s.track,a.receiver=r,a.transceiver={receiver:r},a.streams=[n.stream],this.dispatchEvent(a)}),n.stream.getTracks().forEach(s=>{let r;i.RTCPeerConnection.prototype.getReceivers?r=this.getReceivers().find(o=>o.track&&o.track.id===s.id):r={track:s};const a=new Event("track");a.track=s,a.receiver=r,a.transceiver={receiver:r},a.streams=[n.stream],this.dispatchEvent(a)})},this.addEventListener("addstream",this._ontrackpoly)),e.apply(this,arguments)}}else os(i,"track",e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e))}function Fh(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,c){let l=s.apply(this,arguments);return l||(l=e(this,o),this._senders.push(l)),l};const r=i.RTCPeerConnection.prototype.removeTrack;i.RTCPeerConnection.prototype.removeTrack=function(o){r.apply(this,arguments);const c=this._senders.indexOf(o);c!==-1&&this._senders.splice(c,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(c=>c.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 Bh(i){if(!(typeof i=="object"&&i.RTCPeerConnection&&i.RTCRtpSender&&i.RTCRtpReceiver))return;if(!("getStats"in i.RTCRtpSender.prototype)){const t=i.RTCPeerConnection.prototype.getSenders;t&&(i.RTCPeerConnection.prototype.getSenders=function(){const r=t.apply(this,[]);return r.forEach(a=>a._pc=this),r});const n=i.RTCPeerConnection.prototype.addTrack;n&&(i.RTCPeerConnection.prototype.addTrack=function(){const r=n.apply(this,arguments);return r._pc=this,r}),i.RTCRtpSender.prototype.getStats=function(){const r=this;return this._pc.getStats().then(a=>Dh(a,r.track,!0))}}if(!("getStats"in i.RTCRtpReceiver.prototype)){const t=i.RTCPeerConnection.prototype.getReceivers;t&&(i.RTCPeerConnection.prototype.getReceivers=function(){const s=t.apply(this,[]);return s.forEach(r=>r._pc=this),s}),os(i,"track",n=>(n.receiver._pc=n.srcElement,n)),i.RTCRtpReceiver.prototype.getStats=function(){const s=this;return this._pc.getStats().then(r=>Dh(r,s.track,!1))}}if(!("getStats"in i.RTCRtpSender.prototype&&"getStats"in i.RTCRtpReceiver.prototype))return;const e=i.RTCPeerConnection.prototype.getStats;i.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof i.MediaStreamTrack){const n=arguments[0];let s,r,a;return this.getSenders().forEach(o=>{o.track===n&&(s?a=!0:s=o)}),this.getReceivers().forEach(o=>(o.track===n&&(r?a=!0:r=o),o.track===n)),a||s&&r?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):s?s.getStats():r?r.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return e.apply(this,arguments)}}function zh(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 c=e.apply(this,arguments);return this._shimmedLocalStreams[o.id]?this._shimmedLocalStreams[o.id].indexOf(c)===-1&&this._shimmedLocalStreams[o.id].push(c):this._shimmedLocalStreams[o.id]=[o,c],c};const t=i.RTCPeerConnection.prototype.addStream;i.RTCPeerConnection.prototype.addStream=function(a){this._shimmedLocalStreams=this._shimmedLocalStreams||{},a.getTracks().forEach(l=>{if(this.getSenders().find(u=>u.track===l))throw new DOMException("Track already exists.","InvalidAccessError")});const o=this.getSenders();t.apply(this,arguments);const c=this.getSenders().filter(l=>o.indexOf(l)===-1);this._shimmedLocalStreams[a.id]=[a].concat(c)};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 c=this._shimmedLocalStreams[o].indexOf(a);c!==-1&&this._shimmedLocalStreams[o].splice(c,1),this._shimmedLocalStreams[o].length===1&&delete this._shimmedLocalStreams[o]}),s.apply(this,arguments)}}function Vh(i,e){if(!i.RTCPeerConnection)return;if(i.RTCPeerConnection.prototype.addTrack&&e.version>=65)return zh(i);const t=i.RTCPeerConnection.prototype.getLocalStreams;i.RTCPeerConnection.prototype.getLocalStreams=function(){const d=t.apply(this);return this._reverseStreams=this._reverseStreams||{},d.map(u=>this._reverseStreams[u.id])};const n=i.RTCPeerConnection.prototype.addStream;i.RTCPeerConnection.prototype.addStream=function(d){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},d.getTracks().forEach(u=>{if(this.getSenders().find(f=>f.track===u))throw new DOMException("Track already exists.","InvalidAccessError")}),!this._reverseStreams[d.id]){const u=new i.MediaStream(d.getTracks());this._streams[d.id]=u,this._reverseStreams[u.id]=d,d=u}n.apply(this,[d])};const s=i.RTCPeerConnection.prototype.removeStream;i.RTCPeerConnection.prototype.removeStream=function(d){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},s.apply(this,[this._streams[d.id]||d]),delete this._reverseStreams[this._streams[d.id]?this._streams[d.id].id:d.id],delete this._streams[d.id]},i.RTCPeerConnection.prototype.addTrack=function(d,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(v=>v===d))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(v=>v.track===d))throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};const g=this._streams[u.id];if(g)g.addTrack(d),Promise.resolve().then(()=>{this.dispatchEvent(new Event("negotiationneeded"))});else{const v=new i.MediaStream([d]);this._streams[u.id]=v,this._reverseStreams[v.id]=u,this.addStream(v)}return this.getSenders().find(v=>v.track===d)};function r(l,d){let u=d.sdp;return Object.keys(l._reverseStreams||[]).forEach(h=>{const f=l._reverseStreams[h],g=l._streams[f.id];u=u.replace(new RegExp(g.id,"g"),f.id)}),new RTCSessionDescription({type:d.type,sdp:u})}function a(l,d){let u=d.sdp;return Object.keys(l._reverseStreams||[]).forEach(h=>{const f=l._reverseStreams[h],g=l._streams[f.id];u=u.replace(new RegExp(f.id,"g"),g.id)}),new RTCSessionDescription({type:d.type,sdp:u})}["createOffer","createAnswer"].forEach(function(l){const d=i.RTCPeerConnection.prototype[l],u={[l](){const h=arguments;return arguments.length&&typeof arguments[0]=="function"?d.apply(this,[g=>{const v=r(this,g);h[0].apply(null,[v])},g=>{h[1]&&h[1].apply(null,g)},arguments[2]]):d.apply(this,arguments).then(g=>r(this,g))}};i.RTCPeerConnection.prototype[l]=u[l]});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 c=Object.getOwnPropertyDescriptor(i.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(i.RTCPeerConnection.prototype,"localDescription",{get(){const l=c.get.apply(this);return l.type===""?l:r(this,l)}}),i.RTCPeerConnection.prototype.removeTrack=function(d){if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!d._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(!(d._pc===this))throw new DOMException("Sender was not created by this connection.","InvalidAccessError");this._streams=this._streams||{};let h;Object.keys(this._streams).forEach(f=>{this._streams[f].getTracks().find(v=>d.track===v)&&(h=this._streams[f])}),h&&(h.getTracks().length===1?this.removeStream(this._reverseStreams[h.id]):h.removeTrack(d.track),this.dispatchEvent(new Event("negotiationneeded")))}}function vc(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 Gh(i,e){os(i,"negotiationneeded",t=>{const n=t.target;if(!((e.version<72||n.getConfiguration&&n.getConfiguration().sdpSemantics==="plan-b")&&n.signalingState!=="stable"))return t})}var Hh=Object.freeze({__proto__:null,fixNegotiationNeeded:Gh,shimAddTrackRemoveTrack:Vh,shimAddTrackRemoveTrackWithNative:zh,shimGetSendersWithDtmf:Fh,shimGetUserMedia:Uh,shimMediaStream:Nh,shimOnTrack:Oh,shimPeerConnection:vc,shimSenderReceiverGetStats:Bh});function Wh(i,e){const t=i&&i.navigator,n=i&&i.MediaStreamTrack;if(t.getUserMedia=function(s,r,a){mc("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,c){o in a&&!(c in a)&&(a[c]=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 l0(i,e){i.navigator.mediaDevices&&"getDisplayMedia"in i.navigator.mediaDevices||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 qh(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 bc(i,e){if(typeof i!="object"||!(i.RTCPeerConnection||i.mozRTCPeerConnection))return;!i.RTCPeerConnection&&i.mozRTCPeerConnection&&(i.RTCPeerConnection=i.mozRTCPeerConnection),e.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(s){const r=i.RTCPeerConnection.prototype[s],a={[s](){return arguments[0]=new(s==="addIceCandidate"?i.RTCIceCandidate:i.RTCSessionDescription)(arguments[0]),r.apply(this,arguments)}};i.RTCPeerConnection.prototype[s]=a[s]});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,a,o]=arguments;return n.apply(this,[r||null]).then(c=>{if(e.version<53&&!a)try{c.forEach(l=>{l.type=t[l.type]||l.type})}catch(l){if(l.name!=="TypeError")throw l;c.forEach((d,u)=>{c.set(u,Object.assign({},d,{type:t[d.type]||d.type}))})}return c}).then(a,o)}}function $h(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 jh(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}),os(i,"track",t=>(t.receiver._pc=t.srcElement,t)),i.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function Xh(i){!i.RTCPeerConnection||"removeStream"in i.RTCPeerConnection.prototype||(i.RTCPeerConnection.prototype.removeStream=function(t){mc("removeStream","removeTrack"),this.getSenders().forEach(n=>{n.track&&t.getTracks().includes(n.track)&&this.removeTrack(n)})})}function Yh(i){i.DataChannel&&!i.RTCDataChannel&&(i.RTCDataChannel=i.DataChannel)}function Kh(i){if(!(typeof i=="object"&&i.RTCPeerConnection))return;const e=i.RTCPeerConnection.prototype.addTransceiver;e&&(i.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let n=arguments[1]&&arguments[1].sendEncodings;n===void 0&&(n=[]),n=[...n];const s=n.length>0;s&&n.forEach(a=>{if("rid"in a&&!/^[a-z0-9]{0,16}$/i.test(a.rid))throw new TypeError("Invalid RID value provided.");if("scaleResolutionDownBy"in a&&!(parseFloat(a.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in a&&!(parseFloat(a.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")});const r=e.apply(this,arguments);if(s){const{sender:a}=r,o=a.getParameters();(!("encodings"in o)||o.encodings.length===1&&Object.keys(o.encodings[0]).length===0)&&(o.encodings=n,a.sendEncodings=n,this.setParametersPromises.push(a.setParameters(o).then(()=>{delete a.sendEncodings}).catch(()=>{delete a.sendEncodings})))}return r})}function Jh(i){if(!(typeof i=="object"&&i.RTCRtpSender))return;const e=i.RTCRtpSender.prototype.getParameters;e&&(i.RTCRtpSender.prototype.getParameters=function(){const n=e.apply(this,arguments);return"encodings"in n||(n.encodings=[].concat(this.sendEncodings||[{}])),n})}function Zh(i){if(!(typeof i=="object"&&i.RTCPeerConnection))return;const e=i.RTCPeerConnection.prototype.createOffer;i.RTCPeerConnection.prototype.createOffer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>e.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):e.apply(this,arguments)}}function Qh(i){if(!(typeof i=="object"&&i.RTCPeerConnection))return;const e=i.RTCPeerConnection.prototype.createAnswer;i.RTCPeerConnection.prototype.createAnswer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>e.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):e.apply(this,arguments)}}var ef=Object.freeze({__proto__:null,shimAddTransceiver:Kh,shimCreateAnswer:Qh,shimCreateOffer:Zh,shimGetDisplayMedia:l0,shimGetParameters:Jh,shimGetUserMedia:Wh,shimOnTrack:qh,shimPeerConnection:bc,shimRTCDataChannel:Yh,shimReceiverGetStats:jh,shimRemoveStream:Xh,shimSenderGetStats:$h});function tf(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 nf(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 sf(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(l,d){const u=arguments.length>=2?arguments[2]:arguments[0],h=t.apply(this,[u]);return d?(h.then(l,d),Promise.resolve()):h},e.createAnswer=function(l,d){const u=arguments.length>=2?arguments[2]:arguments[0],h=n.apply(this,[u]);return d?(h.then(l,d),Promise.resolve()):h};let o=function(c,l,d){const u=s.apply(this,[c]);return d?(u.then(l,d),Promise.resolve()):u};e.setLocalDescription=o,o=function(c,l,d){const u=r.apply(this,[c]);return d?(u.then(l,d),Promise.resolve()):u},e.setRemoteDescription=o,o=function(c,l,d){const u=a.apply(this,[c]);return d?(u.then(l,d),Promise.resolve()):u},e.addIceCandidate=o}function rf(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(af(s))}!e.getUserMedia&&e.mediaDevices&&e.mediaDevices.getUserMedia&&(e.getUserMedia=(function(n,s,r){e.mediaDevices.getUserMedia(n).then(s,r)}).bind(e))}function af(i){return i&&i.video!==void 0?Object.assign({},i,{video:Ih(i.video)}):i}function of(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?(mc("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 cf(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 lf(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 df(i){typeof i!="object"||i.AudioContext||(i.AudioContext=i.webkitAudioContext)}var uf=Object.freeze({__proto__:null,shimAudioContext:df,shimCallbacksAPI:sf,shimConstraints:af,shimCreateOfferLegacy:lf,shimGetUserMedia:rf,shimLocalStreamsAPI:tf,shimRTCIceServerUrls:of,shimRemoteStreamsAPI:nf,shimTrackEventTransceiver:cf}),yc={exports:{}},hf;function d0(){return hf||(hf=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(`
|
|
49
49
|
`).map(n=>n.trim())},e.splitSections=function(t){return t.split(`
|
|
50
50
|
m=`).map((s,r)=>(r>0?"m="+s:s).trim()+`\r
|
|
51
51
|
`)},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&&(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
|
|
@@ -79,13 +79,13 @@ t=0 0\r
|
|
|
79
79
|
`},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}(yc)),yc.exports}var ff=d0(),Ns=Zv(ff),u0=Cg({__proto__:null,default:Ns},[ff]);function La(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=Ns.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,os(i,"icecandidate",t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new i.RTCIceCandidate(t.candidate),writable:"false"}),t))}function _c(i){!i.RTCIceCandidate||i.RTCIceCandidate&&"relayProtocol"in i.RTCIceCandidate.prototype||os(i,"icecandidate",e=>{if(e.candidate){const t=Ns.parseCandidate(e.candidate.candidate);t.type==="relay"&&(e.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[t.priority>>24])}return e})}function Ua(i,e){if(!i.RTCPeerConnection)return;"sctp"in i.RTCPeerConnection.prototype||Object.defineProperty(i.RTCPeerConnection.prototype,"sctp",{get(){return typeof this._sctp>"u"?null:this._sctp}});const t=function(o){if(!o||!o.sdp)return!1;const c=Ns.splitSections(o.sdp);return c.shift(),c.some(l=>{const d=Ns.parseMLine(l);return d&&d.kind==="application"&&d.protocol.indexOf("SCTP")!==-1})},n=function(o){const c=o.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(c===null||c.length<2)return-1;const l=parseInt(c[1],10);return l!==l?-1:l},s=function(o){let c=65536;return e.browser==="firefox"&&(e.version<57?o===-1?c=16384:c=2147483637:e.version<60?c=e.version===57?65535:65536:c=2147483637),c},r=function(o,c){let l=65536;e.browser==="firefox"&&e.version===57&&(l=65535);const d=Ns.matchPrefix(o.sdp,"a=max-message-size:");return d.length>0?l=parseInt(d[0].substring(19),10):e.browser==="firefox"&&c!==-1&&(l=2147483637),l},a=i.RTCPeerConnection.prototype.setRemoteDescription;i.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,e.browser==="chrome"&&e.version>=76){const{sdpSemantics:c}=this.getConfiguration();c==="plan-b"&&Object.defineProperty(this,"sctp",{get(){return typeof this._sctp>"u"?null:this._sctp},enumerable:!0,configurable:!0})}if(t(arguments[0])){const c=n(arguments[0]),l=s(c),d=r(arguments[0],c);let u;l===0&&d===0?u=Number.POSITIVE_INFINITY:l===0||d===0?u=Math.max(l,d):u=Math.min(l,d);const h={};Object.defineProperty(h,"maxMessageSize",{get(){return u}}),this._sctp=h}return a.apply(this,arguments)}}function Na(i){if(!(i.RTCPeerConnection&&"createDataChannel"in i.RTCPeerConnection.prototype))return;function e(n,s){const r=n.send;n.send=function(){const o=arguments[0],c=o.length||o.size||o.byteLength;if(n.readyState==="open"&&s.sctp&&c>s.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+s.sctp.maxMessageSize+" bytes)");return r.apply(n,arguments)}}const t=i.RTCPeerConnection.prototype.createDataChannel;i.RTCPeerConnection.prototype.createDataChannel=function(){const s=t.apply(this,arguments);return e(s,this),s},os(i,"datachannel",n=>(e(n.channel,n.target),n))}function Sc(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 xc(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(`
|
|
80
80
|
a=extmap-allow-mixed`)!==-1){const r=s.sdp.split(`
|
|
81
81
|
`).filter(a=>a.trim()!=="a=extmap-allow-mixed").join(`
|
|
82
|
-
`);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 Oa(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.version<78||e.browser==="firefox"&&e.version<68||e.browser==="safari")&&arguments[0]&&arguments[0].candidate===""?Promise.resolve():t.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}function Fa(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 h0=Object.freeze({__proto__:null,removeExtmapAllowMixed:xc,shimAddIceCandidateNullOrEmpty:Oa,shimConnectionState:Sc,shimMaxMessageSize:Ua,shimParameterlessSetLocalDescription:Fa,shimRTCIceCandidate:La,shimRTCIceCandidateRelayProtocol:_c,shimSendThrowTypeError:Na});function f0(){let{window:i}=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{shimChrome:!0,shimFirefox:!0,shimSafari:!0};const t=Ph,n=c0(i),s={browserDetails:n,commonShim:h0,extractVersion:Lr,disableLog:a0,disableWarnings:o0,sdp:u0};switch(n.browser){case"chrome":if(!Hh||!vc||!e.shimChrome)return t("Chrome shim is not included in this adapter release."),s;if(n.version===null)return t("Chrome shim can not determine version, not shimming."),s;t("adapter.js shimming chrome."),s.browserShim=Hh,Oa(i,n),Fa(i),Uh(i,n),Nh(i),vc(i,n),Oh(i),Vh(i,n),Fh(i),Bh(i),Gh(i,n),La(i),_c(i),Sc(i),Ua(i,n),Na(i),xc(i,n);break;case"firefox":if(!ef||!bc||!e.shimFirefox)return t("Firefox shim is not included in this adapter release."),s;t("adapter.js shimming firefox."),s.browserShim=ef,Oa(i,n),Fa(i),Wh(i,n),bc(i,n),qh(i),Xh(i),$h(i),jh(i),Yh(i),Kh(i),Jh(i),Zh(i),Qh(i),La(i),Sc(i),Ua(i,n),Na(i);break;case"safari":if(!uf||!e.shimSafari)return t("Safari shim is not included in this adapter release."),s;t("adapter.js shimming safari."),s.browserShim=uf,Oa(i,n),Fa(i),of(i),lf(i),sf(i),tf(i),nf(i),cf(i),rf(i),df(i),La(i),_c(i),Ua(i,n),Na(i),xc(i,n);break;default:t("Unsupported browser!");break}return s}f0({window:typeof window>"u"?void 0:window});const p0=10,Ur="lk_e2ee",m0={sharedKey:!1,ratchetSalt:"LKFrameEncryptionKey",ratchetWindowSize:8,failureTolerance:p0,keyringSize:16};var Fi;(function(i){i.SetKey="setKey",i.RatchetRequest="ratchetRequest",i.KeyRatcheted="keyRatcheted"})(Fi||(Fi={}));var pf;(function(i){i.KeyRatcheted="keyRatcheted"})(pf||(pf={}));var Bi;(function(i){i.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",i.EncryptionError="encryptionError"})(Bi||(Bi={}));var mf;(function(i){i.Error="cryptorError"})(mf||(mf={}));function g0(){return v0()||Tc()}function Tc(){return typeof window.RTCRtpScriptTransform<"u"}function v0(){return typeof window.RTCRtpSender<"u"&&typeof window.RTCRtpSender.prototype.createEncodedStreams<"u"}class ME extends Xn.EventEmitter{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};super(),this.onKeyRatcheted=(t,n,s)=>{Ke.debug("key ratcheted event received",{ratchetResult:t,participantId:n,keyIndex:s})},this.keyInfoMap=new Map,this.options=Object.assign(Object.assign({},m0),e),this.on(Fi.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),this.emit(Fi.SetKey,s)}getKeys(){return Array.from(this.keyInfoMap.values())}getOptions(){return this.options}ratchetKey(e,t){this.emit(Fi.RatchetRequest,e,t)}}class mi extends Error{constructor(e,t){super(t||"an error has occured"),this.name="LiveKitError",this.code=e}}var tt;(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"})(tt||(tt={}));class _t extends mi{constructor(e,t,n,s){super(1,e),this.name="ConnectionError",this.status=n,this.reason=t,this.context=s,this.reasonName=tt[t]}}class Cc extends mi{constructor(e){super(21,e??"device is unsupported"),this.name="DeviceUnsupportedError"}}class gi extends mi{constructor(e){super(20,e??"track is invalid"),this.name="TrackInvalidError"}}class b0 extends mi{constructor(e){super(10,e??"unsupported server"),this.name="UnsupportedServer"}}class Gt extends mi{constructor(e){super(12,e??"unexpected connection state"),this.name="UnexpectedConnectionState"}}class Ec extends mi{constructor(e){super(13,e??"unable to negotiate"),this.name="NegotiationError"}}class gf extends mi{constructor(e,t){super(15,e),this.name="PublishTrackError",this.status=t}}class vf extends mi{constructor(e,t){super(15,e),this.reason=t,this.reasonName=typeof t=="string"?t:fc[t]}}var Un;(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"})(Un||(Un={}));class zi extends mi{constructor(e,t){super(16,e),this.name="DataStreamError",this.reason=t,this.reasonName=Un[t]}}var Ba;(function(i){i.PermissionDenied="PermissionDenied",i.NotFound="NotFound",i.DeviceInUse="DeviceInUse",i.Other="Other"})(Ba||(Ba={})),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}(Ba||(Ba={}));var bf;(function(i){i[i.InvalidKey=0]="InvalidKey",i[i.MissingKey=1]="MissingKey",i[i.InternalError=2]="InternalError"})(bf||(bf={}));var ie;(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"})(ie||(ie={}));var le;(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"})(le||(le={}));var de;(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"})(de||(de={}));var oe;(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"})(oe||(oe={}));function y0(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))}const _0=/version\/(\d+(\.?_?\d+)+)/i;let Mc;function bn(i){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;if(typeof navigator>"u")return;const t=navigator.userAgent.toLowerCase();if(Mc===void 0||e){const n=S0.find(s=>{let{test:r}=s;return r.test(t)});Mc=n==null?void 0:n.describe(t)}return Mc}const S0=[{test:/firefox|iceweasel|fxios/i,describe(i){return{name:"Firefox",version:za(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,i),os:i.toLowerCase().includes("fxios")?"iOS":void 0,osVersion:wc(i)}}},{test:/chrom|crios|crmo/i,describe(i){return{name:"Chrome",version:za(/(?:chrome|chromium|crios|crmo)\/(\d+(\.?_?\d+)+)/i,i),os:i.toLowerCase().includes("crios")?"iOS":void 0,osVersion:wc(i)}}},{test:/safari|applewebkit/i,describe(i){return{name:"Safari",version:za(_0,i),os:i.includes("mobile/")?"iOS":"macOS",osVersion:wc(i)}}}];function za(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 wc(i){return i.includes("mac os")?za(/\(.+?(\d+_\d+(:?_\d+)?)/,i,1).replace(/_/g,"."):void 0}var x0="2.15.6";const T0=x0,C0=16;class Yt{}Yt.setTimeout=function(){return setTimeout(...arguments)},Yt.setInterval=function(){return setInterval(...arguments)},Yt.clearTimeout=function(){return clearTimeout(...arguments)},Yt.clearInterval=function(){return clearInterval(...arguments)};const E0=5e3,Nr=[];var yn;(function(i){i[i.LOW=0]="LOW",i[i.MEDIUM=1]="MEDIUM",i[i.HIGH=2]="HIGH"})(yn||(yn={}));class Q extends Xn.EventEmitter{get streamState(){return this._streamState}setStreamState(e){this._streamState=e}constructor(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};var s;super(),this.attachedElements=[],this.isMuted=!1,this._streamState=Q.StreamState.Active,this.isInBackground=!1,this._currentBitrate=0,this.log=Ke,this.appVisibilityChangedListener=()=>{this.backgroundTimeout&&clearTimeout(this.backgroundTimeout),document.visibilityState==="hidden"?this.backgroundTimeout=setTimeout(()=>this.handleAppVisibilityChanged(),E0):this.handleAppVisibilityChanged()},this.log=fi((s=n.loggerName)!==null&&s!==void 0?s:Ln.Track),this.loggerContextCb=n.loggerContextCb,this.setMaxListeners(100),this.kind=t,this._mediaStreamTrack=e,this._mediaStreamID=e.id,this.source=Q.Source.Unknown}get logContext(){var e;return Object.assign(Object.assign({},(e=this.loggerContextCb)===null||e===void 0?void 0:e.call(this)),Xe(this))}get currentBitrate(){return this._currentBitrate}get mediaStreamTrack(){return this._mediaStreamTrack}get mediaStreamID(){return this._mediaStreamID}attach(e){let t="audio";this.kind===Q.Kind.Video&&(t="video"),this.attachedElements.length===0&&this.kind===Q.Kind.Video&&this.addAppVisibilityListener(),e||(t==="audio"&&(Nr.forEach(r=>{r.parentElement===null&&!e&&(e=r)}),e&&Nr.splice(Nr.indexOf(e),1)),e||(e=document.createElement(t))),this.attachedElements.includes(e)||this.attachedElements.push(e),Os(this.mediaStreamTrack,e);const n=e.srcObject.getTracks(),s=n.some(r=>r.kind==="audio");return e.play().then(()=>{this.emit(s?oe.AudioPlaybackStarted:oe.VideoPlaybackStarted)}).catch(r=>{r.name==="NotAllowedError"?this.emit(s?oe.AudioPlaybackFailed:oe.VideoPlaybackFailed,r):r.name==="AbortError"?Ke.debug("".concat(s?"audio":"video"," playback aborted, likely due to new play request")):Ke.warn("could not playback ".concat(s?"audio":"video"),r),s&&e&&n.some(a=>a.kind==="video")&&r.name==="NotAllowedError"&&(e.muted=!0,e.play().catch(()=>{}))}),this.emit(oe.ElementAttached,e),e}detach(e){try{if(e){Fs(this.mediaStreamTrack,e);const n=this.attachedElements.indexOf(e);return n>=0&&(this.attachedElements.splice(n,1),this.recycleElement(e),this.emit(oe.ElementDetached,e)),e}const t=[];return this.attachedElements.forEach(n=>{Fs(this.mediaStreamTrack,n),t.push(n),this.recycleElement(n),this.emit(oe.ElementDetached,n)}),this.attachedElements=[],t}finally{this.attachedElements.length===0&&this.removeAppVisibilityListener()}}stop(){this.stopMonitor(),this._mediaStreamTrack.stop()}enable(){this._mediaStreamTrack.enabled=!0}disable(){this._mediaStreamTrack.enabled=!1}stopMonitor(){this.monitorInterval&&clearInterval(this.monitorInterval),this.timeSyncHandle&&cancelAnimationFrame(this.timeSyncHandle)}updateLoggerOptions(e){e.loggerName&&(this.log=fi(e.loggerName)),e.loggerContextCb&&(this.loggerContextCb=e.loggerContextCb)}recycleElement(e){if(e instanceof HTMLAudioElement){let t=!0;e.pause(),Nr.forEach(n=>{n.parentElement||(t=!1)}),t&&Nr.push(e)}}handleAppVisibilityChanged(){return P(this,void 0,void 0,function*(){this.isInBackground=document.visibilityState==="hidden",!this.isInBackground&&this.kind===Q.Kind.Video&&setTimeout(()=>this.attachedElements.forEach(e=>e.play().catch(()=>{})),0)})}addAppVisibilityListener(){dn()?(this.isInBackground=document.visibilityState==="hidden",document.addEventListener("visibilitychange",this.appVisibilityChangedListener)):this.isInBackground=!1}removeAppVisibilityListener(){dn()&&document.removeEventListener("visibilitychange",this.appVisibilityChangedListener)}}function Os(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)),(!ls()||!(e instanceof HTMLVideoElement))&&(e.autoplay=!0),e.muted=t.getAudioTracks().length===0,e instanceof HTMLVideoElement&&(e.playsInline=!0),e.srcObject!==t&&(e.srcObject=t,(ls()||cs())&&e instanceof HTMLVideoElement&&setTimeout(()=>{e.srcObject=t,e.play().catch(()=>{})},0))}function Fs(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(l){l.Audio="audio",l.Video="video",l.Unknown="unknown"})(e=i.Kind||(i.Kind={}));let t;(function(l){l.Camera="camera",l.Microphone="microphone",l.ScreenShare="screen_share",l.ScreenShareAudio="screen_share_audio",l.Unknown="unknown"})(t=i.Source||(i.Source={}));let n;(function(l){l.Active="active",l.Paused="paused",l.Unknown="unknown"})(n=i.StreamState||(i.StreamState={}));function s(l){switch(l){case e.Audio:return kn.AUDIO;case e.Video:return kn.VIDEO;default:return kn.DATA}}i.kindToProto=s;function r(l){switch(l){case kn.AUDIO:return e.Audio;case kn.VIDEO:return e.Video;default:return e.Unknown}}i.kindFromProto=r;function a(l){switch(l){case t.Camera:return Ot.CAMERA;case t.Microphone:return Ot.MICROPHONE;case t.ScreenShare:return Ot.SCREEN_SHARE;case t.ScreenShareAudio:return Ot.SCREEN_SHARE_AUDIO;default:return Ot.UNKNOWN}}i.sourceToProto=a;function o(l){switch(l){case Ot.CAMERA:return t.Camera;case Ot.MICROPHONE:return t.Microphone;case Ot.SCREEN_SHARE:return t.ScreenShare;case Ot.SCREEN_SHARE_AUDIO:return t.ScreenShareAudio;default:return t.Unknown}}i.sourceFromProto=o;function c(l){switch(l){case ac.ACTIVE:return n.Active;case ac.PAUSED:return n.Paused;default:return n.Unknown}}i.streamStateFromProto=c})(Q||(Q={}));class gt{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 M0=["vp8","h264"],w0=["vp8","h264","vp9","av1","h265"];function A0(i){return!!M0.find(e=>e===i)}var yf;(function(i){i[i.PREFER_REGRESSION=0]="PREFER_REGRESSION",i[i.SIMULCAST=1]="SIMULCAST",i[i.REGRESSION=2]="REGRESSION"})(yf||(yf={}));var Ac;(function(i){i.telephone={maxBitrate:12e3},i.speech={maxBitrate:24e3},i.music={maxBitrate:48e3},i.musicStereo={maxBitrate:64e3},i.musicHighQuality={maxBitrate:96e3},i.musicHighQualityStereo={maxBitrate:128e3}})(Ac||(Ac={}));const Or={h90:new gt(160,90,9e4,20),h180:new gt(320,180,16e4,20),h216:new gt(384,216,18e4,20),h360:new gt(640,360,45e4,20),h540:new gt(960,540,8e5,25),h720:new gt(1280,720,17e5,30),h1080:new gt(1920,1080,3e6,30),h1440:new gt(2560,1440,5e6,30),h2160:new gt(3840,2160,8e6,30)},Rc={h120:new gt(160,120,7e4,20),h180:new gt(240,180,125e3,20),h240:new gt(320,240,14e4,20),h360:new gt(480,360,33e4,20),h480:new gt(640,480,5e5,20),h540:new gt(720,540,6e5,25),h720:new gt(960,720,13e5,30),h1080:new gt(1440,1080,23e5,30),h1440:new gt(1920,1440,38e5,30)},Pc={h360fps3:new gt(640,360,2e5,3,"medium"),h360fps15:new gt(640,360,4e5,15,"medium"),h720fps5:new gt(1280,720,8e5,5,"medium"),h720fps15:new gt(1280,720,15e5,15,"medium"),h720fps30:new gt(1280,720,2e6,30,"medium"),h1080fps15:new gt(1920,1080,25e5,15,"medium"),h1080fps30:new gt(1920,1080,5e6,30,"medium"),original:new gt(0,0,7e6,30,"medium")},R0="|",_f="https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension";function P0(i){const e=i.split(R0);return e.length>1?[e[0],i.substr(e[0].length+1)]:[i,""]}function ln(i){return P(this,void 0,void 0,function*(){return new Promise(e=>Yt.setTimeout(e,i))})}function kc(){return"addTransceiver"in RTCPeerConnection.prototype}function Ic(){return"addTrack"in RTCPeerConnection.prototype}function k0(){if(!("getCapabilities"in RTCRtpSender)||ls()||cs())return!1;const i=RTCRtpSender.getCapabilities("video");let e=!1;if(i){for(const t of i.codecs)if(t.mimeType==="video/AV1"){e=!0;break}}return e}function I0(){if(!("getCapabilities"in RTCRtpSender)||cs())return!1;if(ls()){const t=bn();if(t!=null&&t.version&&Jn(t.version,"16")<0||(t==null?void 0:t.os)==="iOS"&&(t!=null&&t.osVersion)&&Jn(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==="video/VP9"){e=!0;break}}return e}function Yn(i){return i==="av1"||i==="vp9"}function Dc(i){return!document||Fr()?!1:(i||(i=document.createElement("audio")),"setSinkId"in i)}function D0(){return typeof RTCPeerConnection>"u"?!1:kc()||Ic()}function cs(){var i;return((i=bn())===null||i===void 0?void 0:i.name)==="Firefox"}function ls(){var i;return((i=bn())===null||i===void 0?void 0:i.name)==="Safari"}function Fr(){const i=bn();return(i==null?void 0:i.name)==="Safari"||(i==null?void 0:i.os)==="iOS"}function L0(){const i=bn();return(i==null?void 0:i.name)==="Safari"&&i.version.startsWith("17.")||(i==null?void 0:i.os)==="iOS"&&!!(i!=null&&i.osVersion)&&Jn(i.osVersion,"17")>=0}function U0(i){return i||(i=bn()),(i==null?void 0:i.name)==="Safari"&&Jn(i.version,"18.3")>0||(i==null?void 0:i.os)==="iOS"&&!!(i!=null&&i.osVersion)&&Jn(i.osVersion,"18.3")>0}function Sf(){var i,e;return dn()?(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 N0(){const i=bn(),e="17.2";if(i)return i.name!=="Safari"&&i.os!=="iOS"||i.os==="iOS"&&i.osVersion&&Jn(i.osVersion,e)>=0?!0:i.name==="Safari"&&Jn(i.version,e)>=0}function dn(){return typeof document<"u"}function Kn(){return navigator.product=="ReactNative"}function Lc(i){return i.hostname.endsWith(".livekit.cloud")||i.hostname.endsWith(".livekit.run")}function xf(){if(global&&global.LiveKitReactNativeGlobal)return global.LiveKitReactNativeGlobal}function Tf(){if(!Kn())return;let i=xf();if(i)return i.platform}function Cf(){if(dn())return window.devicePixelRatio;if(Kn()){let i=xf();if(i)return i.devicePixelRatio}return 1}function Jn(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 O0(i){for(const e of i)e.target.handleResize(e)}function F0(i){for(const e of i)e.target.handleVisibilityChanged(e)}let Uc=null;const Ef=()=>(Uc||(Uc=new ResizeObserver(O0)),Uc);let Nc=null;const Mf=()=>(Nc||(Nc=new IntersectionObserver(F0,{root:null,rootMargin:"0px"})),Nc);function B0(){var i;const e=new wv({sdk:oh.JS,protocol:C0,version:T0});return Kn()&&(e.os=(i=Tf())!==null&&i!==void 0?i:""),e}function wf(){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==null||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 a=s.captureStream(),[o]=a.getTracks();if(!o)throw Error("Could not get empty media stream video track");return o.enabled=t,o}let Br;function Oc(){if(!Br){const i=new AudioContext,e=i.createOscillator(),t=i.createGain();t.gain.setValueAtTime(0,0);const n=i.createMediaStreamDestination();if(e.connect(t),t.connect(n),e.start(),[Br]=n.stream.getAudioTracks(),!Br)throw Error("Could not get empty media stream audio track");Br.enabled=!1}return Br.clone()}class Zn{get isResolved(){return this._isResolved}constructor(e,t){this._isResolved=!1,this.onFinally=t,this.promise=new Promise((n,s)=>P(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 z0(i){return w0.includes(i)}function Vi(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 V0(i){return i.startsWith("http")?i.replace(/^(http)/,"ws"):i}function Fc(i){return i.startsWith("ws")?i.replace(/^(ws)/,"http"):i}function G0(i,e){return i.segments.map(t=>{let{id:n,text:s,language:r,startTime:a,endTime:o,final:c}=t;var l;const d=(l=e.get(n))!==null&&l!==void 0?l:Date.now(),u=Date.now();return c?e.delete(n):e.set(n,d),{id:n,text:s,startTime:Number.parseInt(a.toString()),endTime:Number.parseInt(o.toString()),final:c,language:r,firstReceivedTime:d,lastReceivedTime:u}})}function H0(i){const{id:e,timestamp:t,message:n,editTimestamp:s}=i;return{id:e,timestamp:Number.parseInt(t.toString()),editTimestamp:s?Number.parseInt(s.toString()):void 0,message:n}}function Af(i){switch(i.reason){case tt.LeaveRequest:return i.context;case tt.Cancelled:return In.CLIENT_INITIATED;case tt.NotAllowed:return In.USER_REJECTED;case tt.ServerUnreachable:return In.JOIN_FAILURE;default:return In.UNKNOWN_REASON}}function Va(i){return i!==void 0?Number(i):void 0}function ds(i){return i!==void 0?BigInt(i):void 0}function Bs(i){return!!i&&!(i instanceof MediaStreamTrack)&&i.isLocal}function Qn(i){return!!i&&i.kind==Q.Kind.Audio}function Gi(i){return!!i&&i.kind==Q.Kind.Video}function Hi(i){return Bs(i)&&Gi(i)}function vi(i){return Bs(i)&&Qn(i)}function Bc(i){return!!i&&!i.isLocal}function W0(i){return!!i&&!i.isLocal}function zc(i){return Bc(i)&&Gi(i)}function q0(i){return i.isLocal}function $0(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 Rf(i,e,t){var n,s,r,a;const{optionsWithoutProcessor:o,audioProcessor:c,videoProcessor:l}=If(i??{}),d=e==null?void 0:e.processor,u=t==null?void 0:t.processor,h=o??{};return h.audio===!0&&(h.audio={}),h.video===!0&&(h.video={}),h.audio&&(Vc(h.audio,e),(n=(r=h.audio).deviceId)!==null&&n!==void 0||(r.deviceId={ideal:"default"}),(c||d)&&(h.audio.processor=c??d)),h.video&&(Vc(h.video,t),(s=(a=h.video).deviceId)!==null&&s!==void 0||(a.deviceId={ideal:"default"}),(l||u)&&(h.video.processor=l??u)),h}function Vc(i,e){return Object.keys(e).forEach(t=>{i[t]===void 0&&(i[t]=e[t])}),i}function Gc(i){var e,t,n,s;const r={};if(i.video)if(typeof i.video=="object"){const a={},o=a,c=i.video;Object.keys(c).forEach(l=>{switch(l){case"resolution":Vc(o,c.resolution);break;default:o[l]=c[l]}}),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 Pf(i){return P(this,arguments,void 0,function(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:200;return function*(){const n=kf();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 ln(t),s.getByteTimeDomainData(a);const c=a.some(l=>l!==128&&l!==0);return n.close(),!c}return!1}()})}function kf(){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=()=>P(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)}(s=window.document.body)===null||s===void 0||s.removeEventListener("click",n)});window.document.body.addEventListener("click",n)}return t}}function j0(i){return i==="audioinput"?Q.Source.Microphone:i==="videoinput"?Q.Source.Camera:Q.Source.Unknown}function Hc(i){return i===Q.Source.Microphone?"audioinput":i===Q.Source.Camera?"videoinput":void 0}function X0(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,ls()?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 zr(i){return i.split("/")[1].toLowerCase()}function Y0(i){const e=[];return i.forEach(t=>{t.track!==void 0&&e.push(new uc({cid:t.track.mediaStreamID,track:t.trackInfo}))}),e}function Xe(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?Xe(i.track):{})}}function K0(){return typeof RTCRtpReceiver<"u"&&"getSynchronizationSources"in RTCRtpReceiver}function J0(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 If(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:y0(e)}}function Z0(i){switch(i){case Ot.CAMERA:return Q.Source.Camera;case Ot.MICROPHONE:return Q.Source.Microphone;case Ot.SCREEN_SHARE:return Q.Source.ScreenShare;case Ot.SCREEN_SHARE_AUDIO:return Q.Source.ScreenShareAudio;default:return Q.Source.Unknown}}function Df(i,e){return i.width*i.height<e.width*e.height}function Q0(i,e){var t;return(t=i.layers)===null||t===void 0?void 0:t.find(n=>n.quality===e)}class eb extends Xn.EventEmitter{constructor(e){super(),this.onWorkerMessage=t=>{var n,s;const{kind:r,data:a}=t.data;switch(r){case"error":Ke.error(a.error.message),this.emit(Bi.EncryptionError,a.error);break;case"initAck":a.enabled&&this.keyProvider.getKeys().forEach(o=>{this.postKey(o)});break;case"enable":if(a.enabled&&this.keyProvider.getKeys().forEach(o=>{this.postKey(o)}),this.encryptionEnabled!==a.enabled&&a.participantIdentity===((n=this.room)===null||n===void 0?void 0:n.localParticipant.identity))this.emit(Bi.ParticipantEncryptionStatusChanged,a.enabled,this.room.localParticipant),this.encryptionEnabled=a.enabled;else if(a.participantIdentity){const o=(s=this.room)===null||s===void 0?void 0:s.getParticipantByIdentity(a.participantIdentity);if(!o)throw TypeError("couldn't set encryption status, participant not found".concat(a.participantIdentity));this.emit(Bi.ParticipantEncryptionStatusChanged,a.enabled,o)}break;case"ratchetKey":this.keyProvider.emit(Fi.KeyRatcheted,a.ratchetResult,a.participantIdentity,a.keyIndex);break}},this.onWorkerError=t=>{Ke.error("e2ee worker encountered an error:",{error:t.error}),this.emit(Bi.EncryptionError,t.error)},this.keyProvider=e.keyProvider,this.worker=e.worker,this.encryptionEnabled=!1}setup(e){if(!g0())throw new Cc("tried to setup end-to-end encryption on an unsupported browser");if(Ke.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:t0.getLevel()}};this.worker&&(Ke.info("initializing worker",{worker:this.worker}),this.worker.onmessage=this.onWorkerMessage,this.worker.onerror=this.onWorkerError,this.worker.postMessage(t))}}setParticipantCryptorEnabled(e,t){Ke.debug("set e2ee to ".concat(e," for participant ").concat(t)),this.postEnable(e,t)}setSifTrailer(e){!e||e.length===0?Ke.warn("ignoring server sent trailer as it's empty"):this.postSifTrailer(e)}setupEngine(e){e.on(de.RTPVideoMapUpdate,t=>{this.postRTPMap(t)})}setupEventListeners(e,t){e.on(ie.TrackPublished,(n,s)=>this.setParticipantCryptorEnabled(n.trackInfo.encryption!==vn.NONE,s.identity)),e.on(ie.ConnectionStateChanged,n=>{n===ct.Connected&&e.remoteParticipants.forEach(s=>{s.trackPublications.forEach(r=>{this.setParticipantCryptorEnabled(r.trackInfo.encryption!==vn.NONE,s.identity)})})}).on(ie.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(ie.TrackSubscribed,(n,s,r)=>{this.setupE2EEReceiver(n,r.identity,s.trackInfo)}).on(ie.SignalConnected,()=>{if(!this.room)throw new TypeError("expected room to be present on signal connect");t.getKeys().forEach(n=>{this.postKey(n)}),this.setParticipantCryptorEnabled(this.room.localParticipant.isE2EEEnabled,this.room.localParticipant.identity)}),e.localParticipant.on(le.LocalSenderCreated,(n,s)=>P(this,void 0,void 0,function*(){this.setupE2EESender(s,n)})),e.localParticipant.on(le.LocalTrackPublished,n=>{if(!Gi(n.track)||!Fr())return;const s={kind:"updateCodec",data:{trackId:n.track.mediaStreamID,codec:zr(n.trackInfo.codecs[0].mimeType),participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(s)}),t.on(Fi.SetKey,n=>this.postKey(n)).on(Fi.RatchetRequest,(n,s)=>this.postRatchetRequest(n,s))}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){let{key:t,participantIdentity:n,keyIndex:s}=e;var r;if(!this.worker)throw Error("could not set key, worker is missing");const a={kind:"setKey",data:{participantIdentity:n,isPublisher:n===((r=this.room)===null||r===void 0?void 0:r.localParticipant.identity),key:t,keyIndex:s}};this.worker.postMessage(a)}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){if(!(n!=null&&n.mimeType)||n.mimeType==="")throw new TypeError("MimeType missing from trackInfo, cannot set up E2EE cryptor");this.handleReceiver(e.receiver,e.mediaStreamID,t,e.kind==="video"?zr(n.mimeType):void 0)}}setupE2EESender(e,t){if(!Bs(e)||!t){t||Ke.warn("early return because sender is not ready");return}this.handleSender(t,e.mediaStreamID,void 0)}handleReceiver(e,t,n,s){return P(this,void 0,void 0,function*(){if(this.worker){if(Tc()){const r={kind:"decode",participantIdentity:n,trackId:t,codec:s};e.transform=new RTCRtpScriptTransform(this.worker,r)}else{if(Ur in e&&s){const c={kind:"updateCodec",data:{trackId:t,codec:s,participantIdentity:n}};this.worker.postMessage(c);return}let r=e.writableStream,a=e.readableStream;if(!r||!a){const c=e.createEncodedStreams();e.writableStream=c.writable,r=c.writable,e.readableStream=c.readable,a=c.readable}const o={kind:"decode",data:{readableStream:a,writableStream:r,trackId:t,codec:s,participantIdentity:n,isReuse:Ur in e}};this.worker.postMessage(o,[a,r])}e[Ur]=!0}})}handleSender(e,t,n){var s;if(!(Ur in e||!this.worker)){if(!(!((s=this.room)===null||s===void 0)&&s.localParticipant.identity)||this.room.localParticipant.identity==="")throw TypeError("local identity needs to be known in order to set up encrypted sender");if(Tc()){Ke.info("initialize script transform");const r={kind:"encode",participantIdentity:this.room.localParticipant.identity,trackId:t,codec:n};e.transform=new RTCRtpScriptTransform(this.worker,r)}else{Ke.info("initialize encoded streams");const r=e.createEncodedStreams(),a={kind:"encode",data:{readableStream:r.readable,writableStream:r.writable,codec:n,trackId:t,participantIdentity:this.room.localParticipant.identity,isReuse:!1}};this.worker.postMessage(a,[r.readable,r.writable])}e[Ur]=!0}}}const Wc="default";class $t{constructor(){this._previousDevices=[]}static getInstance(){return this.instance===void 0&&(this.instance=new $t),this.instance}get previousDevices(){return this._previousDevices}getDevices(e){return P(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=$t.userMediaPromiseMap)===null||r===void 0?void 0:r.size)>0){Ke.debug("awaiting getUserMedia promise");try{t?yield $t.userMediaPromiseMap.get(t):yield Promise.all($t.userMediaPromiseMap.values())}catch{Ke.warn("error waiting for media permissons")}}let a=yield navigator.mediaDevices.enumerateDevices();if(s&&!(ls()&&n.hasDeviceInUse(t))&&(a.filter(c=>c.kind===t).length===0||a.some(c=>{const l=c.label==="",d=t?c.kind===t:!0;return l&&d}))){const c={video:t!=="audioinput"&&t!=="audiooutput",audio:t!=="videoinput"&&{deviceId:{ideal:"default"}}},l=yield navigator.mediaDevices.getUserMedia(c);a=yield navigator.mediaDevices.enumerateDevices(),l.getTracks().forEach(d=>{d.stop()})}return n._previousDevices=a,t&&(a=a.filter(o=>o.kind===t)),a}()})}normalizeDeviceId(e,t,n){return P(this,void 0,void 0,function*(){if(t!==Wc)return t;const s=yield this.getDevices(e),r=s.find(o=>o.deviceId===Wc);if(!r){Ke.warn("could not reliably determine default device");return}const a=s.find(o=>o.deviceId!==Wc&&o.groupId===(n??r.groupId));if(!a){Ke.warn("could not reliably determine default device");return}return a==null?void 0:a.deviceId})}hasDeviceInUse(e){return e?$t.userMediaPromiseMap.has(e):$t.userMediaPromiseMap.size>0}}$t.mediaDeviceKinds=["audioinput","audiooutput","videoinput"],$t.userMediaPromiseMap=new Map;var Vr;(function(i){i[i.WAITING=0]="WAITING",i[i.RUNNING=1]="RUNNING",i[i.COMPLETED=2]="COMPLETED"})(Vr||(Vr={}));class tb{constructor(){this.pendingTasks=new Map,this.taskMutex=new an,this.nextTaskIndex=0}run(e){return P(this,void 0,void 0,function*(){const t={id:this.nextTaskIndex++,enqueuedAt:Date.now(),status:Vr.WAITING};this.pendingTasks.set(t.id,t);const n=yield this.taskMutex.lock();try{return t.executedAt=Date.now(),t.status=Vr.RUNNING,yield e()}finally{t.status=Vr.COMPLETED,this.pendingTasks.delete(t.id),n()}})}flush(){return P(this,void 0,void 0,function*(){return this.run(()=>P(this,void 0,void 0,function*(){}))})}snapshot(){return Array.from(this.pendingTasks.values())}}function nb(i,e){const t=new URL(V0(i));return e.forEach((n,s)=>{t.searchParams.set(s,n)}),Lf(t,"rtc")}function ib(i){const e=new URL(Fc(i));return Lf(e,"validate")}function sb(i){return i.endsWith("/")?i:"".concat(i,"/")}function Lf(i,e){return i.pathname="".concat(sb(i.pathname)).concat(e),i.toString()}const rb=["syncState","trickle","offer","answer","simulate","leave"];function ab(i){const e=rb.indexOf(i.case)>=0;return Ke.trace("request allowed to bypass queue:",{canPass:e,req:i}),e}var Mt;(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"})(Mt||(Mt={}));class qc{get currentState(){return this.state}get isDisconnected(){return this.state===Mt.DISCONNECTING||this.state===Mt.DISCONNECTED}get isEstablishingConnection(){return this.state===Mt.CONNECTING||this.state===Mt.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=Mt.DISCONNECTED,this.log=Ke,this._requestId=0,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.log=fi((n=t.loggerName)!==null&&n!==void 0?n:Ln.Signal),this.loggerContextCb=t.loggerContextCb,this.useJSON=e,this.requestQueue=new tb,this.queuedRequests=[],this.closingLock=new an,this.connectionLock=new an,this.state=Mt.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 P(this,void 0,void 0,function*(){return this.state=Mt.CONNECTING,this.options=n,yield this.connect(e,t,n,s)})}reconnect(e,t,n,s){return P(this,void 0,void 0,function*(){if(!this.options){this.log.warn("attempted to reconnect without signal options being set, ignoring",this.logContext);return}return this.state=Mt.RECONNECTING,this.clearPingInterval(),yield this.connect(e,t,Object.assign(Object.assign({},this.options),{reconnect:!0,sid:n,reconnectReason:s}))})}connect(e,t,n,s){this.connectOptions=n;const r=B0(),a=ob(t,r,n),o=nb(e,a),c=ib(o);return new Promise((l,d)=>P(this,void 0,void 0,function*(){const u=yield this.connectionLock.lock();try{const h=()=>P(this,void 0,void 0,function*(){this.close(),clearTimeout(f),d(new _t("room connection has been cancelled (signal)",tt.Cancelled))}),f=setTimeout(()=>{this.close(),d(new _t("room connection has timed out (signal)",tt.ServerUnreachable))},n.websocketTimeout);s!=null&&s.aborted&&h(),s==null||s.addEventListener("abort",h);const g=new URL(o);g.searchParams.has("access_token")&&g.searchParams.set("access_token","<redacted>"),this.log.debug("connecting to ".concat(g),Object.assign({reconnect:n.reconnect,reconnectReason:n.reconnectReason},this.logContext)),this.ws&&(yield this.close(!1)),this.ws=new WebSocket(o),this.ws.binaryType="arraybuffer",this.ws.onopen=()=>{clearTimeout(f)},this.ws.onerror=v=>P(this,void 0,void 0,function*(){if(this.state!==Mt.CONNECTED){this.state=Mt.DISCONNECTED,clearTimeout(f);try{const m=yield fetch(c);if(m.status.toFixed(0).startsWith("4")){const p=yield m.text();d(new _t(p,tt.NotAllowed,m.status))}else d(new _t("Encountered unknown websocket error during connection: ".concat(v.toString()),tt.InternalError,m.status))}catch(m){d(new _t(m instanceof Error?m.message:"server was not reachable",tt.ServerUnreachable))}return}this.handleWSError(v)}),this.ws.onmessage=v=>P(this,void 0,void 0,function*(){var m,p,x;let C;if(typeof v.data=="string"){const b=JSON.parse(v.data);C=fh.fromJson(b,{ignoreUnknownFields:!0})}else if(v.data instanceof ArrayBuffer)C=fh.fromBinary(new Uint8Array(v.data));else{this.log.error("could not decode websocket message: ".concat(typeof v.data),this.logContext);return}if(this.state!==Mt.CONNECTED){let b=!1;if(((m=C.message)===null||m===void 0?void 0:m.case)==="join"?(this.state=Mt.CONNECTED,s==null||s.removeEventListener("abort",h),this.pingTimeoutDuration=C.message.value.pingTimeout,this.pingIntervalDuration=C.message.value.pingInterval,this.pingTimeoutDuration&&this.pingTimeoutDuration>0&&(this.log.debug("ping config",Object.assign(Object.assign({},this.logContext),{timeout:this.pingTimeoutDuration,interval:this.pingIntervalDuration})),this.startPingInterval()),l(C.message.value)):this.state===Mt.RECONNECTING&&C.message.case!=="leave"?(this.state=Mt.CONNECTED,s==null||s.removeEventListener("abort",h),this.startPingInterval(),((p=C.message)===null||p===void 0?void 0:p.case)==="reconnect"?l(C.message.value):(this.log.debug("declaring signal reconnected without reconnect response received",this.logContext),l(void 0),b=!0)):this.isEstablishingConnection&&C.message.case==="leave"?d(new _t("Received leave request while trying to (re)connect",tt.LeaveRequest,void 0,C.message.value.reason)):n.reconnect||d(new _t("did not receive join response, got ".concat((x=C.message)===null||x===void 0?void 0:x.case," instead"),tt.InternalError)),!b)return}this.signalLatency&&(yield ln(this.signalLatency)),this.handleSignalResponse(C)}),this.ws.onclose=v=>{this.isEstablishingConnection&&d(new _t("Websocket got closed during a (re)connection attempt",tt.InternalError)),this.log.warn("websocket closed",Object.assign(Object.assign({},this.logContext),{reason:v.reason,code:v.code,wasClean:v.wasClean,state:this.state})),this.handleOnClose(v.reason)}}finally{u()}}))}close(){return P(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.closingLock.lock();try{if(e.clearPingInterval(),t&&(e.state=Mt.DISCONNECTING),e.ws){e.ws.onmessage=null,e.ws.onopen=null,e.ws.onclose=null;const s=new Promise(r=>{e.ws?e.ws.onclose=()=>{r()}:r()});e.ws.readyState<e.ws.CLOSING&&(e.ws.close(),yield Promise.race([s,ln(250)])),e.ws=void 0}}finally{t&&(e.state=Mt.DISCONNECTED),n()}}()})}sendOffer(e,t){this.log.debug("sending offer",Object.assign(Object.assign({},this.logContext),{offerSdp:e.sdp})),this.sendRequest({case:"offer",value:Ga(e,t)})}sendAnswer(e,t){return this.log.debug("sending answer",Object.assign(Object.assign({},this.logContext),{answerSdp:e.sdp})),this.sendRequest({case:"answer",value:Ga(e,t)})}sendIceCandidate(e,t){return this.log.debug("sending ice candidate",Object.assign(Object.assign({},this.logContext),{candidate:e})),this.sendRequest({case:"trickle",value:new lc({candidateInit:JSON.stringify(e),target:t})})}sendMuteTrack(e,t){return this.sendRequest({case:"mute",value:new dc({sid:e,muted:t})})}sendAddTrack(e){return this.sendRequest({case:"addTrack",value:e})}sendUpdateLocalMetadata(e,t){return P(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 vh({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 gh({trackSid:e,layers:t})})}sendUpdateSubscriptionPermissions(e,t){return this.sendRequest({case:"subscriptionPermission",value:new _h({allParticipants:e,trackPermissions:t})})}sendSimulateScenario(e){return this.sendRequest({case:"simulate",value:e})}sendPing(){return Promise.all([this.sendRequest({case:"ping",value:At.parse(Date.now())}),this.sendRequest({case:"pingReq",value:new Ch({timestamp:At.parse(Date.now()),rtt:At.parse(this.rtt)})})])}sendUpdateLocalAudioTrack(e,t){return this.sendRequest({case:"updateAudioTrack",value:new mh({trackSid:e,features:t})})}sendLeave(){return this.sendRequest({case:"leave",value:new Pa({reason:In.CLIENT_INITIATED,action:Us.DISCONNECT})})}sendRequest(e){return P(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&&!ab(t)&&n.state===Mt.RECONNECTING){n.queuedRequests.push(()=>P(n,void 0,void 0,function*(){yield this.sendRequest(t,!0)}));return}if(s||(yield n.requestQueue.flush()),n.signalLatency&&(yield ln(n.signalLatency)),n.isDisconnected){n.log.debug("skipping signal request (type: ".concat(t.case,") - SignalClient disconnected"));return}if(!n.ws||n.ws.readyState!==n.ws.OPEN){n.log.error("cannot send signal request before connected, type: ".concat(t==null?void 0:t.case),n.logContext);return}const a=new Pv({message:t});try{n.useJSON?n.ws.send(a.toJsonString()):n.ws.send(a.toBinary())}catch(o){n.log.error("error sending signal message",Object.assign(Object.assign({},n.logContext),{error:o}))}}()})}handleSignalResponse(e){var t,n;const s=e.message;if(s==null){this.log.debug("received unsupported message",this.logContext);return}let r=!1;if(s.case==="answer"){const a=Uf(s.value);this.onAnswer&&this.onAnswer(a,s.value.id)}else if(s.case==="offer"){const a=Uf(s.value);this.onOffer&&this.onOffer(a,s.value.id)}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)):this.log.debug("unsupported message",Object.assign(Object.assign({},this.logContext),{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 P(this,void 0,void 0,function*(){if(this.state===Mt.DISCONNECTED)return;const t=this.onClose;yield this.close(),this.log.debug("websocket connection closed: ".concat(e),Object.assign(Object.assign({},this.logContext),{reason:e})),t&&t(e)})}handleWSError(e){this.log.error("websocket error",Object.assign(Object.assign({},this.logContext),{error:e}))}resetPingTimeout(){if(this.clearPingTimeout(),!this.pingTimeoutDuration){this.log.warn("ping timeout duration not set",this.logContext);return}this.pingTimeout=Yt.setTimeout(()=>{this.log.warn("ping timeout triggered. last pong received at: ".concat(new Date(Date.now()-this.pingTimeoutDuration*1e3).toUTCString()),this.logContext),this.handleOnClose("ping timeout")},this.pingTimeoutDuration*1e3)}clearPingTimeout(){this.pingTimeout&&Yt.clearTimeout(this.pingTimeout)}startPingInterval(){if(this.clearPingInterval(),this.resetPingTimeout(),!this.pingIntervalDuration){this.log.warn("ping interval duration not set",this.logContext);return}this.log.debug("start ping interval",this.logContext),this.pingInterval=Yt.setInterval(()=>{this.sendPing()},this.pingIntervalDuration*1e3)}clearPingInterval(){this.log.debug("clearing ping interval",this.logContext),this.clearPingTimeout(),this.pingInterval&&Yt.clearInterval(this.pingInterval)}}function Uf(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 Ga(i,e){return new as({sdp:i.sdp,type:i.type,id:e})}function ob(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",Kn()?"reactnative":"js"),s.set("version",e.version),s.set("protocol",e.protocol.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}class Nf{constructor(){this.buffer=[],this._totalSize=0}push(e){this.buffer.push(e),this._totalSize+=e.data.byteLength}pop(){const e=this.buffer.shift();return e&&(this._totalSize-=e.data.byteLength),e}getAll(){return this.buffer.slice()}popToSequence(e){for(;this.buffer.length>0&&this.buffer[0].sequence<=e;)this.pop()}alignBufferedAmount(e){for(;this.buffer.length>0;){const t=this.buffer[0];if(this._totalSize-t.data.byteLength<=e)break;this.pop()}}get length(){return this.buffer.length}}class cb{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[t,n]of this._map.entries())n.expiresAt<e&&this._map.delete(t);this._lastCleanup=e}get size(){return this.cleanup(),this._map.size}forEach(e){this.cleanup();for(const[t,n]of this._map.entries())n.expiresAt>=Date.now()&&e(n.value,t,this.asValueMap())}map(e){this.cleanup();const t=[],n=this.asValueMap();for(const[s,r]of n.entries())t.push(e(r,s,n));return t}asValueMap(){const e=new Map;for(const[t,n]of this._map.entries())n.expiresAt>=Date.now()&&e.set(t,n.value);return e}}var Nn={},$c={},jc={exports:{}},Of;function Xc(){if(Of)return jc.exports;Of=1;var i=jc.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")})}),jc.exports}var Ff;function lb(){return Ff||(Ff=1,function(i){var e=function(o){return String(Number(o))===o?Number(o):o},t=function(o,c,l,d){if(d&&!l)c[d]=e(o[1]);else for(var u=0;u<l.length;u+=1)o[u+1]!=null&&(c[l[u]]=e(o[u+1]))},n=function(o,c,l){var d=o.name&&o.names;o.push&&!c[o.push]?c[o.push]=[]:d&&!c[o.name]&&(c[o.name]={});var u=o.push?{}:d?c[o.name]:c;t(l.match(o.reg),u,o.names,o.name),o.push&&c[o.push].push(u)},s=Xc(),r=RegExp.prototype.test.bind(/^([a-z])=(.*)/);i.parse=function(o){var c={},l=[],d=c;return o.split(/(\r\n|\r|\n)/).filter(r).forEach(function(u){var h=u[0],f=u.slice(2);h==="m"&&(l.push({rtp:[],fmtp:[]}),d=l[l.length-1]);for(var g=0;g<(s[h]||[]).length;g+=1){var v=s[h][g];if(v.reg.test(f))return n(v,d,f)}}),c.media=l,c};var a=function(o,c){var l=c.split(/=(.+)/,2);return l.length===2?o[l[0]]=e(l[1]):l.length===1&&c.length>1&&(o[l[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 c=[],l=o.split(" ").map(e),d=0;d<l.length;d+=3)c.push({component:l[d],ip:l[d+1],port:l[d+2]});return c},i.parseImageAttributes=function(o){return o.split(" ").map(function(c){return c.substring(1,c.length-1).split(",").reduce(a,{})})},i.parseSimulcastStreamList=function(o){return o.split(";").map(function(c){return c.split(",").map(function(l){var d,u=!1;return l[0]!=="~"?d=e(l):(d=e(l.substring(1,l.length)),u=!0),{scid:d,paused:u}})})}}($c)),$c}var Yc,Bf;function db(){if(Bf)return Yc;Bf=1;var i=Xc(),e=/%[sdv%]/g,t=function(a){var o=1,c=arguments,l=c.length;return a.replace(e,function(d){if(o>=l)return d;var u=c[o];switch(o+=1,d){case"%%":return"%";case"%s":return String(u);case"%d":return Number(u);case"%v":return""}})},n=function(a,o,c){var l=o.format instanceof Function?o.format(o.push?c:c[o.name]):o.format,d=[a+"="+l];if(o.names)for(var u=0;u<o.names.length;u+=1){var h=o.names[u];o.name?d.push(c[o.name][h]):d.push(c[o.names[u]])}else d.push(c[o.name]);return t.apply(null,d)},s=["v","o","s","i","u","e","p","c","b","t","r","z","a"],r=["i","c","b","a"];return Yc=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 c=o.outerOrder||s,l=o.innerOrder||r,d=[];return c.forEach(function(u){i[u].forEach(function(h){h.name in a&&a[h.name]!=null?d.push(n(u,h,a)):h.push in a&&a[h.push]!=null&&a[h.push].forEach(function(f){d.push(n(u,h,f))})})}),a.media.forEach(function(u){d.push(n("m",i.m[0],u)),l.forEach(function(h){i[h].forEach(function(f){f.name in u&&u[f.name]!=null?d.push(n(h,f,u)):f.push in u&&u[f.push]!=null&&u[f.push].forEach(function(g){d.push(n(h,f,g))})})})}),d.join(`\r
|
|
82
|
+
`);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 Oa(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.version<78||e.browser==="firefox"&&e.version<68||e.browser==="safari")&&arguments[0]&&arguments[0].candidate===""?Promise.resolve():t.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}function Fa(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 h0=Object.freeze({__proto__:null,removeExtmapAllowMixed:xc,shimAddIceCandidateNullOrEmpty:Oa,shimConnectionState:Sc,shimMaxMessageSize:Ua,shimParameterlessSetLocalDescription:Fa,shimRTCIceCandidate:La,shimRTCIceCandidateRelayProtocol:_c,shimSendThrowTypeError:Na});function f0(){let{window:i}=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{shimChrome:!0,shimFirefox:!0,shimSafari:!0};const t=Ph,n=c0(i),s={browserDetails:n,commonShim:h0,extractVersion:Lr,disableLog:a0,disableWarnings:o0,sdp:u0};switch(n.browser){case"chrome":if(!Hh||!vc||!e.shimChrome)return t("Chrome shim is not included in this adapter release."),s;if(n.version===null)return t("Chrome shim can not determine version, not shimming."),s;t("adapter.js shimming chrome."),s.browserShim=Hh,Oa(i,n),Fa(i),Uh(i,n),Nh(i),vc(i,n),Oh(i),Vh(i,n),Fh(i),Bh(i),Gh(i,n),La(i),_c(i),Sc(i),Ua(i,n),Na(i),xc(i,n);break;case"firefox":if(!ef||!bc||!e.shimFirefox)return t("Firefox shim is not included in this adapter release."),s;t("adapter.js shimming firefox."),s.browserShim=ef,Oa(i,n),Fa(i),Wh(i,n),bc(i,n),qh(i),Xh(i),$h(i),jh(i),Yh(i),Kh(i),Jh(i),Zh(i),Qh(i),La(i),Sc(i),Ua(i,n),Na(i);break;case"safari":if(!uf||!e.shimSafari)return t("Safari shim is not included in this adapter release."),s;t("adapter.js shimming safari."),s.browserShim=uf,Oa(i,n),Fa(i),of(i),lf(i),sf(i),tf(i),nf(i),cf(i),rf(i),df(i),La(i),_c(i),Ua(i,n),Na(i),xc(i,n);break;default:t("Unsupported browser!");break}return s}f0({window:typeof window>"u"?void 0:window});const p0=10,Ur="lk_e2ee",m0={sharedKey:!1,ratchetSalt:"LKFrameEncryptionKey",ratchetWindowSize:8,failureTolerance:p0,keyringSize:16};var Fi;(function(i){i.SetKey="setKey",i.RatchetRequest="ratchetRequest",i.KeyRatcheted="keyRatcheted"})(Fi||(Fi={}));var pf;(function(i){i.KeyRatcheted="keyRatcheted"})(pf||(pf={}));var Bi;(function(i){i.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",i.EncryptionError="encryptionError"})(Bi||(Bi={}));var mf;(function(i){i.Error="cryptorError"})(mf||(mf={}));function g0(){return v0()||Tc()}function Tc(){return typeof window.RTCRtpScriptTransform<"u"}function v0(){return typeof window.RTCRtpSender<"u"&&typeof window.RTCRtpSender.prototype.createEncodedStreams<"u"}class ME extends Xn.EventEmitter{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};super(),this.onKeyRatcheted=(t,n,s)=>{Ke.debug("key ratcheted event received",{ratchetResult:t,participantId:n,keyIndex:s})},this.keyInfoMap=new Map,this.options=Object.assign(Object.assign({},m0),e),this.on(Fi.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),this.emit(Fi.SetKey,s)}getKeys(){return Array.from(this.keyInfoMap.values())}getOptions(){return this.options}ratchetKey(e,t){this.emit(Fi.RatchetRequest,e,t)}}class mi extends Error{constructor(e,t){super(t||"an error has occured"),this.name="LiveKitError",this.code=e}}var tt;(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"})(tt||(tt={}));class _t extends mi{constructor(e,t,n,s){super(1,e),this.name="ConnectionError",this.status=n,this.reason=t,this.context=s,this.reasonName=tt[t]}}class Cc extends mi{constructor(e){super(21,e??"device is unsupported"),this.name="DeviceUnsupportedError"}}class gi extends mi{constructor(e){super(20,e??"track is invalid"),this.name="TrackInvalidError"}}class b0 extends mi{constructor(e){super(10,e??"unsupported server"),this.name="UnsupportedServer"}}class Gt extends mi{constructor(e){super(12,e??"unexpected connection state"),this.name="UnexpectedConnectionState"}}class Ec extends mi{constructor(e){super(13,e??"unable to negotiate"),this.name="NegotiationError"}}class gf extends mi{constructor(e,t){super(15,e),this.name="PublishTrackError",this.status=t}}class vf extends mi{constructor(e,t){super(15,e),this.reason=t,this.reasonName=typeof t=="string"?t:fc[t]}}var Un;(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"})(Un||(Un={}));class zi extends mi{constructor(e,t){super(16,e),this.name="DataStreamError",this.reason=t,this.reasonName=Un[t]}}var Ba;(function(i){i.PermissionDenied="PermissionDenied",i.NotFound="NotFound",i.DeviceInUse="DeviceInUse",i.Other="Other"})(Ba||(Ba={})),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}(Ba||(Ba={}));var bf;(function(i){i[i.InvalidKey=0]="InvalidKey",i[i.MissingKey=1]="MissingKey",i[i.InternalError=2]="InternalError"})(bf||(bf={}));var ie;(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"})(ie||(ie={}));var le;(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"})(le||(le={}));var de;(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"})(de||(de={}));var oe;(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"})(oe||(oe={}));function y0(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))}const _0=/version\/(\d+(\.?_?\d+)+)/i;let Mc;function bn(i){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;if(typeof navigator>"u")return;const t=navigator.userAgent.toLowerCase();if(Mc===void 0||e){const n=S0.find(s=>{let{test:r}=s;return r.test(t)});Mc=n==null?void 0:n.describe(t)}return Mc}const S0=[{test:/firefox|iceweasel|fxios/i,describe(i){return{name:"Firefox",version:za(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,i),os:i.toLowerCase().includes("fxios")?"iOS":void 0,osVersion:wc(i)}}},{test:/chrom|crios|crmo/i,describe(i){return{name:"Chrome",version:za(/(?:chrome|chromium|crios|crmo)\/(\d+(\.?_?\d+)+)/i,i),os:i.toLowerCase().includes("crios")?"iOS":void 0,osVersion:wc(i)}}},{test:/safari|applewebkit/i,describe(i){return{name:"Safari",version:za(_0,i),os:i.includes("mobile/")?"iOS":"macOS",osVersion:wc(i)}}}];function za(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 wc(i){return i.includes("mac os")?za(/\(.+?(\d+_\d+(:?_\d+)?)/,i,1).replace(/_/g,"."):void 0}var x0="2.15.6";const T0=x0,C0=16;class Yt{}Yt.setTimeout=function(){return setTimeout(...arguments)},Yt.setInterval=function(){return setInterval(...arguments)},Yt.clearTimeout=function(){return clearTimeout(...arguments)},Yt.clearInterval=function(){return clearInterval(...arguments)};const E0=5e3,Nr=[];var yn;(function(i){i[i.LOW=0]="LOW",i[i.MEDIUM=1]="MEDIUM",i[i.HIGH=2]="HIGH"})(yn||(yn={}));class Q extends Xn.EventEmitter{get streamState(){return this._streamState}setStreamState(e){this._streamState=e}constructor(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};var s;super(),this.attachedElements=[],this.isMuted=!1,this._streamState=Q.StreamState.Active,this.isInBackground=!1,this._currentBitrate=0,this.log=Ke,this.appVisibilityChangedListener=()=>{this.backgroundTimeout&&clearTimeout(this.backgroundTimeout),document.visibilityState==="hidden"?this.backgroundTimeout=setTimeout(()=>this.handleAppVisibilityChanged(),E0):this.handleAppVisibilityChanged()},this.log=fi((s=n.loggerName)!==null&&s!==void 0?s:Ln.Track),this.loggerContextCb=n.loggerContextCb,this.setMaxListeners(100),this.kind=t,this._mediaStreamTrack=e,this._mediaStreamID=e.id,this.source=Q.Source.Unknown}get logContext(){var e;return Object.assign(Object.assign({},(e=this.loggerContextCb)===null||e===void 0?void 0:e.call(this)),Xe(this))}get currentBitrate(){return this._currentBitrate}get mediaStreamTrack(){return this._mediaStreamTrack}get mediaStreamID(){return this._mediaStreamID}attach(e){let t="audio";this.kind===Q.Kind.Video&&(t="video"),this.attachedElements.length===0&&this.kind===Q.Kind.Video&&this.addAppVisibilityListener(),e||(t==="audio"&&(Nr.forEach(r=>{r.parentElement===null&&!e&&(e=r)}),e&&Nr.splice(Nr.indexOf(e),1)),e||(e=document.createElement(t))),this.attachedElements.includes(e)||this.attachedElements.push(e),Os(this.mediaStreamTrack,e);const n=e.srcObject.getTracks(),s=n.some(r=>r.kind==="audio");return e.play().then(()=>{this.emit(s?oe.AudioPlaybackStarted:oe.VideoPlaybackStarted)}).catch(r=>{r.name==="NotAllowedError"?this.emit(s?oe.AudioPlaybackFailed:oe.VideoPlaybackFailed,r):r.name==="AbortError"?Ke.debug("".concat(s?"audio":"video"," playback aborted, likely due to new play request")):Ke.warn("could not playback ".concat(s?"audio":"video"),r),s&&e&&n.some(a=>a.kind==="video")&&r.name==="NotAllowedError"&&(e.muted=!0,e.play().catch(()=>{}))}),this.emit(oe.ElementAttached,e),e}detach(e){try{if(e){Fs(this.mediaStreamTrack,e);const n=this.attachedElements.indexOf(e);return n>=0&&(this.attachedElements.splice(n,1),this.recycleElement(e),this.emit(oe.ElementDetached,e)),e}const t=[];return this.attachedElements.forEach(n=>{Fs(this.mediaStreamTrack,n),t.push(n),this.recycleElement(n),this.emit(oe.ElementDetached,n)}),this.attachedElements=[],t}finally{this.attachedElements.length===0&&this.removeAppVisibilityListener()}}stop(){this.stopMonitor(),this._mediaStreamTrack.stop()}enable(){this._mediaStreamTrack.enabled=!0}disable(){this._mediaStreamTrack.enabled=!1}stopMonitor(){this.monitorInterval&&clearInterval(this.monitorInterval),this.timeSyncHandle&&cancelAnimationFrame(this.timeSyncHandle)}updateLoggerOptions(e){e.loggerName&&(this.log=fi(e.loggerName)),e.loggerContextCb&&(this.loggerContextCb=e.loggerContextCb)}recycleElement(e){if(e instanceof HTMLAudioElement){let t=!0;e.pause(),Nr.forEach(n=>{n.parentElement||(t=!1)}),t&&Nr.push(e)}}handleAppVisibilityChanged(){return P(this,void 0,void 0,function*(){this.isInBackground=document.visibilityState==="hidden",!this.isInBackground&&this.kind===Q.Kind.Video&&setTimeout(()=>this.attachedElements.forEach(e=>e.play().catch(()=>{})),0)})}addAppVisibilityListener(){hn()?(this.isInBackground=document.visibilityState==="hidden",document.addEventListener("visibilitychange",this.appVisibilityChangedListener)):this.isInBackground=!1}removeAppVisibilityListener(){hn()&&document.removeEventListener("visibilitychange",this.appVisibilityChangedListener)}}function Os(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)),(!ls()||!(e instanceof HTMLVideoElement))&&(e.autoplay=!0),e.muted=t.getAudioTracks().length===0,e instanceof HTMLVideoElement&&(e.playsInline=!0),e.srcObject!==t&&(e.srcObject=t,(ls()||cs())&&e instanceof HTMLVideoElement&&setTimeout(()=>{e.srcObject=t,e.play().catch(()=>{})},0))}function Fs(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(l){l.Audio="audio",l.Video="video",l.Unknown="unknown"})(e=i.Kind||(i.Kind={}));let t;(function(l){l.Camera="camera",l.Microphone="microphone",l.ScreenShare="screen_share",l.ScreenShareAudio="screen_share_audio",l.Unknown="unknown"})(t=i.Source||(i.Source={}));let n;(function(l){l.Active="active",l.Paused="paused",l.Unknown="unknown"})(n=i.StreamState||(i.StreamState={}));function s(l){switch(l){case e.Audio:return kn.AUDIO;case e.Video:return kn.VIDEO;default:return kn.DATA}}i.kindToProto=s;function r(l){switch(l){case kn.AUDIO:return e.Audio;case kn.VIDEO:return e.Video;default:return e.Unknown}}i.kindFromProto=r;function a(l){switch(l){case t.Camera:return Ot.CAMERA;case t.Microphone:return Ot.MICROPHONE;case t.ScreenShare:return Ot.SCREEN_SHARE;case t.ScreenShareAudio:return Ot.SCREEN_SHARE_AUDIO;default:return Ot.UNKNOWN}}i.sourceToProto=a;function o(l){switch(l){case Ot.CAMERA:return t.Camera;case Ot.MICROPHONE:return t.Microphone;case Ot.SCREEN_SHARE:return t.ScreenShare;case Ot.SCREEN_SHARE_AUDIO:return t.ScreenShareAudio;default:return t.Unknown}}i.sourceFromProto=o;function c(l){switch(l){case ac.ACTIVE:return n.Active;case ac.PAUSED:return n.Paused;default:return n.Unknown}}i.streamStateFromProto=c})(Q||(Q={}));class gt{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 M0=["vp8","h264"],w0=["vp8","h264","vp9","av1","h265"];function A0(i){return!!M0.find(e=>e===i)}var yf;(function(i){i[i.PREFER_REGRESSION=0]="PREFER_REGRESSION",i[i.SIMULCAST=1]="SIMULCAST",i[i.REGRESSION=2]="REGRESSION"})(yf||(yf={}));var Ac;(function(i){i.telephone={maxBitrate:12e3},i.speech={maxBitrate:24e3},i.music={maxBitrate:48e3},i.musicStereo={maxBitrate:64e3},i.musicHighQuality={maxBitrate:96e3},i.musicHighQualityStereo={maxBitrate:128e3}})(Ac||(Ac={}));const Or={h90:new gt(160,90,9e4,20),h180:new gt(320,180,16e4,20),h216:new gt(384,216,18e4,20),h360:new gt(640,360,45e4,20),h540:new gt(960,540,8e5,25),h720:new gt(1280,720,17e5,30),h1080:new gt(1920,1080,3e6,30),h1440:new gt(2560,1440,5e6,30),h2160:new gt(3840,2160,8e6,30)},Rc={h120:new gt(160,120,7e4,20),h180:new gt(240,180,125e3,20),h240:new gt(320,240,14e4,20),h360:new gt(480,360,33e4,20),h480:new gt(640,480,5e5,20),h540:new gt(720,540,6e5,25),h720:new gt(960,720,13e5,30),h1080:new gt(1440,1080,23e5,30),h1440:new gt(1920,1440,38e5,30)},Pc={h360fps3:new gt(640,360,2e5,3,"medium"),h360fps15:new gt(640,360,4e5,15,"medium"),h720fps5:new gt(1280,720,8e5,5,"medium"),h720fps15:new gt(1280,720,15e5,15,"medium"),h720fps30:new gt(1280,720,2e6,30,"medium"),h1080fps15:new gt(1920,1080,25e5,15,"medium"),h1080fps30:new gt(1920,1080,5e6,30,"medium"),original:new gt(0,0,7e6,30,"medium")},R0="|",_f="https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension";function P0(i){const e=i.split(R0);return e.length>1?[e[0],i.substr(e[0].length+1)]:[i,""]}function un(i){return P(this,void 0,void 0,function*(){return new Promise(e=>Yt.setTimeout(e,i))})}function kc(){return"addTransceiver"in RTCPeerConnection.prototype}function Ic(){return"addTrack"in RTCPeerConnection.prototype}function k0(){if(!("getCapabilities"in RTCRtpSender)||ls()||cs())return!1;const i=RTCRtpSender.getCapabilities("video");let e=!1;if(i){for(const t of i.codecs)if(t.mimeType==="video/AV1"){e=!0;break}}return e}function I0(){if(!("getCapabilities"in RTCRtpSender)||cs())return!1;if(ls()){const t=bn();if(t!=null&&t.version&&Jn(t.version,"16")<0||(t==null?void 0:t.os)==="iOS"&&(t!=null&&t.osVersion)&&Jn(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==="video/VP9"){e=!0;break}}return e}function Yn(i){return i==="av1"||i==="vp9"}function Dc(i){return!document||Fr()?!1:(i||(i=document.createElement("audio")),"setSinkId"in i)}function D0(){return typeof RTCPeerConnection>"u"?!1:kc()||Ic()}function cs(){var i;return((i=bn())===null||i===void 0?void 0:i.name)==="Firefox"}function ls(){var i;return((i=bn())===null||i===void 0?void 0:i.name)==="Safari"}function Fr(){const i=bn();return(i==null?void 0:i.name)==="Safari"||(i==null?void 0:i.os)==="iOS"}function L0(){const i=bn();return(i==null?void 0:i.name)==="Safari"&&i.version.startsWith("17.")||(i==null?void 0:i.os)==="iOS"&&!!(i!=null&&i.osVersion)&&Jn(i.osVersion,"17")>=0}function U0(i){return i||(i=bn()),(i==null?void 0:i.name)==="Safari"&&Jn(i.version,"18.3")>0||(i==null?void 0:i.os)==="iOS"&&!!(i!=null&&i.osVersion)&&Jn(i.osVersion,"18.3")>0}function Sf(){var i,e;return hn()?(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 N0(){const i=bn(),e="17.2";if(i)return i.name!=="Safari"&&i.os!=="iOS"||i.os==="iOS"&&i.osVersion&&Jn(i.osVersion,e)>=0?!0:i.name==="Safari"&&Jn(i.version,e)>=0}function hn(){return typeof document<"u"}function Kn(){return navigator.product=="ReactNative"}function Lc(i){return i.hostname.endsWith(".livekit.cloud")||i.hostname.endsWith(".livekit.run")}function xf(){if(global&&global.LiveKitReactNativeGlobal)return global.LiveKitReactNativeGlobal}function Tf(){if(!Kn())return;let i=xf();if(i)return i.platform}function Cf(){if(hn())return window.devicePixelRatio;if(Kn()){let i=xf();if(i)return i.devicePixelRatio}return 1}function Jn(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 O0(i){for(const e of i)e.target.handleResize(e)}function F0(i){for(const e of i)e.target.handleVisibilityChanged(e)}let Uc=null;const Ef=()=>(Uc||(Uc=new ResizeObserver(O0)),Uc);let Nc=null;const Mf=()=>(Nc||(Nc=new IntersectionObserver(F0,{root:null,rootMargin:"0px"})),Nc);function B0(){var i;const e=new wv({sdk:oh.JS,protocol:C0,version:T0});return Kn()&&(e.os=(i=Tf())!==null&&i!==void 0?i:""),e}function wf(){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==null||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 a=s.captureStream(),[o]=a.getTracks();if(!o)throw Error("Could not get empty media stream video track");return o.enabled=t,o}let Br;function Oc(){if(!Br){const i=new AudioContext,e=i.createOscillator(),t=i.createGain();t.gain.setValueAtTime(0,0);const n=i.createMediaStreamDestination();if(e.connect(t),t.connect(n),e.start(),[Br]=n.stream.getAudioTracks(),!Br)throw Error("Could not get empty media stream audio track");Br.enabled=!1}return Br.clone()}class Zn{get isResolved(){return this._isResolved}constructor(e,t){this._isResolved=!1,this.onFinally=t,this.promise=new Promise((n,s)=>P(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 z0(i){return w0.includes(i)}function Vi(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 V0(i){return i.startsWith("http")?i.replace(/^(http)/,"ws"):i}function Fc(i){return i.startsWith("ws")?i.replace(/^(ws)/,"http"):i}function G0(i,e){return i.segments.map(t=>{let{id:n,text:s,language:r,startTime:a,endTime:o,final:c}=t;var l;const d=(l=e.get(n))!==null&&l!==void 0?l:Date.now(),u=Date.now();return c?e.delete(n):e.set(n,d),{id:n,text:s,startTime:Number.parseInt(a.toString()),endTime:Number.parseInt(o.toString()),final:c,language:r,firstReceivedTime:d,lastReceivedTime:u}})}function H0(i){const{id:e,timestamp:t,message:n,editTimestamp:s}=i;return{id:e,timestamp:Number.parseInt(t.toString()),editTimestamp:s?Number.parseInt(s.toString()):void 0,message:n}}function Af(i){switch(i.reason){case tt.LeaveRequest:return i.context;case tt.Cancelled:return In.CLIENT_INITIATED;case tt.NotAllowed:return In.USER_REJECTED;case tt.ServerUnreachable:return In.JOIN_FAILURE;default:return In.UNKNOWN_REASON}}function Va(i){return i!==void 0?Number(i):void 0}function ds(i){return i!==void 0?BigInt(i):void 0}function Bs(i){return!!i&&!(i instanceof MediaStreamTrack)&&i.isLocal}function Qn(i){return!!i&&i.kind==Q.Kind.Audio}function Gi(i){return!!i&&i.kind==Q.Kind.Video}function Hi(i){return Bs(i)&&Gi(i)}function vi(i){return Bs(i)&&Qn(i)}function Bc(i){return!!i&&!i.isLocal}function W0(i){return!!i&&!i.isLocal}function zc(i){return Bc(i)&&Gi(i)}function q0(i){return i.isLocal}function $0(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 Rf(i,e,t){var n,s,r,a;const{optionsWithoutProcessor:o,audioProcessor:c,videoProcessor:l}=If(i??{}),d=e==null?void 0:e.processor,u=t==null?void 0:t.processor,h=o??{};return h.audio===!0&&(h.audio={}),h.video===!0&&(h.video={}),h.audio&&(Vc(h.audio,e),(n=(r=h.audio).deviceId)!==null&&n!==void 0||(r.deviceId={ideal:"default"}),(c||d)&&(h.audio.processor=c??d)),h.video&&(Vc(h.video,t),(s=(a=h.video).deviceId)!==null&&s!==void 0||(a.deviceId={ideal:"default"}),(l||u)&&(h.video.processor=l??u)),h}function Vc(i,e){return Object.keys(e).forEach(t=>{i[t]===void 0&&(i[t]=e[t])}),i}function Gc(i){var e,t,n,s;const r={};if(i.video)if(typeof i.video=="object"){const a={},o=a,c=i.video;Object.keys(c).forEach(l=>{switch(l){case"resolution":Vc(o,c.resolution);break;default:o[l]=c[l]}}),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 Pf(i){return P(this,arguments,void 0,function(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:200;return function*(){const n=kf();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 un(t),s.getByteTimeDomainData(a);const c=a.some(l=>l!==128&&l!==0);return n.close(),!c}return!1}()})}function kf(){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=()=>P(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)}(s=window.document.body)===null||s===void 0||s.removeEventListener("click",n)});window.document.body.addEventListener("click",n)}return t}}function j0(i){return i==="audioinput"?Q.Source.Microphone:i==="videoinput"?Q.Source.Camera:Q.Source.Unknown}function Hc(i){return i===Q.Source.Microphone?"audioinput":i===Q.Source.Camera?"videoinput":void 0}function X0(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,ls()?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 zr(i){return i.split("/")[1].toLowerCase()}function Y0(i){const e=[];return i.forEach(t=>{t.track!==void 0&&e.push(new uc({cid:t.track.mediaStreamID,track:t.trackInfo}))}),e}function Xe(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?Xe(i.track):{})}}function K0(){return typeof RTCRtpReceiver<"u"&&"getSynchronizationSources"in RTCRtpReceiver}function J0(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 If(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:y0(e)}}function Z0(i){switch(i){case Ot.CAMERA:return Q.Source.Camera;case Ot.MICROPHONE:return Q.Source.Microphone;case Ot.SCREEN_SHARE:return Q.Source.ScreenShare;case Ot.SCREEN_SHARE_AUDIO:return Q.Source.ScreenShareAudio;default:return Q.Source.Unknown}}function Df(i,e){return i.width*i.height<e.width*e.height}function Q0(i,e){var t;return(t=i.layers)===null||t===void 0?void 0:t.find(n=>n.quality===e)}class eb extends Xn.EventEmitter{constructor(e){super(),this.onWorkerMessage=t=>{var n,s;const{kind:r,data:a}=t.data;switch(r){case"error":Ke.error(a.error.message),this.emit(Bi.EncryptionError,a.error);break;case"initAck":a.enabled&&this.keyProvider.getKeys().forEach(o=>{this.postKey(o)});break;case"enable":if(a.enabled&&this.keyProvider.getKeys().forEach(o=>{this.postKey(o)}),this.encryptionEnabled!==a.enabled&&a.participantIdentity===((n=this.room)===null||n===void 0?void 0:n.localParticipant.identity))this.emit(Bi.ParticipantEncryptionStatusChanged,a.enabled,this.room.localParticipant),this.encryptionEnabled=a.enabled;else if(a.participantIdentity){const o=(s=this.room)===null||s===void 0?void 0:s.getParticipantByIdentity(a.participantIdentity);if(!o)throw TypeError("couldn't set encryption status, participant not found".concat(a.participantIdentity));this.emit(Bi.ParticipantEncryptionStatusChanged,a.enabled,o)}break;case"ratchetKey":this.keyProvider.emit(Fi.KeyRatcheted,a.ratchetResult,a.participantIdentity,a.keyIndex);break}},this.onWorkerError=t=>{Ke.error("e2ee worker encountered an error:",{error:t.error}),this.emit(Bi.EncryptionError,t.error)},this.keyProvider=e.keyProvider,this.worker=e.worker,this.encryptionEnabled=!1}setup(e){if(!g0())throw new Cc("tried to setup end-to-end encryption on an unsupported browser");if(Ke.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:t0.getLevel()}};this.worker&&(Ke.info("initializing worker",{worker:this.worker}),this.worker.onmessage=this.onWorkerMessage,this.worker.onerror=this.onWorkerError,this.worker.postMessage(t))}}setParticipantCryptorEnabled(e,t){Ke.debug("set e2ee to ".concat(e," for participant ").concat(t)),this.postEnable(e,t)}setSifTrailer(e){!e||e.length===0?Ke.warn("ignoring server sent trailer as it's empty"):this.postSifTrailer(e)}setupEngine(e){e.on(de.RTPVideoMapUpdate,t=>{this.postRTPMap(t)})}setupEventListeners(e,t){e.on(ie.TrackPublished,(n,s)=>this.setParticipantCryptorEnabled(n.trackInfo.encryption!==vn.NONE,s.identity)),e.on(ie.ConnectionStateChanged,n=>{n===ct.Connected&&e.remoteParticipants.forEach(s=>{s.trackPublications.forEach(r=>{this.setParticipantCryptorEnabled(r.trackInfo.encryption!==vn.NONE,s.identity)})})}).on(ie.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(ie.TrackSubscribed,(n,s,r)=>{this.setupE2EEReceiver(n,r.identity,s.trackInfo)}).on(ie.SignalConnected,()=>{if(!this.room)throw new TypeError("expected room to be present on signal connect");t.getKeys().forEach(n=>{this.postKey(n)}),this.setParticipantCryptorEnabled(this.room.localParticipant.isE2EEEnabled,this.room.localParticipant.identity)}),e.localParticipant.on(le.LocalSenderCreated,(n,s)=>P(this,void 0,void 0,function*(){this.setupE2EESender(s,n)})),e.localParticipant.on(le.LocalTrackPublished,n=>{if(!Gi(n.track)||!Fr())return;const s={kind:"updateCodec",data:{trackId:n.track.mediaStreamID,codec:zr(n.trackInfo.codecs[0].mimeType),participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(s)}),t.on(Fi.SetKey,n=>this.postKey(n)).on(Fi.RatchetRequest,(n,s)=>this.postRatchetRequest(n,s))}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){let{key:t,participantIdentity:n,keyIndex:s}=e;var r;if(!this.worker)throw Error("could not set key, worker is missing");const a={kind:"setKey",data:{participantIdentity:n,isPublisher:n===((r=this.room)===null||r===void 0?void 0:r.localParticipant.identity),key:t,keyIndex:s}};this.worker.postMessage(a)}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){if(!(n!=null&&n.mimeType)||n.mimeType==="")throw new TypeError("MimeType missing from trackInfo, cannot set up E2EE cryptor");this.handleReceiver(e.receiver,e.mediaStreamID,t,e.kind==="video"?zr(n.mimeType):void 0)}}setupE2EESender(e,t){if(!Bs(e)||!t){t||Ke.warn("early return because sender is not ready");return}this.handleSender(t,e.mediaStreamID,void 0)}handleReceiver(e,t,n,s){return P(this,void 0,void 0,function*(){if(this.worker){if(Tc()){const r={kind:"decode",participantIdentity:n,trackId:t,codec:s};e.transform=new RTCRtpScriptTransform(this.worker,r)}else{if(Ur in e&&s){const c={kind:"updateCodec",data:{trackId:t,codec:s,participantIdentity:n}};this.worker.postMessage(c);return}let r=e.writableStream,a=e.readableStream;if(!r||!a){const c=e.createEncodedStreams();e.writableStream=c.writable,r=c.writable,e.readableStream=c.readable,a=c.readable}const o={kind:"decode",data:{readableStream:a,writableStream:r,trackId:t,codec:s,participantIdentity:n,isReuse:Ur in e}};this.worker.postMessage(o,[a,r])}e[Ur]=!0}})}handleSender(e,t,n){var s;if(!(Ur in e||!this.worker)){if(!(!((s=this.room)===null||s===void 0)&&s.localParticipant.identity)||this.room.localParticipant.identity==="")throw TypeError("local identity needs to be known in order to set up encrypted sender");if(Tc()){Ke.info("initialize script transform");const r={kind:"encode",participantIdentity:this.room.localParticipant.identity,trackId:t,codec:n};e.transform=new RTCRtpScriptTransform(this.worker,r)}else{Ke.info("initialize encoded streams");const r=e.createEncodedStreams(),a={kind:"encode",data:{readableStream:r.readable,writableStream:r.writable,codec:n,trackId:t,participantIdentity:this.room.localParticipant.identity,isReuse:!1}};this.worker.postMessage(a,[r.readable,r.writable])}e[Ur]=!0}}}const Wc="default";class $t{constructor(){this._previousDevices=[]}static getInstance(){return this.instance===void 0&&(this.instance=new $t),this.instance}get previousDevices(){return this._previousDevices}getDevices(e){return P(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=$t.userMediaPromiseMap)===null||r===void 0?void 0:r.size)>0){Ke.debug("awaiting getUserMedia promise");try{t?yield $t.userMediaPromiseMap.get(t):yield Promise.all($t.userMediaPromiseMap.values())}catch{Ke.warn("error waiting for media permissons")}}let a=yield navigator.mediaDevices.enumerateDevices();if(s&&!(ls()&&n.hasDeviceInUse(t))&&(a.filter(c=>c.kind===t).length===0||a.some(c=>{const l=c.label==="",d=t?c.kind===t:!0;return l&&d}))){const c={video:t!=="audioinput"&&t!=="audiooutput",audio:t!=="videoinput"&&{deviceId:{ideal:"default"}}},l=yield navigator.mediaDevices.getUserMedia(c);a=yield navigator.mediaDevices.enumerateDevices(),l.getTracks().forEach(d=>{d.stop()})}return n._previousDevices=a,t&&(a=a.filter(o=>o.kind===t)),a}()})}normalizeDeviceId(e,t,n){return P(this,void 0,void 0,function*(){if(t!==Wc)return t;const s=yield this.getDevices(e),r=s.find(o=>o.deviceId===Wc);if(!r){Ke.warn("could not reliably determine default device");return}const a=s.find(o=>o.deviceId!==Wc&&o.groupId===(n??r.groupId));if(!a){Ke.warn("could not reliably determine default device");return}return a==null?void 0:a.deviceId})}hasDeviceInUse(e){return e?$t.userMediaPromiseMap.has(e):$t.userMediaPromiseMap.size>0}}$t.mediaDeviceKinds=["audioinput","audiooutput","videoinput"],$t.userMediaPromiseMap=new Map;var Vr;(function(i){i[i.WAITING=0]="WAITING",i[i.RUNNING=1]="RUNNING",i[i.COMPLETED=2]="COMPLETED"})(Vr||(Vr={}));class tb{constructor(){this.pendingTasks=new Map,this.taskMutex=new cn,this.nextTaskIndex=0}run(e){return P(this,void 0,void 0,function*(){const t={id:this.nextTaskIndex++,enqueuedAt:Date.now(),status:Vr.WAITING};this.pendingTasks.set(t.id,t);const n=yield this.taskMutex.lock();try{return t.executedAt=Date.now(),t.status=Vr.RUNNING,yield e()}finally{t.status=Vr.COMPLETED,this.pendingTasks.delete(t.id),n()}})}flush(){return P(this,void 0,void 0,function*(){return this.run(()=>P(this,void 0,void 0,function*(){}))})}snapshot(){return Array.from(this.pendingTasks.values())}}function nb(i,e){const t=new URL(V0(i));return e.forEach((n,s)=>{t.searchParams.set(s,n)}),Lf(t,"rtc")}function ib(i){const e=new URL(Fc(i));return Lf(e,"validate")}function sb(i){return i.endsWith("/")?i:"".concat(i,"/")}function Lf(i,e){return i.pathname="".concat(sb(i.pathname)).concat(e),i.toString()}const rb=["syncState","trickle","offer","answer","simulate","leave"];function ab(i){const e=rb.indexOf(i.case)>=0;return Ke.trace("request allowed to bypass queue:",{canPass:e,req:i}),e}var Mt;(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"})(Mt||(Mt={}));class qc{get currentState(){return this.state}get isDisconnected(){return this.state===Mt.DISCONNECTING||this.state===Mt.DISCONNECTED}get isEstablishingConnection(){return this.state===Mt.CONNECTING||this.state===Mt.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=Mt.DISCONNECTED,this.log=Ke,this._requestId=0,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.log=fi((n=t.loggerName)!==null&&n!==void 0?n:Ln.Signal),this.loggerContextCb=t.loggerContextCb,this.useJSON=e,this.requestQueue=new tb,this.queuedRequests=[],this.closingLock=new cn,this.connectionLock=new cn,this.state=Mt.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 P(this,void 0,void 0,function*(){return this.state=Mt.CONNECTING,this.options=n,yield this.connect(e,t,n,s)})}reconnect(e,t,n,s){return P(this,void 0,void 0,function*(){if(!this.options){this.log.warn("attempted to reconnect without signal options being set, ignoring",this.logContext);return}return this.state=Mt.RECONNECTING,this.clearPingInterval(),yield this.connect(e,t,Object.assign(Object.assign({},this.options),{reconnect:!0,sid:n,reconnectReason:s}))})}connect(e,t,n,s){this.connectOptions=n;const r=B0(),a=ob(t,r,n),o=nb(e,a),c=ib(o);return new Promise((l,d)=>P(this,void 0,void 0,function*(){const u=yield this.connectionLock.lock();try{const h=()=>P(this,void 0,void 0,function*(){this.close(),clearTimeout(f),d(new _t("room connection has been cancelled (signal)",tt.Cancelled))}),f=setTimeout(()=>{this.close(),d(new _t("room connection has timed out (signal)",tt.ServerUnreachable))},n.websocketTimeout);s!=null&&s.aborted&&h(),s==null||s.addEventListener("abort",h);const g=new URL(o);g.searchParams.has("access_token")&&g.searchParams.set("access_token","<redacted>"),this.log.debug("connecting to ".concat(g),Object.assign({reconnect:n.reconnect,reconnectReason:n.reconnectReason},this.logContext)),this.ws&&(yield this.close(!1)),this.ws=new WebSocket(o),this.ws.binaryType="arraybuffer",this.ws.onopen=()=>{clearTimeout(f)},this.ws.onerror=v=>P(this,void 0,void 0,function*(){if(this.state!==Mt.CONNECTED){this.state=Mt.DISCONNECTED,clearTimeout(f);try{const m=yield fetch(c);if(m.status.toFixed(0).startsWith("4")){const p=yield m.text();d(new _t(p,tt.NotAllowed,m.status))}else d(new _t("Encountered unknown websocket error during connection: ".concat(v.toString()),tt.InternalError,m.status))}catch(m){d(new _t(m instanceof Error?m.message:"server was not reachable",tt.ServerUnreachable))}return}this.handleWSError(v)}),this.ws.onmessage=v=>P(this,void 0,void 0,function*(){var m,p,x;let C;if(typeof v.data=="string"){const b=JSON.parse(v.data);C=fh.fromJson(b,{ignoreUnknownFields:!0})}else if(v.data instanceof ArrayBuffer)C=fh.fromBinary(new Uint8Array(v.data));else{this.log.error("could not decode websocket message: ".concat(typeof v.data),this.logContext);return}if(this.state!==Mt.CONNECTED){let b=!1;if(((m=C.message)===null||m===void 0?void 0:m.case)==="join"?(this.state=Mt.CONNECTED,s==null||s.removeEventListener("abort",h),this.pingTimeoutDuration=C.message.value.pingTimeout,this.pingIntervalDuration=C.message.value.pingInterval,this.pingTimeoutDuration&&this.pingTimeoutDuration>0&&(this.log.debug("ping config",Object.assign(Object.assign({},this.logContext),{timeout:this.pingTimeoutDuration,interval:this.pingIntervalDuration})),this.startPingInterval()),l(C.message.value)):this.state===Mt.RECONNECTING&&C.message.case!=="leave"?(this.state=Mt.CONNECTED,s==null||s.removeEventListener("abort",h),this.startPingInterval(),((p=C.message)===null||p===void 0?void 0:p.case)==="reconnect"?l(C.message.value):(this.log.debug("declaring signal reconnected without reconnect response received",this.logContext),l(void 0),b=!0)):this.isEstablishingConnection&&C.message.case==="leave"?d(new _t("Received leave request while trying to (re)connect",tt.LeaveRequest,void 0,C.message.value.reason)):n.reconnect||d(new _t("did not receive join response, got ".concat((x=C.message)===null||x===void 0?void 0:x.case," instead"),tt.InternalError)),!b)return}this.signalLatency&&(yield un(this.signalLatency)),this.handleSignalResponse(C)}),this.ws.onclose=v=>{this.isEstablishingConnection&&d(new _t("Websocket got closed during a (re)connection attempt",tt.InternalError)),this.log.warn("websocket closed",Object.assign(Object.assign({},this.logContext),{reason:v.reason,code:v.code,wasClean:v.wasClean,state:this.state})),this.handleOnClose(v.reason)}}finally{u()}}))}close(){return P(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.closingLock.lock();try{if(e.clearPingInterval(),t&&(e.state=Mt.DISCONNECTING),e.ws){e.ws.onmessage=null,e.ws.onopen=null,e.ws.onclose=null;const s=new Promise(r=>{e.ws?e.ws.onclose=()=>{r()}:r()});e.ws.readyState<e.ws.CLOSING&&(e.ws.close(),yield Promise.race([s,un(250)])),e.ws=void 0}}finally{t&&(e.state=Mt.DISCONNECTED),n()}}()})}sendOffer(e,t){this.log.debug("sending offer",Object.assign(Object.assign({},this.logContext),{offerSdp:e.sdp})),this.sendRequest({case:"offer",value:Ga(e,t)})}sendAnswer(e,t){return this.log.debug("sending answer",Object.assign(Object.assign({},this.logContext),{answerSdp:e.sdp})),this.sendRequest({case:"answer",value:Ga(e,t)})}sendIceCandidate(e,t){return this.log.debug("sending ice candidate",Object.assign(Object.assign({},this.logContext),{candidate:e})),this.sendRequest({case:"trickle",value:new lc({candidateInit:JSON.stringify(e),target:t})})}sendMuteTrack(e,t){return this.sendRequest({case:"mute",value:new dc({sid:e,muted:t})})}sendAddTrack(e){return this.sendRequest({case:"addTrack",value:e})}sendUpdateLocalMetadata(e,t){return P(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 vh({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 gh({trackSid:e,layers:t})})}sendUpdateSubscriptionPermissions(e,t){return this.sendRequest({case:"subscriptionPermission",value:new _h({allParticipants:e,trackPermissions:t})})}sendSimulateScenario(e){return this.sendRequest({case:"simulate",value:e})}sendPing(){return Promise.all([this.sendRequest({case:"ping",value:At.parse(Date.now())}),this.sendRequest({case:"pingReq",value:new Ch({timestamp:At.parse(Date.now()),rtt:At.parse(this.rtt)})})])}sendUpdateLocalAudioTrack(e,t){return this.sendRequest({case:"updateAudioTrack",value:new mh({trackSid:e,features:t})})}sendLeave(){return this.sendRequest({case:"leave",value:new Pa({reason:In.CLIENT_INITIATED,action:Us.DISCONNECT})})}sendRequest(e){return P(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&&!ab(t)&&n.state===Mt.RECONNECTING){n.queuedRequests.push(()=>P(n,void 0,void 0,function*(){yield this.sendRequest(t,!0)}));return}if(s||(yield n.requestQueue.flush()),n.signalLatency&&(yield un(n.signalLatency)),n.isDisconnected){n.log.debug("skipping signal request (type: ".concat(t.case,") - SignalClient disconnected"));return}if(!n.ws||n.ws.readyState!==n.ws.OPEN){n.log.error("cannot send signal request before connected, type: ".concat(t==null?void 0:t.case),n.logContext);return}const a=new Pv({message:t});try{n.useJSON?n.ws.send(a.toJsonString()):n.ws.send(a.toBinary())}catch(o){n.log.error("error sending signal message",Object.assign(Object.assign({},n.logContext),{error:o}))}}()})}handleSignalResponse(e){var t,n;const s=e.message;if(s==null){this.log.debug("received unsupported message",this.logContext);return}let r=!1;if(s.case==="answer"){const a=Uf(s.value);this.onAnswer&&this.onAnswer(a,s.value.id)}else if(s.case==="offer"){const a=Uf(s.value);this.onOffer&&this.onOffer(a,s.value.id)}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)):this.log.debug("unsupported message",Object.assign(Object.assign({},this.logContext),{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 P(this,void 0,void 0,function*(){if(this.state===Mt.DISCONNECTED)return;const t=this.onClose;yield this.close(),this.log.debug("websocket connection closed: ".concat(e),Object.assign(Object.assign({},this.logContext),{reason:e})),t&&t(e)})}handleWSError(e){this.log.error("websocket error",Object.assign(Object.assign({},this.logContext),{error:e}))}resetPingTimeout(){if(this.clearPingTimeout(),!this.pingTimeoutDuration){this.log.warn("ping timeout duration not set",this.logContext);return}this.pingTimeout=Yt.setTimeout(()=>{this.log.warn("ping timeout triggered. last pong received at: ".concat(new Date(Date.now()-this.pingTimeoutDuration*1e3).toUTCString()),this.logContext),this.handleOnClose("ping timeout")},this.pingTimeoutDuration*1e3)}clearPingTimeout(){this.pingTimeout&&Yt.clearTimeout(this.pingTimeout)}startPingInterval(){if(this.clearPingInterval(),this.resetPingTimeout(),!this.pingIntervalDuration){this.log.warn("ping interval duration not set",this.logContext);return}this.log.debug("start ping interval",this.logContext),this.pingInterval=Yt.setInterval(()=>{this.sendPing()},this.pingIntervalDuration*1e3)}clearPingInterval(){this.log.debug("clearing ping interval",this.logContext),this.clearPingTimeout(),this.pingInterval&&Yt.clearInterval(this.pingInterval)}}function Uf(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 Ga(i,e){return new as({sdp:i.sdp,type:i.type,id:e})}function ob(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",Kn()?"reactnative":"js"),s.set("version",e.version),s.set("protocol",e.protocol.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}class Nf{constructor(){this.buffer=[],this._totalSize=0}push(e){this.buffer.push(e),this._totalSize+=e.data.byteLength}pop(){const e=this.buffer.shift();return e&&(this._totalSize-=e.data.byteLength),e}getAll(){return this.buffer.slice()}popToSequence(e){for(;this.buffer.length>0&&this.buffer[0].sequence<=e;)this.pop()}alignBufferedAmount(e){for(;this.buffer.length>0;){const t=this.buffer[0];if(this._totalSize-t.data.byteLength<=e)break;this.pop()}}get length(){return this.buffer.length}}class cb{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[t,n]of this._map.entries())n.expiresAt<e&&this._map.delete(t);this._lastCleanup=e}get size(){return this.cleanup(),this._map.size}forEach(e){this.cleanup();for(const[t,n]of this._map.entries())n.expiresAt>=Date.now()&&e(n.value,t,this.asValueMap())}map(e){this.cleanup();const t=[],n=this.asValueMap();for(const[s,r]of n.entries())t.push(e(r,s,n));return t}asValueMap(){const e=new Map;for(const[t,n]of this._map.entries())n.expiresAt>=Date.now()&&e.set(t,n.value);return e}}var Nn={},$c={},jc={exports:{}},Of;function Xc(){if(Of)return jc.exports;Of=1;var i=jc.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")})}),jc.exports}var Ff;function lb(){return Ff||(Ff=1,function(i){var e=function(o){return String(Number(o))===o?Number(o):o},t=function(o,c,l,d){if(d&&!l)c[d]=e(o[1]);else for(var u=0;u<l.length;u+=1)o[u+1]!=null&&(c[l[u]]=e(o[u+1]))},n=function(o,c,l){var d=o.name&&o.names;o.push&&!c[o.push]?c[o.push]=[]:d&&!c[o.name]&&(c[o.name]={});var u=o.push?{}:d?c[o.name]:c;t(l.match(o.reg),u,o.names,o.name),o.push&&c[o.push].push(u)},s=Xc(),r=RegExp.prototype.test.bind(/^([a-z])=(.*)/);i.parse=function(o){var c={},l=[],d=c;return o.split(/(\r\n|\r|\n)/).filter(r).forEach(function(u){var h=u[0],f=u.slice(2);h==="m"&&(l.push({rtp:[],fmtp:[]}),d=l[l.length-1]);for(var g=0;g<(s[h]||[]).length;g+=1){var v=s[h][g];if(v.reg.test(f))return n(v,d,f)}}),c.media=l,c};var a=function(o,c){var l=c.split(/=(.+)/,2);return l.length===2?o[l[0]]=e(l[1]):l.length===1&&c.length>1&&(o[l[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 c=[],l=o.split(" ").map(e),d=0;d<l.length;d+=3)c.push({component:l[d],ip:l[d+1],port:l[d+2]});return c},i.parseImageAttributes=function(o){return o.split(" ").map(function(c){return c.substring(1,c.length-1).split(",").reduce(a,{})})},i.parseSimulcastStreamList=function(o){return o.split(";").map(function(c){return c.split(",").map(function(l){var d,u=!1;return l[0]!=="~"?d=e(l):(d=e(l.substring(1,l.length)),u=!0),{scid:d,paused:u}})})}}($c)),$c}var Yc,Bf;function db(){if(Bf)return Yc;Bf=1;var i=Xc(),e=/%[sdv%]/g,t=function(a){var o=1,c=arguments,l=c.length;return a.replace(e,function(d){if(o>=l)return d;var u=c[o];switch(o+=1,d){case"%%":return"%";case"%s":return String(u);case"%d":return Number(u);case"%v":return""}})},n=function(a,o,c){var l=o.format instanceof Function?o.format(o.push?c:c[o.name]):o.format,d=[a+"="+l];if(o.names)for(var u=0;u<o.names.length;u+=1){var h=o.names[u];o.name?d.push(c[o.name][h]):d.push(c[o.names[u]])}else d.push(c[o.name]);return t.apply(null,d)},s=["v","o","s","i","u","e","p","c","b","t","r","z","a"],r=["i","c","b","a"];return Yc=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 c=o.outerOrder||s,l=o.innerOrder||r,d=[];return c.forEach(function(u){i[u].forEach(function(h){h.name in a&&a[h.name]!=null?d.push(n(u,h,a)):h.push in a&&a[h.push]!=null&&a[h.push].forEach(function(f){d.push(n(u,h,f))})})}),a.media.forEach(function(u){d.push(n("m",i.m[0],u)),l.forEach(function(h){i[h].forEach(function(f){f.name in u&&u[f.name]!=null?d.push(n(h,f,u)):f.push in u&&u[f.push]!=null&&u[f.push].forEach(function(g){d.push(n(h,f,g))})})})}),d.join(`\r
|
|
83
83
|
`)+`\r
|
|
84
|
-
`},Yc}var zf;function ub(){if(zf)return Nn;zf=1;var i=lb(),e=db(),t=Xc();return Nn.grammar=t,Nn.write=e,Nn.parse=i.parse,Nn.parseParams=i.parseParams,Nn.parseFmtpConfig=i.parseFmtpConfig,Nn.parsePayloads=i.parsePayloads,Nn.parseRemoteCandidates=i.parseRemoteCandidates,Nn.parseImageAttributes=i.parseImageAttributes,Nn.parseSimulcastStreamList=i.parseSimulcastStreamList,Nn}var Wi=ub();function Kc(i,e,t){var n,s,r;e===void 0&&(e=50),t===void 0&&(t={});var a=(n=t.isImmediate)!=null&&n,o=(s=t.callback)!=null&&s,c=t.maxWait,l=Date.now(),d=[];function u(){if(c!==void 0){var f=Date.now()-l;if(f+e>=c)return c-f}return e}var h=function(){var f=[].slice.call(arguments),g=this;return new Promise(function(v,m){var p=a&&r===void 0;if(r!==void 0&&clearTimeout(r),r=setTimeout(function(){if(r=void 0,l=Date.now(),!a){var C=i.apply(g,f);o&&o(C),d.forEach(function(b){return(0,b.resolve)(C)}),d=[]}},u()),p){var x=i.apply(g,f);return o&&o(x),v(x)}d.push({resolve:v,reject:m})})};return h.cancel=function(f){r!==void 0&&clearTimeout(r),d.forEach(function(g){return(0,g.reject)(f)}),d=[]},h}const hb=.7,fb=20,zs={NegotiationStarted:"negotiationStarted",NegotiationComplete:"negotiationComplete",RTPVideoPayloadTypes:"rtpVideoPayloadTypes"};class Vf extends Xn.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=Ke,this.ddExtID=0,this.latestOfferId=0,this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate=!1,this.trackBitrates=[],this.remoteStereoMids=[],this.remoteNackMids=[],this.negotiate=Kc(s=>P(this,void 0,void 0,function*(){this.emit(zs.NegotiationStarted);try{yield this.createAndSendOffer()}catch(r){if(s)s(r);else throw r}}),fb),this.close=()=>{this._pc&&(this._pc.close(),this._pc.onconnectionstatechange=null,this._pc.oniceconnectionstatechange=null,this._pc.onicegatheringstatechange=null,this._pc.ondatachannel=null,this._pc.onnegotiationneeded=null,this._pc.onsignalingstatechange=null,this._pc.onicecandidate=null,this._pc.ondatachannel=null,this._pc.ontrack=null,this._pc.onconnectionstatechange=null,this._pc.oniceconnectionstatechange=null,this._pc=null)},this.log=fi((n=t.loggerName)!==null&&n!==void 0?n:Ln.PCTransport),this.loggerOptions=t,this.config=e,this._pc=this.createPC(),this.offerLock=new an}createPC(){const e=new RTCPeerConnection(this.config);return e.onicecandidate=t=>{var n;t.candidate&&((n=this.onIceCandidate)===null||n===void 0||n.call(this,t.candidate))},e.onicecandidateerror=t=>{var n;(n=this.onIceCandidateError)===null||n===void 0||n.call(this,t)},e.oniceconnectionstatechange=()=>{var t;(t=this.onIceConnectionStateChange)===null||t===void 0||t.call(this,e.iceConnectionState)},e.onsignalingstatechange=()=>{var t;(t=this.onSignalingStatechange)===null||t===void 0||t.call(this,e.signalingState)},e.onconnectionstatechange=()=>{var t;(t=this.onConnectionStateChange)===null||t===void 0||t.call(this,e.connectionState)},e.ondatachannel=t=>{var n;(n=this.onDataChannel)===null||n===void 0||n.call(this,t)},e.ontrack=t=>{var n;(n=this.onTrack)===null||n===void 0||n.call(this,t)},e}get logContext(){var e,t;return Object.assign({},(t=(e=this.loggerOptions).loggerContextCb)===null||t===void 0?void 0:t.call(e))}get isICEConnected(){return this._pc!==null&&(this.pc.iceConnectionState==="connected"||this.pc.iceConnectionState==="completed")}addIceCandidate(e){return P(this,void 0,void 0,function*(){if(this.pc.remoteDescription&&!this.restartingIce)return this.pc.addIceCandidate(e);this.pendingCandidates.push(e)})}setRemoteDescription(e,t){return P(this,void 0,void 0,function*(){var n;if(e.type==="answer"&&this.latestOfferId>0&&t>0&&t!==this.latestOfferId)return this.log.warn("ignoring answer for old offer",Object.assign(Object.assign({},this.logContext),{offerId:t,latestOfferId:this.latestOfferId})),!1;let s;if(e.type==="offer"){let{stereoMids:r,nackMids:a}=pb(e);this.remoteStereoMids=r,this.remoteNackMids=a}else if(e.type==="answer"){const r=Wi.parse((n=e.sdp)!==null&&n!==void 0?n:"");r.media.forEach(a=>{a.type==="audio"&&this.trackBitrates.some(o=>{if(!o.transceiver||a.mid!=o.transceiver.mid)return!1;let c=0;if(a.rtp.some(d=>d.codec.toUpperCase()===o.codec.toUpperCase()?(c=d.payload,!0):!1),c===0)return!0;let l=!1;for(const d of a.fmtp)if(d.payload===c){d.config=d.config.split(";").filter(u=>!u.includes("maxaveragebitrate")).join(";"),o.maxbr>0&&(d.config+=";maxaveragebitrate=".concat(o.maxbr*1e3)),l=!0;break}return l||o.maxbr>0&&a.fmtp.push({payload:c,config:"maxaveragebitrate=".concat(o.maxbr*1e3)}),!0})}),s=Wi.write(r)}return yield this.setMungedSDP(e,s,!0),this.pendingCandidates.forEach(r=>{this.pc.addIceCandidate(r)}),this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate?(this.renegotiate=!1,yield this.createAndSendOffer()):e.type==="answer"&&(this.emit(zs.NegotiationComplete),e.sdp&&Wi.parse(e.sdp).media.forEach(a=>{a.type==="video"&&this.emit(zs.RTPVideoPayloadTypes,a.rtp)})),!0})}createAndSendOffer(e){return P(this,void 0,void 0,function*(){var t;const n=yield this.offerLock.lock();try{if(this.onOffer===void 0)return;if(e!=null&&e.iceRestart&&(this.log.debug("restarting ICE",this.logContext),this.restartingIce=!0),this._pc&&this._pc.signalingState==="have-local-offer"){const o=this._pc.remoteDescription;if(e!=null&&e.iceRestart&&o)yield this._pc.setRemoteDescription(o);else{this.renegotiate=!0;return}}else if(!this._pc||this._pc.signalingState==="closed"){this.log.warn("could not createOffer with closed peer connection",this.logContext);return}this.log.debug("starting to negotiate",this.logContext);const s=this.latestOfferId+1;this.latestOfferId=s;const r=yield this.pc.createOffer(e);this.log.debug("original offer",Object.assign({sdp:r.sdp},this.logContext));const a=Wi.parse((t=r.sdp)!==null&&t!==void 0?t:"");if(a.media.forEach(o=>{Hf(o),o.type==="audio"?Gf(o,[],[]):o.type==="video"&&this.trackBitrates.some(c=>{if(!o.msid||!c.cid||!o.msid.includes(c.cid))return!1;let l=0;if(o.rtp.some(u=>u.codec.toUpperCase()===c.codec.toUpperCase()?(l=u.payload,!0):!1),l===0||(Yn(c.codec)&&!ls()&&this.ensureVideoDDExtensionForSVC(o,a),c.codec!=="av1"))return!0;const d=Math.round(c.maxbr*hb);for(const u of o.fmtp)if(u.payload===l){u.config.includes("x-google-start-bitrate")||(u.config+=";x-google-start-bitrate=".concat(d));break}return!0})}),this.latestOfferId>s){this.log.warn("latestOfferId mismatch",Object.assign(Object.assign({},this.logContext),{latestOfferId:this.latestOfferId,offerId:s}));return}yield this.setMungedSDP(r,Wi.write(a)),this.onOffer(r,this.latestOfferId)}finally{n()}})}createAndSetAnswer(){return P(this,void 0,void 0,function*(){var e;const t=yield this.pc.createAnswer(),n=Wi.parse((e=t.sdp)!==null&&e!==void 0?e:"");return n.media.forEach(s=>{Hf(s),s.type==="audio"&&Gf(s,this.remoteStereoMids,this.remoteNackMids)}),yield this.setMungedSDP(t,Wi.write(n)),t})}createDataChannel(e,t){return this.pc.createDataChannel(e,t)}addTransceiver(e,t){return this.pc.addTransceiver(e,t)}addTrack(e){if(!this._pc)throw new Gt("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 Gt("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()}getConnectedAddress(){return P(this,void 0,void 0,function*(){var e;if(!this._pc)return;let t="";const n=new Map,s=new Map;if((yield this._pc.getStats()).forEach(o=>{switch(o.type){case"transport":t=o.selectedCandidatePairId;break;case"candidate-pair":t===""&&o.selected&&(t=o.id),n.set(o.id,o);break;case"remote-candidate":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 P(this,void 0,void 0,function*(){if(t){const s=e.sdp;e.sdp=t;try{this.log.debug("setting munged ".concat(n?"remote":"local"," description"),this.logContext),n?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e);return}catch(r){this.log.warn("not able to set ".concat(e.type,", falling back to unmodified sdp"),Object.assign(Object.assign({},this.logContext),{error:r,sdp:t})),e.sdp=s}}try{n?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e)}catch(s){let r="unknown error";s instanceof Error?r=s.message:typeof s=="string"&&(r=s);const a={error:r,sdp:e.sdp};throw!n&&this.pc.remoteDescription&&(a.remoteSdp=this.pc.remoteDescription),this.log.error("unable to set ".concat(e.type),Object.assign(Object.assign({},this.logContext),{fields:a})),new Ec(r)}})}ensureVideoDDExtensionForSVC(e,t){var n,s;if(!((n=e.ext)===null||n===void 0?void 0:n.some(a=>a.uri===_f))){if(this.ddExtID===0){let a=0;t.media.forEach(o=>{var c;o.type==="video"&&((c=o.ext)===null||c===void 0||c.forEach(l=>{l.value>a&&(a=l.value)}))}),this.ddExtID=a+1}(s=e.ext)===null||s===void 0||s.push({value:this.ddExtID,uri:_f})}}}function Gf(i,e,t){let n=0;i.rtp.some(s=>s.codec==="opus"?(n=s.payload,!0):!1),n>0&&(i.rtcpFb||(i.rtcpFb=[]),t.includes(i.mid)&&!i.rtcpFb.some(s=>s.payload===n&&s.type==="nack")&&i.rtcpFb.push({payload:n,type:"nack"}),e.includes(i.mid)&&i.fmtp.some(s=>s.payload===n?(s.config.includes("stereo=1")||(s.config+=";stereo=1"),!0):!1))}function pb(i){var e;const t=[],n=[],s=Wi.parse((e=i.sdp)!==null&&e!==void 0?e:"");let r=0;return s.media.forEach(a=>{var o;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(a.mid),a.fmtp.some(c=>c.payload===r?(c.config.includes("sprop-stereo=1")&&t.push(a.mid),!0):!1))}),{stereoMids:t,nackMids:n}}function Hf(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)}}const Jc="vp8",mb={audioPreset:Ac.music,dtx:!0,red:!0,forceStereo:!1,simulcast:!0,screenShareEncoding:Pc.h1080fps15.encoding,stopMicTrackOnMute:!1,videoCodec:Jc,backupCodec:!0,preConnectBuffer:!1},Wf={deviceId:{ideal:"default"},autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0,voiceIsolation:!0},qf={deviceId:{ideal:"default"},resolution:Or.h720.resolution},gb={adaptiveStream:!1,dynacast:!1,stopLocalTrackOnUnpublish:!0,reconnectPolicy:new i0,disconnectOnPageLeave:!0,webAudioMix:!1},Zc={autoSubscribe:!0,maxRetries:1,peerConnectionTimeout:15e3,websocketTimeout:15e3};var Pt;(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"})(Pt||(Pt={}));class vb{get needsPublisher(){return this.isPublisherConnectionRequired}get needsSubscriber(){return this.isSubscriberConnectionRequired}get currentState(){return this.state}constructor(e,t,n){var s;this.peerConnectionTimeout=Zc.peerConnectionTimeout,this.log=Ke,this.updateState=()=>{var r;const a=this.state,o=this.requiredTransports.map(c=>c.getConnectionState());o.every(c=>c==="connected")?this.state=Pt.CONNECTED:o.some(c=>c==="failed")?this.state=Pt.FAILED:o.some(c=>c==="connecting")?this.state=Pt.CONNECTING:o.every(c=>c==="closed")?this.state=Pt.CLOSED:o.some(c=>c==="closed")?this.state=Pt.CLOSING:o.every(c=>c==="new")&&(this.state=Pt.NEW),a!==this.state&&(this.log.debug("pc state change: from ".concat(Pt[a]," to ").concat(Pt[this.state]),this.logContext),(r=this.onStateChange)===null||r===void 0||r.call(this,this.state,this.publisher.getConnectionState(),this.subscriber.getConnectionState()))},this.log=fi((s=n.loggerName)!==null&&s!==void 0?s:Ln.PCManager),this.loggerOptions=n,this.isPublisherConnectionRequired=!t,this.isSubscriberConnectionRequired=t,this.publisher=new Vf(e,n),this.subscriber=new Vf(e,n),this.publisher.onConnectionStateChange=this.updateState,this.subscriber.onConnectionStateChange=this.updateState,this.publisher.onIceConnectionStateChange=this.updateState,this.subscriber.onIceConnectionStateChange=this.updateState,this.publisher.onSignalingStatechange=this.updateState,this.subscriber.onSignalingStatechange=this.updateState,this.publisher.onIceCandidate=r=>{var a;(a=this.onIceCandidate)===null||a===void 0||a.call(this,r,Dn.PUBLISHER)},this.subscriber.onIceCandidate=r=>{var a;(a=this.onIceCandidate)===null||a===void 0||a.call(this,r,Dn.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.onOffer=(r,a)=>{var o;(o=this.onPublisherOffer)===null||o===void 0||o.call(this,r,a)},this.state=Pt.NEW,this.connectionLock=new an,this.remoteOfferLock=new an}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()}requireSubscriber(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;this.isSubscriberConnectionRequired=e,this.updateState()}createAndSendPublisherOffer(e){return this.publisher.createAndSendOffer(e)}setPublisherAnswer(e,t){return this.publisher.setRemoteDescription(e,t)}removeTrack(e){return this.publisher.removeTrack(e)}close(){return P(this,void 0,void 0,function*(){if(this.publisher&&this.publisher.getSignallingState()!=="closed"){const e=this.publisher;for(const t of e.getSenders())try{e.canRemoveTrack()&&e.removeTrack(t)}catch(n){this.log.warn("could not removeTrack",Object.assign(Object.assign({},this.logContext),{error:n}))}}yield Promise.all([this.publisher.close(),this.subscriber.close()]),this.updateState()})}triggerIceRestart(){return P(this,void 0,void 0,function*(){this.subscriber.restartingIce=!0,this.needsPublisher&&(yield this.createAndSendPublisherOffer({iceRestart:!0}))})}addIceCandidate(e,t){return P(this,void 0,void 0,function*(){t===Dn.PUBLISHER?yield this.publisher.addIceCandidate(e):yield this.subscriber.addIceCandidate(e)})}createSubscriberAnswerFromOffer(e,t){return P(this,void 0,void 0,function*(){this.log.debug("received server offer",Object.assign(Object.assign({},this.logContext),{RTCSdpType:e.type,sdp:e.sdp,signalingState:this.subscriber.getSignallingState().toString()}));const n=yield this.remoteOfferLock.lock();try{return(yield this.subscriber.setRemoteDescription(e,t))?yield this.subscriber.createAndSetAnswer():void 0}finally{n()}})}updateConfiguration(e,t){this.publisher.setConfiguration(e),this.subscriber.setConfiguration(e),t&&this.triggerIceRestart()}ensurePCTransportConnection(e,t){return P(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.logContext),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 P(this,void 0,void 0,function*(){return new Promise((t,n)=>P(this,void 0,void 0,function*(){const s=setTimeout(()=>{n("negotiation timed out")},this.peerConnectionTimeout),r=()=>{clearTimeout(s),n("negotiation aborted")};e.signal.addEventListener("abort",r),this.publisher.once(zs.NegotiationStarted,()=>{e.signal.aborted||this.publisher.once(zs.NegotiationComplete,()=>{clearTimeout(s),t()})}),yield this.publisher.negotiate(a=>{clearTimeout(s),n(a)})}))})}addPublisherTransceiver(e,t){return this.publisher.addTransceiver(e,t)}addPublisherTrack(e){return this.publisher.addTrack(e)}createPublisherDataChannel(e,t){return this.publisher.createDataChannel(e,t)}getConnectedAddress(e){return e===Dn.PUBLISHER?this.publisher.getConnectedAddress():e===Dn.SUBSCRIBER?this.publisher.getConnectedAddress():this.requiredTransports[0].getConnectedAddress()}get requiredTransports(){const e=[];return this.isPublisherConnectionRequired&&e.push(this.publisher),this.isSubscriberConnectionRequired&&e.push(this.subscriber),e}ensureTransportConnected(e,t){return P(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((c,l)=>P(r,void 0,void 0,function*(){const d=()=>{this.log.warn("abort transport connection",this.logContext),Yt.clearTimeout(u),l(new _t("room connection has been cancelled",tt.Cancelled))};s!=null&&s.signal.aborted&&d(),s==null||s.signal.addEventListener("abort",d);const u=Yt.setTimeout(()=>{s==null||s.signal.removeEventListener("abort",d),l(new _t("could not establish pc connection",tt.InternalError))},a);for(;this.state!==Pt.CONNECTED;)if(yield ln(50),s!=null&&s.signal.aborted){l(new _t("room connection has been cancelled",tt.Cancelled));return}Yt.clearTimeout(u),s==null||s.signal.removeEventListener("abort",d),c()}))}()})}}class kt extends Error{constructor(e,t,n){super(t),this.code=e,this.message=jf(t,kt.MAX_MESSAGE_BYTES),this.data=n?jf(n,kt.MAX_DATA_BYTES):void 0}static fromProto(e){return new kt(e.code,e.message,e.data)}toProto(){return new ih({code:this.code,message:this.message,data:this.data})}static builtIn(e,t){return new kt(kt.ErrorCode[e],kt.ErrorMessage[e],t)}}kt.MAX_MESSAGE_BYTES=256,kt.MAX_DATA_BYTES=15360,kt.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},kt.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 $f=15360;function Qc(i){return new TextEncoder().encode(i).length}function jf(i,e){if(Qc(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)}const el=2e3;function Ha(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)}const tl=typeof MediaRecorder<"u";class bb{constructor(){throw new Error("MediaRecorder is not available in this environment")}}const yb=tl?MediaRecorder:bb;class _b extends yb{constructor(e,t){if(!tl)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==null||s.close(),s=void 0},o=c=>{s==null||s.error(c),this.removeEventListener("dataavailable",n),this.removeEventListener("stop",a),this.removeEventListener("error",o),s=void 0};this.byteStream=new ReadableStream({start:c=>{s=c,n=l=>P(this,void 0,void 0,function*(){let d;if(l.data.arrayBuffer){const u=yield l.data.arrayBuffer();d=new Uint8Array(u)}else if(l.data.byteArray)d=l.data.byteArray;else throw new Error("no data available!");r()||c.enqueue(d)}),this.addEventListener("dataavailable",n)},cancel:()=>{a()}}),this.addEventListener("stop",a),this.addEventListener("error",o)}}function Sb(){return tl}const xb=1e3,Tb=1e4;class Xf extends Q{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._isUpstreamPaused=!1,this.handleTrackMuteEvent=()=>this.debouncedTrackMuteHandler().catch(()=>this.log.debug("track mute bounce got cancelled by an unmute event",this.logContext)),this.debouncedTrackMuteHandler=Kc(()=>P(this,void 0,void 0,function*(){yield this.pauseUpstream()}),5e3),this.handleTrackUnmuteEvent=()=>P(this,void 0,void 0,function*(){this.debouncedTrackMuteHandler.cancel("unmute"),yield this.resumeUpstream()}),this.handleEnded=()=>{this.isInBackground&&(this.reacquireTrack=!0),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent),this.emit(oe.Ended,this)},this.reacquireTrack=!1,this.providedByUser=s,this.muteLock=new an,this.pauseUpstreamLock=new an,this.trackChangeLock=new an,this.trackChangeLock.lock().then(a=>P(this,void 0,void 0,function*(){try{yield this.setMediaStreamTrack(e,!0)}finally{a()}})),this._constraints=e.getConstraints(),n&&(this._constraints=n)}get id(){return this._mediaStreamTrack.id}get dimensions(){if(this.kind!==Q.Kind.Video)return;const{width:e,height:t}=this._mediaStreamTrack.getSettings();if(e&&t)return{width:e,height:t}}get isUpstreamPaused(){return this._isUpstreamPaused}get isUserProvided(){return this.providedByUser}get mediaStreamTrack(){var e,t;return(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){return P(this,void 0,void 0,function*(){var n;if(e===this._mediaStreamTrack&&!t)return;this._mediaStreamTrack&&(this.attachedElements.forEach(r=>{Fs(this._mediaStreamTrack,r)}),this.debouncedTrackMuteHandler.cancel("new-track"),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent)),this.mediaStream=new MediaStream([e]),e&&(e.addEventListener("ended",this.handleEnded),e.addEventListener("mute",this.handleTrackMuteEvent),e.addEventListener("unmute",this.handleTrackUnmuteEvent),this._constraints=e.getConstraints());let s;if(this.processor&&e){if(this.log.debug("restarting processor",this.logContext),this.kind==="unknown")throw TypeError("cannot set processor on track of unknown kind");this.processorElement&&(Os(e,this.processorElement),this.processorElement.muted=!0),yield this.processor.restart({track:e,kind:this.kind,element:this.processorElement}),s=this.processor.processedTrack}this.sender&&((n=this.sender.transport)===null||n===void 0?void 0:n.state)!=="closed"&&(yield this.sender.replaceTrack(s??e)),!this.providedByUser&&this._mediaStreamTrack!==e&&this._mediaStreamTrack.stop(),this._mediaStreamTrack=e,e&&(this._mediaStreamTrack.enabled=!this.isMuted,yield this.resumeUpstream(),this.attachedElements.forEach(r=>{Os(s??e,r)}))})}waitForDimensions(){return P(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:xb;return function*(){var n;if(e.kind===Q.Kind.Audio)throw new Error("cannot get dimensions for audio tracks");((n=bn())===null||n===void 0?void 0:n.os)==="iOS"&&(yield ln(10));const s=Date.now();for(;Date.now()-s<t;){const r=e.dimensions;if(r)return r;yield ln(50)}throw new gi("unable to get track dimensions after timeout")}()})}setDeviceId(e){return P(this,void 0,void 0,function*(){return this._constraints.deviceId===e&&this._mediaStreamTrack.getSettings().deviceId===Vi(e)||(this._constraints.deviceId=e,this.isMuted)?!0:(yield this.restartTrack(),Vi(e)===this._mediaStreamTrack.getSettings().deviceId)})}getDeviceId(){return P(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){if(e.source===Q.Source.ScreenShare)return;const{deviceId:n,groupId:s}=e._mediaStreamTrack.getSettings(),r=e.kind===Q.Kind.Audio?"audioinput":"videoinput";return t?$t.getInstance().normalizeDeviceId(r,n,s):n}()})}mute(){return P(this,void 0,void 0,function*(){return this.setTrackMuted(!0),this})}unmute(){return P(this,void 0,void 0,function*(){return this.setTrackMuted(!1),this})}replaceTrack(e,t){return P(this,void 0,void 0,function*(){const n=yield this.trackChangeLock.lock();try{if(!this.sender)throw new gi("unable to replace an unpublished track");let s,r;return 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()),this}finally{n()}})}restart(e){return P(this,void 0,void 0,function*(){this.manuallyStopped=!1;const t=yield this.trackChangeLock.lock();try{e||(e=this._constraints);const{deviceId:n,facingMode:s}=e,r=s0(e,["deviceId","facingMode"]);this.log.debug("restarting track with constraints",Object.assign(Object.assign({},this.logContext),{constraints:e}));const a={audio:!1,video:!1};this.kind===Q.Kind.Video?a.video=n||s?{deviceId:n,facingMode:s}:!0:a.audio=n?Object.assign({deviceId:n},r):!0,this.attachedElements.forEach(l=>{Fs(this.mediaStreamTrack,l)}),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.stop();const c=(yield navigator.mediaDevices.getUserMedia(a)).getTracks()[0];return this.kind===Q.Kind.Video&&(yield c.applyConstraints(r)),c.addEventListener("ended",this.handleEnded),this.log.debug("re-acquired MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(c),this._constraints=e,this.emit(oe.Restarted,this),this.manuallyStopped&&(this.log.warn("track was stopped during a restart, stopping restarted track",this.logContext),this.stop()),this}finally{t()}})}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?oe.Muted:oe.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 P(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),Sf()&&(this.log.debug("visibility changed, is in Background: ".concat(this.isInBackground),this.logContext),!this.isInBackground&&this.needsReAcquisition&&!this.isUserProvided&&!this.isMuted&&(this.log.debug("track needs to be reacquired, restarting ".concat(this.source),this.logContext),yield this.restart(),this.reacquireTrack=!1))})}stop(){var e;this.manuallyStopped=!0,super.stop(),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent),(e=this.processor)===null||e===void 0||e.destroy(),this.processor=void 0}pauseUpstream(){return P(this,void 0,void 0,function*(){var e;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(oe.UpstreamPaused,this);const n=bn();if((n==null?void 0:n.name)==="Safari"&&Jn(n.version,"12.0")<0)throw new Cc("pauseUpstream is not supported on Safari < 12.");((e=this.sender.transport)===null||e===void 0?void 0:e.state)!=="closed"&&(yield this.sender.replaceTrack(null))}finally{t()}})}resumeUpstream(){return P(this,void 0,void 0,function*(){var e;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(oe.UpstreamResumed,this),((e=this.sender.transport)===null||e===void 0?void 0:e.state)!=="closed"&&(yield this.sender.replaceTrack(this.mediaStreamTrack))}finally{t()}})}getRTCStatsReport(){return P(this,void 0,void 0,function*(){var e;return!((e=this.sender)===null||e===void 0)&&e.getStats?yield this.sender.getStats():void 0})}setProcessor(e){return P(this,arguments,void 0,function(t){var n=this;let 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),c={kind:n.kind,track:n._mediaStreamTrack,element:o,audioContext:n.audioContext};if(yield t.init(c),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(Os(n._mediaStreamTrack,o),o.muted=!0,o.play().catch(l=>{l instanceof DOMException&&l.name==="AbortError"?(n.log.warn("failed to play processor element, retrying",Object.assign(Object.assign({},n.logContext),{error:l})),setTimeout(()=>{o.play().catch(d=>{n.log.error("failed to play processor element",Object.assign(Object.assign({},n.logContext),{err:d}))})},100)):n.log.error("failed to play processor element",Object.assign(Object.assign({},n.logContext),{error:l}))}),n.processor=t,n.processorElement=o,n.processor.processedTrack){for(const l of n.attachedElements)l!==n.processorElement&&s&&(Fs(n._mediaStreamTrack,l),Os(n.processor.processedTrack,l));yield(r=n.sender)===null||r===void 0?void 0:r.replaceTrack(n.processor.processedTrack)}n.emit(oe.TrackProcessorUpdate,n.processor)}finally{a()}}()})}getProcessor(){return this.processor}stopProcessor(){return P(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){const n=yield e.trackChangeLock.lock();try{yield e.internalStopProcessor(t)}finally{n()}}()})}internalStopProcessor(){return P(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){var n,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(oe.TrackProcessorUpdate))}()})}startPreConnectBuffer(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:100;if(!Sb()){this.log.warn("MediaRecorder is not available, cannot start preconnect buffer",this.logContext);return}if(this.localTrackRecorder){this.log.warn("preconnect buffer already started");return}else{let t="audio/webm;codecs=opus";MediaRecorder.isTypeSupported(t)||(t="video/mp4"),this.localTrackRecorder=new _b(this,{mimeType:t})}this.localTrackRecorder.start(e),this.autoStopPreConnectBuffer=setTimeout(()=>{this.log.warn("preconnect buffer timed out, stopping recording automatically",this.logContext),this.stopPreConnectBuffer()},Tb)}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 Wa extends Xf{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,Q.Kind.Audio,t,n,r),this.stopOnMute=!1,this.isKrispNoiseFilterEnabled=!1,this.monitorSender=()=>P(this,void 0,void 0,function*(){if(!this.sender){this._currentBitrate=0;return}let a;try{a=yield this.getSenderStats()}catch(o){this.log.error("could not get audio sender stats",Object.assign(Object.assign({},this.logContext),{error:o}));return}a&&this.prevStats&&(this._currentBitrate=Ha(a,this.prevStats)),this.prevStats=a}),this.handleKrispNoiseFilterEnable=()=>{this.isKrispNoiseFilterEnabled=!0,this.log.debug("Krisp noise filter enabled",this.logContext),this.emit(oe.AudioTrackFeatureUpdate,this,qt.TF_ENHANCED_NOISE_CANCELLATION,!0)},this.handleKrispNoiseFilterDisable=()=>{this.isKrispNoiseFilterEnabled=!1,this.log.debug("Krisp noise filter disabled",this.logContext),this.emit(oe.AudioTrackFeatureUpdate,this,qt.TF_ENHANCED_NOISE_CANCELLATION,!1)},this.audioContext=s,this.checkForSilence()}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return P(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===Q.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 P(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{if(!this.isMuted)return this.log.debug("Track already unmuted",this.logContext),this;const n=this._constraints.deviceId&&this._mediaStreamTrack.getSettings().deviceId!==Vi(this._constraints.deviceId);return this.source===Q.Source.Microphone&&(this.stopOnMute||this._mediaStreamTrack.readyState==="ended"||n)&&!this.isUserProvided&&(this.log.debug("reacquiring mic track",this.logContext),yield this.restartTrack()),yield e.unmute.call(this),this}finally{t()}})}restartTrack(e){return P(this,void 0,void 0,function*(){let t;if(e){const n=Gc({audio:e});typeof n.audio!="boolean"&&(t=n.audio)}yield this.restart(t)})}restart(e){const t=Object.create(null,{restart:{get:()=>super.restart}});return P(this,void 0,void 0,function*(){const n=yield t.restart.call(this,e);return this.checkForSilence(),n})}startMonitor(){dn()&&(this.monitorInterval||(this.monitorInterval=setInterval(()=>{this.monitorSender()},el)))}setProcessor(e){return P(this,void 0,void 0,function*(){var t;const n=yield this.trackChangeLock.lock();try{if(!Kn()&&!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};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(oe.TrackProcessorUpdate,this.processor)}finally{n()}})}setAudioContext(e){this.audioContext=e}getSenderStats(){return P(this,void 0,void 0,function*(){var e;if(!(!((e=this.sender)===null||e===void 0)&&e.getStats))return;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 P(this,void 0,void 0,function*(){const e=yield Pf(this);return e&&(this.isMuted||this.log.warn("silence detected on local audio track",this.logContext),this.emit(oe.AudioSilenceDetected)),e})}}function Cb(i,e,t){switch(i.kind){case"audio":return new Wa(i,e,!1,void 0,t);case"video":return new qa(i,e,!1,t);default:throw new gi("unsupported track type: ".concat(i.kind))}}const Eb=Object.values(Or),Mb=Object.values(Rc),wb=Object.values(Pc),Ab=[Or.h180,Or.h360],Rb=[Rc.h180,Rc.h360],Pb=i=>[{scaleResolutionDownBy:2,fps:i.encoding.maxFramerate}].map(t=>{var n,s;return new gt(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)}),nl=["q","h","f"];function il(i,e,t,n){var s,r;let a=n==null?void 0:n.videoEncoding;i&&(a=n==null?void 0:n.screenShareEncoding);const o=n==null?void 0:n.simulcast,c=n==null?void 0:n.scalabilityMode,l=n==null?void 0:n.videoCodec;if(!a&&!o&&!c||!e||!t)return[{}];a||(a=Ib(i,e,t,l),Ke.debug("using video encoding",a));const d=a.maxFramerate,u=new gt(e,t,a.maxBitrate,a.maxFramerate,a.priority);if(c&&Yn(l)){const g=new Jf(c),v=[];if(g.spatial>3)throw new Error("unsupported scalabilityMode: ".concat(c));const m=bn();if(Fr()||Kn()||(m==null?void 0:m.name)==="Chrome"&&Jn(m==null?void 0:m.version,"113")<0){const p=g.suffix=="h"?2:3,x=U0(m);for(let C=0;C<g.spatial;C+=1)v.push({rid:nl[2-C],maxBitrate:a.maxBitrate/Math.pow(p,C),maxFramerate:u.encoding.maxFramerate,scaleResolutionDownBy:x?Math.pow(2,C):void 0});v[0].scalabilityMode=c}else v.push({maxBitrate:a.maxBitrate,maxFramerate:u.encoding.maxFramerate,scalabilityMode:c});return u.encoding.priority&&(v[0].priority=u.encoding.priority,v[0].networkPriority=u.encoding.priority),Ke.debug("using svc encoding",{encodings:v}),v}if(!o)return[a];let h=[];i?h=(s=Kf(n==null?void 0:n.screenShareSimulcastLayers))!==null&&s!==void 0?s:Yf(i,u):h=(r=Kf(n==null?void 0:n.videoSimulcastLayers))!==null&&r!==void 0?r:Yf(i,u);let f;if(h.length>0){const g=h[0];h.length>1&&([,f]=h);const v=Math.max(e,t);if(v>=960&&f)return sl(e,t,[g,f,u],d);if(v>=480)return sl(e,t,[g,u],d)}return sl(e,t,[u])}function kb(i,e,t){var n,s,r,a;if(!t.backupCodec||t.backupCodec===!0||t.backupCodec.codec===t.videoCodec)return;e!==t.backupCodec.codec&&Ke.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(),c=(n=o.width)!==null&&n!==void 0?n:(s=i.dimensions)===null||s===void 0?void 0:s.width,l=(r=o.height)!==null&&r!==void 0?r:(a=i.dimensions)===null||a===void 0?void 0:a.height;return i.source===Q.Source.ScreenShare&&t.simulcast&&(t.simulcast=!1),il(i.source===Q.Source.ScreenShare,c,l,t)}function Ib(i,e,t,n){const s=Db(i,e,t);let{encoding:r}=s[0];const a=Math.max(e,t);for(let o=0;o<s.length;o+=1){const c=s[o];if(r=c.encoding,c.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 Db(i,e,t){if(i)return wb;const n=e>t?e/t:t/e;return Math.abs(n-16/9)<Math.abs(n-4/3)?Eb:Mb}function Yf(i,e){if(i)return Pb(e);const{width:t,height:n}=e,s=t>n?t/n:n/t;return Math.abs(s-16/9)<Math.abs(s-4/3)?Ab:Rb}function sl(i,e,t,n){const s=[];if(t.forEach((r,a)=>{if(a>=nl.length)return;const o=Math.min(i,e),l={rid:nl[a],scaleResolutionDownBy:Math.max(1,o/Math.min(r.width,r.height)),maxBitrate:r.encoding.maxBitrate},d=n&&r.encoding.maxFramerate?Math.min(n,r.encoding.maxFramerate):r.encoding.maxFramerate;d&&(l.maxFramerate=d);const u=cs()||a===0;r.encoding.priority&&u&&(l.priority=r.encoding.priority,l.networkPriority=r.encoding.priority),s.push(l)}),Kn()&&Tf()==="ios"){let r;s.forEach(o=>{r?o.maxFramerate&&o.maxFramerate>r&&(r=o.maxFramerate):r=o.maxFramerate});let a=!0;s.forEach(o=>{var c;o.maxFramerate!=r&&(a&&(a=!1,Ke.info("Simulcast on iOS React-Native requires all encodings to share the same framerate.")),Ke.info('Setting framerate of encoding "'.concat((c=o.rid)!==null&&c!==void 0?c:"",'" to ').concat(r)),o.maxFramerate=r)})}return s}function Kf(i){if(i)return i.sort((e,t)=>{const{encoding:n}=e,{encoding:s}=t;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 Jf{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 Lb(i){return i.source===Q.Source.ScreenShare||i.constraints.height&&Vi(i.constraints.height)>=1080?"maintain-resolution":"balanced"}const Ub=5e3;class qa extends Xf{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,Q.Kind.Video,t,n,s),this.simulcastCodecs=new Map,this.degradationPreference="balanced",this.isCpuConstrained=!1,this.optimizeForPerformance=!1,this.monitorSender=()=>P(this,void 0,void 0,function*(){if(!this.sender){this._currentBitrate=0;return}let r;try{r=yield this.getSenderStats()}catch(c){this.log.error("could not get video sender stats",Object.assign(Object.assign({},this.logContext),{error:c}));return}const a=new Map(r.map(c=>[c.rid,c])),o=r.some(c=>c.qualityLimitationReason==="cpu");if(o!==this.isCpuConstrained&&(this.isCpuConstrained=o,this.isCpuConstrained&&this.emit(oe.CpuConstrained)),this.prevStats){let c=0;a.forEach((l,d)=>{var u;const h=(u=this.prevStats)===null||u===void 0?void 0:u.get(d);c+=Ha(l,h)}),this._currentBitrate=c}this.prevStats=a}),this.senderLock=new an}get isSimulcast(){return!!(this.sender&&this.sender.getParameters().encodings.length>1)}startMonitor(e){var t;if(this.signalClient=e,!dn())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()},el))}stop(){this._mediaStreamTrack.getConstraints(),this.simulcastCodecs.forEach(e=>{e.mediaStreamTrack.stop()}),super.stop()}pauseUpstream(){const e=Object.create(null,{pauseUpstream:{get:()=>super.pauseUpstream}});return P(this,void 0,void 0,function*(){var t,n,s,r,a;yield e.pauseUpstream.call(this);try{for(var o=!0,c=pi(this.simulcastCodecs.values()),l;l=yield c.next(),t=l.done,!t;o=!0)r=l.value,o=!1,yield(a=r.sender)===null||a===void 0?void 0:a.replaceTrack(null)}catch(d){n={error:d}}finally{try{!o&&!t&&(s=c.return)&&(yield s.call(c))}finally{if(n)throw n.error}}})}resumeUpstream(){const e=Object.create(null,{resumeUpstream:{get:()=>super.resumeUpstream}});return P(this,void 0,void 0,function*(){var t,n,s,r,a;yield e.resumeUpstream.call(this);try{for(var o=!0,c=pi(this.simulcastCodecs.values()),l;l=yield c.next(),t=l.done,!t;o=!0){r=l.value,o=!1;const d=r;yield(a=d.sender)===null||a===void 0?void 0:a.replaceTrack(d.mediaStreamTrack)}}catch(d){n={error:d}}finally{try{!o&&!t&&(s=c.return)&&(yield s.call(c))}finally{if(n)throw n.error}}})}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return P(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===Q.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 P(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.source===Q.Source.Camera&&!this.isUserProvided&&(this.log.debug("reacquiring camera track",this.logContext),yield this.restartTrack()),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 P(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=yn.LOW;n<=yn.HIGH;n+=1)t.push(new hc({quality:n,enabled:n<=e}));this.log.debug("setting publishing quality. max quality ".concat(e),this.logContext),this.setPublishingLayers(Yn(this.codec),t)}restartTrack(e){return P(this,void 0,void 0,function*(){var t,n,s,r,a;let o;if(e){const u=Gc({video:e});typeof u.video!="boolean"&&(o=u.video)}yield this.restart(o),this.isCpuConstrained=!1;try{for(var c=!0,l=pi(this.simulcastCodecs.values()),d;d=yield l.next(),t=d.done,!t;c=!0){r=d.value,c=!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{!c&&!t&&(s=l.return)&&(yield s.call(l))}finally{if(n)throw n.error}}})}setProcessor(e){const t=Object.create(null,{setProcessor:{get:()=>super.setProcessor}});return P(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,c,l,d,u;if(yield t.setProcessor.call(s,n,r),!((d=s.processor)===null||d===void 0)&&d.processedTrack)try{for(var h=!0,f=pi(s.simulcastCodecs.values()),g;g=yield f.next(),a=g.done,!a;h=!0)l=g.value,h=!1,yield(u=l.sender)===null||u===void 0?void 0:u.replaceTrack(s.processor.processedTrack)}catch(v){o={error:v}}finally{try{!h&&!a&&(c=f.return)&&(yield c.call(f))}finally{if(o)throw o.error}}}()})}setDegradationPreference(e){return P(this,void 0,void 0,function*(){if(this.degradationPreference=e,this.sender)try{this.log.debug("setting degradationPreference to ".concat(e),this.logContext);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)},Ub))}setPublishingCodecs(e){return P(this,void 0,void 0,function*(){var t,n,s,r,a,o,c;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(Yn(e[0].codec),e[0].qualities),[];this.subscribedCodecs=e;const l=[];try{for(t=!0,n=pi(e);s=yield n.next(),r=s.done,!r;t=!0){c=s.value,t=!1;const d=c;if(!this.codec||this.codec===d.codec)yield this.setPublishingLayers(Yn(d.codec),d.qualities);else{const u=this.simulcastCodecs.get(d.codec);if(this.log.debug("try setPublishingCodec for ".concat(d.codec),Object.assign(Object.assign({},this.logContext),{simulcastCodecInfo:u})),!u||!u.sender){for(const h of d.qualities)if(h.enabled){l.push(d.codec);break}}else u.encodings&&(this.log.debug("try setPublishingLayersForSender ".concat(d.codec),this.logContext),yield Zf(u.sender,u.encodings,d.qualities,this.senderLock,Yn(d.codec),this.log,this.logContext))}}}catch(d){a={error:d}}finally{try{!t&&!r&&(o=n.return)&&(yield o.call(n))}finally{if(a)throw a.error}}return l})}setPublishingLayers(e,t){return P(this,void 0,void 0,function*(){if(this.optimizeForPerformance){this.log.info("skipping setPublishingLayers due to optimized publishing performance",Object.assign(Object.assign({},this.logContext),{qualities:t}));return}this.log.debug("setting publishing layers",Object.assign(Object.assign({},this.logContext),{qualities:t})),!(!this.sender||!this.encodings)&&(yield Zf(this.sender,this.encodings,t,this.senderLock,e,this.log,this.logContext))})}prioritizePerformance(){return P(this,void 0,void 0,function*(){if(!this.sender)throw new Error("sender not found");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&&Yn(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 P(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),Sf()&&this.isInBackground&&this.source===Q.Source.Camera&&(this._mediaStreamTrack.enabled=!1)})}}function Zf(i,e,t,n,s,r,a){return P(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 c=i.getParameters(),{encodings:l}=c;if(!l)return;if(l.length!==e.length){r.warn("cannot set publishing layers, encodings mismatch",Object.assign(Object.assign({},a),{encodings:l,senderEncodings:e}));return}let d=!1;!1&&l[0].scalabilityMode||(s&&t.some(f=>f.enabled)&&t.forEach(f=>f.enabled=!0),l.forEach((h,f)=>{var g;let v=(g=h.rid)!==null&&g!==void 0?g:"";v===""&&(v="q");const m=Qf(v),p=t.find(x=>x.quality===m);p&&h.active!==p.enabled&&(d=!0,h.active=p.enabled,r.debug("setting layer ".concat(p.quality," to ").concat(h.active?"enabled":"disabled"),a),cs()&&(p.enabled?(h.scaleResolutionDownBy=e[f].scaleResolutionDownBy,h.maxBitrate=e[f].maxBitrate,h.maxFrameRate=e[f].maxFrameRate):(h.scaleResolutionDownBy=4,h.maxBitrate=10,h.maxFrameRate=2)))})),d&&(c.encodings=l,r.debug("setting encodings",Object.assign(Object.assign({},a),{encodings:c.encodings})),yield i.setParameters(c))}finally{o()}})}function Qf(i){switch(i){case"f":return yn.HIGH;case"h":return yn.MEDIUM;case"q":return yn.LOW;default:return yn.HIGH}}function ep(i,e,t,n){if(!t)return[new rs({quality:yn.HIGH,width:i,height:e,bitrate:0,ssrc:0})];if(n){const s=t[0].scalabilityMode,r=new Jf(s),a=[],o=r.suffix=="h"?1.5:2,c=r.suffix=="h"?2:3;for(let l=0;l<r.spatial;l+=1)a.push(new rs({quality:Math.min(yn.HIGH,r.spatial-1)-l,width:Math.ceil(i/Math.pow(o,l)),height:Math.ceil(e/Math.pow(o,l)),bitrate:t[0].maxBitrate?Math.ceil(t[0].maxBitrate/Math.pow(c,l)):0,ssrc:0}));return a}return t.map(s=>{var r,a,o;const c=(r=s.scaleResolutionDownBy)!==null&&r!==void 0?r:1;let l=Qf((a=s.rid)!==null&&a!==void 0?a:"");return new rs({quality:l,width:Math.ceil(i/c),height:Math.ceil(e/c),bitrate:(o=s.maxBitrate)!==null&&o!==void 0?o:0,ssrc:0})})}const tp="_lossy",np="_reliable",Nb=2*1e3,rl="leave-reconnect",Ob=3e4;var On;(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"})(On||(On={}));class Fb extends Xn.EventEmitter{get isClosed(){return this._isClosed}get pendingReconnect(){return!!this.reconnectTimeout}constructor(e){var t;super(),this.options=e,this.rtcConfig={},this.peerConnectionTimeout=Zc.peerConnectionTimeout,this.fullReconnectOnNext=!1,this.latestRemoteOfferId=0,this.subscriberPrimary=!1,this.pcState=On.New,this._isClosed=!0,this.pendingTrackResolvers={},this.reconnectAttempts=0,this.reconnectStart=0,this.attemptingReconnect=!1,this.joinAttempts=0,this.maxJoinAttempts=1,this.shouldFailNext=!1,this.log=Ke,this.reliableDataSequence=1,this.reliableMessageBuffer=new Nf,this.reliableReceivedState=new cb(Ob),this.handleDataChannel=n=>P(this,[n],void 0,function(s){var r=this;let{channel:a}=s;return function*(){if(a){if(a.label===np)r.reliableDCSub=a;else if(a.label===tp)r.lossyDCSub=a;else return;r.log.debug("on data channel ".concat(a.id,", ").concat(a.label),r.logContext),a.onmessage=r.handleDataMessage}}()}),this.handleDataMessage=n=>P(this,void 0,void 0,function*(){var s,r;const a=yield this.dataProcessLock.lock();try{let o;if(n.data instanceof ArrayBuffer)o=n.data;else if(n.data instanceof Blob)o=yield n.data.arrayBuffer();else{this.log.error("unsupported data type",Object.assign(Object.assign({},this.logContext),{data:n.data}));return}const c=cn.fromBinary(new Uint8Array(o));if(c.sequence>0&&c.participantSid!==""){const l=this.reliableReceivedState.get(c.participantSid);if(l&&c.sequence<=l)return;this.reliableReceivedState.set(c.participantSid,c.sequence)}((s=c.value)===null||s===void 0?void 0:s.case)==="speaker"?this.emit(de.ActiveSpeakersUpdate,c.value.value.speakers):(((r=c.value)===null||r===void 0?void 0:r.case)==="user"&&zb(c,c.value.value),this.emit(de.DataPacketReceived,c))}finally{a()}}),this.handleDataError=n=>{const r=n.currentTarget.maxRetransmits===0?"lossy":"reliable";if(n instanceof ErrorEvent&&n.error){const{error:a}=n.error;this.log.error("DataChannel error on ".concat(r,": ").concat(n.message),Object.assign(Object.assign({},this.logContext),{error:a}))}else this.log.error("Unknown DataChannel error on ".concat(r),Object.assign(Object.assign({},this.logContext),{event:n}))},this.handleBufferedAmountLow=n=>{const r=n.currentTarget.maxRetransmits===0?We.LOSSY:We.RELIABLE;this.updateAndEmitDCBufferStatus(r)},this.handleDisconnect=(n,s)=>{if(this._isClosed)return;this.log.warn("".concat(n," disconnected"),this.logContext),this.reconnectAttempts===0&&(this.reconnectStart=Date.now());const r=c=>{this.log.warn("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(c,"ms. giving up"),this.logContext),this.emit(de.Disconnected),this.close()},a=Date.now()-this.reconnectStart;let o=this.getNextRetryDelay({elapsedMs:a,retryCount:this.reconnectAttempts});if(o===null){r(a);return}n===rl&&(o=0),this.log.debug("reconnecting in ".concat(o,"ms"),this.logContext),this.clearReconnectTimeout(),this.token&&this.regionUrlProvider&&this.regionUrlProvider.updateToken(this.token),this.reconnectTimeout=Yt.setTimeout(()=>this.attemptReconnect(s).finally(()=>this.reconnectTimeout=void 0),o)},this.waitForRestarted=()=>new Promise((n,s)=>{this.pcState===On.Connected&&n();const r=()=>{this.off(de.Disconnected,a),n()},a=()=>{this.off(de.Restarted,r),s()};this.once(de.Restarted,r),this.once(de.Disconnected,a)}),this.updateAndEmitDCBufferStatus=n=>{const s=this.isBufferStatusLow(n);typeof s<"u"&&s!==this.dcBufferStatus.get(n)&&(this.dcBufferStatus.set(n,s),this.emit(de.DCBufferStatusChanged,s,n))},this.isBufferStatusLow=n=>{const s=this.dataChannelForKind(n);if(s)return n===We.RELIABLE&&this.reliableMessageBuffer.alignBufferedAmount(s.bufferedAmount),s.bufferedAmount<=s.bufferedAmountLowThreshold},this.handleBrowserOnLine=()=>{this.client.currentState===Mt.RECONNECTING&&(this.clearReconnectTimeout(),this.attemptReconnect(Is.RR_SIGNAL_DISCONNECTED))},this.log=fi((t=e.loggerName)!==null&&t!==void 0?t:Ln.Engine),this.loggerOptions={loggerName:e.loggerName,loggerContextCb:()=>this.logContext},this.client=new qc(void 0,this.loggerOptions),this.client.signalLatency=this.options.expSignalLatency,this.reconnectPolicy=this.options.reconnectPolicy,this.registerOnLineListener(),this.closingLock=new an,this.dataProcessLock=new an,this.dcBufferStatus=new Map([[We.LOSSY,!0],[We.RELIABLE,!0]]),this.client.onParticipantUpdate=n=>this.emit(de.ParticipantUpdate,n),this.client.onConnectionQuality=n=>this.emit(de.ConnectionQualityUpdate,n),this.client.onRoomUpdate=n=>this.emit(de.RoomUpdate,n),this.client.onSubscriptionError=n=>this.emit(de.SubscriptionError,n),this.client.onSubscriptionPermissionUpdate=n=>this.emit(de.SubscriptionPermissionUpdate,n),this.client.onSpeakersChanged=n=>this.emit(de.SpeakersChanged,n),this.client.onStreamStateUpdate=n=>this.emit(de.StreamStateChanged,n),this.client.onRequestResponse=n=>this.emit(de.SignalRequestResponse,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,pID:this.participantSid}}join(e,t,n,s){return P(this,void 0,void 0,function*(){this.url=e,this.token=t,this.signalOpts=n,this.maxJoinAttempts=n.maxRetries;try{this.joinAttempts+=1,this.setupSignalClientCallbacks();const r=yield this.client.join(e,t,n,s);return this._isClosed=!1,this.latestJoinResponse=r,this.subscriberPrimary=r.subscriberPrimary,this.pcManager||(yield this.configure(r)),(!this.subscriberPrimary||r.fastPublish)&&this.negotiate(),this.clientConfiguration=r.clientConfiguration,this.emit(de.SignalConnected,r),r}catch(r){if(r instanceof _t&&r.reason===tt.ServerUnreachable&&(this.log.warn("Couldn't connect to server, attempt ".concat(this.joinAttempts," of ").concat(this.maxJoinAttempts),this.logContext),this.joinAttempts<this.maxJoinAttempts))return this.join(e,t,n,s);throw r}})}close(){return P(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(de.Closing),this.removeAllListeners(),this.deregisterOnLineListener(),this.clearPendingReconnect(),yield this.cleanupPeerConnections(),yield this.cleanupClient()}finally{e()}})}cleanupPeerConnections(){return P(this,void 0,void 0,function*(){var e;yield(e=this.pcManager)===null||e===void 0?void 0:e.close(),this.pcManager=void 0;const t=n=>{n&&(n.close(),n.onbufferedamountlow=null,n.onclose=null,n.onclosing=null,n.onerror=null,n.onmessage=null,n.onopen=null)};t(this.lossyDC),t(this.lossyDCSub),t(this.reliableDC),t(this.reliableDCSub),this.lossyDC=void 0,this.lossyDCSub=void 0,this.reliableDC=void 0,this.reliableDCSub=void 0,this.reliableMessageBuffer=new Nf,this.reliableDataSequence=1,this.reliableReceivedState.clear()})}cleanupClient(){return P(this,void 0,void 0,function*(){yield this.client.close(),this.client.resetCallbacks()})}addTrack(e){if(this.pendingTrackResolvers[e.cid])throw new gi("a track with the same ID has already been published");return new Promise((t,n)=>{const s=setTimeout(()=>{delete this.pendingTrackResolvers[e.cid],n(new _t("publication of local track timed out, no response from server",tt.Timeout))},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{reject:t}=this.pendingTrackResolvers[e.track.id];t&&t(),delete this.pendingTrackResolvers[e.track.id]}try{return this.pcManager.removeTrack(e),!0}catch(t){this.log.warn("failed to remove track",Object.assign(Object.assign({},this.logContext),{error:t}))}return!1}updateMuteStatus(e,t){this.client.sendMuteTrack(e,t)}get dataSubscriberReadyState(){var e;return(e=this.reliableDCSub)===null||e===void 0?void 0:e.readyState}getConnectedServerAddress(){return P(this,void 0,void 0,function*(){var e;return(e=this.pcManager)===null||e===void 0?void 0:e.getConnectedAddress()})}setRegionUrlProvider(e){this.regionUrlProvider=e}configure(e){return P(this,void 0,void 0,function*(){var t,n;if(this.pcManager&&this.pcManager.currentState!==Pt.NEW)return;this.participantSid=(t=e.participant)===null||t===void 0?void 0:t.sid;const s=this.makeRTCConfiguration(e);this.pcManager=new vb(s,e.subscriberPrimary,this.loggerOptions),this.emit(de.TransportsCreated,this.pcManager.publisher,this.pcManager.subscriber),this.pcManager.onIceCandidate=(r,a)=>{this.client.sendIceCandidate(r,a)},this.pcManager.onPublisherOffer=(r,a)=>{this.client.sendOffer(r,a)},this.pcManager.onDataChannel=this.handleDataChannel,this.pcManager.onStateChange=(r,a,o)=>P(this,void 0,void 0,function*(){if(this.log.debug("primary PC state changed ".concat(r),this.logContext),["closed","disconnected","failed"].includes(a)&&(this.publisherConnectionPromise=void 0),r===Pt.CONNECTED){const d=this.pcState===On.New;this.pcState=On.Connected,d&&this.emit(de.Connected,e)}else r===Pt.FAILED&&this.pcState===On.Connected&&(this.pcState=On.Disconnected,this.handleDisconnect("peerconnection failed",o==="failed"?Is.RR_SUBSCRIBER_FAILED:Is.RR_PUBLISHER_FAILED));const c=this.client.isDisconnected||this.client.currentState===Mt.RECONNECTING,l=[Pt.FAILED,Pt.CLOSING,Pt.CLOSED].includes(r);c&&l&&!this._isClosed&&this.emit(de.Offline)}),this.pcManager.onTrack=r=>{this.emit(de.MediaTrackAdded,r.track,r.streams[0],r.receiver)},Bb((n=e.serverInfo)===null||n===void 0?void 0:n.protocol)||this.createDataChannels()})}setupSignalClientCallbacks(){this.client.onAnswer=(e,t)=>P(this,void 0,void 0,function*(){this.pcManager&&(this.log.debug("received server answer",Object.assign(Object.assign({},this.logContext),{RTCSdpType:e.type})),yield this.pcManager.setPublisherAnswer(e,t))}),this.client.onTrickle=(e,t)=>{this.pcManager&&(this.log.debug("got ICE candidate from peer",Object.assign(Object.assign({},this.logContext),{candidate:e,target:t})),this.pcManager.addIceCandidate(e,t))},this.client.onOffer=(e,t)=>P(this,void 0,void 0,function*(){if(this.latestRemoteOfferId=t,!this.pcManager)return;const n=yield this.pcManager.createSubscriberAnswerFromOffer(e,t);n&&this.client.sendAnswer(n,t)}),this.client.onLocalTrackPublished=e=>{var t;if(this.log.debug("received trackPublishedResponse",Object.assign(Object.assign({},this.logContext),{cid:e.cid,track:(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),Object.assign(Object.assign({},this.logContext),{cid:e.cid}));return}const{resolve:n}=this.pendingTrackResolvers[e.cid];delete this.pendingTrackResolvers[e.cid],n(e.track)},this.client.onLocalTrackUnpublished=e=>{this.emit(de.LocalTrackUnpublished,e)},this.client.onLocalTrackSubscribed=e=>{this.emit(de.LocalTrackSubscribed,e)},this.client.onTokenRefresh=e=>{this.token=e},this.client.onRemoteMuteChanged=(e,t)=>{this.emit(de.RemoteMute,e,t)},this.client.onSubscribedQualityUpdate=e=>{this.emit(de.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(de.RoomMoved,e)},this.client.onClose=()=>{this.handleDisconnect("signal",Is.RR_SIGNAL_DISCONNECTED)},this.client.onLeave=e=>{switch(this.log.debug("client leave request",Object.assign(Object.assign({},this.logContext),{reason:e==null?void 0:e.reason})),e.regions&&this.regionUrlProvider&&(this.log.debug("updating regions",this.logContext),this.regionUrlProvider.setServerReportedRegions(e.regions)),e.action){case Us.DISCONNECT:this.emit(de.Disconnected,e==null?void 0:e.reason),this.close();break;case Us.RECONNECT:this.fullReconnectOnNext=!0,this.handleDisconnect(rl);break;case Us.RESUME:this.handleDisconnect(rl)}}}makeRTCConfiguration(e){var t;const n=Object.assign({},this.rtcConfig);if(!((t=this.signalOpts)===null||t===void 0)&&t.e2eeEnabled&&(this.log.debug("E2EE - setting up transports with insertable streams",this.logContext),n.encodedInsertableStreams=!0),e.iceServers&&!n.iceServers){const s=[];e.iceServers.forEach(r=>{const a={urls:r.urls};r.username&&(a.username=r.username),r.credential&&(a.credential=r.credential),s.push(a)}),n.iceServers=s}return e.clientConfiguration&&e.clientConfiguration.forceRelay===kr.ENABLED&&(n.iceTransportPolicy="relay"),n.sdpSemantics="unified-plan",n.continualGatheringPolicy="gather_continually",n}createDataChannels(){this.pcManager&&(this.lossyDC&&(this.lossyDC.onmessage=null,this.lossyDC.onerror=null),this.reliableDC&&(this.reliableDC.onmessage=null,this.reliableDC.onerror=null),this.lossyDC=this.pcManager.createPublisherDataChannel(tp,{ordered:!1,maxRetransmits:0}),this.reliableDC=this.pcManager.createPublisherDataChannel(np,{ordered:!0}),this.lossyDC.onmessage=this.handleDataMessage,this.reliableDC.onmessage=this.handleDataMessage,this.lossyDC.onerror=this.handleDataError,this.reliableDC.onerror=this.handleDataError,this.lossyDC.bufferedAmountLowThreshold=65535,this.reliableDC.bufferedAmountLowThreshold=65535,this.lossyDC.onbufferedamountlow=this.handleBufferedAmountLow,this.reliableDC.onbufferedamountlow=this.handleBufferedAmountLow)}createSender(e,t,n){return P(this,void 0,void 0,function*(){if(kc())return yield this.createTransceiverRTCRtpSender(e,t,n);if(Ic())return this.log.warn("using add-track fallback",this.logContext),yield this.createRTCRtpSender(e.mediaStreamTrack);throw new Gt("Required webRTC APIs not supported on this device")})}createSimulcastSender(e,t,n,s){return P(this,void 0,void 0,function*(){if(kc())return this.createSimulcastTransceiverSender(e,t,n,s);if(Ic())return this.log.debug("using add-track fallback",this.logContext),this.createRTCRtpSender(e.mediaStreamTrack);throw new Gt("Cannot stream on this device")})}createTransceiverRTCRtpSender(e,t,n){return P(this,void 0,void 0,function*(){if(!this.pcManager)throw new Gt("publisher is closed");const s=[];e.mediaStream&&s.push(e.mediaStream),Gi(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 P(this,void 0,void 0,function*(){if(!this.pcManager)throw new Gt("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 P(this,void 0,void 0,function*(){if(!this.pcManager)throw new Gt("publisher is closed");return this.pcManager.addPublisherTrack(e)})}attemptReconnect(e){return P(this,void 0,void 0,function*(){var t,n,s;if(!this._isClosed){if(this.attemptingReconnect){Ke.warn("already attempting reconnect, returning early",this.logContext);return}(((t=this.clientConfiguration)===null||t===void 0?void 0:t.resumeConnection)===kr.DISABLED||((s=(n=this.pcManager)===null||n===void 0?void 0:n.currentState)!==null&&s!==void 0?s:Pt.NEW)===Pt.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 Gt?(this.log.debug("received unrecoverable error",Object.assign(Object.assign({},this.logContext),{error:r})),a=!1):r instanceof Vs||(this.fullReconnectOnNext=!0),a?this.handleDisconnect("reconnect",Is.RR_UNKNOWN):(this.log.info("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(Date.now()-this.reconnectStart,"ms. giving up"),this.logContext),this.emit(de.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",Object.assign(Object.assign({},this.logContext),{error:t}))}return null}restartConnection(e){return P(this,void 0,void 0,function*(){var t,n,s;try{if(!this.url||!this.token)throw new Gt("could not reconnect, url or token not saved");this.log.info("reconnecting, attempt: ".concat(this.reconnectAttempts),this.logContext),this.emit(de.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",this.logContext),new Vs;r=yield this.join(e??this.url,this.token,this.signalOpts)}catch(a){throw a instanceof _t&&a.reason===tt.NotAllowed?new Gt("could not reconnect, token might be expired"):new Vs}if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(this.client.setReconnected(),this.emit(de.SignalRestarted,r),yield this.waitForPCReconnected(),this.client.currentState!==Mt.CONNECTED)throw new Vs("Signal connection got severed during reconnect");(t=this.regionUrlProvider)===null||t===void 0||t.resetAttempts(),this.emit(de.Restarted)}catch(r){const a=yield(n=this.regionUrlProvider)===null||n===void 0?void 0:n.getNextBestRegionUrl();if(a){yield this.restartConnection(a);return}else throw(s=this.regionUrlProvider)===null||s===void 0||s.resetAttempts(),r}})}resumeConnection(e){return P(this,void 0,void 0,function*(){var t;if(!this.url||!this.token)throw new Gt("could not reconnect, url or token not saved");if(!this.pcManager)throw new Gt("publisher and subscriber connections unset");this.log.info("resuming signal connection, attempt ".concat(this.reconnectAttempts),this.logContext),this.emit(de.Resuming);let n;try{this.setupSignalClientCallbacks(),n=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,Object.assign(Object.assign({},this.logContext),{error:s}))),s instanceof _t&&s.reason===tt.NotAllowed?new Gt("could not reconnect, token might be expired"):s instanceof _t&&s.reason===tt.LeaveRequest?s:new Vs(r)}if(this.emit(de.SignalResumed),n){const s=this.makeRTCConfiguration(n);this.pcManager.updateConfiguration(s),this.latestJoinResponse&&(this.latestJoinResponse.serverInfo=n.serverInfo)}else this.log.warn("Did not receive reconnect response",this.logContext);if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(yield this.pcManager.triggerIceRestart(),yield this.waitForPCReconnected(),this.client.currentState!==Mt.CONNECTED)throw new Vs("Signal connection got severed during reconnect");this.client.setReconnected(),((t=this.reliableDC)===null||t===void 0?void 0:t.readyState)==="open"&&this.reliableDC.id===null&&this.createDataChannels(),n!=null&&n.lastMessageSeq&&this.resendReliableMessagesForResume(n.lastMessageSeq),this.emit(de.Resumed)})}waitForPCInitialConnection(e,t){return P(this,void 0,void 0,function*(){if(!this.pcManager)throw new Gt("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(t,e)})}waitForPCReconnected(){return P(this,void 0,void 0,function*(){this.pcState=On.Reconnecting,this.log.debug("waiting for peer connection to reconnect",this.logContext);try{if(yield ln(Nb),!this.pcManager)throw new Gt("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(void 0,this.peerConnectionTimeout),this.pcState=On.Connected}catch(e){throw this.pcState=On.Disconnected,new _t("could not establish PC connection, ".concat(e.message),tt.InternalError)}})}publishRpcResponse(e,t,n,s){return P(this,void 0,void 0,function*(){const r=new cn({destinationIdentities:[e],kind:We.RELIABLE,value:{case:"rpcResponse",value:new nh({requestId:t,value:s?{case:"error",value:s.toProto()}:{case:"payload",value:n??""}})}});yield this.sendDataPacket(r,We.RELIABLE)})}publishRpcAck(e,t){return P(this,void 0,void 0,function*(){const n=new cn({destinationIdentities:[e],kind:We.RELIABLE,value:{case:"rpcAck",value:new th({requestId:t})}});yield this.sendDataPacket(n,We.RELIABLE)})}sendDataPacket(e,t){return P(this,void 0,void 0,function*(){yield this.ensurePublisherConnected(t),t===We.RELIABLE&&(e.sequence=this.reliableDataSequence,this.reliableDataSequence+=1);const n=e.toBinary(),s=this.dataChannelForKind(t);if(s){if(t===We.RELIABLE&&this.reliableMessageBuffer.push({data:n,sequence:e.sequence}),this.attemptingReconnect)return;s.send(n)}this.updateAndEmitDCBufferStatus(t)})}resendReliableMessagesForResume(e){return P(this,void 0,void 0,function*(){yield this.ensurePublisherConnected(We.RELIABLE);const t=this.dataChannelForKind(We.RELIABLE);t&&(this.reliableMessageBuffer.popToSequence(e),this.reliableMessageBuffer.getAll().forEach(n=>{t.send(n.data)})),this.updateAndEmitDCBufferStatus(We.RELIABLE)})}waitForBufferStatusLow(e){return new Promise((t,n)=>P(this,void 0,void 0,function*(){if(this.isBufferStatusLow(e))t();else{const s=()=>n("Engine closed");for(this.once(de.Closing,s);!this.dcBufferStatus.get(e);)yield ln(10);this.off(de.Closing,s),t()}}))}ensureDataTransportConnected(e){return P(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 Gt("PC manager is closed");const a=s?n.pcManager.subscriber:n.pcManager.publisher,o=s?"Subscriber":"Publisher";if(!a)throw new _t("".concat(o," connection not set"),tt.InternalError);let c=!1;!s&&!n.dataChannelForKind(t,s)&&(n.createDataChannels(),c=!0),!c&&!s&&!n.pcManager.publisher.isICEConnected&&n.pcManager.publisher.getICEConnectionState()!=="checking"&&(c=!0),c&&n.negotiate();const l=n.dataChannelForKind(t,s);if((l==null?void 0:l.readyState)==="open")return;const d=new Date().getTime()+n.peerConnectionTimeout;for(;new Date().getTime()<d;){if(a.isICEConnected&&((r=n.dataChannelForKind(t,s))===null||r===void 0?void 0:r.readyState)==="open")return;yield ln(50)}throw new _t("could not establish ".concat(o," connection, state: ").concat(a.getICEConnectionState()),tt.InternalError)}()})}ensurePublisherConnected(e){return P(this,void 0,void 0,function*(){this.publisherConnectionPromise||(this.publisherConnectionPromise=this.ensureDataTransportConnected(e,!1)),yield this.publisherConnectionPromise})}verifyTransport(){return!(!this.pcManager||this.pcManager.currentState!==Pt.CONNECTED||!this.client.ws||this.client.ws.readyState===WebSocket.CLOSED)}negotiate(){return P(this,void 0,void 0,function*(){return new Promise((e,t)=>P(this,void 0,void 0,function*(){if(!this.pcManager){t(new Ec("PC manager is closed"));return}this.pcManager.requirePublisher(),this.pcManager.publisher.getTransceivers().length==0&&!this.lossyDC&&!this.reliableDC&&this.createDataChannels();const n=new AbortController,s=()=>{n.abort(),this.log.debug("engine disconnected while negotiation was ongoing",this.logContext),e()};this.isClosed&&t("cannot negotiate on closed engine"),this.on(de.Closing,s),this.pcManager.publisher.once(zs.RTPVideoPayloadTypes,r=>{const a=new Map;r.forEach(o=>{const c=o.codec.toLowerCase();z0(c)&&a.set(o.payload,c)}),this.emit(de.RTPVideoMapUpdate,a)});try{yield this.pcManager.negotiate(n),e()}catch(r){r instanceof Ec&&(this.fullReconnectOnNext=!0),this.handleDisconnect("negotiation",Is.RR_UNKNOWN),t(r)}finally{this.off(de.Closing,s)}}))})}dataChannelForKind(e,t){if(t){if(e===We.LOSSY)return this.lossyDCSub;if(e===We.RELIABLE)return this.reliableDCSub}else{if(e===We.LOSSY)return this.lossyDC;if(e===We.RELIABLE)return this.reliableDC}}sendSyncState(e,t){var n,s;if(!this.pcManager){this.log.warn("sync state cannot be sent without peer connection setup",this.logContext);return}const r=this.pcManager.subscriber.getLocalDescription(),a=this.pcManager.subscriber.getRemoteDescription(),o=(s=(n=this.signalOpts)===null||n===void 0?void 0:n.autoSubscribe)!==null&&s!==void 0?s:!0,c=new Array,l=new Array;e.forEach(d=>{d.isDesired!==o&&c.push(d.trackSid),d.isEnabled||l.push(d.trackSid)}),this.client.sendSyncState(new Sh({answer:r?Ga({sdp:r.sdp,type:r.type}):void 0,offer:a?Ga({sdp:a.sdp,type:a.type}):void 0,subscription:new Ra({trackSids:c,subscribe:!o,participantTracks:[]}),publishTracks:Y0(t),dataChannels:this.dataChannelsInfo(),trackSidsDisabled:l,datachannelReceiveStates:this.reliableReceivedState.map((d,u)=>new xh({publisherSid:u,lastSeq:d}))}))}failNext(){this.shouldFailNext=!0}dataChannelsInfo(){const e=[],t=(n,s)=>{(n==null?void 0:n.id)!==void 0&&n.id!==null&&e.push(new Th({label:n.label,id:n.id,target:s}))};return t(this.dataChannelForKind(We.LOSSY),Dn.PUBLISHER),t(this.dataChannelForKind(We.RELIABLE),Dn.PUBLISHER),t(this.dataChannelForKind(We.LOSSY,!0),Dn.SUBSCRIBER),t(this.dataChannelForKind(We.RELIABLE,!0),Dn.SUBSCRIBER),e}clearReconnectTimeout(){this.reconnectTimeout&&Yt.clearTimeout(this.reconnectTimeout)}clearPendingReconnect(){this.clearReconnectTimeout(),this.reconnectAttempts=0}registerOnLineListener(){dn()&&window.addEventListener("online",this.handleBrowserOnLine)}deregisterOnLineListener(){dn()&&window.removeEventListener("online",this.handleBrowserOnLine)}}class Vs extends Error{}function Bb(i){return i!==void 0&&i>13}function zb(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}class al{constructor(e,t){this.lastUpdateAt=0,this.settingsCacheTime=3e3,this.attemptedRegions=[],this.serverUrl=new URL(e),this.token=t}updateToken(e){this.token=e}isCloud(){return Lc(this.serverUrl)}getServerUrl(){return this.serverUrl}getNextBestRegionUrl(e){return P(this,void 0,void 0,function*(){if(!this.isCloud())throw Error("region availability is only supported for LiveKit Cloud domains");(!this.regionSettings||Date.now()-this.lastUpdateAt>this.settingsCacheTime)&&(this.regionSettings=yield this.fetchRegionSettings(e));const t=this.regionSettings.regions.filter(n=>!this.attemptedRegions.find(s=>s.url===n.url));if(t.length>0){const n=t[0];return this.attemptedRegions.push(n),Ke.debug("next region: ".concat(n.region)),n.url}else return null})}resetAttempts(){this.attemptedRegions=[]}fetchRegionSettings(e){return P(this,void 0,void 0,function*(){const t=yield fetch("".concat(Vb(this.serverUrl),"/regions"),{headers:{authorization:"Bearer ".concat(this.token)},signal:e});if(t.ok){const n=yield t.json();return this.lastUpdateAt=Date.now(),n}else throw new _t("Could not fetch region settings: ".concat(t.statusText),t.status===401?tt.NotAllowed:tt.InternalError,t.status)})}setServerReportedRegions(e){this.regionSettings=e,this.lastUpdateAt=Date.now()}}function Vb(i){return"".concat(i.protocol.replace("ws","http"),"//").concat(i.host,"/settings")}class ip{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 zi("Not enough chunk(s) received - expected ".concat(this.totalByteSize," bytes of data total, only received ").concat(this.bytesReceived," bytes"),Un.Incomplete);if(this.bytesReceived>this.totalByteSize)throw new zi("Extra chunk(s) received - expected ".concat(this.totalByteSize," bytes of data total, received ").concat(this.bytesReceived," bytes"),Un.LengthExceeded)}}constructor(e,t,n,s){this.reader=t,this.totalByteSize=n,this._info=e,this.bytesReceived=0,this.outOfBandFailureRejectingFuture=s}}class Gb extends ip{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();let t=new Zn,n=null,s=null;if(this.signal){const a=this.signal;s=()=>{var o;(o=t.reject)===null||o===void 0||o.call(t,a.reason)},a.addEventListener("abort",s),n=a}const r=()=>{e.releaseLock(),n&&s&&n.removeEventListener("abort",s),this.signal=void 0};return{next:()=>P(this,void 0,void 0,function*(){var a,o;try{const{done:c,value:l}=yield Promise.race([e.read(),t.promise,(o=(a=this.outOfBandFailureRejectingFuture)===null||a===void 0?void 0:a.promise)!==null&&o!==void 0?o:new Promise(()=>{})]);return c?(this.validateBytesReceived(!0),{done:!0,value:void 0}):(this.handleChunkReceived(l),{done:!1,value:l.content})}catch(c){throw r(),c}}),return(){return P(this,void 0,void 0,function*(){return r(),{done:!0,value:void 0}})}}}withAbortSignal(e){return this.signal=e,this}readAll(){return P(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return function*(){var n,s,r,a;let o=new Set;const c=t.signal?e.withAbortSignal(t.signal):e;try{for(var l=!0,d=pi(c),u;u=yield d.next(),n=u.done,!n;l=!0){a=u.value,l=!1;const h=a;o.add(h)}}catch(h){s={error:h}}finally{try{!l&&!n&&(r=d.return)&&(yield r.call(d))}finally{if(s)throw s.error}}return Array.from(o)}()})}}class Hb extends ip{constructor(e,t,n,s){super(e,t,n,s),this.receivedChunks=new Map}handleChunkReceived(e){var t;const n=Va(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(),t=new TextDecoder("utf-8",{fatal:!0});let n=new Zn,s=null,r=null;if(this.signal){const o=this.signal;r=()=>{var c;(c=n.reject)===null||c===void 0||c.call(n,o.reason)},o.addEventListener("abort",r),s=o}const a=()=>{e.releaseLock(),s&&r&&s.removeEventListener("abort",r),this.signal=void 0};return{next:()=>P(this,void 0,void 0,function*(){var o,c;try{const{done:l,value:d}=yield Promise.race([e.read(),n.promise,(c=(o=this.outOfBandFailureRejectingFuture)===null||o===void 0?void 0:o.promise)!==null&&c!==void 0?c:new Promise(()=>{})]);if(l)return this.validateBytesReceived(!0),{done:!0,value:void 0};{this.handleChunkReceived(d);let u;try{u=t.decode(d.content)}catch(h){throw new zi("Cannot decode datastream chunk ".concat(d.chunkIndex," as text: ").concat(h),Un.DecodeFailed)}return{done:!1,value:u}}}catch(l){throw a(),l}}),return(){return P(this,void 0,void 0,function*(){return a(),{done:!0,value:void 0}})}}}withAbortSignal(e){return this.signal=e,this}readAll(){return P(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return function*(){var n,s,r,a;let o="";const c=t.signal?e.withAbortSignal(t.signal):e;try{for(var l=!0,d=pi(c),u;u=yield d.next(),n=u.done,!n;l=!0)a=u.value,l=!1,o+=a}catch(h){s={error:h}}finally{try{!l&&!n&&(r=d.return)&&(yield r.call(d))}finally{if(s)throw s.error}}return o}()})}}class Wb{constructor(){this.log=Ke,this.byteStreamControllers=new Map,this.textStreamControllers=new Map,this.byteStreamHandlers=new Map,this.textStreamHandlers=new Map}registerTextStreamHandler(e,t){if(this.textStreamHandlers.has(e))throw new zi('A text stream handler for topic "'.concat(e,'" has already been set.'),Un.HandlerAlreadyRegistered);this.textStreamHandlers.set(e,t)}unregisterTextStreamHandler(e){this.textStreamHandlers.delete(e)}registerByteStreamHandler(e,t){if(this.byteStreamHandlers.has(e))throw new zi('A byte stream handler for topic "'.concat(e,'" has already been set.'),Un.HandlerAlreadyRegistered);this.byteStreamHandlers.set(e,t)}unregisterByteStreamHandler(e){this.byteStreamHandlers.delete(e)}clearHandlersAndControllers(){this.byteStreamControllers.clear(),this.textStreamControllers.clear(),this.byteStreamHandlers.clear(),this.textStreamHandlers.clear()}validateParticipantHasNoActiveDataStreams(e){var t,n,s,r;const a=Array.from(this.textStreamControllers.entries()).filter(c=>c[1].sendingParticipantIdentity===e),o=Array.from(this.byteStreamControllers.entries()).filter(c=>c[1].sendingParticipantIdentity===e);if(a.length>0||o.length>0){const c=new zi("Participant ".concat(e," unexpectedly disconnected in the middle of sending data"),Un.AbnormalEnd);for(const[l,d]of o)(n=(t=d.outOfBandFailureRejectingFuture).reject)===null||n===void 0||n.call(t,c),this.byteStreamControllers.delete(l);for(const[l,d]of a)(r=(s=d.outOfBandFailureRejectingFuture).reject)===null||r===void 0||r.call(s,c),this.textStreamControllers.delete(l)}}handleDataStreamPacket(e){return P(this,void 0,void 0,function*(){switch(e.value.case){case"streamHeader":return this.handleStreamHeader(e.value.value,e.participantIdentity);case"streamChunk":return this.handleStreamChunk(e.value.value);case"streamTrailer":return this.handleStreamTrailer(e.value.value);default:throw new Error('DataPacket of value "'.concat(e.value.case,'" is not data stream related!'))}})}handleStreamHeader(e,t){return P(this,void 0,void 0,function*(){var n;if(e.contentHeader.case==="byteHeader"){const s=this.byteStreamHandlers.get(e.topic);if(!s){this.log.debug("ignoring incoming byte stream due to no handler for topic",e.topic);return}let r;const a=new Zn,o={id:e.streamId,name:(n=e.contentHeader.value.name)!==null&&n!==void 0?n:"unknown",mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:Va(e.timestamp),attributes:e.attributes},c=new ReadableStream({start:l=>{if(r=l,this.textStreamControllers.has(e.streamId))throw new zi("A data stream read is already in progress for a stream with id ".concat(e.streamId,"."),Un.AlreadyOpened);this.byteStreamControllers.set(e.streamId,{info:o,controller:r,startTime:Date.now(),sendingParticipantIdentity:t,outOfBandFailureRejectingFuture:a})}});s(new Gb(o,c,Va(e.totalLength),a),{identity:t})}else if(e.contentHeader.case==="textHeader"){const s=this.textStreamHandlers.get(e.topic);if(!s){this.log.debug("ignoring incoming text stream due to no handler for topic",e.topic);return}let r;const a=new Zn,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},c=new ReadableStream({start:l=>{if(r=l,this.textStreamControllers.has(e.streamId))throw new zi("A data stream read is already in progress for a stream with id ".concat(e.streamId,"."),Un.AlreadyOpened);this.textStreamControllers.set(e.streamId,{info:o,controller:r,startTime:Date.now(),sendingParticipantIdentity:t,outOfBandFailureRejectingFuture:a})}});s(new Hb(o,c,Va(e.totalLength),a),{identity:t})}})}handleStreamChunk(e){const t=this.byteStreamControllers.get(e.streamId);t&&e.content.length>0&&t.controller.enqueue(e);const n=this.textStreamControllers.get(e.streamId);n&&e.content.length>0&&n.controller.enqueue(e)}handleStreamTrailer(e){const t=this.textStreamControllers.get(e.streamId);t&&(t.info.attributes=Object.assign(Object.assign({},t.info.attributes),e.attributes),t.controller.close(),this.textStreamControllers.delete(e.streamId));const n=this.byteStreamControllers.get(e.streamId);n&&(n.info.attributes=Object.assign(Object.assign({},n.info.attributes),e.attributes),n.controller.close(),this.byteStreamControllers.delete(e.streamId))}}class sp{constructor(e,t,n){this.writableStream=e,this.defaultWriter=e.getWriter(),this.onClose=n,this.info=t}write(e){return this.defaultWriter.write(e)}close(){return P(this,void 0,void 0,function*(){var e;yield this.defaultWriter.close(),this.defaultWriter.releaseLock(),(e=this.onClose)===null||e===void 0||e.call(this)})}}class qb extends sp{}class $b extends sp{}const rp=15e3;class jb{constructor(e,t){this.engine=e,this.log=t}setupEngine(e){this.engine=e}sendText(e,t){return P(this,void 0,void 0,function*(){var n;const s=crypto.randomUUID(),a=new TextEncoder().encode(e).byteLength,o=(n=t==null?void 0:t.attachments)===null||n===void 0?void 0:n.map(()=>crypto.randomUUID()),c=new Array(o?o.length+1:1).fill(0),l=(u,h)=>{var f;c[h]=u;const g=c.reduce((v,m)=>v+m,0);(f=t==null?void 0:t.onProgress)===null||f===void 0||f.call(t,g)},d=yield this.streamText({streamId:s,totalSize:a,destinationIdentities:t==null?void 0:t.destinationIdentities,topic:t==null?void 0:t.topic,attachedStreamIds:o,attributes:t==null?void 0:t.attributes});return yield d.write(e),l(1,0),yield d.close(),t!=null&&t.attachments&&o&&(yield Promise.all(t.attachments.map((u,h)=>P(this,void 0,void 0,function*(){return this._sendFile(o[h],u,{topic:t.topic,mimeType:u.type,onProgress:f=>{l(f,h+1)}})})))),d.info})}streamText(e){return P(this,void 0,void 0,function*(){var t,n;const s=(t=e==null?void 0:e.streamId)!==null&&t!==void 0?t:crypto.randomUUID(),r={id:s,mimeType:"text/plain",timestamp:Date.now(),topic:(n=e==null?void 0:e.topic)!==null&&n!==void 0?n:"",size:e==null?void 0:e.totalSize,attributes:e==null?void 0:e.attributes},a=new ic({streamId:s,mimeType:r.mimeType,topic:r.topic,timestamp:ds(r.timestamp),totalLength:ds(e==null?void 0:e.totalSize),attributes:r.attributes,contentHeader:{case:"textHeader",value:new uh({version:e==null?void 0:e.version,attachedStreamIds:e==null?void 0:e.attachedStreamIds,replyToStreamId:e==null?void 0:e.replyToStreamId,operationType:(e==null?void 0:e.type)==="update"?nc.UPDATE:nc.CREATE})}}),o=e==null?void 0:e.destinationIdentities,c=new cn({destinationIdentities:o,value:{case:"streamHeader",value:a}});yield this.engine.sendDataPacket(c,We.RELIABLE);let l=0;const d=this.engine,u=new WritableStream({write(g){return P(this,void 0,void 0,function*(){for(const v of $0(g,rp)){yield d.waitForBufferStatusLow(We.RELIABLE);const m=new sc({content:v,streamId:s,chunkIndex:ds(l)}),p=new cn({destinationIdentities:o,value:{case:"streamChunk",value:m}});yield d.sendDataPacket(p,We.RELIABLE),l+=1}})},close(){return P(this,void 0,void 0,function*(){const g=new rc({streamId:s}),v=new cn({destinationIdentities:o,value:{case:"streamTrailer",value:g}});yield d.sendDataPacket(v,We.RELIABLE)})},abort(g){console.log("Sink error:",g)}});let h=()=>P(this,void 0,void 0,function*(){yield f.close()});d.once(de.Closing,h);const f=new qb(u,r,()=>this.engine.off(de.Closing,h));return f})}sendFile(e,t){return P(this,void 0,void 0,function*(){const n=crypto.randomUUID();return yield this._sendFile(n,e,t),{id:n}})}_sendFile(e,t,n){return P(this,void 0,void 0,function*(){var s;const r=yield this.streamBytes({streamId:e,totalSize:t.size,name:t.name,mimeType:(s=n==null?void 0:n.mimeType)!==null&&s!==void 0?s:t.type,topic:n==null?void 0:n.topic,destinationIdentities:n==null?void 0:n.destinationIdentities}),a=t.stream().getReader();for(;;){const{done:o,value:c}=yield a.read();if(o)break;yield r.write(c)}return yield r.close(),r.info})}streamBytes(e){return P(this,void 0,void 0,function*(){var t,n,s,r,a;const o=(t=e==null?void 0:e.streamId)!==null&&t!==void 0?t:crypto.randomUUID(),c=e==null?void 0:e.destinationIdentities,l={id:o,mimeType:(n=e==null?void 0:e.mimeType)!==null&&n!==void 0?n:"application/octet-stream",topic:(s=e==null?void 0:e.topic)!==null&&s!==void 0?s:"",timestamp:Date.now(),attributes:e==null?void 0:e.attributes,size:e==null?void 0:e.totalSize,name:(r=e==null?void 0:e.name)!==null&&r!==void 0?r:"unknown"},d=new ic({totalLength:ds((a=l.size)!==null&&a!==void 0?a:0),mimeType:l.mimeType,streamId:o,topic:l.topic,timestamp:ds(Date.now()),attributes:l.attributes,contentHeader:{case:"byteHeader",value:new hh({name:l.name})}}),u=new cn({destinationIdentities:c,value:{case:"streamHeader",value:d}});yield this.engine.sendDataPacket(u,We.RELIABLE);let h=0;const f=new an,g=this.engine,v=this.log,m=new WritableStream({write(x){return P(this,void 0,void 0,function*(){const C=yield f.lock();let b=0;try{for(;b<x.byteLength;){const S=x.slice(b,b+rp);yield g.waitForBufferStatusLow(We.RELIABLE);const M=new cn({destinationIdentities:c,value:{case:"streamChunk",value:new sc({content:S,streamId:o,chunkIndex:ds(h)})}});yield g.sendDataPacket(M,We.RELIABLE),h+=1,b+=S.byteLength}}finally{C()}})},close(){return P(this,void 0,void 0,function*(){const x=new rc({streamId:o}),C=new cn({destinationIdentities:c,value:{case:"streamTrailer",value:x}});yield g.sendDataPacket(C,We.RELIABLE)})},abort(x){v.error("Sink error:",x)}});return new $b(m,l)})}}class ap extends Q{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?oe.Muted:oe.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(oe.Ended,this))};e.addEventListener("removetrack",t)}start(){this.startMonitor(),super.enable()}stop(){this.stopMonitor(),super.disable()}getRTCStatsReport(){return P(this,void 0,void 0,function*(){var e;return!((e=this.receiver)===null||e===void 0)&&e.getStats?yield this.receiver.getStats():void 0})}setPlayoutDelay(e){this.receiver?"playoutDelayHint"in this.receiver?this.receiver.playoutDelayHint=e:this.log.warn("Playout delay not supported in this browser"):this.log.warn("Cannot set playout delay, track already ended")}getPlayoutDelay(){if(this.receiver){if("playoutDelayHint"in this.receiver)return this.receiver.playoutDelayHint;this.log.warn("Playout delay not supported in this browser")}else this.log.warn("Cannot get playout delay, track already ended");return 0}startMonitor(){this.monitorInterval||(this.monitorInterval=setInterval(()=>this.monitorReceiver(),el)),K0()&&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{timestamp:s,rtpTimestamp:r}=n;r&&this.rtpTimestamp!==r&&(this.emit(oe.TimeSyncUpdate,{timestamp:s,rtpTimestamp:r}),this.rtpTimestamp=r)}};e()}}class Xb extends ap{constructor(e,t,n,s,r,a){super(e,t,Q.Kind.Audio,n,a),this.monitorReceiver=()=>P(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=Ha(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;Kn()&&this._mediaStreamTrack._setVolume(e),this.elementVolume=e}getVolume(){if(this.elementVolume)return this.elementVolume;if(Kn())return 1;let e=0;return this.attachedElements.forEach(t=>{t.volume>e&&(e=t.volume)}),e}setSinkId(e){return P(this,void 0,void 0,function*(){this.sinkId=e,yield Promise.all(this.attachedElements.map(t=>{if(Dc(t))return t.setSinkId(e)}))})}attach(e){const t=this.attachedElements.length===0;return e?super.attach(e):e=super.attach(),this.sinkId&&Dc(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(oe.AudioPlaybackFailed,new Error("Audio Context couldn't be started automatically"))}).catch(s=>{this.emit(oe.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 P(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})}}const ol=100;class Yb extends ap{constructor(e,t,n,s,r){super(e,t,Q.Kind.Video,n,r),this.elementInfos=[],this.monitorReceiver=()=>P(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=Ha(a,this.prevStats)),this.prevStats=a}),this.debouncedHandleResize=Kc(()=>{this.updateDimensions()},ol),this.adaptiveStreamSettings=s}get isAdaptiveStream(){return this.adaptiveStreamSettings!==void 0}setStreamState(e){super.setStreamState(e),console.log("setStreamState",e),e===Q.StreamState.Active&&this.updateVisibility()}get mediaStreamTrack(){return this._mediaStreamTrack}setMuted(e){super.setMuted(e),this.attachedElements.forEach(t=>{e?Fs(this._mediaStreamTrack,t):Os(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 Kb(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){let t=[];if(e)return this.stopObservingElement(e),super.detach(e);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 P(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 P(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((c,l)=>Math.max(c,l.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(c=>c.pictureInPicture),o=this.elementInfos.some(c=>c.visible)&&!r||a;if(!(this.lastVisible===o&&!e)){if(!o&&Date.now()-s<ol){Yt.setTimeout(()=>{this.updateVisibility()},ol);return}this.lastVisible=o,this.emit(oe.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,c=a.height()*r;o+c>n+s&&(n=o,s=c)}((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},this.emit(oe.VideoDimensionsChanged,this.lastDimensions,this))}getPixelDensity(){var e;const t=(e=this.adaptiveStreamSettings)===null||e===void 0?void 0:e.pixelDensity;return t==="screen"?Cf():t||(Cf()>2?2:1)}}class Kb{get visible(){return this.isPiP||this.isIntersecting}get pictureInPicture(){return this.isPiP}constructor(e,t){this.onVisibilityChanged=n=>{var s;const{target:r,isIntersecting:a}=n;r===this.element&&(this.isIntersecting=a,this.isPiP=Gr(this.element),this.visibilityChangedAt=Date.now(),(s=this.handleVisibilityChanged)===null||s===void 0||s.call(this))},this.onEnterPiP=()=>{var n,s,r;(s=(n=window.documentPictureInPicture)===null||n===void 0?void 0:n.window)===null||s===void 0||s.addEventListener("pagehide",this.onLeavePiP),this.isPiP=Gr(this.element),(r=this.handleVisibilityChanged)===null||r===void 0||r.call(this)},this.onLeavePiP=()=>{var n;this.isPiP=Gr(this.element),(n=this.handleVisibilityChanged)===null||n===void 0||n.call(this)},this.element=e,this.isIntersecting=t??cl(e),this.isPiP=dn()&&Gr(e),this.visibilityChangedAt=0}width(){return this.element.clientWidth}height(){return this.element.clientHeight}observe(){var e,t,n;this.isIntersecting=cl(this.element),this.isPiP=Gr(this.element),this.element.handleResize=()=>{var s;(s=this.handleResize)===null||s===void 0||s.call(this)},this.element.handleVisibilityChanged=this.onVisibilityChanged,Mf().observe(this.element),Ef().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=Mf())===null||e===void 0||e.unobserve(this.element),(t=Ef())===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 Gr(i){var e,t;return document.pictureInPictureElement===i?!0:!((e=window.documentPictureInPicture)===null||e===void 0)&&e.window?cl(i,(t=window.documentPictureInPicture)===null||t===void 0?void 0:t.window):!1}function cl(i,e){const t=e||window;let n=i.offsetTop,s=i.offsetLeft;const r=i.offsetWidth,a=i.offsetHeight,{hidden:o}=i,{display:c}=getComputedStyle(i);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&&!o&&c!=="none"}class bi extends Xn.EventEmitter{constructor(e,t,n,s){var r;super(),this.metadataMuted=!1,this.encryption=vn.NONE,this.log=Ke,this.handleMuted=()=>{this.emit(oe.Muted)},this.handleUnmuted=()=>{this.emit(oe.Unmuted)},this.log=fi((r=s==null?void 0:s.loggerName)!==null&&r!==void 0?r:Ln.Publication),this.loggerContextCb=this.loggerContextCb,this.setMaxListeners(100),this.kind=e,this.trackSid=t,this.trackName=n,this.source=Q.Source.Unknown}setTrack(e){this.track&&(this.track.off(oe.Muted,this.handleMuted),this.track.off(oe.Unmuted,this.handleUnmuted)),this.track=e,e&&(e.on(oe.Muted,this.handleMuted),e.on(oe.Unmuted,this.handleUnmuted))}get logContext(){var e;return Object.assign(Object.assign({},(e=this.loggerContextCb)===null||e===void 0?void 0:e.call(this)),Xe(this))}get isMuted(){return this.metadataMuted}get isEnabled(){return!0}get isSubscribed(){return this.track!==void 0}get isEncrypted(){return this.encryption!==vn.NONE}get audioTrack(){if(Qn(this.track))return this.track}get videoTrack(){if(Gi(this.track))return this.track}updateInfo(e){this.trackSid=e.sid,this.trackName=e.name,this.source=Q.sourceFromProto(e.source),this.mimeType=e.mimeType,this.kind===Q.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={}))})(bi||(bi={}));class ll extends bi{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=()=>{this.emit(oe.Ended)},this.handleCpuConstrained=()=>{this.track&&Gi(this.track)&&this.emit(oe.CpuConstrained,this.track)},this.updateInfo(t),this.setTrack(n)}setTrack(e){this.track&&(this.track.off(oe.Ended,this.handleTrackEnded),this.track.off(oe.CpuConstrained,this.handleCpuConstrained)),super.setTrack(e),e&&(e.on(oe.Ended,this.handleTrackEnded),e.on(oe.CpuConstrained,this.handleCpuConstrained))}get isMuted(){return this.track?this.track.isMuted:super.isMuted}get audioTrack(){return super.audioTrack}get videoTrack(){return super.videoTrack}get isLocal(){return!0}mute(){return P(this,void 0,void 0,function*(){var e;return(e=this.track)===null||e===void 0?void 0:e.mute()})}unmute(){return P(this,void 0,void 0,function*(){var e;return(e=this.track)===null||e===void 0?void 0:e.unmute()})}pauseUpstream(){return P(this,void 0,void 0,function*(){var e;yield(e=this.track)===null||e===void 0?void 0:e.pauseUpstream()})}resumeUpstream(){return P(this,void 0,void 0,function*(){var e;yield(e=this.track)===null||e===void 0?void 0:e.resumeUpstream()})}getTrackFeatures(){var e;if(Qn(this.track)){const t=this.track.getSourceTrackSettings(),n=new Set;return t.autoGainControl&&n.add(qt.TF_AUTO_GAIN_CONTROL),t.echoCancellation&&n.add(qt.TF_ECHO_CANCELLATION),t.noiseSuppression&&n.add(qt.TF_NOISE_SUPPRESSION),t.channelCount&&t.channelCount>1&&n.add(qt.TF_STEREO),!((e=this.options)===null||e===void 0)&&e.dtx||n.add(qt.TF_NO_DTX),this.track.enhancedNoiseCancellation&&n.add(qt.TF_ENHANCED_NOISE_CANCELLATION),Array.from(n.values())}else return[]}}function $a(i,e){return P(this,void 0,void 0,function*(){i??(i={});let t=!1;const{audioProcessor:n,videoProcessor:s,optionsWithoutProcessor:r}=If(i);let a=r.audio,o=r.video;if(n&&typeof r.audio=="object"&&(r.audio.processor=n),s&&typeof r.video=="object"&&(r.video.processor=s),i.audio&&typeof r.audio=="object"&&typeof r.audio.deviceId=="string"){const u=r.audio.deviceId;r.audio.deviceId={exact:u},t=!0,a=Object.assign(Object.assign({},r.audio),{deviceId:{ideal:u}})}if(r.video&&typeof r.video=="object"&&typeof r.video.deviceId=="string"){const u=r.video.deviceId;r.video.deviceId={exact:u},t=!0,o=Object.assign(Object.assign({},r.video),{deviceId:{ideal:u}})}(r.audio===!0||typeof r.audio=="object"&&!r.audio.deviceId)&&(r.audio={deviceId:"default"}),r.video===!0?r.video={deviceId:"default"}:typeof r.video=="object"&&!r.video.deviceId&&(r.video.deviceId="default");const c=Rf(r,Wf,qf),l=Gc(c),d=navigator.mediaDevices.getUserMedia(l);r.audio&&($t.userMediaPromiseMap.set("audioinput",d),d.catch(()=>$t.userMediaPromiseMap.delete("audioinput"))),r.video&&($t.userMediaPromiseMap.set("videoinput",d),d.catch(()=>$t.userMediaPromiseMap.delete("videoinput")));try{const u=yield d;return yield Promise.all(u.getTracks().map(h=>P(this,void 0,void 0,function*(){const f=h.kind==="audio";let g=f?c.audio:c.video;(typeof g=="boolean"||!g)&&(g={});let v;const m=f?l.audio:l.video;typeof m!="boolean"&&(v=m);const p=h.getSettings().deviceId;v!=null&&v.deviceId&&Vi(v.deviceId)!==p?v.deviceId=p:v||(v={deviceId:p});const x=Cb(h,v,e);return x.kind===Q.Kind.Video?x.source=Q.Source.Camera:x.kind===Q.Kind.Audio&&(x.source=Q.Source.Microphone),x.mediaStream=u,Qn(x)&&n?yield x.setProcessor(n):Gi(x)&&s&&(yield x.setProcessor(s)),x})))}catch(u){if(!t)throw u;return $a(Object.assign(Object.assign({},i),{audio:a,video:o}),e)}})}function Jb(i){return P(this,void 0,void 0,function*(){return(yield $a({audio:!1,video:!0}))[0]})}function Zb(i){return P(this,void 0,void 0,function*(){return(yield $a({audio:!0,video:!1}))[0]})}var qi;(function(i){i.Excellent="excellent",i.Good="good",i.Poor="poor",i.Lost="lost",i.Unknown="unknown"})(qi||(qi={}));function Qb(i){switch(i){case Pr.EXCELLENT:return qi.Excellent;case Pr.GOOD:return qi.Good;case Pr.POOR:return qi.Poor;case Pr.LOST:return qi.Lost;default:return qi.Unknown}}class op extends Xn.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===Ir.AGENT}get isActive(){var e;return((e=this.participantInfo)===null||e===void 0?void 0:e.state)===Ds.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]:Ir.STANDARD;var c;super(),this.audioLevel=0,this.isSpeaking=!1,this._connectionQuality=qi.Unknown,this.log=Ke,this.log=fi((c=a==null?void 0:a.loggerName)!==null&&c!==void 0?c:Ln.Participant),this.loggerOptions=a,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[,t]of this.trackPublications)if(t.source===e)return t}getTrackPublicationByName(e){for(const[,t]of this.trackPublications)if(t.trackName===e)return t}waitUntilActive(){return this.isActive?Promise.resolve():this.activeFuture?this.activeFuture.promise:(this.activeFuture=new Zn,this.once(le.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(Q.Source.Camera);return!(!((e=t==null?void 0:t.isMuted)!==null&&e!==void 0)||e)}get isMicrophoneEnabled(){var e;const t=this.getTrackPublication(Q.Source.Microphone);return!(!((e=t==null?void 0:t.isMuted)!==null&&e!==void 0)||e)}get isScreenShareEnabled(){return!!this.getTrackPublication(Q.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===Ds.ACTIVE&&((t=this.participantInfo)===null||t===void 0?void 0:t.state)!==Ds.ACTIVE&&this.emit(le.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(le.ParticipantMetadataChanged,n)}_setName(e){const t=this.name!==e;this.name=e,t&&this.emit(le.ParticipantNameChanged,e)}_setAttributes(e){const t=J0(this.attributes,e);this._attributes=e,Object.keys(t).length>0&&this.emit(le.AttributesChanged,t)}setPermissions(e){var t,n,s,r,a,o;const c=this.permissions,l=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((d,u)=>{var h;return d!==((h=this.permissions)===null||h===void 0?void 0:h.canPublishSources[u])})||e.canSubscribeMetrics!==((o=this.permissions)===null||o===void 0?void 0:o.canSubscribeMetrics);return this.permissions=e,l&&this.emit(le.ParticipantPermissionsChanged,c),l}setIsSpeaking(e){e!==this.isSpeaking&&(this.isSpeaking=e,e&&(this.lastSpokeAt=new Date),this.emit(le.IsSpeakingChanged,e))}setConnectionQuality(e){const t=this._connectionQuality;this._connectionQuality=Qb(e),t!==this._connectionQuality&&this.emit(le.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=>Qn(t.track)&&t.track.setAudioContext(e))}addTrackPublication(e){e.on(oe.Muted,()=>{this.emit(le.TrackMuted,e)}),e.on(oe.Unmuted,()=>{this.emit(le.TrackUnmuted,e)});const t=e;switch(t.track&&(t.track.sid=e.trackSid),this.trackPublications.set(e.trackSid,e),e.kind){case Q.Kind.Audio:this.audioTrackPublications.set(e.trackSid,e);break;case Q.Kind.Video:this.videoTrackPublications.set(e.trackSid,e);break}}}function ey(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 yh({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 ty extends op{constructor(e,t,n,s,r,a){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=vn.NONE,this.enabledPublishVideoCodecs=[],this.pendingAcks=new Map,this.pendingResponses=new Map,this.handleReconnecting=()=>{this.reconnectFuture||(this.reconnectFuture=new Zn)},this.handleReconnected=()=>{var o,c;(c=(o=this.reconnectFuture)===null||o===void 0?void 0:o.resolve)===null||c===void 0||c.call(o),this.reconnectFuture=void 0,this.updateTrackSubscriptionPermissions()},this.handleClosing=()=>{var o,c,l,d,u,h;this.reconnectFuture&&(this.reconnectFuture.promise.catch(f=>this.log.warn(f.message,this.logContext)),(c=(o=this.reconnectFuture)===null||o===void 0?void 0:o.reject)===null||c===void 0||c.call(o,"Got disconnected during reconnection attempt"),this.reconnectFuture=void 0),this.signalConnectedFuture&&((d=(l=this.signalConnectedFuture).reject)===null||d===void 0||d.call(l,"Got disconnected without signal connected"),this.signalConnectedFuture=void 0),(h=(u=this.activeAgentFuture)===null||u===void 0?void 0:u.reject)===null||h===void 0||h.call(u,"Got disconnected without active agent present"),this.activeAgentFuture=void 0,this.firstActiveAgent=void 0},this.handleSignalConnected=o=>{var c,l;o.participant&&this.updateInfo(o.participant),this.signalConnectedFuture||(this.signalConnectedFuture=new Zn),(l=(c=this.signalConnectedFuture).resolve)===null||l===void 0||l.call(c)},this.handleSignalRequestResponse=o=>{const{requestId:c,reason:l,message:d}=o,u=this.pendingSignalRequests.get(c);u&&(l!==fc.OK&&u.reject(new vf(d,l)),this.pendingSignalRequests.delete(c))},this.handleDataPacket=o=>{switch(o.value.case){case"rpcResponse":let c=o.value.value,l=null,d=null;c.value.case==="payload"?l=c.value.value:c.value.case==="error"&&(d=kt.fromProto(c.value.value)),this.handleIncomingRpcResponse(c.requestId,l,d);break;case"rpcAck":let u=o.value.value;this.handleIncomingRpcAck(u.requestId);break}},this.updateTrackSubscriptionPermissions=()=>{this.log.debug("updating track subscription permissions",Object.assign(Object.assign({},this.logContext),{allParticipantsAllowed:this.allParticipantsAllowedToSubscribe,participantTrackPermissions:this.participantTrackPermissions})),this.engine.client.sendUpdateSubscriptionPermissions(this.allParticipantsAllowedToSubscribe,this.participantTrackPermissions.map(o=>ey(o)))},this.onTrackUnmuted=o=>{this.onTrackMuted(o,o.isUpstreamPaused)},this.onTrackMuted=(o,c)=>{if(c===void 0&&(c=!0),!o.sid){this.log.error("could not update mute status for unpublished track",Object.assign(Object.assign({},this.logContext),Xe(o)));return}this.engine.updateMuteStatus(o.sid,c)},this.onTrackUpstreamPaused=o=>{this.log.debug("upstream paused",Object.assign(Object.assign({},this.logContext),Xe(o))),this.onTrackMuted(o,!0)},this.onTrackUpstreamResumed=o=>{this.log.debug("upstream resumed",Object.assign(Object.assign({},this.logContext),Xe(o))),this.onTrackMuted(o,o.isMuted)},this.onTrackFeatureUpdate=o=>{const c=this.audioTrackPublications.get(o.sid);if(!c){this.log.warn("Could not update local audio track settings, missing publication for track ".concat(o.sid),this.logContext);return}this.engine.client.sendUpdateLocalAudioTrack(c.trackSid,c.getTrackFeatures())},this.onTrackCpuConstrained=(o,c)=>{this.log.debug("track cpu constrained",Object.assign(Object.assign({},this.logContext),Xe(c))),this.emit(le.LocalTrackCpuConstrained,o,c)},this.handleSubscribedQualityUpdate=o=>P(this,void 0,void 0,function*(){var c,l,d,u,h;if(!(!((h=this.roomOptions)===null||h===void 0)&&h.dynacast))return;const f=this.videoTrackPublications.get(o.trackSid);if(!f){this.log.warn("received subscribed quality update for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:o.trackSid}));return}if(!f.videoTrack)return;const g=yield f.videoTrack.setPublishingCodecs(o.subscribedCodecs);try{for(var v=!0,m=pi(g),p;p=yield m.next(),c=p.done,!c;v=!0){u=p.value,v=!1;const x=u;A0(x)&&(this.log.debug("publish ".concat(x," for ").concat(f.videoTrack.sid),Object.assign(Object.assign({},this.logContext),Xe(f))),yield this.publishAdditionalCodecForTrack(f.videoTrack,x,f.options))}}catch(x){l={error:x}}finally{try{!v&&!c&&(d=m.return)&&(yield d.call(m))}finally{if(l)throw l.error}}}),this.handleLocalTrackUnpublished=o=>{const c=this.trackPublications.get(o.trackSid);if(!c){this.log.warn("received unpublished event for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:o.trackSid}));return}this.unpublishTrack(c.track)},this.handleTrackEnded=o=>P(this,void 0,void 0,function*(){if(o.source===Q.Source.ScreenShare||o.source===Q.Source.ScreenShareAudio)this.log.debug("unpublishing local track due to TrackEnded",Object.assign(Object.assign({},this.logContext),Xe(o))),this.unpublishTrack(o);else if(o.isUserProvided)yield o.mute();else if(vi(o)||Hi(o))try{if(dn())try{const c=yield navigator==null?void 0:navigator.permissions.query({name:o.source===Q.Source.Camera?"camera":"microphone"});if(c&&c.state==="denied")throw this.log.warn("user has revoked access to ".concat(o.source),Object.assign(Object.assign({},this.logContext),Xe(o))),c.onchange=()=>{c.state!=="denied"&&(o.isMuted||o.restartTrack(),c.onchange=null)},new Error("GetUserMedia Permission denied")}catch{}o.isMuted||(this.log.debug("track ended, attempting to use a different device",Object.assign(Object.assign({},this.logContext),Xe(o))),vi(o)?yield o.restartTrack({deviceId:"default"}):yield o.restartTrack())}catch{this.log.warn("could not restart track, muting instead",Object.assign(Object.assign({},this.logContext),Xe(o))),yield o.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.rpcHandlers=r,this.roomOutgoingDataStreamManager=a}get lastCameraError(){return this.cameraError}get lastMicrophoneError(){return this.microphoneError}get isE2EEEnabled(){return this.encryptionType!==vn.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(de.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(de.Connected,this.handleReconnected).on(de.SignalConnected,this.handleSignalConnected).on(de.SignalRestarted,this.handleReconnected).on(de.SignalResumed,this.handleReconnected).on(de.Restarting,this.handleReconnecting).on(de.Resuming,this.handleReconnecting).on(de.LocalTrackUnpublished,this.handleLocalTrackUnpublished).on(de.SubscribedQualityUpdate,this.handleSubscribedQualityUpdate).on(de.Closing,this.handleClosing).on(de.SignalRequestResponse,this.handleSignalRequestResponse).on(de.DataPacketReceived,this.handleDataPacket)}setMetadata(e){return P(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({metadata:e})})}setName(e){return P(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({name:e})})}setAttributes(e){return P(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({attributes:e})})}requestMetadataUpdate(e){return P(this,arguments,void 0,function(t){var n=this;let{metadata:s,name:r,attributes:a}=t;return function*(){return new Promise((o,c)=>P(n,void 0,void 0,function*(){var l,d;try{let u=!1;const h=yield this.engine.client.sendUpdateLocalMetadata((l=s??this.metadata)!==null&&l!==void 0?l:"",(d=r??this.name)!==null&&d!==void 0?d:"",a),f=performance.now();for(this.pendingSignalRequests.set(h,{resolve:o,reject:g=>{c(g),u=!0},values:{name:r,metadata:s,attributes:a}});performance.now()-f<5e3&&!u;){if((!r||this.name===r)&&(!s||this.metadata===s)&&(!a||Object.entries(a).every(g=>{let[v,m]=g;return this.attributes[v]===m||m===""&&!this.attributes[v]}))){this.pendingSignalRequests.delete(h),o();return}yield ln(50)}c(new vf("Request to update local metadata timed out","TimeoutError"))}catch(u){u instanceof Error&&c(u)}}))}()})}setCameraEnabled(e,t,n){return this.setTrackEnabled(Q.Source.Camera,e,t,n)}setMicrophoneEnabled(e,t,n){return this.setTrackEnabled(Q.Source.Microphone,e,t,n)}setScreenShareEnabled(e,t,n){return this.setTrackEnabled(Q.Source.ScreenShare,e,t,n)}setPermissions(e){const t=this.permissions,n=super.setPermissions(e);return n&&t&&this.emit(le.ParticipantPermissionsChanged,t),n}setE2EEEnabled(e){return P(this,void 0,void 0,function*(){this.encryptionType=e?vn.GCM:vn.NONE,yield this.republishAllTracks(void 0,!1)})}setTrackEnabled(e,t,n,s){return P(this,void 0,void 0,function*(){var r,a;this.log.debug("setTrackEnabled",Object.assign(Object.assign({},this.logContext),{source:e,enabled:t})),this.republishPromise&&(yield this.republishPromise);let o=this.getTrackPublication(e);if(t)if(o)yield o.unmute();else{let c;if(this.pendingPublishing.has(e)){const l=yield this.waitForPendingPublicationOfSource(e);return l||this.log.info("waiting for pending publication promise timed out",Object.assign(Object.assign({},this.logContext),{source:e})),yield l==null?void 0:l.unmute(),l}this.pendingPublishing.add(e);try{switch(e){case Q.Source.Camera:c=yield this.createTracks({video:(r=n)!==null&&r!==void 0?r:!0});break;case Q.Source.Microphone:c=yield this.createTracks({audio:(a=n)!==null&&a!==void 0?a:!0});break;case Q.Source.ScreenShare:c=yield this.createScreenTracks(Object.assign({},n));break;default:throw new gi(e)}}catch(l){throw c==null||c.forEach(d=>{d.stop()}),l instanceof Error&&this.emit(le.MediaDevicesError,l,Hc(e)),this.pendingPublishing.delete(e),l}for(const l of c){const d=Object.assign(Object.assign({},this.roomOptions.publishDefaults),n);e===Q.Source.Microphone&&Qn(l)&&d.preConnectBuffer&&(this.log.info("starting preconnect buffer for microphone",Object.assign({},this.logContext)),l.startPreConnectBuffer())}try{const l=[];for(const u of c)this.log.info("publishing track",Object.assign(Object.assign({},this.logContext),Xe(u))),l.push(this.publishTrack(u,s));[o]=yield Promise.all(l)}catch(l){throw c==null||c.forEach(d=>{d.stop()}),l}finally{this.pendingPublishing.delete(e)}}else if(!(o!=null&&o.track)&&this.pendingPublishing.has(e)&&(o=yield this.waitForPendingPublicationOfSource(e),o||this.log.info("waiting for pending publication promise timed out",Object.assign(Object.assign({},this.logContext),{source:e}))),o&&o.track)if(e===Q.Source.ScreenShare){o=yield this.unpublishTrack(o.track);const c=this.getTrackPublication(Q.Source.ScreenShareAudio);c&&c.track&&this.unpublishTrack(c.track)}else yield o.mute();return o})}enableCameraAndMicrophone(){return P(this,void 0,void 0,function*(){if(!(this.pendingPublishing.has(Q.Source.Camera)||this.pendingPublishing.has(Q.Source.Microphone))){this.pendingPublishing.add(Q.Source.Camera),this.pendingPublishing.add(Q.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(Q.Source.Camera),this.pendingPublishing.delete(Q.Source.Microphone)}}})}createTracks(e){return P(this,void 0,void 0,function*(){var t,n;e??(e={});const s=Rf(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 $a(s,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext})).map(o=>(Qn(o)&&(this.microphoneError=void 0,o.setAudioContext(this.audioContext),o.source=Q.Source.Microphone,this.emit(le.AudioStreamAcquired)),Gi(o)&&(this.cameraError=void 0,o.source=Q.Source.Camera),o))}catch(r){throw r instanceof Error&&(e.audio&&(this.microphoneError=r),e.video&&(this.cameraError=r)),r}})}createScreenTracks(e){return P(this,void 0,void 0,function*(){if(e===void 0&&(e={}),navigator.mediaDevices.getDisplayMedia===void 0)throw new Cc("getDisplayMedia not supported");e.resolution===void 0&&!L0()&&(e.resolution=Pc.h1080fps30.resolution);const t=X0(e),n=yield navigator.mediaDevices.getDisplayMedia(t),s=n.getVideoTracks();if(s.length===0)throw new gi("no video track found");const r=new qa(s[0],void 0,!1,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});r.source=Q.Source.ScreenShare,e.contentHint&&(r.mediaStreamTrack.contentHint=e.contentHint);const a=[r];if(n.getAudioTracks().length>0){this.emit(le.AudioStreamAcquired);const o=new Wa(n.getAudioTracks()[0],void 0,!1,this.audioContext,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});o.source=Q.Source.ScreenShareAudio,a.push(o)}return a})}publishTrack(e,t){return P(this,void 0,void 0,function*(){return this.publishOrRepublishTrack(e,t)})}publishOrRepublishTrack(e,t){return P(this,arguments,void 0,function(n,s){var r=this;let a=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1;return function*(){var o,c,l,d;vi(n)&&n.setAudioContext(r.audioContext),yield(o=r.reconnectFuture)===null||o===void 0?void 0:o.promise,r.republishPromise&&!a&&(yield r.republishPromise),Bs(n)&&r.pendingPublishPromises.has(n)&&(yield r.pendingPublishPromises.get(n));let u;if(n instanceof MediaStreamTrack)u=n.getConstraints();else{u=n.constraints;let p;switch(n.source){case Q.Source.Microphone:p="audioinput";break;case Q.Source.Camera:p="videoinput"}p&&r.activeDeviceMap.has(p)&&(u=Object.assign(Object.assign({},u),{deviceId:r.activeDeviceMap.get(p)}))}if(n instanceof MediaStreamTrack)switch(n.kind){case"audio":n=new Wa(n,u,!0,r.audioContext,{loggerName:r.roomOptions.loggerName,loggerContextCb:()=>r.logContext});break;case"video":n=new qa(n,u,!0,{loggerName:r.roomOptions.loggerName,loggerContextCb:()=>r.logContext});break;default:throw new gi("unsupported MediaStreamTrack kind ".concat(n.kind))}else n.updateLoggerOptions({loggerName:r.roomOptions.loggerName,loggerContextCb:()=>r.logContext});let h;if(r.trackPublications.forEach(p=>{p.track&&p.track===n&&(h=p)}),h)return r.log.warn("track has already been published, skipping",Object.assign(Object.assign({},r.logContext),Xe(h))),h;const f="channelCount"in n.mediaStreamTrack.getSettings()&&n.mediaStreamTrack.getSettings().channelCount===2||n.mediaStreamTrack.getConstraints().channelCount===2,g=(c=s==null?void 0:s.forceStereo)!==null&&c!==void 0?c:f;g&&(s||(s={}),s.dtx===void 0&&r.log.info("Opus DTX will be disabled for stereo tracks by default. Enable them explicitly to make it work.",Object.assign(Object.assign({},r.logContext),Xe(n))),s.red===void 0&&r.log.info("Opus RED will be disabled for stereo tracks by default. Enable them explicitly to make it work."),(l=s.dtx)!==null&&l!==void 0||(s.dtx=!1),(d=s.red)!==null&&d!==void 0||(s.red=!1));const v=Object.assign(Object.assign({},r.roomOptions.publishDefaults),s);!N0()&&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",Object.assign({},r.logContext)),v.simulcast=!1),v.source&&(n.source=v.source);const m=new Promise((p,x)=>P(r,void 0,void 0,function*(){try{if(this.engine.client.currentState!==Mt.CONNECTED){this.log.debug("deferring track publication until signal is connected",Object.assign(Object.assign({},this.logContext),{track:Xe(n)}));const C=setTimeout(()=>{x(new gf("publishing rejected as engine not connected within timeout",408))},15e3);yield this.waitUntilEngineConnected(),clearTimeout(C);const b=yield this.publish(n,v,g);p(b)}else try{const C=yield this.publish(n,v,g);p(C)}catch(C){x(C)}}catch(C){x(C)}}));r.pendingPublishPromises.set(n,m);try{return yield m}catch(p){throw p}finally{r.pendingPublishPromises.delete(n)}}()})}waitUntilEngineConnected(){return this.signalConnectedFuture||(this.signalConnectedFuture=new Zn),this.signalConnectedFuture.promise}hasPermissionsToPublish(e){if(!this.permissions)return this.log.warn("no permissions present for publishing track",Object.assign(Object.assign({},this.logContext),Xe(e))),!1;const{canPublish:t,canPublishSources:n}=this.permissions;return t&&(n.length===0||n.map(s=>Z0(s)).includes(e.source))?!0:(this.log.warn("insufficient permissions to publish",Object.assign(Object.assign({},this.logContext),Xe(e))),!1)}publish(e,t,n){return P(this,void 0,void 0,function*(){var s,r,a,o,c,l,d,u,h,f;if(!this.hasPermissionsToPublish(e))throw new gf("failed to publish track, insufficient permissions",403);Array.from(this.trackPublications.values()).find(_=>Bs(e)&&_.source===e.source)&&e.source!==Q.Source.Unknown&&this.log.info("publishing a second track with the same source: ".concat(e.source),Object.assign(Object.assign({},this.logContext),Xe(e))),t.stopMicTrackOnMute&&Qn(e)&&(e.stopOnMute=!0),e.source===Q.Source.ScreenShare&&cs()&&(t.simulcast=!1),t.videoCodec==="av1"&&!k0()&&(t.videoCodec=void 0),t.videoCodec==="vp9"&&!I0()&&(t.videoCodec=void 0),t.videoCodec===void 0&&(t.videoCodec=Jc),this.enabledPublishVideoCodecs.length>0&&(this.enabledPublishVideoCodecs.some(_=>t.videoCodec===zr(_.mime))||(t.videoCodec=zr(this.enabledPublishVideoCodecs[0].mime)));const v=t.videoCodec;e.on(oe.Muted,this.onTrackMuted),e.on(oe.Unmuted,this.onTrackUnmuted),e.on(oe.Ended,this.handleTrackEnded),e.on(oe.UpstreamPaused,this.onTrackUpstreamPaused),e.on(oe.UpstreamResumed,this.onTrackUpstreamResumed),e.on(oe.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate);const m=[],p=!(!((s=t.dtx)!==null&&s!==void 0)||s),x=e.getSourceTrackSettings();x.autoGainControl&&m.push(qt.TF_AUTO_GAIN_CONTROL),x.echoCancellation&&m.push(qt.TF_ECHO_CANCELLATION),x.noiseSuppression&&m.push(qt.TF_NOISE_SUPPRESSION),x.channelCount&&x.channelCount>1&&m.push(qt.TF_STEREO),p&&m.push(qt.TF_NO_DTX),vi(e)&&e.hasPreConnectBuffer&&m.push(qt.TF_PRECONNECT_BUFFER);const C=new cc({cid:e.mediaStreamTrack.id,name:t.name,type:Q.kindToProto(e.kind),muted:e.isMuted,source:Q.sourceToProto(e.source),disableDtx:p,encryption:this.encryptionType,stereo:n,disableRed:this.isE2EEEnabled||!(!((r=t.red)!==null&&r!==void 0)||r),stream:t==null?void 0:t.stream,backupCodecPolicy:t==null?void 0:t.backupCodecPolicy,audioFeatures:m});let b;if(e.kind===Q.Kind.Video){let _={width:0,height:0};try{_=yield e.waitForDimensions()}catch{const R=(o=(a=this.roomOptions.videoCaptureDefaults)===null||a===void 0?void 0:a.resolution)!==null&&o!==void 0?o:Or.h720.resolution;_={width:R.width,height:R.height},this.log.error("could not determine track dimensions, using defaults",Object.assign(Object.assign(Object.assign({},this.logContext),Xe(e)),{dims:_}))}C.width=_.width,C.height=_.height,Hi(e)&&(Yn(v)&&(e.source===Q.Source.ScreenShare&&(t.scalabilityMode="L1T3","contentHint"in e.mediaStreamTrack&&(e.mediaStreamTrack.contentHint="motion",this.log.info("forcing contentHint to motion for screenshare with SVC codecs",Object.assign(Object.assign({},this.logContext),Xe(e))))),t.scalabilityMode=(c=t.scalabilityMode)!==null&&c!==void 0?c:"L3T3_KEY"),C.simulcastCodecs=[new oc({codec:v,cid:e.mediaStreamTrack.id})],t.backupCodec===!0&&(t.backupCodec={codec:Jc}),t.backupCodec&&v!==t.backupCodec.codec&&C.encryption===vn.NONE&&(this.roomOptions.dynacast||(this.roomOptions.dynacast=!0),C.simulcastCodecs.push(new oc({codec:t.backupCodec.codec,cid:""})))),b=il(e.source===Q.Source.ScreenShare,C.width,C.height,t),C.layers=ep(C.width,C.height,b,Yn(t.videoCodec))}else e.kind===Q.Kind.Audio&&(b=[{maxBitrate:(l=t.audioPreset)===null||l===void 0?void 0:l.maxBitrate,priority:(u=(d=t.audioPreset)===null||d===void 0?void 0:d.priority)!==null&&u!==void 0?u:"high",networkPriority:(f=(h=t.audioPreset)===null||h===void 0?void 0:h.priority)!==null&&f!==void 0?f:"high"}]);if(!this.engine||this.engine.isClosed)throw new Gt("cannot publish track when not connected");const S=()=>P(this,void 0,void 0,function*(){var _,T,R;if(!this.engine.pcManager)throw new Gt("pcManager is not ready");if(e.sender=yield this.engine.createSender(e,t,b),this.emit(le.LocalSenderCreated,e.sender,e),Hi(e)&&((_=t.degradationPreference)!==null&&_!==void 0||(t.degradationPreference=Lb(e)),e.setDegradationPreference(t.degradationPreference)),b)if(cs()&&e.kind===Q.Kind.Audio){let O;for(const z of this.engine.pcManager.publisher.getTransceivers())if(z.sender===e.sender){O=z;break}O&&this.engine.pcManager.publisher.setTrackCodecBitrate({transceiver:O,codec:"opus",maxbr:!((T=b[0])===null||T===void 0)&&T.maxBitrate?b[0].maxBitrate/1e3:0})}else e.codec&&Yn(e.codec)&&(!((R=b[0])===null||R===void 0)&&R.maxBitrate)&&this.engine.pcManager.publisher.setTrackCodecBitrate({cid:C.cid,codec:e.codec,maxbr:b[0].maxBitrate/1e3});yield this.engine.negotiate()});let M;const A=new Promise((_,T)=>P(this,void 0,void 0,function*(){var R;try{M=yield this.engine.addTrack(C),_(M)}catch(O){e.sender&&(!((R=this.engine.pcManager)===null||R===void 0)&&R.publisher)&&(this.engine.pcManager.publisher.removeTrack(e.sender),yield this.engine.negotiate().catch(z=>{this.log.error("failed to negotiate after removing track due to failed add track request",Object.assign(Object.assign(Object.assign({},this.logContext),Xe(e)),{error:z}))})),T(O)}}));if(this.enabledPublishVideoCodecs.length>0)M=(yield Promise.all([A,S()]))[0];else{M=yield A;let _;if(M.codecs.forEach(T=>{_===void 0&&(_=T.mimeType)}),_&&e.kind===Q.Kind.Video){const T=zr(_);T!==v&&(this.log.debug("falling back to server selected codec",Object.assign(Object.assign(Object.assign({},this.logContext),Xe(e)),{codec:T})),t.videoCodec=T,b=il(e.source===Q.Source.ScreenShare,C.width,C.height,t))}yield S()}const k=new ll(e.kind,M,e,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});if(k.on(oe.CpuConstrained,_=>this.onTrackCpuConstrained(_,k)),k.options=t,e.sid=M.sid,this.log.debug("publishing ".concat(e.kind," with encodings"),Object.assign(Object.assign({},this.logContext),{encodings:b,trackInfo:M})),Hi(e)?e.startMonitor(this.engine.client):vi(e)&&e.startMonitor(),this.addTrackPublication(k),this.emit(le.LocalTrackPublished,k),vi(e)&&M.audioFeatures.includes(qt.TF_PRECONNECT_BUFFER)){const _=e.getPreConnectBuffer(),T=e.getPreConnectBufferMimeType();this.on(le.LocalTrackSubscribed,R=>{if(R.trackSid===M.sid){if(!e.hasPreConnectBuffer){this.log.warn("subscribe event came to late, buffer already closed",this.logContext);return}this.log.debug("finished recording preconnect buffer",Object.assign(Object.assign({},this.logContext),Xe(e))),e.stopPreConnectBuffer()}}),_&&new Promise((O,z)=>P(this,void 0,void 0,function*(){var $,J,W,q,ne,be;try{this.log.debug("waiting for agent",Object.assign(Object.assign({},this.logContext),Xe(e)));const Be=setTimeout(()=>{z(new Error("agent not active within 10 seconds"))},1e4),wt=yield this.waitUntilActiveAgentPresent();clearTimeout(Be),this.log.debug("sending preconnect buffer",Object.assign(Object.assign({},this.logContext),Xe(e)));const vt=yield this.streamBytes({name:"preconnect-buffer",mimeType:T,topic:"lk.agent.pre-connect-audio-buffer",destinationIdentities:[wt.identity],attributes:{trackId:k.trackSid,sampleRate:String((ne=x.sampleRate)!==null&&ne!==void 0?ne:"48000"),channels:String((be=x.channelCount)!==null&&be!==void 0?be:"1")}});try{for(var ue=!0,_e=pi(_),ze;ze=yield _e.next(),$=ze.done,!$;ue=!0){q=ze.value,ue=!1;const K=q;yield vt.write(K)}}catch(K){J={error:K}}finally{try{!ue&&!$&&(W=_e.return)&&(yield W.call(_e))}finally{if(J)throw J.error}}yield vt.close(),O()}catch(Be){z(Be)}})).then(()=>{this.log.debug("preconnect buffer sent successfully",Object.assign(Object.assign({},this.logContext),Xe(e)))}).catch(O=>{this.log.error("error sending preconnect buffer",Object.assign(Object.assign(Object.assign({},this.logContext),Xe(e)),{error:O}))})}return k})}get isLocal(){return!0}publishAdditionalCodecForTrack(e,t,n){return P(this,void 0,void 0,function*(){var s;if(this.encryptionType!==vn.NONE)return;let r;if(this.trackPublications.forEach(f=>{f.track&&f.track===e&&(r=f)}),!r)throw new gi("track is not published");if(!Hi(e))throw new gi("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=kb(e,t,a);if(!o){this.log.info("backup codec has been disabled, ignoring request to add additional codec for track",Object.assign(Object.assign({},this.logContext),Xe(e)));return}const c=e.addSimulcastTrack(t,o);if(!c)return;const l=new cc({cid:c.mediaStreamTrack.id,type:Q.kindToProto(e.kind),muted:e.isMuted,source:Q.sourceToProto(e.source),sid:e.sid,simulcastCodecs:[{codec:a.videoCodec,cid:c.mediaStreamTrack.id}]});if(l.layers=ep(l.width,l.height,o),!this.engine||this.engine.isClosed)throw new Gt("cannot publish track when not connected");const d=()=>P(this,void 0,void 0,function*(){yield this.engine.createSimulcastSender(e,c,a,o),yield this.engine.negotiate()}),h=(yield Promise.all([this.engine.addTrack(l),d()]))[0];this.log.debug("published ".concat(t," for track ").concat(e.sid),Object.assign(Object.assign({},this.logContext),{encodings:o,trackInfo:h}))})}unpublishTrack(e,t){return P(this,void 0,void 0,function*(){var n,s;if(Bs(e)){const l=this.pendingPublishPromises.get(e);l&&(this.log.info("awaiting publish promise before attempting to unpublish",Object.assign(Object.assign({},this.logContext),Xe(e))),yield l)}const r=this.getPublicationForTrack(e),a=r?Xe(r):void 0;if(this.log.debug("unpublishing track",Object.assign(Object.assign({},this.logContext),a)),!r||!r.track){this.log.warn("track was not unpublished because no publication was found",Object.assign(Object.assign({},this.logContext),a));return}e=r.track,e.off(oe.Muted,this.onTrackMuted),e.off(oe.Unmuted,this.onTrackUnmuted),e.off(oe.Ended,this.handleTrackEnded),e.off(oe.UpstreamPaused,this.onTrackUpstreamPaused),e.off(oe.UpstreamResumed,this.onTrackUpstreamResumed),e.off(oe.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 c=e.sender;if(e.sender=void 0,this.engine.pcManager&&this.engine.pcManager.currentState<Pt.FAILED&&c)try{for(const l of this.engine.pcManager.publisher.getTransceivers())l.sender===c&&(l.direction="inactive",o=!0);if(this.engine.removeTrack(c)&&(o=!0),Hi(e)){for(const[,l]of e.simulcastCodecs)l.sender&&(this.engine.removeTrack(l.sender)&&(o=!0),l.sender=void 0);e.simulcastCodecs.clear()}}catch(l){this.log.warn("failed to unpublish track",Object.assign(Object.assign(Object.assign({},this.logContext),a),{error:l}))}switch(this.trackPublications.delete(r.trackSid),r.kind){case Q.Kind.Audio:this.audioTrackPublications.delete(r.trackSid);break;case Q.Kind.Video:this.videoTrackPublications.delete(r.trackSid);break}return this.emit(le.LocalTrackUnpublished,r),r.setTrack(void 0),o&&(yield this.engine.negotiate()),r})}unpublishTracks(e){return P(this,void 0,void 0,function*(){return(yield Promise.all(e.map(n=>this.unpublishTrack(n)))).filter(n=>!!n)})}republishAllTracks(e){return P(this,arguments,void 0,function(t){var n=this;let s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){n.republishPromise&&(yield n.republishPromise),n.republishPromise=new Promise((r,a)=>P(n,void 0,void 0,function*(){try{const o=[];this.trackPublications.forEach(c=>{c.track&&(t&&(c.options=Object.assign(Object.assign({},c.options),t)),o.push(c))}),yield Promise.all(o.map(c=>P(this,void 0,void 0,function*(){const l=c.track;yield this.unpublishTrack(l,!1),s&&!l.isMuted&&l.source!==Q.Source.ScreenShare&&l.source!==Q.Source.ScreenShareAudio&&(vi(l)||Hi(l))&&!l.isUserProvided&&(this.log.debug("restarting existing track",Object.assign(Object.assign({},this.logContext),{track:c.trackSid})),yield l.restartTrack()),yield this.publishOrRepublishTrack(l,c.options,!0)}))),r()}catch(o){a(o)}finally{this.republishPromise=void 0}})),yield n.republishPromise}()})}publishData(e){return P(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?We.RELIABLE:We.LOSSY,a=s.destinationIdentities,o=s.topic,c=new cn({kind:r,value:{case:"user",value:new Zu({participantIdentity:n.identity,payload:t,destinationIdentities:a,topic:o})}});yield n.engine.sendDataPacket(c,r)}()})}publishDtmf(e,t){return P(this,void 0,void 0,function*(){const n=new cn({kind:We.RELIABLE,value:{case:"sipDtmf",value:new Qu({code:e,digit:t})}});yield this.engine.sendDataPacket(n,We.RELIABLE)})}sendChatMessage(e,t){return P(this,void 0,void 0,function*(){const n={id:crypto.randomUUID(),message:e,timestamp:Date.now(),attachedFiles:t==null?void 0:t.attachments},s=new cn({value:{case:"chatMessage",value:new tc(Object.assign(Object.assign({},n),{timestamp:At.parse(n.timestamp)}))}});return yield this.engine.sendDataPacket(s,We.RELIABLE),this.emit(le.ChatMessage,n),n})}editChatMessage(e,t){return P(this,void 0,void 0,function*(){const n=Object.assign(Object.assign({},t),{message:e,editTimestamp:Date.now()}),s=new cn({value:{case:"chatMessage",value:new tc(Object.assign(Object.assign({},n),{timestamp:At.parse(n.timestamp),editTimestamp:At.parse(n.editTimestamp)}))}});return yield this.engine.sendDataPacket(s,We.RELIABLE),this.emit(le.ChatMessage,n),n})}sendText(e,t){return P(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.sendText(e,t)})}streamText(e){return P(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.streamText(e)})}sendFile(e,t){return P(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.sendFile(e,t)})}streamBytes(e){return P(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.streamBytes(e)})}performRpc(e){return P(this,arguments,void 0,function(t){var n=this;let{destinationIdentity:s,method:r,payload:a,responseTimeout:o=1e4}=t;return function*(){return new Promise((l,d)=>P(n,void 0,void 0,function*(){var u,h,f,g;if(Qc(a)>$f){d(kt.builtIn("REQUEST_PAYLOAD_TOO_LARGE"));return}if(!((h=(u=this.engine.latestJoinResponse)===null||u===void 0?void 0:u.serverInfo)===null||h===void 0)&&h.version&&Jn((g=(f=this.engine.latestJoinResponse)===null||f===void 0?void 0:f.serverInfo)===null||g===void 0?void 0:g.version,"1.8.0")<0){d(kt.builtIn("UNSUPPORTED_SERVER"));return}const v=crypto.randomUUID();yield this.publishRpcRequest(s,v,r,a,o-2e3);const m=setTimeout(()=>{this.pendingAcks.delete(v),d(kt.builtIn("CONNECTION_TIMEOUT")),this.pendingResponses.delete(v),clearTimeout(p)},2e3);this.pendingAcks.set(v,{resolve:()=>{clearTimeout(m)},participantIdentity:s});const p=setTimeout(()=>{this.pendingResponses.delete(v),d(kt.builtIn("RESPONSE_TIMEOUT"))},o);this.pendingResponses.set(v,{resolve:(x,C)=>{clearTimeout(p),this.pendingAcks.has(v)&&(console.warn("RPC response received before ack",v),this.pendingAcks.delete(v),clearTimeout(m)),C?d(C):l(x??"")},participantIdentity:s})}))}()})}registerRpcMethod(e,t){this.rpcHandlers.has(e)&&this.log.warn("you're overriding the RPC handler for method ".concat(e,", in the future this will throw an error")),this.rpcHandlers.set(e,t)}unregisterRpcMethod(e){this.rpcHandlers.delete(e)}setTrackSubscriptionPermissions(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:[];this.participantTrackPermissions=t,this.allParticipantsAllowedToSubscribe=e,this.engine.client.isDisconnected||this.updateTrackSubscriptionPermissions()}handleIncomingRpcAck(e){const t=this.pendingAcks.get(e);t?(t.resolve(),this.pendingAcks.delete(e)):console.error("Ack received for unexpected RPC request",e)}handleIncomingRpcResponse(e,t,n){const s=this.pendingResponses.get(e);s?(s.resolve(t,n),this.pendingResponses.delete(e)):console.error("Response received for unexpected RPC request",e)}publishRpcRequest(e,t,n,s,r){return P(this,void 0,void 0,function*(){const a=new cn({destinationIdentities:[e],kind:We.RELIABLE,value:{case:"rpcRequest",value:new eh({id:t,method:n,payload:s,responseTimeoutMs:r,version:1})}});yield this.engine.sendDataPacket(a,We.RELIABLE)})}handleParticipantDisconnected(e){for(const[t,{participantIdentity:n}]of this.pendingAcks)n===e&&this.pendingAcks.delete(t);for(const[t,{participantIdentity:n,resolve:s}]of this.pendingResponses)n===e&&(s(null,kt.builtIn("RECIPIENT_DISCONNECTED")),this.pendingResponses.delete(t))}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(Object.assign({},this.logContext),Xe(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,"Agent disconnected"),this.activeAgentFuture=void 0}waitUntilActiveAgentPresent(){return this.firstActiveAgent?Promise.resolve(this.firstActiveAgent):(this.activeAgentFuture||(this.activeAgentFuture=new Zn),this.activeAgentFuture.promise)}getPublicationForTrack(e){let t;return this.trackPublications.forEach(n=>{const s=n.track;s&&(e instanceof MediaStreamTrack?(vi(s)||Hi(s))&&s.mediaStreamTrack===e&&(t=n):e===s&&(t=n))}),t}waitForPendingPublicationOfSource(e){return P(this,void 0,void 0,function*(){const n=Date.now();for(;Date.now()<n+1e4;){const s=Array.from(this.pendingPublishPromises.entries()).find(r=>{let[a]=r;return a.source===e});if(s)return s[1];yield ln(20)}})}}class ny extends bi{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(oe.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 Ra({trackSids:[this.trackSid],subscribe:this.subscribed,participantTracks:[new sh({participantSid:"",trackSids:[this.trackSid]})]});this.emit(oe.UpdateSubscription,s),this.emitSubscriptionUpdateIfChanged(t),this.emitPermissionUpdateIfChanged(n)}get subscriptionStatus(){return this.subscribed===!1?bi.SubscriptionStatus.Unsubscribed:super.isSubscribed?bi.SubscriptionStatus.Subscribed:bi.SubscriptionStatus.Desired}get permissionStatus(){return this.allowed?bi.PermissionStatus.Allowed:bi.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||(zc(this.track)&&(this.requestedVideoDimensions=e),this.requestedMaxQuality=void 0,this.emitTrackUpdate()))}setVideoFPS(e){this.isManualOperationAllowed()&&zc(this.track)&&this.fps!==e&&(this.fps=e,this.emitTrackUpdate())}get videoQuality(){var e;return(e=this.requestedMaxQuality)!==null&&e!==void 0?e:yn.HIGH}setTrack(e){const t=this.subscriptionStatus,n=this.permissionStatus,s=this.track;s!==e&&(s&&(s.off(oe.VideoDimensionsChanged,this.handleVideoDimensionsChange),s.off(oe.VisibilityChanged,this.handleVisibilityChange),s.off(oe.Ended,this.handleEnded),s.detach(),s.stopMonitor(),this.emit(oe.Unsubscribed,s)),super.setTrack(e),e&&(e.sid=this.trackSid,e.on(oe.VideoDimensionsChanged,this.handleVideoDimensionsChange),e.on(oe.VisibilityChanged,this.handleVisibilityChange),e.on(oe.Ended,this.handleEnded),this.emit(oe.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(oe.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?oe.Muted:oe.Unmuted)}emitSubscriptionUpdateIfChanged(e){const t=this.subscriptionStatus;e!==t&&this.emit(oe.SubscriptionStatusChanged,t,e)}emitPermissionUpdateIfChanged(e){this.permissionStatus!==e&&this.emit(oe.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 zc(this.track)&&this.track.isAdaptiveStream}emitTrackUpdate(){const e=new ph({trackSids:[this.trackSid],disabled:!this.isEnabled,fps:this.fps});if(this.kind===Q.Kind.Video){let t=this.requestedVideoDimensions;if(this.videoDimensionsAdaptiveStream!==void 0)if(t)Df(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=Q0(this.trackInfo,this.requestedMaxQuality);n&&Df(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:yn.HIGH})),e.quality=yn.HIGH)}this.emit(oe.UpdateSettings,e)}}class ja extends op{static fromParticipantInfo(e,t,n){return new ja(e,t.sid,t.identity,t.name,t.metadata,t.attributes,n,t.kind)}get logContext(){return Object.assign(Object.assign({},super.logContext),{rpID:this.sid,remoteParticipant:this.identity})}constructor(e,t,n,s,r,a,o){let c=arguments.length>7&&arguments[7]!==void 0?arguments[7]:Ir.STANDARD;super(t,n||"",s,r,a,o,c),this.signalClient=e,this.trackPublications=new Map,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.volumeMap=new Map}addTrackPublication(e){super.addTrackPublication(e),e.on(oe.UpdateSettings,t=>{this.log.debug("send update settings",Object.assign(Object.assign(Object.assign({},this.logContext),Xe(e)),{settings:t})),this.signalClient.sendUpdateTrackSettings(t)}),e.on(oe.UpdateSubscription,t=>{t.participantTracks.forEach(n=>{n.participantSid=this.sid}),this.signalClient.sendUpdateSubscription(t)}),e.on(oe.SubscriptionPermissionChanged,t=>{this.emit(le.TrackSubscriptionPermissionChanged,e,t)}),e.on(oe.SubscriptionStatusChanged,t=>{this.emit(le.TrackSubscriptionStatusChanged,e,t)}),e.on(oe.Subscribed,t=>{this.emit(le.TrackSubscribed,t,e)}),e.on(oe.Unsubscribed,t=>{this.emit(le.TrackUnsubscribed,t,e)}),e.on(oe.SubscriptionFailed,t=>{this.emit(le.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]:Q.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]:Q.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(d=>{!o&&e.kind===d.kind.toString()&&(o=d)}),!o){if(a===0){this.log.error("could not find published track",Object.assign(Object.assign({},this.logContext),{trackSid:t})),this.emit(le.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),Xe(o))),this.emit(le.TrackSubscriptionFailed,t);return}const c=e.kind==="video";let l;return c?l=new Yb(e,t,s,r):l=new Xb(e,t,s,this.audioContext,this.audioOutput),l.source=o.source,l.isMuted=o.isMuted,l.setMediaStream(n),l.start(),o.setTrack(l),this.volumeMap.has(o.source)&&Bc(l)&&Qn(l)&&l.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 c=Q.kindFromProto(s.type);if(!c)return;o=new ny(c,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 l=Array.from(this.trackPublications.values()).find(d=>d.source===(o==null?void 0:o.source));l&&o.source!==Q.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:Xe(l),newTrack:Xe(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),Xe(s))),this.unpublishTrack(s.trackSid,!0))}),n.forEach(s=>{this.emit(le.TrackPublished,s)}),!0}unpublishTrack(e,t){const n=this.trackPublications.get(e);if(!n)return;const{track:s}=n;switch(s&&(s.stop(),n.setTrack(void 0)),this.trackPublications.delete(e),n.kind){case Q.Kind.Audio:this.audioTrackPublications.delete(e);break;case Q.Kind.Video:this.videoTrackPublications.delete(e);break}t&&this.emit(le.TrackUnpublished,n)}setAudioOutput(e){return P(this,void 0,void 0,function*(){this.audioOutput=e;const t=[];this.audioTrackPublications.forEach(n=>{var s;Qn(n.track)&&Bc(n.track)&&t.push(n.track.setSinkId((s=e.deviceId)!==null&&s!==void 0?s:"default"))}),yield Promise.all(t)})}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 ct;(function(i){i.Disconnected="disconnected",i.Connecting="connecting",i.Connected="connected",i.Reconnecting="reconnecting",i.SignalReconnecting="signalReconnecting"})(ct||(ct={}));const iy=4*1e3;class Gs extends Xn.EventEmitter{constructor(e){var t,n,s,r;if(super(),t=this,this.state=ct.Disconnected,this.activeSpeakers=[],this.isE2EEEnabled=!1,this.audioEnabled=!0,this.isVideoPlaybackBlocked=!1,this.log=Ke,this.bufferedEvents=[],this.isResuming=!1,this.rpcHandlers=new Map,this.connect=(a,o,c)=>P(this,void 0,void 0,function*(){var l;if(!D0())throw Kn()?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 d=yield this.disconnectLock.lock();if(this.state===ct.Connected)return this.log.info("already connected to room ".concat(this.name),this.logContext),d(),Promise.resolve();if(this.connectFuture)return d(),this.connectFuture.promise;this.setAndEmitConnectionState(ct.Connecting),((l=this.regionUrlProvider)===null||l===void 0?void 0:l.getServerUrl().toString())!==a&&(this.regionUrl=void 0,this.regionUrlProvider=void 0),Lc(new URL(a))&&(this.regionUrlProvider===void 0?this.regionUrlProvider=new al(a,o):this.regionUrlProvider.updateToken(o),this.regionUrlProvider.fetchRegionSettings().then(f=>{var g;(g=this.regionUrlProvider)===null||g===void 0||g.setServerReportedRegions(f)}).catch(f=>{this.log.warn("could not fetch region settings",Object.assign(Object.assign({},this.logContext),{error:f}))}));const u=(f,g,v)=>P(this,void 0,void 0,function*(){var m,p;this.abortController&&this.abortController.abort();const x=new AbortController;this.abortController=x,d==null||d();try{yield this.attemptConnection(v??a,o,c,x),this.abortController=void 0,f()}catch(C){if(this.regionUrlProvider&&C instanceof _t&&C.reason!==tt.Cancelled&&C.reason!==tt.NotAllowed){let b=null;try{b=yield this.regionUrlProvider.getNextBestRegionUrl((m=this.abortController)===null||m===void 0?void 0:m.signal)}catch(S){if(S instanceof _t&&(S.status===401||S.reason===tt.Cancelled)){this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),g(S);return}}b&&!(!((p=this.abortController)===null||p===void 0)&&p.signal.aborted)?(this.log.info("Initial connection failed with ConnectionError: ".concat(C.message,". Retrying with another region: ").concat(b),this.logContext),this.recreateEngine(),yield u(f,g,b)):(this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,Af(C)),g(C))}else{let b=In.UNKNOWN_REASON;C instanceof _t&&(b=Af(C)),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,b),g(C)}}}),h=this.regionUrl;return this.regionUrl=void 0,this.connectFuture=new Zn((f,g)=>{u(f,g,h)},()=>{this.clearConnectionFutures()}),this.connectFuture.promise}),this.connectSignal=(a,o,c,l,d,u)=>P(this,void 0,void 0,function*(){var h,f,g;const v=yield c.join(a,o,{autoSubscribe:l.autoSubscribe,adaptiveStream:typeof d.adaptiveStream=="object"?!0:d.adaptiveStream,maxRetries:l.maxRetries,e2eeEnabled:!!this.e2eeManager,websocketTimeout:l.websocketTimeout},u.signal);let m=v.serverInfo;if(m||(m={version:v.serverVersion,region:v.serverRegion}),this.serverInfo=m,this.log.debug("connected to Livekit Server ".concat(Object.entries(m).map(p=>{let[x,C]=p;return"".concat(x,": ").concat(C)}).join(", ")),{room:(h=v.room)===null||h===void 0?void 0:h.name,roomSid:(f=v.room)===null||f===void 0?void 0:f.sid,identity:(g=v.participant)===null||g===void 0?void 0:g.identity}),!m.version)throw new b0("unknown server version");return m.version==="0.15.1"&&this.options.dynacast&&(this.log.debug("disabling dynacast due to server version",this.logContext),d.dynacast=!1),v}),this.applyJoinResponse=a=>{const o=a.participant;if(this.localParticipant.sid=o.sid,this.localParticipant.identity=o.identity,this.localParticipant.setEnabledPublishCodecs(a.enabledPublishCodecs),this.options.e2ee&&this.e2eeManager)try{this.e2eeManager.setSifTrailer(a.sifTrailer)}catch(c){this.log.error(c instanceof Error?c.message:"Could not set SifTrailer",Object.assign(Object.assign({},this.logContext),{error:c}))}this.handleParticipantUpdates([o,...a.otherParticipants]),a.room&&this.handleRoomUpdate(a.room)},this.attemptConnection=(a,o,c,l)=>P(this,void 0,void 0,function*(){var d,u;this.state===ct.Reconnecting||this.isResuming||!((d=this.engine)===null||d===void 0)&&d.pendingReconnect?(this.log.info("Reconnection attempt replaced by new connection attempt",this.logContext),this.recreateEngine()):this.maybeCreateEngine(),!((u=this.regionUrlProvider)===null||u===void 0)&&u.isCloud()&&this.engine.setRegionUrlProvider(this.regionUrlProvider),this.acquireAudioContext(),this.connOptions=Object.assign(Object.assign({},Zc),c),this.connOptions.rtcConfig&&(this.engine.rtcConfig=this.connOptions.rtcConfig),this.connOptions.peerConnectionTimeout&&(this.engine.peerConnectionTimeout=this.connOptions.peerConnectionTimeout);try{const h=yield this.connectSignal(a,o,this.engine,this.connOptions,this.options,l);this.applyJoinResponse(h),this.setupLocalParticipantEvents(),this.emit(ie.SignalConnected)}catch(h){yield this.engine.close(),this.recreateEngine();const f=new _t("could not establish signal connection",tt.ServerUnreachable);throw h instanceof Error&&(f.message="".concat(f.message,": ").concat(h.message)),h instanceof _t&&(f.reason=h.reason,f.status=h.status),this.log.debug("error trying to establish signal connection",Object.assign(Object.assign({},this.logContext),{error:h})),f}if(l.signal.aborted)throw yield this.engine.close(),this.recreateEngine(),new _t("Connection attempt aborted",tt.Cancelled);try{yield this.engine.waitForPCInitialConnection(this.connOptions.peerConnectionTimeout,l)}catch(h){throw yield this.engine.close(),this.recreateEngine(),h}dn()&&this.options.disconnectOnPageLeave&&(window.addEventListener("pagehide",this.onPageLeave),window.addEventListener("beforeunload",this.onPageLeave)),dn()&&document.addEventListener("freeze",this.onPageLeave),this.setAndEmitConnectionState(ct.Connected),this.emit(ie.Connected),this.registerConnectionReconcile()}),this.disconnect=function(){for(var a=arguments.length,o=new Array(a),c=0;c<a;c++)o[c]=arguments[c];return P(t,[...o],void 0,function(){var l=this;let d=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){var u,h,f,g;const v=yield l.disconnectLock.lock();try{if(l.state===ct.Disconnected){l.log.debug("already disconnected",l.logContext);return}l.log.info("disconnect from room",Object.assign({},l.logContext)),(l.state===ct.Connecting||l.state===ct.Reconnecting||l.isResuming)&&(l.log.warn("abort connection attempt",l.logContext),(u=l.abortController)===null||u===void 0||u.abort(),(f=(h=l.connectFuture)===null||h===void 0?void 0:h.reject)===null||f===void 0||f.call(h,new _t("Client initiated disconnect",tt.Cancelled)),l.connectFuture=void 0),!((g=l.engine)===null||g===void 0)&&g.client.isDisconnected||(yield l.engine.client.sendLeave()),l.engine&&(yield l.engine.close()),l.handleDisconnect(d,In.CLIENT_INITIATED),l.engine=void 0}finally{v()}}()})},this.onPageLeave=()=>P(this,void 0,void 0,function*(){this.log.info("Page leave detected, disconnecting",this.logContext),yield this.disconnect()}),this.startAudio=()=>P(this,void 0,void 0,function*(){const a=[],o=bn();if(o&&o.os==="iOS"){const c="livekit-dummy-audio-el";let l=document.getElementById(c);if(!l){l=document.createElement("audio"),l.id=c,l.autoplay=!0,l.hidden=!0;const d=Oc();d.enabled=!0;const u=new MediaStream([d]);l.srcObject=u,document.addEventListener("visibilitychange",()=>{l&&(l.srcObject=document.hidden?null:u,document.hidden||(this.log.debug("page visible again, triggering startAudio to resume playback and update playback status",this.logContext),this.startAudio()))}),document.body.append(l),this.once(ie.Disconnected,()=>{l==null||l.remove(),l=null})}a.push(l)}this.remoteParticipants.forEach(c=>{c.audioTrackPublications.forEach(l=>{l.track&&l.track.attachedElements.forEach(d=>{a.push(d)})})});try{yield Promise.all([this.acquireAudioContext(),...a.map(c=>(c.muted=!1,c.play()))]),this.handleAudioPlaybackStarted()}catch(c){throw this.handleAudioPlaybackFailed(c),c}}),this.startVideo=()=>P(this,void 0,void 0,function*(){const a=[];for(const o of this.remoteParticipants.values())o.videoTrackPublications.forEach(c=>{var l;(l=c.track)===null||l===void 0||l.attachedElements.forEach(d=>{a.includes(d)||a.push(d)})});yield Promise.all(a.map(o=>o.play())).then(()=>{this.handleVideoPlaybackStarted()}).catch(o=>{o.name==="NotAllowedError"?this.handleVideoPlaybackFailed():this.log.warn("Resuming video playback failed, make sure you call `startVideo` directly in a user gesture handler",this.logContext)})}),this.handleRestarting=()=>{this.clearConnectionReconcile(),this.isResuming=!1;for(const a of this.remoteParticipants.values())this.handleParticipantDisconnected(a.identity,a);this.setAndEmitConnectionState(ct.Reconnecting)&&this.emit(ie.Reconnecting)},this.handleSignalRestarted=a=>P(this,void 0,void 0,function*(){this.log.debug("signal reconnected to server, region ".concat(a.serverRegion),Object.assign(Object.assign({},this.logContext),{region:a.serverRegion})),this.bufferedEvents=[],this.applyJoinResponse(a);try{yield this.localParticipant.republishAllTracks(void 0,!0)}catch(o){this.log.error("error trying to re-publish tracks after reconnection",Object.assign(Object.assign({},this.logContext),{error:o}))}try{yield this.engine.waitForRestarted(),this.log.debug("fully reconnected to server",Object.assign(Object.assign({},this.logContext),{region:a.serverRegion}))}catch{return}this.setAndEmitConnectionState(ct.Connected),this.emit(ie.Reconnected),this.registerConnectionReconcile(),this.emitBufferedEvents()}),this.handleParticipantUpdates=a=>{a.forEach(o=>{var c;if(o.identity===this.localParticipant.identity){this.localParticipant.updateInfo(o);return}o.identity===""&&(o.identity=(c=this.sidToIdentity.get(o.sid))!==null&&c!==void 0?c:"");let l=this.remoteParticipants.get(o.identity);o.state===Ds.DISCONNECTED?this.handleParticipantDisconnected(o.identity,l):l=this.getOrCreateParticipant(o.identity,o)})},this.handleActiveSpeakersUpdate=a=>{const o=[],c={};a.forEach(l=>{if(c[l.sid]=!0,l.sid===this.localParticipant.sid)this.localParticipant.audioLevel=l.level,this.localParticipant.setIsSpeaking(!0),o.push(this.localParticipant);else{const d=this.getRemoteParticipantBySid(l.sid);d&&(d.audioLevel=l.level,d.setIsSpeaking(!0),o.push(d))}}),c[this.localParticipant.sid]||(this.localParticipant.audioLevel=0,this.localParticipant.setIsSpeaking(!1)),this.remoteParticipants.forEach(l=>{c[l.sid]||(l.audioLevel=0,l.setIsSpeaking(!1))}),this.activeSpeakers=o,this.emitWhenConnected(ie.ActiveSpeakersChanged,o)},this.handleSpeakersChanged=a=>{const o=new Map;this.activeSpeakers.forEach(l=>{const d=this.remoteParticipants.get(l.identity);d&&d.sid!==l.sid||o.set(l.sid,l)}),a.forEach(l=>{let d=this.getRemoteParticipantBySid(l.sid);l.sid===this.localParticipant.sid&&(d=this.localParticipant),d&&(d.audioLevel=l.level,d.setIsSpeaking(l.active),l.active?o.set(l.sid,d):o.delete(l.sid))});const c=Array.from(o.values());c.sort((l,d)=>d.audioLevel-l.audioLevel),this.activeSpeakers=c,this.emitWhenConnected(ie.ActiveSpeakersChanged,c)},this.handleStreamStateUpdate=a=>{a.streamStates.forEach(o=>{const c=this.getRemoteParticipantBySid(o.participantSid);if(!c)return;const l=c.getTrackPublicationBySid(o.trackSid);if(!l||!l.track)return;const d=Q.streamStateFromProto(o.state);l.track.setStreamState(d),d!==l.track.streamState&&(c.emit(le.TrackStreamStateChanged,l,l.track.streamState),this.emitWhenConnected(ie.TrackStreamStateChanged,l,l.track.streamState,c))})},this.handleSubscriptionPermissionUpdate=a=>{const o=this.getRemoteParticipantBySid(a.participantSid);if(!o)return;const c=o.getTrackPublicationBySid(a.trackSid);c&&c.setAllowed(a.allowed)},this.handleSubscriptionError=a=>{const o=Array.from(this.remoteParticipants.values()).find(l=>l.trackPublications.has(a.trackSid));if(!o)return;const c=o.getTrackPublicationBySid(a.trackSid);c&&c.setSubscriptionError(a.err)},this.handleDataPacket=a=>{const o=this.remoteParticipants.get(a.participantIdentity);if(a.value.case==="user")this.handleUserPacket(o,a.value.value,a.kind);else if(a.value.case==="transcription")this.handleTranscription(o,a.value.value);else if(a.value.case==="sipDtmf")this.handleSipDtmf(o,a.value.value);else if(a.value.case==="chatMessage")this.handleChatMessage(o,a.value.value);else if(a.value.case==="metrics")this.handleMetrics(a.value.value,o);else if(a.value.case==="streamHeader"||a.value.case==="streamChunk"||a.value.case==="streamTrailer")this.handleDataStream(a);else if(a.value.case==="rpcRequest"){const c=a.value.value;this.handleIncomingRpcRequest(a.participantIdentity,c.id,c.method,c.payload,c.responseTimeoutMs,c.version)}},this.handleUserPacket=(a,o,c)=>{this.emit(ie.DataReceived,o.payload,a,c,o.topic),a==null||a.emit(le.DataReceived,o.payload,c)},this.handleSipDtmf=(a,o)=>{this.emit(ie.SipDTMFReceived,o,a),a==null||a.emit(le.SipDTMFReceived,o)},this.handleTranscription=(a,o)=>{const c=o.transcribedParticipantIdentity===this.localParticipant.identity?this.localParticipant:this.getParticipantByIdentity(o.transcribedParticipantIdentity),l=c==null?void 0:c.trackPublications.get(o.trackId),d=G0(o,this.transcriptionReceivedTimes);l==null||l.emit(oe.TranscriptionReceived,d),c==null||c.emit(le.TranscriptionReceived,d,l),this.emit(ie.TranscriptionReceived,d,c,l)},this.handleChatMessage=(a,o)=>{const c=H0(o);this.emit(ie.ChatMessage,c,a)},this.handleMetrics=(a,o)=>{this.emit(ie.MetricsReceived,a,o)},this.handleDataStream=a=>{this.incomingDataStreamManager.handleDataStreamPacket(a)},this.bufferedSegments=new Map,this.handleAudioPlaybackStarted=()=>{this.canPlaybackAudio||(this.audioEnabled=!0,this.emit(ie.AudioPlaybackStatusChanged,!0))},this.handleAudioPlaybackFailed=a=>{this.log.warn("could not playback audio",Object.assign(Object.assign({},this.logContext),{error:a})),this.canPlaybackAudio&&(this.audioEnabled=!1,this.emit(ie.AudioPlaybackStatusChanged,!1))},this.handleVideoPlaybackStarted=()=>{this.isVideoPlaybackBlocked&&(this.isVideoPlaybackBlocked=!1,this.emit(ie.VideoPlaybackStatusChanged,!0))},this.handleVideoPlaybackFailed=()=>{this.isVideoPlaybackBlocked||(this.isVideoPlaybackBlocked=!0,this.emit(ie.VideoPlaybackStatusChanged,!1))},this.handleDeviceChange=()=>P(this,void 0,void 0,function*(){var a;((a=bn())===null||a===void 0?void 0:a.os)!=="iOS"&&(yield this.selectDefaultDevices()),this.emit(ie.MediaDevicesChanged)}),this.handleRoomUpdate=a=>{const o=this.roomInfo;this.roomInfo=a,o&&o.metadata!==a.metadata&&this.emitWhenConnected(ie.RoomMetadataChanged,a.metadata),(o==null?void 0:o.activeRecording)!==a.activeRecording&&this.emitWhenConnected(ie.RecordingStatusChanged,a.activeRecording)},this.handleConnectionQualityUpdate=a=>{a.updates.forEach(o=>{if(o.participantSid===this.localParticipant.sid){this.localParticipant.setConnectionQuality(o.quality);return}const c=this.getRemoteParticipantBySid(o.participantSid);c&&c.setConnectionQuality(o.quality)})},this.onLocalParticipantMetadataChanged=a=>{this.emit(ie.ParticipantMetadataChanged,a,this.localParticipant)},this.onLocalParticipantNameChanged=a=>{this.emit(ie.ParticipantNameChanged,a,this.localParticipant)},this.onLocalAttributesChanged=a=>{this.emit(ie.ParticipantAttributesChanged,a,this.localParticipant)},this.onLocalTrackMuted=a=>{this.emit(ie.TrackMuted,a,this.localParticipant)},this.onLocalTrackUnmuted=a=>{this.emit(ie.TrackUnmuted,a,this.localParticipant)},this.onTrackProcessorUpdate=a=>{var o;(o=a==null?void 0:a.onPublish)===null||o===void 0||o.call(a,this)},this.onLocalTrackPublished=a=>P(this,void 0,void 0,function*(){var o,c,l,d,u,h;(o=a.track)===null||o===void 0||o.on(oe.TrackProcessorUpdate,this.onTrackProcessorUpdate),(c=a.track)===null||c===void 0||c.on(oe.Restarted,this.onLocalTrackRestarted),(u=(d=(l=a.track)===null||l===void 0?void 0:l.getProcessor())===null||d===void 0?void 0:d.onPublish)===null||u===void 0||u.call(d,this),this.emit(ie.LocalTrackPublished,a,this.localParticipant),vi(a.track)&&(yield a.track.checkForSilence())&&this.emit(ie.LocalAudioSilenceDetected,a);const f=yield(h=a.track)===null||h===void 0?void 0:h.getDeviceId(!1),g=Hc(a.source);g&&f&&f!==this.localParticipant.activeDeviceMap.get(g)&&(this.localParticipant.activeDeviceMap.set(g,f),this.emit(ie.ActiveDeviceChanged,g,f))}),this.onLocalTrackUnpublished=a=>{var o,c;(o=a.track)===null||o===void 0||o.off(oe.TrackProcessorUpdate,this.onTrackProcessorUpdate),(c=a.track)===null||c===void 0||c.off(oe.Restarted,this.onLocalTrackRestarted),this.emit(ie.LocalTrackUnpublished,a,this.localParticipant)},this.onLocalTrackRestarted=a=>P(this,void 0,void 0,function*(){const o=yield a.getDeviceId(!1),c=Hc(a.source);c&&o&&o!==this.localParticipant.activeDeviceMap.get(c)&&(this.log.debug("local track restarted, setting ".concat(c," ").concat(o," active"),this.logContext),this.localParticipant.activeDeviceMap.set(c,o),this.emit(ie.ActiveDeviceChanged,c,o))}),this.onLocalConnectionQualityChanged=a=>{this.emit(ie.ConnectionQualityChanged,a,this.localParticipant)},this.onMediaDevicesError=(a,o)=>{this.emit(ie.MediaDevicesError,a,o)},this.onLocalParticipantPermissionsChanged=a=>{this.emit(ie.ParticipantPermissionsChanged,a,this.localParticipant)},this.onLocalChatMessageSent=a=>{this.emit(ie.ChatMessage,a,this.localParticipant)},this.setMaxListeners(100),this.remoteParticipants=new Map,this.sidToIdentity=new Map,this.options=Object.assign(Object.assign({},gb),e),this.log=fi((n=this.options.loggerName)!==null&&n!==void 0?n:Ln.Room),this.transcriptionReceivedTimes=new Map,this.options.audioCaptureDefaults=Object.assign(Object.assign({},Wf),e==null?void 0:e.audioCaptureDefaults),this.options.videoCaptureDefaults=Object.assign(Object.assign({},qf),e==null?void 0:e.videoCaptureDefaults),this.options.publishDefaults=Object.assign(Object.assign({},mb),e==null?void 0:e.publishDefaults),this.maybeCreateEngine(),this.incomingDataStreamManager=new Wb,this.outgoingDataStreamManager=new jb(this.engine,this.log),this.disconnectLock=new an,this.localParticipant=new ty("","",this.engine,this.options,this.rpcHandlers,this.outgoingDataStreamManager),this.options.videoCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("videoinput",Vi(this.options.videoCaptureDefaults.deviceId)),this.options.audioCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("audioinput",Vi(this.options.audioCaptureDefaults.deviceId)),!((s=this.options.audioOutput)===null||s===void 0)&&s.deviceId&&this.switchActiveDevice("audiooutput",Vi(this.options.audioOutput.deviceId)).catch(a=>this.log.warn("Could not set audio output: ".concat(a.message),this.logContext)),this.options.e2ee&&this.setupE2EE(),dn()){const a=new AbortController;(r=navigator.mediaDevices)===null||r===void 0||r.addEventListener("devicechange",this.handleDeviceChange,{signal:a.signal}),Gs.cleanupRegistry&&Gs.cleanupRegistry.register(this,()=>{a.abort()})}}registerTextStreamHandler(e,t){return this.incomingDataStreamManager.registerTextStreamHandler(e,t)}unregisterTextStreamHandler(e){return this.incomingDataStreamManager.unregisterTextStreamHandler(e)}registerByteStreamHandler(e,t){return this.incomingDataStreamManager.registerByteStreamHandler(e,t)}unregisterByteStreamHandler(e){return this.incomingDataStreamManager.unregisterByteStreamHandler(e)}registerRpcMethod(e,t){if(this.rpcHandlers.has(e))throw Error("RPC handler already registered for method ".concat(e,", unregisterRpcMethod before trying to register again"));this.rpcHandlers.set(e,t)}unregisterRpcMethod(e){this.rpcHandlers.delete(e)}setE2EEEnabled(e){return P(this,void 0,void 0,function*(){if(this.e2eeManager)yield Promise.all([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")})}setupE2EE(){var e;this.options.e2ee&&("e2eeManager"in this.options.e2ee?this.e2eeManager=this.options.e2ee.e2eeManager:this.e2eeManager=new eb(this.options.e2ee),this.e2eeManager.on(Bi.ParticipantEncryptionStatusChanged,(t,n)=>{q0(n)&&(this.isE2EEEnabled=t),this.emit(ie.ParticipantEncryptionStatusChanged,t,n)}),this.e2eeManager.on(Bi.EncryptionError,t=>this.emit(ie.EncryptionError,t)),(e=this.e2eeManager)===null||e===void 0||e.setup(this))}get logContext(){var e;return{room:this.name,roomID:(e=this.roomInfo)===null||e===void 0?void 0:e.sid,participant:this.localParticipant.identity,pID:this.localParticipant.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 P(this,void 0,void 0,function*(){return this.state===ct.Disconnected?"":this.roomInfo&&this.roomInfo.sid!==""?this.roomInfo.sid:new Promise((e,t)=>{const n=s=>{s.sid!==""&&(this.engine.off(de.RoomUpdate,n),e(s.sid))};this.engine.on(de.RoomUpdate,n),this.once(ie.Disconnected,()=>{this.engine.off(de.RoomUpdate,n),t("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.isClosed||(this.engine=new Fb(this.options),this.engine.on(de.ParticipantUpdate,this.handleParticipantUpdates).on(de.RoomUpdate,this.handleRoomUpdate).on(de.SpeakersChanged,this.handleSpeakersChanged).on(de.StreamStateChanged,this.handleStreamStateUpdate).on(de.ConnectionQualityUpdate,this.handleConnectionQualityUpdate).on(de.SubscriptionError,this.handleSubscriptionError).on(de.SubscriptionPermissionUpdate,this.handleSubscriptionPermissionUpdate).on(de.MediaTrackAdded,(e,t,n)=>{this.onTrackAdded(e,t,n)}).on(de.Disconnected,e=>{this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e)}).on(de.ActiveSpeakersUpdate,this.handleActiveSpeakersUpdate).on(de.DataPacketReceived,this.handleDataPacket).on(de.Resuming,()=>{this.clearConnectionReconcile(),this.isResuming=!0,this.log.info("Resuming signal connection",this.logContext),this.setAndEmitConnectionState(ct.SignalReconnecting)&&this.emit(ie.SignalReconnecting)}).on(de.Resumed,()=>{this.registerConnectionReconcile(),this.isResuming=!1,this.log.info("Resumed signal connection",this.logContext),this.updateSubscriptions(),this.emitBufferedEvents(),this.setAndEmitConnectionState(ct.Connected)&&this.emit(ie.Reconnected)}).on(de.SignalResumed,()=>{this.bufferedEvents=[],(this.state===ct.Reconnecting||this.isResuming)&&this.sendSyncState()}).on(de.Restarting,this.handleRestarting).on(de.SignalRestarted,this.handleSignalRestarted).on(de.Offline,()=>{this.setAndEmitConnectionState(ct.Reconnecting)&&this.emit(ie.Reconnecting)}).on(de.DCBufferStatusChanged,(e,t)=>{this.emit(ie.DCBufferStatusChanged,e,t)}).on(de.LocalTrackSubscribed,e=>{const t=this.localParticipant.getTrackPublications().find(n=>{let{trackSid:s}=n;return s===e});if(!t){this.log.warn("could not find local track subscription for subscribed event",this.logContext);return}this.localParticipant.emit(le.LocalTrackSubscribed,t),this.emitWhenConnected(ie.LocalTrackSubscribed,t,this.localParticipant)}).on(de.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(ie.Moved,e.room.name),e.participant?this.handleParticipantUpdates([e.participant,...e.otherParticipants]):this.handleParticipantUpdates(e.otherParticipants)}),this.localParticipant&&this.localParticipant.setupEngine(this.engine),this.e2eeManager&&this.e2eeManager.setupEngine(this.engine),this.outgoingDataStreamManager&&this.outgoingDataStreamManager.setupEngine(this.engine))}static getLocalDevices(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return $t.getInstance().getDevices(e,t)}prepareConnection(e,t){return P(this,void 0,void 0,function*(){if(this.state===ct.Disconnected){this.log.debug("prepareConnection to ".concat(e),this.logContext);try{if(Lc(new URL(e))&&t){this.regionUrlProvider=new al(e,t);const n=yield this.regionUrlProvider.getNextBestRegionUrl();n&&this.state===ct.Disconnected&&(this.regionUrl=n,yield fetch(Fc(n),{method:"HEAD"}),this.log.debug("prepared connection to ".concat(n),this.logContext))}else yield fetch(Fc(e),{method:"HEAD"})}catch(n){this.log.warn("could not prepare connection",Object.assign(Object.assign({},this.logContext),{error:n}))}}})}getParticipantByIdentity(e){return this.localParticipant.identity===e?this.localParticipant:this.remoteParticipants.get(e)}clearConnectionFutures(){this.connectFuture=void 0}simulateScenario(e,t){return P(this,void 0,void 0,function*(){let n=()=>{},s;switch(e){case"signal-reconnect":yield this.engine.client.handleOnClose("simulate disconnect");break;case"speaker":s=new jn({scenario:{case:"speakerUpdate",value:3}});break;case"node-failure":s=new jn({scenario:{case:"nodeFailure",value:!0}});break;case"server-leave":s=new jn({scenario:{case:"serverLeave",value:!0}});break;case"migration":s=new jn({scenario:{case:"migration",value:!0}});break;case"resume-reconnect":this.engine.failNext(),yield this.engine.client.handleOnClose("simulate resume-disconnect");break;case"disconnect-signal-on-resume":n=()=>P(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),s=new jn({scenario:{case:"disconnectSignalOnResume",value:!0}});break;case"disconnect-signal-on-resume-no-messages":n=()=>P(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),s=new jn({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 jn({scenario:{case:"switchCandidateProtocol",value:e==="force-tls"?2:1}}),n=()=>P(this,void 0,void 0,function*(){const r=this.engine.client.onLeave;r&&r(new Pa({reason:In.CLIENT_INITIATED,action:Us.RECONNECT}))});break;case"subscriber-bandwidth":if(t===void 0||typeof t!="number")throw new Error("subscriber-bandwidth requires a number as argument");s=new jn({scenario:{case:"subscriberBandwidth",value:ds(t)}});break;case"leave-full-reconnect":s=new jn({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 P(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,c,l,d,u,h,f;let g=!0,v=!1;const m=a?{exact:s}:s;if(n==="audioinput"){v=r.localParticipant.audioTrackPublications.size===0;const p=(o=r.getActiveDevice(n))!==null&&o!==void 0?o:r.options.audioCaptureDefaults.deviceId;r.options.audioCaptureDefaults.deviceId=m;const x=Array.from(r.localParticipant.audioTrackPublications.values()).filter(b=>b.source===Q.Source.Microphone);try{g=(yield Promise.all(x.map(b=>{var S;return(S=b.audioTrack)===null||S===void 0?void 0:S.setDeviceId(m)}))).every(b=>b===!0)}catch(b){throw r.options.audioCaptureDefaults.deviceId=p,b}const C=x.some(b=>{var S,M;return(M=(S=b.track)===null||S===void 0?void 0:S.isMuted)!==null&&M!==void 0?M:!1});g&&C&&(v=!0)}else if(n==="videoinput"){v=r.localParticipant.videoTrackPublications.size===0;const p=(c=r.getActiveDevice(n))!==null&&c!==void 0?c:r.options.videoCaptureDefaults.deviceId;r.options.videoCaptureDefaults.deviceId=m;const x=Array.from(r.localParticipant.videoTrackPublications.values()).filter(b=>b.source===Q.Source.Camera);try{g=(yield Promise.all(x.map(b=>{var S;return(S=b.videoTrack)===null||S===void 0?void 0:S.setDeviceId(m)}))).every(b=>b===!0)}catch(b){throw r.options.videoCaptureDefaults.deviceId=p,b}const C=x.some(b=>{var S,M;return(M=(S=b.track)===null||S===void 0?void 0:S.isMuted)!==null&&M!==void 0?M:!1});g&&C&&(v=!0)}else if(n==="audiooutput"){if(v=!0,!Dc()&&!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=(l=yield $t.getInstance().normalizeDeviceId("audiooutput",s))!==null&&l!==void 0?l:""),(d=(f=r.options).audioOutput)!==null&&d!==void 0||(f.audioOutput={});const p=(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(x=>x.setAudioOutput({deviceId:s})))}catch(x){throw r.options.audioOutput.deviceId=p,x}}return v&&(r.localParticipant.activeDeviceMap.set(n,s),r.emit(ie.ActiveDeviceChanged,n,s)),g}()})}setupLocalParticipantEvents(){this.localParticipant.on(le.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).on(le.ParticipantNameChanged,this.onLocalParticipantNameChanged).on(le.AttributesChanged,this.onLocalAttributesChanged).on(le.TrackMuted,this.onLocalTrackMuted).on(le.TrackUnmuted,this.onLocalTrackUnmuted).on(le.LocalTrackPublished,this.onLocalTrackPublished).on(le.LocalTrackUnpublished,this.onLocalTrackUnpublished).on(le.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).on(le.MediaDevicesError,this.onMediaDevicesError).on(le.AudioStreamAcquired,this.startAudio).on(le.ChatMessage,this.onLocalChatMessageSent).on(le.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged)}recreateEngine(){var e;(e=this.engine)===null||e===void 0||e.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===ct.Connecting||this.state===ct.Reconnecting){const u=()=>{this.onTrackAdded(e,t,n),h()},h=()=>{this.off(ie.Reconnected,u),this.off(ie.Connected,u),this.off(ie.Disconnected,h)};this.once(ie.Reconnected,u),this.once(ie.Connected,u),this.once(ie.Disconnected,h);return}if(this.state===ct.Disconnected){this.log.warn("skipping incoming track after Room disconnected",this.logContext);return}if(e.readyState==="ended"){this.log.info("skipping incoming track as it already ended",this.logContext);return}const s=P0(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",this.logContext);return}const c=Array.from(this.remoteParticipants.values()).find(u=>u.sid===r);if(!c){this.log.error("Tried to add a track for a participant, that's not present. Sid: ".concat(r),this.logContext);return}let l;this.options.adaptiveStream&&(typeof this.options.adaptiveStream=="object"?l=this.options.adaptiveStream:l={});const d=c.addSubscribedMediaTrack(e,o,t,n,l);d!=null&&d.isEncrypted&&!this.e2eeManager&&this.emit(ie.EncryptionError,new Error("Encrypted ".concat(d.source," track received from participant ").concat(c.sid,", but room does not have encryption enabled!")))}handleDisconnect(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0,t=arguments.length>1?arguments[1]:void 0;var n;if(this.clearConnectionReconcile(),this.isResuming=!1,this.bufferedEvents=[],this.transcriptionReceivedTimes.clear(),this.incomingDataStreamManager.clearHandlersAndControllers(),this.state!==ct.Disconnected){this.regionUrl=void 0;try{this.remoteParticipants.forEach(s=>{s.trackPublications.forEach(r=>{s.unpublishTrack(r.trackSid)})}),this.localParticipant.trackPublications.forEach(s=>{var r,a,o;s.track&&this.localParticipant.unpublishTrack(s.track,e),e?((r=s.track)===null||r===void 0||r.detach(),(a=s.track)===null||a===void 0||a.stop()):(o=s.track)===null||o===void 0||o.stopMonitor()}),this.localParticipant.off(le.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).off(le.ParticipantNameChanged,this.onLocalParticipantNameChanged).off(le.AttributesChanged,this.onLocalAttributesChanged).off(le.TrackMuted,this.onLocalTrackMuted).off(le.TrackUnmuted,this.onLocalTrackUnmuted).off(le.LocalTrackPublished,this.onLocalTrackPublished).off(le.LocalTrackUnpublished,this.onLocalTrackUnpublished).off(le.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).off(le.MediaDevicesError,this.onMediaDevicesError).off(le.AudioStreamAcquired,this.startAudio).off(le.ChatMessage,this.onLocalChatMessageSent).off(le.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),dn()&&(window.removeEventListener("beforeunload",this.onPageLeave),window.removeEventListener("pagehide",this.onPageLeave),window.removeEventListener("freeze",this.onPageLeave),(n=navigator.mediaDevices)===null||n===void 0||n.removeEventListener("devicechange",this.handleDeviceChange))}finally{this.setAndEmitConnectionState(ct.Disconnected),this.emit(ie.Disconnected,t)}}}handleParticipantDisconnected(e,t){var n;this.remoteParticipants.delete(e),t&&(this.incomingDataStreamManager.validateParticipantHasNoActiveDataStreams(e),t.trackPublications.forEach(s=>{t.unpublishTrack(s.trackSid,!0)}),this.emit(ie.ParticipantDisconnected,t),t.setDisconnected(),(n=this.localParticipant)===null||n===void 0||n.handleParticipantDisconnected(t.identity))}handleIncomingRpcRequest(e,t,n,s,r,a){return P(this,void 0,void 0,function*(){if(yield this.engine.publishRpcAck(e,t),a!==1){yield this.engine.publishRpcResponse(e,t,null,kt.builtIn("UNSUPPORTED_VERSION"));return}const o=this.rpcHandlers.get(n);if(!o){yield this.engine.publishRpcResponse(e,t,null,kt.builtIn("UNSUPPORTED_METHOD"));return}let c=null,l=null;try{const d=yield o({requestId:t,callerIdentity:e,payload:s,responseTimeout:r});Qc(d)>$f?(c=kt.builtIn("RESPONSE_PAYLOAD_TOO_LARGE"),console.warn("RPC Response payload too large for ".concat(n))):l=d}catch(d){d instanceof kt?c=d:(console.warn("Uncaught error returned by RPC handler for ".concat(n,". Returning APPLICATION_ERROR instead."),d),c=kt.builtIn("APPLICATION_ERROR"))}yield this.engine.publishRpcResponse(e,t,l,c)})}selectDefaultDevices(){return P(this,void 0,void 0,function*(){var e,t,n;const s=$t.getInstance().previousDevices,r=yield $t.getInstance().getDevices(void 0,!1),a=bn();if((a==null?void 0:a.name)==="Chrome"&&a.os!=="iOS")for(let c of r){const l=s.find(d=>d.deviceId===c.deviceId);l&&l.label!==""&&l.kind===c.kind&&l.label!==c.label&&this.getActiveDevice(c.kind)==="default"&&this.emit(ie.ActiveDeviceChanged,c.kind,c.deviceId)}const o=["audiooutput","audioinput","videoinput"];for(let c of o){const l=j0(c),d=this.localParticipant.getTrackPublication(l);if(d&&(!((e=d.track)===null||e===void 0)&&e.isUserProvided))continue;const u=r.filter(f=>f.kind===c),h=this.getActiveDevice(c);if(h===((t=s.filter(f=>f.kind===c)[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(c,u[0].deviceId);continue}c==="audioinput"&&!Fr()||c==="videoinput"||u.length>0&&!u.find(f=>f.deviceId===this.getActiveDevice(c))&&(c!=="audiooutput"||!Fr())&&(yield this.switchActiveDevice(c,u[0].deviceId))}})}acquireAudioContext(){return P(this,void 0,void 0,function*(){var e,t;if(typeof this.options.webAudioMix!="boolean"&&this.options.webAudioMix.audioContext?this.audioContext=this.options.webAudioMix.audioContext:(!this.audioContext||this.audioContext.state==="closed")&&(this.audioContext=(e=kf())!==null&&e!==void 0?e:void 0),this.options.webAudioMix&&this.remoteParticipants.forEach(s=>s.setAudioContext(this.audioContext)),this.localParticipant.setAudioContext(this.audioContext),this.audioContext&&this.audioContext.state==="suspended")try{yield Promise.race([this.audioContext.resume(),ln(200)])}catch(s){this.log.warn("Could not resume audio context",Object.assign(Object.assign({},this.logContext),{error:s}))}const n=((t=this.audioContext)===null||t===void 0?void 0:t.state)==="running";n!==this.canPlaybackAudio&&(this.audioEnabled=n,this.emit(ie.AudioPlaybackStatusChanged,n))})}createParticipant(e,t){var n;let s;return t?s=ja.fromParticipantInfo(this.engine.client,t,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}):s=new ja(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),this.logContext)),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(ie.ParticipantConnected,n),n.on(le.TrackPublished,s=>{this.emitWhenConnected(ie.TrackPublished,s,n)}).on(le.TrackSubscribed,(s,r)=>{s.kind===Q.Kind.Audio?(s.on(oe.AudioPlaybackStarted,this.handleAudioPlaybackStarted),s.on(oe.AudioPlaybackFailed,this.handleAudioPlaybackFailed)):s.kind===Q.Kind.Video&&(s.on(oe.VideoPlaybackFailed,this.handleVideoPlaybackFailed),s.on(oe.VideoPlaybackStarted,this.handleVideoPlaybackStarted)),this.emit(ie.TrackSubscribed,s,r,n)}).on(le.TrackUnpublished,s=>{this.emit(ie.TrackUnpublished,s,n)}).on(le.TrackUnsubscribed,(s,r)=>{this.emit(ie.TrackUnsubscribed,s,r,n)}).on(le.TrackMuted,s=>{this.emitWhenConnected(ie.TrackMuted,s,n)}).on(le.TrackUnmuted,s=>{this.emitWhenConnected(ie.TrackUnmuted,s,n)}).on(le.ParticipantMetadataChanged,s=>{this.emitWhenConnected(ie.ParticipantMetadataChanged,s,n)}).on(le.ParticipantNameChanged,s=>{this.emitWhenConnected(ie.ParticipantNameChanged,s,n)}).on(le.AttributesChanged,s=>{this.emitWhenConnected(ie.ParticipantAttributesChanged,s,n)}).on(le.ConnectionQualityChanged,s=>{this.emitWhenConnected(ie.ConnectionQualityChanged,s,n)}).on(le.ParticipantPermissionsChanged,s=>{this.emitWhenConnected(ie.ParticipantPermissionsChanged,s,n)}).on(le.TrackSubscriptionStatusChanged,(s,r)=>{this.emitWhenConnected(ie.TrackSubscriptionStatusChanged,s,r,n)}).on(le.TrackSubscriptionFailed,(s,r)=>{this.emit(ie.TrackSubscriptionFailed,s,n,r)}).on(le.TrackSubscriptionPermissionChanged,(s,r)=>{this.emitWhenConnected(ie.TrackSubscriptionPermissionChanged,s,r,n)}).on(le.Active,()=>{this.emitWhenConnected(ie.ParticipantActive,n),n.kind===Ir.AGENT&&this.localParticipant.setActiveAgent(n)}),t&&n.updateInfo(t),n}sendSyncState(){const e=Array.from(this.remoteParticipants.values()).reduce((n,s)=>(n.push(...s.getTrackPublications()),n),[]),t=this.localParticipant.getTrackPublications();this.engine.sendSyncState(e,t)}updateSubscriptions(){for(const e of this.remoteParticipants.values())for(const t of e.videoTrackPublications.values())t.isSubscribed&&W0(t)&&t.emitTrackUpdate()}getRemoteParticipantBySid(e){const t=this.sidToIdentity.get(e);if(t)return this.remoteParticipants.get(t)}registerConnectionReconcile(){this.clearConnectionReconcile();let e=0;this.connectionReconcileInterval=Yt.setInterval(()=>{!this.engine||this.engine.isClosed||!this.engine.verifyTransport()?(e++,this.log.warn("detected connection state mismatch",Object.assign(Object.assign({},this.logContext),{numFailures:e,engine:this.engine?{closed:this.engine.isClosed,transportsConnected:this.engine.verifyTransport()}:void 0})),e>=3&&(this.recreateEngine(),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,In.STATE_MISMATCH))):e=0},iy)}clearConnectionReconcile(){this.connectionReconcileInterval&&Yt.clearInterval(this.connectionReconcileInterval)}setAndEmitConnectionState(e){return e===this.state?!1:(this.state=e,this.emit(ie.ConnectionStateChanged,this.state),!0)}emitBufferedEvents(){this.bufferedEvents.forEach(e=>{let[t,n]=e;this.emit(t,...n)}),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===ct.Reconnecting||this.isResuming||!this.engine||this.engine.pendingReconnect)this.bufferedEvents.push([e,n]);else if(this.state===ct.Connected)return this.emit(e,...n);return!1}simulateParticipants(e){return P(this,void 0,void 0,function*(){var t,n;const s=Object.assign({audio:!0,video:!0,useRealTracks:!1},e.publish),r=Object.assign({count:9,audio:!1,video:!0,aspectRatios:[1.66,1.7,1.3]},e.participants);if(this.handleDisconnect(),this.roomInfo=new wa({sid:"RM_SIMULATED",name:"simulated-room",emptyTimeout:0,maxParticipants:0,creationTime:At.parse(new Date().getTime()),metadata:"",numParticipants:1,numPublishers:1,turnPassword:"",enabledCodecs:[],activeRecording:!1}),this.localParticipant.updateInfo(new ss({identity:"simulated-local",name:"local-name"})),this.setupLocalParticipantEvents(),this.emit(ie.SignalConnected),this.emit(ie.Connected),this.setAndEmitConnectionState(ct.Connected),s.video){const a=new ll(Q.Kind.Video,new Ls({source:Ot.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:kn.AUDIO,name:"video-dummy"}),new qa(s.useRealTracks?(yield window.navigator.mediaDevices.getUserMedia({video:!0})).getVideoTracks()[0]:wf(160*((t=r.aspectRatios[0])!==null&&t!==void 0?t:1),160,!0,!0),void 0,!1,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(a),this.localParticipant.emit(le.LocalTrackPublished,a)}if(s.audio){const a=new ll(Q.Kind.Audio,new Ls({source:Ot.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:kn.AUDIO}),new Wa(s.useRealTracks?(yield navigator.mediaDevices.getUserMedia({audio:!0})).getAudioTracks()[0]:Oc(),void 0,!1,this.audioContext,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(a),this.localParticipant.emit(le.LocalTrackPublished,a)}for(let a=0;a<r.count-1;a+=1){let o=new ss({sid:Math.floor(Math.random()*1e4).toString(),identity:"simulated-".concat(a),state:Ds.ACTIVE,tracks:[],joinedAt:At.parse(Date.now())});const c=this.getOrCreateParticipant(o.identity,o);if(r.video){const l=wf(160*((n=r.aspectRatios[a%r.aspectRatios.length])!==null&&n!==void 0?n:1),160,!1,!0),d=new Ls({source:Ot.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:kn.AUDIO});c.addSubscribedMediaTrack(l,d.sid,new MediaStream([l]),new RTCRtpReceiver),o.tracks=[...o.tracks,d]}if(r.audio){const l=Oc(),d=new Ls({source:Ot.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:kn.AUDIO});c.addSubscribedMediaTrack(l,d.sid,new MediaStream([l]),new RTCRtpReceiver),o.tracks=[...o.tracks,d]}c.updateInfo(o)}})}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!==ie.ActiveSpeakersChanged&&e!==ie.TranscriptionReceived){const r=cp(n).filter(a=>a!==void 0);this.log.debug("room event ".concat(e),Object.assign(Object.assign({},this.logContext),{event:e,args:r}))}return super.emit(e,...n)}}Gs.cleanupRegistry=typeof FinalizationRegistry<"u"&&new FinalizationRegistry(i=>{i()});function cp(i){return i.map(e=>{if(e)return Array.isArray(e)?cp(e):typeof e=="object"?"logContext"in e?e.logContext:void 0:e})}var Fn;(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"})(Fn||(Fn={}));class $i extends Xn.EventEmitter{constructor(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.status=Fn.IDLE,this.logs=[],this.options={},this.url=e,this.token=t,this.name=this.constructor.name,this.room=new Gs(n.roomOptions),this.connectOptions=n.connectOptions,this.options=n}run(e){return P(this,void 0,void 0,function*(){if(this.status!==Fn.IDLE)throw Error("check is running already");this.setStatus(Fn.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!==Fn.SKIPPED&&this.setStatus(this.isSuccess()?Fn.SUCCESS:Fn.FAILED),e&&e(),this.getInfo()})}isSuccess(){return!this.logs.some(e=>e.level==="error")}connect(e){return P(this,void 0,void 0,function*(){return this.room.state===ct.Connected?this.room:(e||(e=this.url),yield this.room.connect(e,this.token,this.connectOptions),this.room)})}disconnect(){return P(this,void 0,void 0,function*(){this.room&&this.room.state!==ct.Disconnected&&(yield this.room.disconnect(),yield new Promise(e=>setTimeout(e,500)))})}skip(){this.setStatus(Fn.SKIPPED)}switchProtocol(e){return P(this,void 0,void 0,function*(){let t=!1,n=!1;if(this.room.on(ie.Reconnecting,()=>{t=!0}),this.room.once(ie.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 ln(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 sy extends $i{get description(){return"Cloud regions"}perform(){return P(this,void 0,void 0,function*(){const e=new al(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 P(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,c=1e6/a,l="A".repeat(a),d=Date.now();for(let g=0;g<c;g++)yield r.write(l);yield r.close();const u=Date.now(),h=yield(n=this.room.engine.pcManager)===null||n===void 0?void 0:n.publisher.getStats(),f={region:s,rtt:1e4,duration:u-d};return h==null||h.forEach(g=>{g.type==="candidate-pair"&&g.nominated&&(f.rtt=g.currentRoundTripTime*1e3)}),yield this.disconnect(),f})}}const dl=1e4;class ry extends $i{get description(){return"Connection via UDP vs TCP"}perform(){return P(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/(dl/1e3)*100).toFixed(2),"%")),n.qualityLimitationDurations.cpu>0&&this.appendWarning("cpu limited ".concat((n.qualityLimitationDurations.cpu/(dl/1e3)*100).toFixed(2),"%"))})}getInfo(){const e=super.getInfo();return e.data=this.bestStats,e}checkConnectionProtocol(e){return P(this,void 0,void 0,function*(){yield this.connect(),e==="tcp"?yield this.switchProtocol("tcp"):yield this.switchProtocol("udp");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],l=(yield this.room.localParticipant.publishTrack(o,{simulcast:!1,degradationPreference:"maintain-resolution",videoEncoding:{maxBitrate:2e6}})).track,d={protocol:e,packetsLost:0,packetsSent:0,qualityLimitationDurations:{},rttTotal:0,jitterTotal:0,bitrateTotal:0,count:0},u=setInterval(()=>P(this,void 0,void 0,function*(){const h=yield l.getRTCStatsReport();h==null||h.forEach(f=>{f.type==="outbound-rtp"?(d.packetsSent=f.packetsSent,d.qualityLimitationDurations=f.qualityLimitationDurations,d.bitrateTotal+=f.targetBitrate,d.count++):f.type==="remote-inbound-rtp"&&(d.packetsLost=f.packetsLost,d.rttTotal+=f.roundTripTime,d.jitterTotal+=f.jitter)})}),1e3);return yield new Promise(h=>setTimeout(h,dl)),clearInterval(u),o.stop(),t.remove(),yield this.disconnect(),d})}}class ay extends $i{get description(){return"Can publish audio"}perform(){return P(this,void 0,void 0,function*(){var e;const t=yield this.connect(),n=yield Zb();if(yield Pf(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 oy extends $i{get description(){return"Can publish video"}perform(){return P(this,void 0,void 0,function*(){var e;const t=yield this.connect(),n=yield Jb();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=>{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 P(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,yield new Promise(s=>{n.onplay=()=>{setTimeout(()=>{var r,a,o,c;const l=document.createElement("canvas"),d=e.getSettings(),u=(a=(r=d.width)!==null&&r!==void 0?r:n.videoWidth)!==null&&a!==void 0?a:1280,h=(c=(o=d.height)!==null&&o!==void 0?o:n.videoHeight)!==null&&c!==void 0?c:720;l.width=u,l.height=h;const f=l.getContext("2d");f.drawImage(n,0,0);const v=f.getImageData(0,0,l.width,l.height).data;let m=!0;for(let p=0;p<v.length;p+=4)if(v[p]!==0||v[p+1]!==0||v[p+2]!==0){m=!1;break}m?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 cy extends $i{get description(){return"Resuming connection after interruption"}perform(){return P(this,void 0,void 0,function*(){var e;const t=yield this.connect();let n=!1,s=!1,r;const a=new Promise(l=>{setTimeout(l,5e3),r=l}),o=()=>{n=!0};t.on(ie.SignalReconnecting,o).on(ie.Reconnecting,o).on(ie.Reconnected,()=>{s=!0,r(!0)}),(e=t.engine.client.ws)===null||e===void 0||e.close();const c=t.engine.client.onClose;if(c&&c(""),yield a,n){if(!s||t.state!==ct.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 ly extends $i{get description(){return"Can connect via TURN"}perform(){return P(this,void 0,void 0,function*(){var e,t;const n=new qc,s=yield n.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3});let r=!1,a=!1,o=!1;for(let c of s.iceServers)for(let l of c.urls)l.startsWith("turn:")?(a=!0,o=!0):l.startsWith("turns:")&&(a=!0,o=!0,r=!0),l.startsWith("stun:")&&(o=!0);o?a&&!r&&this.appendWarning("TURN is configured server side, but TURN/TLS is unavailable."):this.appendWarning("No STUN servers configured on server side."),yield n.close(),!((t=(e=this.connectOptions)===null||e===void 0?void 0:e.rtcConfig)===null||t===void 0)&&t.iceServers||a?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 dy extends $i{get description(){return"Establishing WebRTC connection"}perform(){return P(this,void 0,void 0,function*(){let e=!1,t=!1;this.room.on(ie.SignalConnected,()=>{const n=this.room.engine.client.onTrickle;this.room.engine.client.onTrickle=(s,r)=>{if(s.candidate){const a=new RTCIceCandidate(s);let o="".concat(a.protocol," ").concat(a.address,":").concat(a.port," ").concat(a.type);a.address&&(uy(a.address)?o+=" (private)":a.protocol==="tcp"&&a.tcpType==="passive"?(e=!0,o+=" (passive)"):a.protocol==="udp"&&(t=!0)),this.appendMessage(o)}n&&n(s,r)},this.room.engine.pcManager&&(this.room.engine.pcManager.subscriber.onIceCandidateError=s=>{s instanceof RTCPeerConnectionIceErrorEvent&&this.appendWarning("error with ICE candidate: ".concat(s.errorCode," ").concat(s.errorText," ").concat(s.url))})});try{yield this.connect(),Ke.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 uy(i){const e=i.split(".");if(e.length===4){if(e[0]==="10")return!0;if(e[0]==="192"&&e[1]==="168")return!0;if(e[0]==="172"){const t=parseInt(e[1],10);if(t>=16&&t<=31)return!0}}return!1}class hy extends $i{get description(){return"Connecting to signal connection via WebSocket"}perform(){return P(this,void 0,void 0,function*(){var e,t,n;(this.url.startsWith("ws:")||this.url.startsWith("http:"))&&this.appendWarning("Server is insecure, clients may block connections to it");let s=new qc;const r=yield s.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3});this.appendMessage("Connected to server, version ".concat(r.serverVersion,".")),((e=r.serverInfo)===null||e===void 0?void 0:e.edition)===ah.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)),yield s.close()})}}class wE extends Xn.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:Fn.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!==Fn.FAILED)}getResults(){return Array.from(this.checkResults.values())}createAndRunCheck(e){return P(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 P(this,void 0,void 0,function*(){return this.createAndRunCheck(hy)})}checkWebRTC(){return P(this,void 0,void 0,function*(){return this.createAndRunCheck(dy)})}checkTURN(){return P(this,void 0,void 0,function*(){return this.createAndRunCheck(ly)})}checkReconnect(){return P(this,void 0,void 0,function*(){return this.createAndRunCheck(cy)})}checkPublishAudio(){return P(this,void 0,void 0,function*(){return this.createAndRunCheck(ay)})}checkPublishVideo(){return P(this,void 0,void 0,function*(){return this.createAndRunCheck(oy)})}checkConnectionProtocol(){return P(this,void 0,void 0,function*(){const e=yield this.createAndRunCheck(ry);if(e.data&&"protocol"in e.data){const t=e.data;this.options.protocol=t.protocol}return e})}checkCloudRegion(){return P(this,void 0,void 0,function*(){return this.createAndRunCheck(sy)})}}class Hs{constructor(){this.audioContext=null,this.refCount=0,this.resumePromise=null}static getInstance(){return Hs.instance||(Hs.instance=new Hs),Hs.instance}async acquire(){if(this.refCount++,!this.audioContext)try{const e=window.AudioContext||window.webkitAudioContext;if(!e)return console.warn("[SharedAudioContext] Web Audio API not supported"),null;this.audioContext=new e,console.log("[SharedAudioContext] Created shared AudioContext")}catch(e){return console.warn("[SharedAudioContext] Failed to create AudioContext:",e),null}return await this.ensureResumed(),this.audioContext}release(){this.refCount=Math.max(0,this.refCount-1),this.refCount===0&&console.log("[SharedAudioContext] All references released, context kept alive for reuse")}forceClose(){if(this.audioContext){try{this.audioContext.close()}catch{}this.audioContext=null,this.refCount=0,console.log("[SharedAudioContext] Force closed")}}getContext(){return this.audioContext}async ensureResumed(){if(!this.audioContext)return!1;if(this.audioContext.state==="suspended"){this.resumePromise||(this.resumePromise=this.audioContext.resume().finally(()=>{this.resumePromise=null}));try{await this.resumePromise}catch{return!1}}return this.audioContext.state==="running"}isRunning(){return this.audioContext!==null&&this.audioContext.state==="running"}getState(){var e;return((e=this.audioContext)==null?void 0:e.state)??null}getSampleRate(){var e;return((e=this.audioContext)==null?void 0:e.sampleRate)??44100}getCurrentTime(){var e;return((e=this.audioContext)==null?void 0:e.currentTime)??0}getDestination(){var e;return((e=this.audioContext)==null?void 0:e.destination)??null}}const ei=Hs.getInstance();typeof window<"u"&&window.addEventListener("pagehide",()=>{ei.forceClose()});const pn=class pn extends EventTarget{constructor(){super(...arguments),this.room=null,this.callStatus="idle",this.isReady=!1,this.error=null,this.microphoneEnabled=!1,this.connectedParticipants=[],this.userIdentity="",this.roomName="",this.audioPlaybackPrompt=!1,this.isAppleDevice=/iPhone|iPad|iPod|Macintosh|Mac OS/i.test(navigator.userAgent),this.agentAudioElements=[],this.unmuteTimer=null,this.speakingHandler=null,this.fadeContext=null,this.fadeContextAcquired=!1,this.fadeGains=new Map,this.fadeSetupPromise=null}static isAgentIdentity(e){return e.includes("agent")||e.includes("voice-assistant")||e.includes("AJ_")}set serviceUrl(e){this._serviceUrl=e}get serviceUrl(){return this._serviceUrl??"https://voice.hanc.ai"}get status(){return this.callStatus}get ready(){return this.isReady}get currentError(){return this.error}get currentRoom(){return this.room}get isMicrophoneEnabled(){return this.microphoneEnabled}get participants(){return this.connectedParticipants}get identity(){return this.userIdentity}get roomNameValue(){return this.roomName}get showAudioPrompt(){return this.audioPlaybackPrompt}updateStatus(e){this.callStatus=e,this.dispatchEvent(new CustomEvent("status-changed",{detail:e}))}async makeCall({agentId:e,user_identity:t}){var n;if(!(this.room&&this.room.state==="connected")){this.updateStatus("connecting"),this.error=null,this.isReady=!1,this.room&&(await this.room.disconnect(),this.room=null);try{const s=new Gs({webAudioMix:!1,dynacast:!0,adaptiveStream:!0});this.room=s,this.setupRoomEventListeners(s);const r=await fetch(`${this.serviceUrl}/create-room-token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({metadata:{user_identity:t,agent_id:e,timestamp:Date.now(),is_apple_device:this.isAppleDevice}})});if(!r.ok){const u=await r.text();throw new Error(`Failed to get room token: ${r.status} ${u}`)}const{token:a,url:o,room_name:c,user_identity:l}=await r.json();this.roomName=c,this.userIdentity=l;const d={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0};await Promise.all([s.localParticipant.setMicrophoneEnabled(!0,d).then(()=>{this.microphoneEnabled=!0,this.dispatchEvent(new CustomEvent("microphone-enabled"))}).catch(u=>{console.warn("Could not enable microphone:",u),this.microphoneEnabled=!1,this.dispatchEvent(new CustomEvent("microphone-disabled"))}),s.connect(o,a)]),await new Promise(u=>{const h=setTimeout(()=>{s.off(ie.ParticipantConnected,f),u()},2e3),f=g=>{pn.isAgentIdentity(g.identity)&&(clearTimeout(h),s.off(ie.ParticipantConnected,f),u())};for(const g of s.remoteParticipants.values())if(pn.isAgentIdentity(g.identity)){clearTimeout(h),u();return}s.on(ie.ParticipantConnected,f)}),this.updateStatus("connected"),this.isReady=!0;for(const u of s.localParticipant.audioTrackPublications.values())(n=u.track)!=null&&n.mediaStreamTrack&&this.dispatchEvent(new CustomEvent("local-audio-track",{detail:u.track.mediaStreamTrack}));this.dispatchEvent(new CustomEvent("room-connected",{detail:{roomName:c,identity:l}}))}catch(s){this.error=`Connection failed: ${s instanceof Error?s.message:String(s)}`,this.updateStatus("error"),this.isReady=!1,this.room=null,this.dispatchEvent(new CustomEvent("error",{detail:{error:this.error}}))}}}setupRoomEventListeners(e){e.on(ie.Disconnected,()=>{this.callStatus!=="disconnected"&&this.updateStatus("disconnected"),this.connectedParticipants=[],this.microphoneEnabled=!1,this.audioPlaybackPrompt=!1,this.isReady=!1,this.cleanupFadeContext(),this.unmuteTimer&&(clearTimeout(this.unmuteTimer),this.unmuteTimer=null),this.speakingHandler&&(e.localParticipant.off("isSpeakingChanged",this.speakingHandler),this.speakingHandler=null),this.room=null,this.dispatchEvent(new CustomEvent("disconnected"))}),e.on(ie.ParticipantConnected,t=>{this.connectedParticipants=[...this.connectedParticipants,t.identity];const n=pn.isAgentIdentity(t.identity);n&&(this.updateStatus("agent-connected"),this.audioPlaybackPrompt=!0,this.dispatchEvent(new CustomEvent("agent-connected",{detail:{participant:t.identity}}))),this.dispatchEvent(new CustomEvent("participant-connected",{detail:{participant:t.identity,isAgent:n}}))}),e.on(ie.ParticipantDisconnected,t=>{this.connectedParticipants=this.connectedParticipants.filter(s=>s!==t.identity);const n=pn.isAgentIdentity(t.identity);n&&(this.audioPlaybackPrompt=!1,this.updateStatus("connected"),this.dispatchEvent(new CustomEvent("agent-disconnected",{detail:{participant:t.identity}}))),this.dispatchEvent(new CustomEvent("participant-disconnected",{detail:{participant:t.identity,isAgent:n}}))}),e.on(ie.TrackSubscribed,(t,n,s)=>{if(t.kind==="audio"){const r=t.attach();document.body.appendChild(r),pn.isAgentIdentity(s.identity)&&(this.agentAudioElements.push(r),this.setupAgentAudioFade(r)),this.dispatchEvent(new CustomEvent("audio-track-added",{detail:{participant:s.identity,element:r}}));const a=t.mediaStreamTrack;a&&this.dispatchEvent(new CustomEvent("audio-track",{detail:a}))}}),e.on(ie.TrackUnsubscribed,(t,n,s)=>{const r=t.detach();for(const a of r){const o=this.fadeGains.get(a);if(o){try{o.source.disconnect()}catch{}try{o.gain.disconnect()}catch{}this.fadeGains.delete(a)}}this.agentAudioElements=this.agentAudioElements.filter(a=>!r.includes(a)),this.dispatchEvent(new CustomEvent("audio-track-removed",{detail:{participant:s.identity}}))}),e.on(ie.MediaDevicesError,t=>{this.error=`Media device error: ${t.message}`,this.updateStatus("error"),this.dispatchEvent(new CustomEvent("error",{detail:{error:this.error}}))}),e.on(ie.AudioPlaybackStatusChanged,async()=>{e.canPlaybackAudio||this.connectedParticipants.some(n=>pn.isAgentIdentity(n))&&!this.audioPlaybackPrompt&&(this.updateStatus("agent-connected"),this.audioPlaybackPrompt=!0),this.dispatchEvent(new CustomEvent("audio-playback-status-changed",{detail:{canPlayback:e.canPlaybackAudio}}))}),this.speakingHandler=t=>{t?(this.unmuteTimer&&(clearTimeout(this.unmuteTimer),this.unmuteTimer=null),this.rampAgentGain(0,pn.FADEOUT_TC)):this.unmuteTimer=setTimeout(()=>{this.unmuteTimer=null,this.rampAgentGain(1,pn.FADEIN_TC)},pn.UNMUTE_HOLDOVER_MS)},e.localParticipant.on("isSpeakingChanged",this.speakingHandler)}async toggleMicrophone(){if(this.room)try{this.microphoneEnabled?(await this.room.localParticipant.setMicrophoneEnabled(!1),this.microphoneEnabled=!1,this.dispatchEvent(new CustomEvent("microphone-disabled"))):(await this.room.localParticipant.setMicrophoneEnabled(!0,{echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0}),this.microphoneEnabled=!0,this.dispatchEvent(new CustomEvent("microphone-enabled")))}catch(e){this.error=`Failed to toggle microphone: ${e instanceof Error?e.message:String(e)}`,this.dispatchEvent(new CustomEvent("error",{detail:{error:this.error}}))}}setupAgentAudioFade(e){const t=(async()=>{try{if(this.fadeContext)await ei.ensureResumed();else{const r=await ei.acquire();if(!r){console.warn("[CallManager] Could not acquire shared AudioContext for fade");return}this.fadeContext=r,this.fadeContextAcquired=!0}const n=this.fadeContext.createMediaElementSource(e),s=this.fadeContext.createGain();n.connect(s),s.connect(this.fadeContext.destination),this.fadeGains.set(e,{source:n,gain:s})}catch(n){console.warn("[CallManager] Audio fade setup failed:",n)}})();this.fadeSetupPromise=t,t.then(()=>{this.fadeSetupPromise=null})}rampAgentGain(e,t,n=!1){const s=this.fadeContext;if(s&&s.state==="running"&&this.fadeGains.size>0)for(const{gain:r}of this.fadeGains.values())r.gain.cancelScheduledValues(s.currentTime),r.gain.setValueAtTime(r.gain.value,s.currentTime),r.gain.setTargetAtTime(e,s.currentTime,t);else if(this.fadeSetupPromise)this.fadeSetupPromise.then(()=>this.rampAgentGain(e,t));else if(!n&&s&&s.state==="suspended"&&this.fadeGains.size>0)ei.ensureResumed().then(r=>{if(r)this.rampAgentGain(e,t,!0);else for(const a of this.agentAudioElements)a.volume=e});else for(const r of this.agentAudioElements)r.volume=e}cleanupFadeContext(){this.agentAudioElements=[];for(const{source:e,gain:t}of this.fadeGains.values()){try{e.disconnect()}catch{}try{t.disconnect()}catch{}}this.fadeGains.clear(),this.fadeSetupPromise=null,this.fadeContextAcquired&&(ei.release(),this.fadeContextAcquired=!1),this.fadeContext=null}async enableAudio(){if(this.room)try{await this.room.startAudio(),this.audioPlaybackPrompt=!1;const e=JSON.stringify({type:"audio_enabled"}),n=new TextEncoder().encode(e);await this.room.localParticipant.publishData(n,{reliable:!0}),this.dispatchEvent(new CustomEvent("audio-enabled"))}catch(e){this.error=`Failed to enable audio: ${e instanceof Error?e.message:String(e)}`,this.dispatchEvent(new CustomEvent("error",{detail:{error:this.error}}))}}async hangUp(){if(!this.room){this.error="No active connection to end.";return}this.updateStatus("disconnecting");const e=this.room;this.room=null,this.connectedParticipants=[],this.microphoneEnabled=!1,this.audioPlaybackPrompt=!1,this.isReady=!1,this.cleanupFadeContext(),this.unmuteTimer&&(clearTimeout(this.unmuteTimer),this.unmuteTimer=null),this.speakingHandler&&(e.localParticipant.off("isSpeakingChanged",this.speakingHandler),this.speakingHandler=null),this.updateStatus("disconnected"),this.dispatchEvent(new CustomEvent("call-ended")),requestAnimationFrame(()=>{setTimeout(async()=>{try{await e.disconnect()}catch(t){console.warn("Error during room disconnect:",t)}},0)})}};pn.UNMUTE_HOLDOVER_MS=350,pn.FADEOUT_TC=.045,pn.FADEIN_TC=.03;let Ws=pn;/**
|
|
84
|
+
`},Yc}var zf;function ub(){if(zf)return Nn;zf=1;var i=lb(),e=db(),t=Xc();return Nn.grammar=t,Nn.write=e,Nn.parse=i.parse,Nn.parseParams=i.parseParams,Nn.parseFmtpConfig=i.parseFmtpConfig,Nn.parsePayloads=i.parsePayloads,Nn.parseRemoteCandidates=i.parseRemoteCandidates,Nn.parseImageAttributes=i.parseImageAttributes,Nn.parseSimulcastStreamList=i.parseSimulcastStreamList,Nn}var Wi=ub();function Kc(i,e,t){var n,s,r;e===void 0&&(e=50),t===void 0&&(t={});var a=(n=t.isImmediate)!=null&&n,o=(s=t.callback)!=null&&s,c=t.maxWait,l=Date.now(),d=[];function u(){if(c!==void 0){var f=Date.now()-l;if(f+e>=c)return c-f}return e}var h=function(){var f=[].slice.call(arguments),g=this;return new Promise(function(v,m){var p=a&&r===void 0;if(r!==void 0&&clearTimeout(r),r=setTimeout(function(){if(r=void 0,l=Date.now(),!a){var C=i.apply(g,f);o&&o(C),d.forEach(function(b){return(0,b.resolve)(C)}),d=[]}},u()),p){var x=i.apply(g,f);return o&&o(x),v(x)}d.push({resolve:v,reject:m})})};return h.cancel=function(f){r!==void 0&&clearTimeout(r),d.forEach(function(g){return(0,g.reject)(f)}),d=[]},h}const hb=.7,fb=20,zs={NegotiationStarted:"negotiationStarted",NegotiationComplete:"negotiationComplete",RTPVideoPayloadTypes:"rtpVideoPayloadTypes"};class Vf extends Xn.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=Ke,this.ddExtID=0,this.latestOfferId=0,this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate=!1,this.trackBitrates=[],this.remoteStereoMids=[],this.remoteNackMids=[],this.negotiate=Kc(s=>P(this,void 0,void 0,function*(){this.emit(zs.NegotiationStarted);try{yield this.createAndSendOffer()}catch(r){if(s)s(r);else throw r}}),fb),this.close=()=>{this._pc&&(this._pc.close(),this._pc.onconnectionstatechange=null,this._pc.oniceconnectionstatechange=null,this._pc.onicegatheringstatechange=null,this._pc.ondatachannel=null,this._pc.onnegotiationneeded=null,this._pc.onsignalingstatechange=null,this._pc.onicecandidate=null,this._pc.ondatachannel=null,this._pc.ontrack=null,this._pc.onconnectionstatechange=null,this._pc.oniceconnectionstatechange=null,this._pc=null)},this.log=fi((n=t.loggerName)!==null&&n!==void 0?n:Ln.PCTransport),this.loggerOptions=t,this.config=e,this._pc=this.createPC(),this.offerLock=new cn}createPC(){const e=new RTCPeerConnection(this.config);return e.onicecandidate=t=>{var n;t.candidate&&((n=this.onIceCandidate)===null||n===void 0||n.call(this,t.candidate))},e.onicecandidateerror=t=>{var n;(n=this.onIceCandidateError)===null||n===void 0||n.call(this,t)},e.oniceconnectionstatechange=()=>{var t;(t=this.onIceConnectionStateChange)===null||t===void 0||t.call(this,e.iceConnectionState)},e.onsignalingstatechange=()=>{var t;(t=this.onSignalingStatechange)===null||t===void 0||t.call(this,e.signalingState)},e.onconnectionstatechange=()=>{var t;(t=this.onConnectionStateChange)===null||t===void 0||t.call(this,e.connectionState)},e.ondatachannel=t=>{var n;(n=this.onDataChannel)===null||n===void 0||n.call(this,t)},e.ontrack=t=>{var n;(n=this.onTrack)===null||n===void 0||n.call(this,t)},e}get logContext(){var e,t;return Object.assign({},(t=(e=this.loggerOptions).loggerContextCb)===null||t===void 0?void 0:t.call(e))}get isICEConnected(){return this._pc!==null&&(this.pc.iceConnectionState==="connected"||this.pc.iceConnectionState==="completed")}addIceCandidate(e){return P(this,void 0,void 0,function*(){if(this.pc.remoteDescription&&!this.restartingIce)return this.pc.addIceCandidate(e);this.pendingCandidates.push(e)})}setRemoteDescription(e,t){return P(this,void 0,void 0,function*(){var n;if(e.type==="answer"&&this.latestOfferId>0&&t>0&&t!==this.latestOfferId)return this.log.warn("ignoring answer for old offer",Object.assign(Object.assign({},this.logContext),{offerId:t,latestOfferId:this.latestOfferId})),!1;let s;if(e.type==="offer"){let{stereoMids:r,nackMids:a}=pb(e);this.remoteStereoMids=r,this.remoteNackMids=a}else if(e.type==="answer"){const r=Wi.parse((n=e.sdp)!==null&&n!==void 0?n:"");r.media.forEach(a=>{a.type==="audio"&&this.trackBitrates.some(o=>{if(!o.transceiver||a.mid!=o.transceiver.mid)return!1;let c=0;if(a.rtp.some(d=>d.codec.toUpperCase()===o.codec.toUpperCase()?(c=d.payload,!0):!1),c===0)return!0;let l=!1;for(const d of a.fmtp)if(d.payload===c){d.config=d.config.split(";").filter(u=>!u.includes("maxaveragebitrate")).join(";"),o.maxbr>0&&(d.config+=";maxaveragebitrate=".concat(o.maxbr*1e3)),l=!0;break}return l||o.maxbr>0&&a.fmtp.push({payload:c,config:"maxaveragebitrate=".concat(o.maxbr*1e3)}),!0})}),s=Wi.write(r)}return yield this.setMungedSDP(e,s,!0),this.pendingCandidates.forEach(r=>{this.pc.addIceCandidate(r)}),this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate?(this.renegotiate=!1,yield this.createAndSendOffer()):e.type==="answer"&&(this.emit(zs.NegotiationComplete),e.sdp&&Wi.parse(e.sdp).media.forEach(a=>{a.type==="video"&&this.emit(zs.RTPVideoPayloadTypes,a.rtp)})),!0})}createAndSendOffer(e){return P(this,void 0,void 0,function*(){var t;const n=yield this.offerLock.lock();try{if(this.onOffer===void 0)return;if(e!=null&&e.iceRestart&&(this.log.debug("restarting ICE",this.logContext),this.restartingIce=!0),this._pc&&this._pc.signalingState==="have-local-offer"){const o=this._pc.remoteDescription;if(e!=null&&e.iceRestart&&o)yield this._pc.setRemoteDescription(o);else{this.renegotiate=!0;return}}else if(!this._pc||this._pc.signalingState==="closed"){this.log.warn("could not createOffer with closed peer connection",this.logContext);return}this.log.debug("starting to negotiate",this.logContext);const s=this.latestOfferId+1;this.latestOfferId=s;const r=yield this.pc.createOffer(e);this.log.debug("original offer",Object.assign({sdp:r.sdp},this.logContext));const a=Wi.parse((t=r.sdp)!==null&&t!==void 0?t:"");if(a.media.forEach(o=>{Hf(o),o.type==="audio"?Gf(o,[],[]):o.type==="video"&&this.trackBitrates.some(c=>{if(!o.msid||!c.cid||!o.msid.includes(c.cid))return!1;let l=0;if(o.rtp.some(u=>u.codec.toUpperCase()===c.codec.toUpperCase()?(l=u.payload,!0):!1),l===0||(Yn(c.codec)&&!ls()&&this.ensureVideoDDExtensionForSVC(o,a),c.codec!=="av1"))return!0;const d=Math.round(c.maxbr*hb);for(const u of o.fmtp)if(u.payload===l){u.config.includes("x-google-start-bitrate")||(u.config+=";x-google-start-bitrate=".concat(d));break}return!0})}),this.latestOfferId>s){this.log.warn("latestOfferId mismatch",Object.assign(Object.assign({},this.logContext),{latestOfferId:this.latestOfferId,offerId:s}));return}yield this.setMungedSDP(r,Wi.write(a)),this.onOffer(r,this.latestOfferId)}finally{n()}})}createAndSetAnswer(){return P(this,void 0,void 0,function*(){var e;const t=yield this.pc.createAnswer(),n=Wi.parse((e=t.sdp)!==null&&e!==void 0?e:"");return n.media.forEach(s=>{Hf(s),s.type==="audio"&&Gf(s,this.remoteStereoMids,this.remoteNackMids)}),yield this.setMungedSDP(t,Wi.write(n)),t})}createDataChannel(e,t){return this.pc.createDataChannel(e,t)}addTransceiver(e,t){return this.pc.addTransceiver(e,t)}addTrack(e){if(!this._pc)throw new Gt("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 Gt("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()}getConnectedAddress(){return P(this,void 0,void 0,function*(){var e;if(!this._pc)return;let t="";const n=new Map,s=new Map;if((yield this._pc.getStats()).forEach(o=>{switch(o.type){case"transport":t=o.selectedCandidatePairId;break;case"candidate-pair":t===""&&o.selected&&(t=o.id),n.set(o.id,o);break;case"remote-candidate":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 P(this,void 0,void 0,function*(){if(t){const s=e.sdp;e.sdp=t;try{this.log.debug("setting munged ".concat(n?"remote":"local"," description"),this.logContext),n?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e);return}catch(r){this.log.warn("not able to set ".concat(e.type,", falling back to unmodified sdp"),Object.assign(Object.assign({},this.logContext),{error:r,sdp:t})),e.sdp=s}}try{n?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e)}catch(s){let r="unknown error";s instanceof Error?r=s.message:typeof s=="string"&&(r=s);const a={error:r,sdp:e.sdp};throw!n&&this.pc.remoteDescription&&(a.remoteSdp=this.pc.remoteDescription),this.log.error("unable to set ".concat(e.type),Object.assign(Object.assign({},this.logContext),{fields:a})),new Ec(r)}})}ensureVideoDDExtensionForSVC(e,t){var n,s;if(!((n=e.ext)===null||n===void 0?void 0:n.some(a=>a.uri===_f))){if(this.ddExtID===0){let a=0;t.media.forEach(o=>{var c;o.type==="video"&&((c=o.ext)===null||c===void 0||c.forEach(l=>{l.value>a&&(a=l.value)}))}),this.ddExtID=a+1}(s=e.ext)===null||s===void 0||s.push({value:this.ddExtID,uri:_f})}}}function Gf(i,e,t){let n=0;i.rtp.some(s=>s.codec==="opus"?(n=s.payload,!0):!1),n>0&&(i.rtcpFb||(i.rtcpFb=[]),t.includes(i.mid)&&!i.rtcpFb.some(s=>s.payload===n&&s.type==="nack")&&i.rtcpFb.push({payload:n,type:"nack"}),e.includes(i.mid)&&i.fmtp.some(s=>s.payload===n?(s.config.includes("stereo=1")||(s.config+=";stereo=1"),!0):!1))}function pb(i){var e;const t=[],n=[],s=Wi.parse((e=i.sdp)!==null&&e!==void 0?e:"");let r=0;return s.media.forEach(a=>{var o;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(a.mid),a.fmtp.some(c=>c.payload===r?(c.config.includes("sprop-stereo=1")&&t.push(a.mid),!0):!1))}),{stereoMids:t,nackMids:n}}function Hf(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)}}const Jc="vp8",mb={audioPreset:Ac.music,dtx:!0,red:!0,forceStereo:!1,simulcast:!0,screenShareEncoding:Pc.h1080fps15.encoding,stopMicTrackOnMute:!1,videoCodec:Jc,backupCodec:!0,preConnectBuffer:!1},Wf={deviceId:{ideal:"default"},autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0,voiceIsolation:!0},qf={deviceId:{ideal:"default"},resolution:Or.h720.resolution},gb={adaptiveStream:!1,dynacast:!1,stopLocalTrackOnUnpublish:!0,reconnectPolicy:new i0,disconnectOnPageLeave:!0,webAudioMix:!1},Zc={autoSubscribe:!0,maxRetries:1,peerConnectionTimeout:15e3,websocketTimeout:15e3};var Pt;(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"})(Pt||(Pt={}));class vb{get needsPublisher(){return this.isPublisherConnectionRequired}get needsSubscriber(){return this.isSubscriberConnectionRequired}get currentState(){return this.state}constructor(e,t,n){var s;this.peerConnectionTimeout=Zc.peerConnectionTimeout,this.log=Ke,this.updateState=()=>{var r;const a=this.state,o=this.requiredTransports.map(c=>c.getConnectionState());o.every(c=>c==="connected")?this.state=Pt.CONNECTED:o.some(c=>c==="failed")?this.state=Pt.FAILED:o.some(c=>c==="connecting")?this.state=Pt.CONNECTING:o.every(c=>c==="closed")?this.state=Pt.CLOSED:o.some(c=>c==="closed")?this.state=Pt.CLOSING:o.every(c=>c==="new")&&(this.state=Pt.NEW),a!==this.state&&(this.log.debug("pc state change: from ".concat(Pt[a]," to ").concat(Pt[this.state]),this.logContext),(r=this.onStateChange)===null||r===void 0||r.call(this,this.state,this.publisher.getConnectionState(),this.subscriber.getConnectionState()))},this.log=fi((s=n.loggerName)!==null&&s!==void 0?s:Ln.PCManager),this.loggerOptions=n,this.isPublisherConnectionRequired=!t,this.isSubscriberConnectionRequired=t,this.publisher=new Vf(e,n),this.subscriber=new Vf(e,n),this.publisher.onConnectionStateChange=this.updateState,this.subscriber.onConnectionStateChange=this.updateState,this.publisher.onIceConnectionStateChange=this.updateState,this.subscriber.onIceConnectionStateChange=this.updateState,this.publisher.onSignalingStatechange=this.updateState,this.subscriber.onSignalingStatechange=this.updateState,this.publisher.onIceCandidate=r=>{var a;(a=this.onIceCandidate)===null||a===void 0||a.call(this,r,Dn.PUBLISHER)},this.subscriber.onIceCandidate=r=>{var a;(a=this.onIceCandidate)===null||a===void 0||a.call(this,r,Dn.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.onOffer=(r,a)=>{var o;(o=this.onPublisherOffer)===null||o===void 0||o.call(this,r,a)},this.state=Pt.NEW,this.connectionLock=new cn,this.remoteOfferLock=new cn}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()}requireSubscriber(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;this.isSubscriberConnectionRequired=e,this.updateState()}createAndSendPublisherOffer(e){return this.publisher.createAndSendOffer(e)}setPublisherAnswer(e,t){return this.publisher.setRemoteDescription(e,t)}removeTrack(e){return this.publisher.removeTrack(e)}close(){return P(this,void 0,void 0,function*(){if(this.publisher&&this.publisher.getSignallingState()!=="closed"){const e=this.publisher;for(const t of e.getSenders())try{e.canRemoveTrack()&&e.removeTrack(t)}catch(n){this.log.warn("could not removeTrack",Object.assign(Object.assign({},this.logContext),{error:n}))}}yield Promise.all([this.publisher.close(),this.subscriber.close()]),this.updateState()})}triggerIceRestart(){return P(this,void 0,void 0,function*(){this.subscriber.restartingIce=!0,this.needsPublisher&&(yield this.createAndSendPublisherOffer({iceRestart:!0}))})}addIceCandidate(e,t){return P(this,void 0,void 0,function*(){t===Dn.PUBLISHER?yield this.publisher.addIceCandidate(e):yield this.subscriber.addIceCandidate(e)})}createSubscriberAnswerFromOffer(e,t){return P(this,void 0,void 0,function*(){this.log.debug("received server offer",Object.assign(Object.assign({},this.logContext),{RTCSdpType:e.type,sdp:e.sdp,signalingState:this.subscriber.getSignallingState().toString()}));const n=yield this.remoteOfferLock.lock();try{return(yield this.subscriber.setRemoteDescription(e,t))?yield this.subscriber.createAndSetAnswer():void 0}finally{n()}})}updateConfiguration(e,t){this.publisher.setConfiguration(e),this.subscriber.setConfiguration(e),t&&this.triggerIceRestart()}ensurePCTransportConnection(e,t){return P(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.logContext),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 P(this,void 0,void 0,function*(){return new Promise((t,n)=>P(this,void 0,void 0,function*(){const s=setTimeout(()=>{n("negotiation timed out")},this.peerConnectionTimeout),r=()=>{clearTimeout(s),n("negotiation aborted")};e.signal.addEventListener("abort",r),this.publisher.once(zs.NegotiationStarted,()=>{e.signal.aborted||this.publisher.once(zs.NegotiationComplete,()=>{clearTimeout(s),t()})}),yield this.publisher.negotiate(a=>{clearTimeout(s),n(a)})}))})}addPublisherTransceiver(e,t){return this.publisher.addTransceiver(e,t)}addPublisherTrack(e){return this.publisher.addTrack(e)}createPublisherDataChannel(e,t){return this.publisher.createDataChannel(e,t)}getConnectedAddress(e){return e===Dn.PUBLISHER?this.publisher.getConnectedAddress():e===Dn.SUBSCRIBER?this.publisher.getConnectedAddress():this.requiredTransports[0].getConnectedAddress()}get requiredTransports(){const e=[];return this.isPublisherConnectionRequired&&e.push(this.publisher),this.isSubscriberConnectionRequired&&e.push(this.subscriber),e}ensureTransportConnected(e,t){return P(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((c,l)=>P(r,void 0,void 0,function*(){const d=()=>{this.log.warn("abort transport connection",this.logContext),Yt.clearTimeout(u),l(new _t("room connection has been cancelled",tt.Cancelled))};s!=null&&s.signal.aborted&&d(),s==null||s.signal.addEventListener("abort",d);const u=Yt.setTimeout(()=>{s==null||s.signal.removeEventListener("abort",d),l(new _t("could not establish pc connection",tt.InternalError))},a);for(;this.state!==Pt.CONNECTED;)if(yield un(50),s!=null&&s.signal.aborted){l(new _t("room connection has been cancelled",tt.Cancelled));return}Yt.clearTimeout(u),s==null||s.signal.removeEventListener("abort",d),c()}))}()})}}class kt extends Error{constructor(e,t,n){super(t),this.code=e,this.message=jf(t,kt.MAX_MESSAGE_BYTES),this.data=n?jf(n,kt.MAX_DATA_BYTES):void 0}static fromProto(e){return new kt(e.code,e.message,e.data)}toProto(){return new ih({code:this.code,message:this.message,data:this.data})}static builtIn(e,t){return new kt(kt.ErrorCode[e],kt.ErrorMessage[e],t)}}kt.MAX_MESSAGE_BYTES=256,kt.MAX_DATA_BYTES=15360,kt.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},kt.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 $f=15360;function Qc(i){return new TextEncoder().encode(i).length}function jf(i,e){if(Qc(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)}const el=2e3;function Ha(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)}const tl=typeof MediaRecorder<"u";class bb{constructor(){throw new Error("MediaRecorder is not available in this environment")}}const yb=tl?MediaRecorder:bb;class _b extends yb{constructor(e,t){if(!tl)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==null||s.close(),s=void 0},o=c=>{s==null||s.error(c),this.removeEventListener("dataavailable",n),this.removeEventListener("stop",a),this.removeEventListener("error",o),s=void 0};this.byteStream=new ReadableStream({start:c=>{s=c,n=l=>P(this,void 0,void 0,function*(){let d;if(l.data.arrayBuffer){const u=yield l.data.arrayBuffer();d=new Uint8Array(u)}else if(l.data.byteArray)d=l.data.byteArray;else throw new Error("no data available!");r()||c.enqueue(d)}),this.addEventListener("dataavailable",n)},cancel:()=>{a()}}),this.addEventListener("stop",a),this.addEventListener("error",o)}}function Sb(){return tl}const xb=1e3,Tb=1e4;class Xf extends Q{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._isUpstreamPaused=!1,this.handleTrackMuteEvent=()=>this.debouncedTrackMuteHandler().catch(()=>this.log.debug("track mute bounce got cancelled by an unmute event",this.logContext)),this.debouncedTrackMuteHandler=Kc(()=>P(this,void 0,void 0,function*(){yield this.pauseUpstream()}),5e3),this.handleTrackUnmuteEvent=()=>P(this,void 0,void 0,function*(){this.debouncedTrackMuteHandler.cancel("unmute"),yield this.resumeUpstream()}),this.handleEnded=()=>{this.isInBackground&&(this.reacquireTrack=!0),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent),this.emit(oe.Ended,this)},this.reacquireTrack=!1,this.providedByUser=s,this.muteLock=new cn,this.pauseUpstreamLock=new cn,this.trackChangeLock=new cn,this.trackChangeLock.lock().then(a=>P(this,void 0,void 0,function*(){try{yield this.setMediaStreamTrack(e,!0)}finally{a()}})),this._constraints=e.getConstraints(),n&&(this._constraints=n)}get id(){return this._mediaStreamTrack.id}get dimensions(){if(this.kind!==Q.Kind.Video)return;const{width:e,height:t}=this._mediaStreamTrack.getSettings();if(e&&t)return{width:e,height:t}}get isUpstreamPaused(){return this._isUpstreamPaused}get isUserProvided(){return this.providedByUser}get mediaStreamTrack(){var e,t;return(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){return P(this,void 0,void 0,function*(){var n;if(e===this._mediaStreamTrack&&!t)return;this._mediaStreamTrack&&(this.attachedElements.forEach(r=>{Fs(this._mediaStreamTrack,r)}),this.debouncedTrackMuteHandler.cancel("new-track"),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent)),this.mediaStream=new MediaStream([e]),e&&(e.addEventListener("ended",this.handleEnded),e.addEventListener("mute",this.handleTrackMuteEvent),e.addEventListener("unmute",this.handleTrackUnmuteEvent),this._constraints=e.getConstraints());let s;if(this.processor&&e){if(this.log.debug("restarting processor",this.logContext),this.kind==="unknown")throw TypeError("cannot set processor on track of unknown kind");this.processorElement&&(Os(e,this.processorElement),this.processorElement.muted=!0),yield this.processor.restart({track:e,kind:this.kind,element:this.processorElement}),s=this.processor.processedTrack}this.sender&&((n=this.sender.transport)===null||n===void 0?void 0:n.state)!=="closed"&&(yield this.sender.replaceTrack(s??e)),!this.providedByUser&&this._mediaStreamTrack!==e&&this._mediaStreamTrack.stop(),this._mediaStreamTrack=e,e&&(this._mediaStreamTrack.enabled=!this.isMuted,yield this.resumeUpstream(),this.attachedElements.forEach(r=>{Os(s??e,r)}))})}waitForDimensions(){return P(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:xb;return function*(){var n;if(e.kind===Q.Kind.Audio)throw new Error("cannot get dimensions for audio tracks");((n=bn())===null||n===void 0?void 0:n.os)==="iOS"&&(yield un(10));const s=Date.now();for(;Date.now()-s<t;){const r=e.dimensions;if(r)return r;yield un(50)}throw new gi("unable to get track dimensions after timeout")}()})}setDeviceId(e){return P(this,void 0,void 0,function*(){return this._constraints.deviceId===e&&this._mediaStreamTrack.getSettings().deviceId===Vi(e)||(this._constraints.deviceId=e,this.isMuted)?!0:(yield this.restartTrack(),Vi(e)===this._mediaStreamTrack.getSettings().deviceId)})}getDeviceId(){return P(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){if(e.source===Q.Source.ScreenShare)return;const{deviceId:n,groupId:s}=e._mediaStreamTrack.getSettings(),r=e.kind===Q.Kind.Audio?"audioinput":"videoinput";return t?$t.getInstance().normalizeDeviceId(r,n,s):n}()})}mute(){return P(this,void 0,void 0,function*(){return this.setTrackMuted(!0),this})}unmute(){return P(this,void 0,void 0,function*(){return this.setTrackMuted(!1),this})}replaceTrack(e,t){return P(this,void 0,void 0,function*(){const n=yield this.trackChangeLock.lock();try{if(!this.sender)throw new gi("unable to replace an unpublished track");let s,r;return 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()),this}finally{n()}})}restart(e){return P(this,void 0,void 0,function*(){this.manuallyStopped=!1;const t=yield this.trackChangeLock.lock();try{e||(e=this._constraints);const{deviceId:n,facingMode:s}=e,r=s0(e,["deviceId","facingMode"]);this.log.debug("restarting track with constraints",Object.assign(Object.assign({},this.logContext),{constraints:e}));const a={audio:!1,video:!1};this.kind===Q.Kind.Video?a.video=n||s?{deviceId:n,facingMode:s}:!0:a.audio=n?Object.assign({deviceId:n},r):!0,this.attachedElements.forEach(l=>{Fs(this.mediaStreamTrack,l)}),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.stop();const c=(yield navigator.mediaDevices.getUserMedia(a)).getTracks()[0];return this.kind===Q.Kind.Video&&(yield c.applyConstraints(r)),c.addEventListener("ended",this.handleEnded),this.log.debug("re-acquired MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(c),this._constraints=e,this.emit(oe.Restarted,this),this.manuallyStopped&&(this.log.warn("track was stopped during a restart, stopping restarted track",this.logContext),this.stop()),this}finally{t()}})}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?oe.Muted:oe.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 P(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),Sf()&&(this.log.debug("visibility changed, is in Background: ".concat(this.isInBackground),this.logContext),!this.isInBackground&&this.needsReAcquisition&&!this.isUserProvided&&!this.isMuted&&(this.log.debug("track needs to be reacquired, restarting ".concat(this.source),this.logContext),yield this.restart(),this.reacquireTrack=!1))})}stop(){var e;this.manuallyStopped=!0,super.stop(),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.removeEventListener("mute",this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener("unmute",this.handleTrackUnmuteEvent),(e=this.processor)===null||e===void 0||e.destroy(),this.processor=void 0}pauseUpstream(){return P(this,void 0,void 0,function*(){var e;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(oe.UpstreamPaused,this);const n=bn();if((n==null?void 0:n.name)==="Safari"&&Jn(n.version,"12.0")<0)throw new Cc("pauseUpstream is not supported on Safari < 12.");((e=this.sender.transport)===null||e===void 0?void 0:e.state)!=="closed"&&(yield this.sender.replaceTrack(null))}finally{t()}})}resumeUpstream(){return P(this,void 0,void 0,function*(){var e;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(oe.UpstreamResumed,this),((e=this.sender.transport)===null||e===void 0?void 0:e.state)!=="closed"&&(yield this.sender.replaceTrack(this.mediaStreamTrack))}finally{t()}})}getRTCStatsReport(){return P(this,void 0,void 0,function*(){var e;return!((e=this.sender)===null||e===void 0)&&e.getStats?yield this.sender.getStats():void 0})}setProcessor(e){return P(this,arguments,void 0,function(t){var n=this;let 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),c={kind:n.kind,track:n._mediaStreamTrack,element:o,audioContext:n.audioContext};if(yield t.init(c),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(Os(n._mediaStreamTrack,o),o.muted=!0,o.play().catch(l=>{l instanceof DOMException&&l.name==="AbortError"?(n.log.warn("failed to play processor element, retrying",Object.assign(Object.assign({},n.logContext),{error:l})),setTimeout(()=>{o.play().catch(d=>{n.log.error("failed to play processor element",Object.assign(Object.assign({},n.logContext),{err:d}))})},100)):n.log.error("failed to play processor element",Object.assign(Object.assign({},n.logContext),{error:l}))}),n.processor=t,n.processorElement=o,n.processor.processedTrack){for(const l of n.attachedElements)l!==n.processorElement&&s&&(Fs(n._mediaStreamTrack,l),Os(n.processor.processedTrack,l));yield(r=n.sender)===null||r===void 0?void 0:r.replaceTrack(n.processor.processedTrack)}n.emit(oe.TrackProcessorUpdate,n.processor)}finally{a()}}()})}getProcessor(){return this.processor}stopProcessor(){return P(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){const n=yield e.trackChangeLock.lock();try{yield e.internalStopProcessor(t)}finally{n()}}()})}internalStopProcessor(){return P(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){var n,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(oe.TrackProcessorUpdate))}()})}startPreConnectBuffer(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:100;if(!Sb()){this.log.warn("MediaRecorder is not available, cannot start preconnect buffer",this.logContext);return}if(this.localTrackRecorder){this.log.warn("preconnect buffer already started");return}else{let t="audio/webm;codecs=opus";MediaRecorder.isTypeSupported(t)||(t="video/mp4"),this.localTrackRecorder=new _b(this,{mimeType:t})}this.localTrackRecorder.start(e),this.autoStopPreConnectBuffer=setTimeout(()=>{this.log.warn("preconnect buffer timed out, stopping recording automatically",this.logContext),this.stopPreConnectBuffer()},Tb)}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 Wa extends Xf{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,Q.Kind.Audio,t,n,r),this.stopOnMute=!1,this.isKrispNoiseFilterEnabled=!1,this.monitorSender=()=>P(this,void 0,void 0,function*(){if(!this.sender){this._currentBitrate=0;return}let a;try{a=yield this.getSenderStats()}catch(o){this.log.error("could not get audio sender stats",Object.assign(Object.assign({},this.logContext),{error:o}));return}a&&this.prevStats&&(this._currentBitrate=Ha(a,this.prevStats)),this.prevStats=a}),this.handleKrispNoiseFilterEnable=()=>{this.isKrispNoiseFilterEnabled=!0,this.log.debug("Krisp noise filter enabled",this.logContext),this.emit(oe.AudioTrackFeatureUpdate,this,qt.TF_ENHANCED_NOISE_CANCELLATION,!0)},this.handleKrispNoiseFilterDisable=()=>{this.isKrispNoiseFilterEnabled=!1,this.log.debug("Krisp noise filter disabled",this.logContext),this.emit(oe.AudioTrackFeatureUpdate,this,qt.TF_ENHANCED_NOISE_CANCELLATION,!1)},this.audioContext=s,this.checkForSilence()}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return P(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===Q.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 P(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{if(!this.isMuted)return this.log.debug("Track already unmuted",this.logContext),this;const n=this._constraints.deviceId&&this._mediaStreamTrack.getSettings().deviceId!==Vi(this._constraints.deviceId);return this.source===Q.Source.Microphone&&(this.stopOnMute||this._mediaStreamTrack.readyState==="ended"||n)&&!this.isUserProvided&&(this.log.debug("reacquiring mic track",this.logContext),yield this.restartTrack()),yield e.unmute.call(this),this}finally{t()}})}restartTrack(e){return P(this,void 0,void 0,function*(){let t;if(e){const n=Gc({audio:e});typeof n.audio!="boolean"&&(t=n.audio)}yield this.restart(t)})}restart(e){const t=Object.create(null,{restart:{get:()=>super.restart}});return P(this,void 0,void 0,function*(){const n=yield t.restart.call(this,e);return this.checkForSilence(),n})}startMonitor(){hn()&&(this.monitorInterval||(this.monitorInterval=setInterval(()=>{this.monitorSender()},el)))}setProcessor(e){return P(this,void 0,void 0,function*(){var t;const n=yield this.trackChangeLock.lock();try{if(!Kn()&&!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};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(oe.TrackProcessorUpdate,this.processor)}finally{n()}})}setAudioContext(e){this.audioContext=e}getSenderStats(){return P(this,void 0,void 0,function*(){var e;if(!(!((e=this.sender)===null||e===void 0)&&e.getStats))return;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 P(this,void 0,void 0,function*(){const e=yield Pf(this);return e&&(this.isMuted||this.log.warn("silence detected on local audio track",this.logContext),this.emit(oe.AudioSilenceDetected)),e})}}function Cb(i,e,t){switch(i.kind){case"audio":return new Wa(i,e,!1,void 0,t);case"video":return new qa(i,e,!1,t);default:throw new gi("unsupported track type: ".concat(i.kind))}}const Eb=Object.values(Or),Mb=Object.values(Rc),wb=Object.values(Pc),Ab=[Or.h180,Or.h360],Rb=[Rc.h180,Rc.h360],Pb=i=>[{scaleResolutionDownBy:2,fps:i.encoding.maxFramerate}].map(t=>{var n,s;return new gt(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)}),nl=["q","h","f"];function il(i,e,t,n){var s,r;let a=n==null?void 0:n.videoEncoding;i&&(a=n==null?void 0:n.screenShareEncoding);const o=n==null?void 0:n.simulcast,c=n==null?void 0:n.scalabilityMode,l=n==null?void 0:n.videoCodec;if(!a&&!o&&!c||!e||!t)return[{}];a||(a=Ib(i,e,t,l),Ke.debug("using video encoding",a));const d=a.maxFramerate,u=new gt(e,t,a.maxBitrate,a.maxFramerate,a.priority);if(c&&Yn(l)){const g=new Jf(c),v=[];if(g.spatial>3)throw new Error("unsupported scalabilityMode: ".concat(c));const m=bn();if(Fr()||Kn()||(m==null?void 0:m.name)==="Chrome"&&Jn(m==null?void 0:m.version,"113")<0){const p=g.suffix=="h"?2:3,x=U0(m);for(let C=0;C<g.spatial;C+=1)v.push({rid:nl[2-C],maxBitrate:a.maxBitrate/Math.pow(p,C),maxFramerate:u.encoding.maxFramerate,scaleResolutionDownBy:x?Math.pow(2,C):void 0});v[0].scalabilityMode=c}else v.push({maxBitrate:a.maxBitrate,maxFramerate:u.encoding.maxFramerate,scalabilityMode:c});return u.encoding.priority&&(v[0].priority=u.encoding.priority,v[0].networkPriority=u.encoding.priority),Ke.debug("using svc encoding",{encodings:v}),v}if(!o)return[a];let h=[];i?h=(s=Kf(n==null?void 0:n.screenShareSimulcastLayers))!==null&&s!==void 0?s:Yf(i,u):h=(r=Kf(n==null?void 0:n.videoSimulcastLayers))!==null&&r!==void 0?r:Yf(i,u);let f;if(h.length>0){const g=h[0];h.length>1&&([,f]=h);const v=Math.max(e,t);if(v>=960&&f)return sl(e,t,[g,f,u],d);if(v>=480)return sl(e,t,[g,u],d)}return sl(e,t,[u])}function kb(i,e,t){var n,s,r,a;if(!t.backupCodec||t.backupCodec===!0||t.backupCodec.codec===t.videoCodec)return;e!==t.backupCodec.codec&&Ke.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(),c=(n=o.width)!==null&&n!==void 0?n:(s=i.dimensions)===null||s===void 0?void 0:s.width,l=(r=o.height)!==null&&r!==void 0?r:(a=i.dimensions)===null||a===void 0?void 0:a.height;return i.source===Q.Source.ScreenShare&&t.simulcast&&(t.simulcast=!1),il(i.source===Q.Source.ScreenShare,c,l,t)}function Ib(i,e,t,n){const s=Db(i,e,t);let{encoding:r}=s[0];const a=Math.max(e,t);for(let o=0;o<s.length;o+=1){const c=s[o];if(r=c.encoding,c.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 Db(i,e,t){if(i)return wb;const n=e>t?e/t:t/e;return Math.abs(n-16/9)<Math.abs(n-4/3)?Eb:Mb}function Yf(i,e){if(i)return Pb(e);const{width:t,height:n}=e,s=t>n?t/n:n/t;return Math.abs(s-16/9)<Math.abs(s-4/3)?Ab:Rb}function sl(i,e,t,n){const s=[];if(t.forEach((r,a)=>{if(a>=nl.length)return;const o=Math.min(i,e),l={rid:nl[a],scaleResolutionDownBy:Math.max(1,o/Math.min(r.width,r.height)),maxBitrate:r.encoding.maxBitrate},d=n&&r.encoding.maxFramerate?Math.min(n,r.encoding.maxFramerate):r.encoding.maxFramerate;d&&(l.maxFramerate=d);const u=cs()||a===0;r.encoding.priority&&u&&(l.priority=r.encoding.priority,l.networkPriority=r.encoding.priority),s.push(l)}),Kn()&&Tf()==="ios"){let r;s.forEach(o=>{r?o.maxFramerate&&o.maxFramerate>r&&(r=o.maxFramerate):r=o.maxFramerate});let a=!0;s.forEach(o=>{var c;o.maxFramerate!=r&&(a&&(a=!1,Ke.info("Simulcast on iOS React-Native requires all encodings to share the same framerate.")),Ke.info('Setting framerate of encoding "'.concat((c=o.rid)!==null&&c!==void 0?c:"",'" to ').concat(r)),o.maxFramerate=r)})}return s}function Kf(i){if(i)return i.sort((e,t)=>{const{encoding:n}=e,{encoding:s}=t;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 Jf{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 Lb(i){return i.source===Q.Source.ScreenShare||i.constraints.height&&Vi(i.constraints.height)>=1080?"maintain-resolution":"balanced"}const Ub=5e3;class qa extends Xf{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,Q.Kind.Video,t,n,s),this.simulcastCodecs=new Map,this.degradationPreference="balanced",this.isCpuConstrained=!1,this.optimizeForPerformance=!1,this.monitorSender=()=>P(this,void 0,void 0,function*(){if(!this.sender){this._currentBitrate=0;return}let r;try{r=yield this.getSenderStats()}catch(c){this.log.error("could not get video sender stats",Object.assign(Object.assign({},this.logContext),{error:c}));return}const a=new Map(r.map(c=>[c.rid,c])),o=r.some(c=>c.qualityLimitationReason==="cpu");if(o!==this.isCpuConstrained&&(this.isCpuConstrained=o,this.isCpuConstrained&&this.emit(oe.CpuConstrained)),this.prevStats){let c=0;a.forEach((l,d)=>{var u;const h=(u=this.prevStats)===null||u===void 0?void 0:u.get(d);c+=Ha(l,h)}),this._currentBitrate=c}this.prevStats=a}),this.senderLock=new cn}get isSimulcast(){return!!(this.sender&&this.sender.getParameters().encodings.length>1)}startMonitor(e){var t;if(this.signalClient=e,!hn())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()},el))}stop(){this._mediaStreamTrack.getConstraints(),this.simulcastCodecs.forEach(e=>{e.mediaStreamTrack.stop()}),super.stop()}pauseUpstream(){const e=Object.create(null,{pauseUpstream:{get:()=>super.pauseUpstream}});return P(this,void 0,void 0,function*(){var t,n,s,r,a;yield e.pauseUpstream.call(this);try{for(var o=!0,c=pi(this.simulcastCodecs.values()),l;l=yield c.next(),t=l.done,!t;o=!0)r=l.value,o=!1,yield(a=r.sender)===null||a===void 0?void 0:a.replaceTrack(null)}catch(d){n={error:d}}finally{try{!o&&!t&&(s=c.return)&&(yield s.call(c))}finally{if(n)throw n.error}}})}resumeUpstream(){const e=Object.create(null,{resumeUpstream:{get:()=>super.resumeUpstream}});return P(this,void 0,void 0,function*(){var t,n,s,r,a;yield e.resumeUpstream.call(this);try{for(var o=!0,c=pi(this.simulcastCodecs.values()),l;l=yield c.next(),t=l.done,!t;o=!0){r=l.value,o=!1;const d=r;yield(a=d.sender)===null||a===void 0?void 0:a.replaceTrack(d.mediaStreamTrack)}}catch(d){n={error:d}}finally{try{!o&&!t&&(s=c.return)&&(yield s.call(c))}finally{if(n)throw n.error}}})}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return P(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===Q.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 P(this,void 0,void 0,function*(){const t=yield this.muteLock.lock();try{return this.isMuted?(this.source===Q.Source.Camera&&!this.isUserProvided&&(this.log.debug("reacquiring camera track",this.logContext),yield this.restartTrack()),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 P(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=yn.LOW;n<=yn.HIGH;n+=1)t.push(new hc({quality:n,enabled:n<=e}));this.log.debug("setting publishing quality. max quality ".concat(e),this.logContext),this.setPublishingLayers(Yn(this.codec),t)}restartTrack(e){return P(this,void 0,void 0,function*(){var t,n,s,r,a;let o;if(e){const u=Gc({video:e});typeof u.video!="boolean"&&(o=u.video)}yield this.restart(o),this.isCpuConstrained=!1;try{for(var c=!0,l=pi(this.simulcastCodecs.values()),d;d=yield l.next(),t=d.done,!t;c=!0){r=d.value,c=!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{!c&&!t&&(s=l.return)&&(yield s.call(l))}finally{if(n)throw n.error}}})}setProcessor(e){const t=Object.create(null,{setProcessor:{get:()=>super.setProcessor}});return P(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,c,l,d,u;if(yield t.setProcessor.call(s,n,r),!((d=s.processor)===null||d===void 0)&&d.processedTrack)try{for(var h=!0,f=pi(s.simulcastCodecs.values()),g;g=yield f.next(),a=g.done,!a;h=!0)l=g.value,h=!1,yield(u=l.sender)===null||u===void 0?void 0:u.replaceTrack(s.processor.processedTrack)}catch(v){o={error:v}}finally{try{!h&&!a&&(c=f.return)&&(yield c.call(f))}finally{if(o)throw o.error}}}()})}setDegradationPreference(e){return P(this,void 0,void 0,function*(){if(this.degradationPreference=e,this.sender)try{this.log.debug("setting degradationPreference to ".concat(e),this.logContext);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)},Ub))}setPublishingCodecs(e){return P(this,void 0,void 0,function*(){var t,n,s,r,a,o,c;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(Yn(e[0].codec),e[0].qualities),[];this.subscribedCodecs=e;const l=[];try{for(t=!0,n=pi(e);s=yield n.next(),r=s.done,!r;t=!0){c=s.value,t=!1;const d=c;if(!this.codec||this.codec===d.codec)yield this.setPublishingLayers(Yn(d.codec),d.qualities);else{const u=this.simulcastCodecs.get(d.codec);if(this.log.debug("try setPublishingCodec for ".concat(d.codec),Object.assign(Object.assign({},this.logContext),{simulcastCodecInfo:u})),!u||!u.sender){for(const h of d.qualities)if(h.enabled){l.push(d.codec);break}}else u.encodings&&(this.log.debug("try setPublishingLayersForSender ".concat(d.codec),this.logContext),yield Zf(u.sender,u.encodings,d.qualities,this.senderLock,Yn(d.codec),this.log,this.logContext))}}}catch(d){a={error:d}}finally{try{!t&&!r&&(o=n.return)&&(yield o.call(n))}finally{if(a)throw a.error}}return l})}setPublishingLayers(e,t){return P(this,void 0,void 0,function*(){if(this.optimizeForPerformance){this.log.info("skipping setPublishingLayers due to optimized publishing performance",Object.assign(Object.assign({},this.logContext),{qualities:t}));return}this.log.debug("setting publishing layers",Object.assign(Object.assign({},this.logContext),{qualities:t})),!(!this.sender||!this.encodings)&&(yield Zf(this.sender,this.encodings,t,this.senderLock,e,this.log,this.logContext))})}prioritizePerformance(){return P(this,void 0,void 0,function*(){if(!this.sender)throw new Error("sender not found");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&&Yn(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 P(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),Sf()&&this.isInBackground&&this.source===Q.Source.Camera&&(this._mediaStreamTrack.enabled=!1)})}}function Zf(i,e,t,n,s,r,a){return P(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 c=i.getParameters(),{encodings:l}=c;if(!l)return;if(l.length!==e.length){r.warn("cannot set publishing layers, encodings mismatch",Object.assign(Object.assign({},a),{encodings:l,senderEncodings:e}));return}let d=!1;!1&&l[0].scalabilityMode||(s&&t.some(f=>f.enabled)&&t.forEach(f=>f.enabled=!0),l.forEach((h,f)=>{var g;let v=(g=h.rid)!==null&&g!==void 0?g:"";v===""&&(v="q");const m=Qf(v),p=t.find(x=>x.quality===m);p&&h.active!==p.enabled&&(d=!0,h.active=p.enabled,r.debug("setting layer ".concat(p.quality," to ").concat(h.active?"enabled":"disabled"),a),cs()&&(p.enabled?(h.scaleResolutionDownBy=e[f].scaleResolutionDownBy,h.maxBitrate=e[f].maxBitrate,h.maxFrameRate=e[f].maxFrameRate):(h.scaleResolutionDownBy=4,h.maxBitrate=10,h.maxFrameRate=2)))})),d&&(c.encodings=l,r.debug("setting encodings",Object.assign(Object.assign({},a),{encodings:c.encodings})),yield i.setParameters(c))}finally{o()}})}function Qf(i){switch(i){case"f":return yn.HIGH;case"h":return yn.MEDIUM;case"q":return yn.LOW;default:return yn.HIGH}}function ep(i,e,t,n){if(!t)return[new rs({quality:yn.HIGH,width:i,height:e,bitrate:0,ssrc:0})];if(n){const s=t[0].scalabilityMode,r=new Jf(s),a=[],o=r.suffix=="h"?1.5:2,c=r.suffix=="h"?2:3;for(let l=0;l<r.spatial;l+=1)a.push(new rs({quality:Math.min(yn.HIGH,r.spatial-1)-l,width:Math.ceil(i/Math.pow(o,l)),height:Math.ceil(e/Math.pow(o,l)),bitrate:t[0].maxBitrate?Math.ceil(t[0].maxBitrate/Math.pow(c,l)):0,ssrc:0}));return a}return t.map(s=>{var r,a,o;const c=(r=s.scaleResolutionDownBy)!==null&&r!==void 0?r:1;let l=Qf((a=s.rid)!==null&&a!==void 0?a:"");return new rs({quality:l,width:Math.ceil(i/c),height:Math.ceil(e/c),bitrate:(o=s.maxBitrate)!==null&&o!==void 0?o:0,ssrc:0})})}const tp="_lossy",np="_reliable",Nb=2*1e3,rl="leave-reconnect",Ob=3e4;var On;(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"})(On||(On={}));class Fb extends Xn.EventEmitter{get isClosed(){return this._isClosed}get pendingReconnect(){return!!this.reconnectTimeout}constructor(e){var t;super(),this.options=e,this.rtcConfig={},this.peerConnectionTimeout=Zc.peerConnectionTimeout,this.fullReconnectOnNext=!1,this.latestRemoteOfferId=0,this.subscriberPrimary=!1,this.pcState=On.New,this._isClosed=!0,this.pendingTrackResolvers={},this.reconnectAttempts=0,this.reconnectStart=0,this.attemptingReconnect=!1,this.joinAttempts=0,this.maxJoinAttempts=1,this.shouldFailNext=!1,this.log=Ke,this.reliableDataSequence=1,this.reliableMessageBuffer=new Nf,this.reliableReceivedState=new cb(Ob),this.handleDataChannel=n=>P(this,[n],void 0,function(s){var r=this;let{channel:a}=s;return function*(){if(a){if(a.label===np)r.reliableDCSub=a;else if(a.label===tp)r.lossyDCSub=a;else return;r.log.debug("on data channel ".concat(a.id,", ").concat(a.label),r.logContext),a.onmessage=r.handleDataMessage}}()}),this.handleDataMessage=n=>P(this,void 0,void 0,function*(){var s,r;const a=yield this.dataProcessLock.lock();try{let o;if(n.data instanceof ArrayBuffer)o=n.data;else if(n.data instanceof Blob)o=yield n.data.arrayBuffer();else{this.log.error("unsupported data type",Object.assign(Object.assign({},this.logContext),{data:n.data}));return}const c=dn.fromBinary(new Uint8Array(o));if(c.sequence>0&&c.participantSid!==""){const l=this.reliableReceivedState.get(c.participantSid);if(l&&c.sequence<=l)return;this.reliableReceivedState.set(c.participantSid,c.sequence)}((s=c.value)===null||s===void 0?void 0:s.case)==="speaker"?this.emit(de.ActiveSpeakersUpdate,c.value.value.speakers):(((r=c.value)===null||r===void 0?void 0:r.case)==="user"&&zb(c,c.value.value),this.emit(de.DataPacketReceived,c))}finally{a()}}),this.handleDataError=n=>{const r=n.currentTarget.maxRetransmits===0?"lossy":"reliable";if(n instanceof ErrorEvent&&n.error){const{error:a}=n.error;this.log.error("DataChannel error on ".concat(r,": ").concat(n.message),Object.assign(Object.assign({},this.logContext),{error:a}))}else this.log.error("Unknown DataChannel error on ".concat(r),Object.assign(Object.assign({},this.logContext),{event:n}))},this.handleBufferedAmountLow=n=>{const r=n.currentTarget.maxRetransmits===0?We.LOSSY:We.RELIABLE;this.updateAndEmitDCBufferStatus(r)},this.handleDisconnect=(n,s)=>{if(this._isClosed)return;this.log.warn("".concat(n," disconnected"),this.logContext),this.reconnectAttempts===0&&(this.reconnectStart=Date.now());const r=c=>{this.log.warn("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(c,"ms. giving up"),this.logContext),this.emit(de.Disconnected),this.close()},a=Date.now()-this.reconnectStart;let o=this.getNextRetryDelay({elapsedMs:a,retryCount:this.reconnectAttempts});if(o===null){r(a);return}n===rl&&(o=0),this.log.debug("reconnecting in ".concat(o,"ms"),this.logContext),this.clearReconnectTimeout(),this.token&&this.regionUrlProvider&&this.regionUrlProvider.updateToken(this.token),this.reconnectTimeout=Yt.setTimeout(()=>this.attemptReconnect(s).finally(()=>this.reconnectTimeout=void 0),o)},this.waitForRestarted=()=>new Promise((n,s)=>{this.pcState===On.Connected&&n();const r=()=>{this.off(de.Disconnected,a),n()},a=()=>{this.off(de.Restarted,r),s()};this.once(de.Restarted,r),this.once(de.Disconnected,a)}),this.updateAndEmitDCBufferStatus=n=>{const s=this.isBufferStatusLow(n);typeof s<"u"&&s!==this.dcBufferStatus.get(n)&&(this.dcBufferStatus.set(n,s),this.emit(de.DCBufferStatusChanged,s,n))},this.isBufferStatusLow=n=>{const s=this.dataChannelForKind(n);if(s)return n===We.RELIABLE&&this.reliableMessageBuffer.alignBufferedAmount(s.bufferedAmount),s.bufferedAmount<=s.bufferedAmountLowThreshold},this.handleBrowserOnLine=()=>{this.client.currentState===Mt.RECONNECTING&&(this.clearReconnectTimeout(),this.attemptReconnect(Is.RR_SIGNAL_DISCONNECTED))},this.log=fi((t=e.loggerName)!==null&&t!==void 0?t:Ln.Engine),this.loggerOptions={loggerName:e.loggerName,loggerContextCb:()=>this.logContext},this.client=new qc(void 0,this.loggerOptions),this.client.signalLatency=this.options.expSignalLatency,this.reconnectPolicy=this.options.reconnectPolicy,this.registerOnLineListener(),this.closingLock=new cn,this.dataProcessLock=new cn,this.dcBufferStatus=new Map([[We.LOSSY,!0],[We.RELIABLE,!0]]),this.client.onParticipantUpdate=n=>this.emit(de.ParticipantUpdate,n),this.client.onConnectionQuality=n=>this.emit(de.ConnectionQualityUpdate,n),this.client.onRoomUpdate=n=>this.emit(de.RoomUpdate,n),this.client.onSubscriptionError=n=>this.emit(de.SubscriptionError,n),this.client.onSubscriptionPermissionUpdate=n=>this.emit(de.SubscriptionPermissionUpdate,n),this.client.onSpeakersChanged=n=>this.emit(de.SpeakersChanged,n),this.client.onStreamStateUpdate=n=>this.emit(de.StreamStateChanged,n),this.client.onRequestResponse=n=>this.emit(de.SignalRequestResponse,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,pID:this.participantSid}}join(e,t,n,s){return P(this,void 0,void 0,function*(){this.url=e,this.token=t,this.signalOpts=n,this.maxJoinAttempts=n.maxRetries;try{this.joinAttempts+=1,this.setupSignalClientCallbacks();const r=yield this.client.join(e,t,n,s);return this._isClosed=!1,this.latestJoinResponse=r,this.subscriberPrimary=r.subscriberPrimary,this.pcManager||(yield this.configure(r)),(!this.subscriberPrimary||r.fastPublish)&&this.negotiate(),this.clientConfiguration=r.clientConfiguration,this.emit(de.SignalConnected,r),r}catch(r){if(r instanceof _t&&r.reason===tt.ServerUnreachable&&(this.log.warn("Couldn't connect to server, attempt ".concat(this.joinAttempts," of ").concat(this.maxJoinAttempts),this.logContext),this.joinAttempts<this.maxJoinAttempts))return this.join(e,t,n,s);throw r}})}close(){return P(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(de.Closing),this.removeAllListeners(),this.deregisterOnLineListener(),this.clearPendingReconnect(),yield this.cleanupPeerConnections(),yield this.cleanupClient()}finally{e()}})}cleanupPeerConnections(){return P(this,void 0,void 0,function*(){var e;yield(e=this.pcManager)===null||e===void 0?void 0:e.close(),this.pcManager=void 0;const t=n=>{n&&(n.close(),n.onbufferedamountlow=null,n.onclose=null,n.onclosing=null,n.onerror=null,n.onmessage=null,n.onopen=null)};t(this.lossyDC),t(this.lossyDCSub),t(this.reliableDC),t(this.reliableDCSub),this.lossyDC=void 0,this.lossyDCSub=void 0,this.reliableDC=void 0,this.reliableDCSub=void 0,this.reliableMessageBuffer=new Nf,this.reliableDataSequence=1,this.reliableReceivedState.clear()})}cleanupClient(){return P(this,void 0,void 0,function*(){yield this.client.close(),this.client.resetCallbacks()})}addTrack(e){if(this.pendingTrackResolvers[e.cid])throw new gi("a track with the same ID has already been published");return new Promise((t,n)=>{const s=setTimeout(()=>{delete this.pendingTrackResolvers[e.cid],n(new _t("publication of local track timed out, no response from server",tt.Timeout))},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{reject:t}=this.pendingTrackResolvers[e.track.id];t&&t(),delete this.pendingTrackResolvers[e.track.id]}try{return this.pcManager.removeTrack(e),!0}catch(t){this.log.warn("failed to remove track",Object.assign(Object.assign({},this.logContext),{error:t}))}return!1}updateMuteStatus(e,t){this.client.sendMuteTrack(e,t)}get dataSubscriberReadyState(){var e;return(e=this.reliableDCSub)===null||e===void 0?void 0:e.readyState}getConnectedServerAddress(){return P(this,void 0,void 0,function*(){var e;return(e=this.pcManager)===null||e===void 0?void 0:e.getConnectedAddress()})}setRegionUrlProvider(e){this.regionUrlProvider=e}configure(e){return P(this,void 0,void 0,function*(){var t,n;if(this.pcManager&&this.pcManager.currentState!==Pt.NEW)return;this.participantSid=(t=e.participant)===null||t===void 0?void 0:t.sid;const s=this.makeRTCConfiguration(e);this.pcManager=new vb(s,e.subscriberPrimary,this.loggerOptions),this.emit(de.TransportsCreated,this.pcManager.publisher,this.pcManager.subscriber),this.pcManager.onIceCandidate=(r,a)=>{this.client.sendIceCandidate(r,a)},this.pcManager.onPublisherOffer=(r,a)=>{this.client.sendOffer(r,a)},this.pcManager.onDataChannel=this.handleDataChannel,this.pcManager.onStateChange=(r,a,o)=>P(this,void 0,void 0,function*(){if(this.log.debug("primary PC state changed ".concat(r),this.logContext),["closed","disconnected","failed"].includes(a)&&(this.publisherConnectionPromise=void 0),r===Pt.CONNECTED){const d=this.pcState===On.New;this.pcState=On.Connected,d&&this.emit(de.Connected,e)}else r===Pt.FAILED&&this.pcState===On.Connected&&(this.pcState=On.Disconnected,this.handleDisconnect("peerconnection failed",o==="failed"?Is.RR_SUBSCRIBER_FAILED:Is.RR_PUBLISHER_FAILED));const c=this.client.isDisconnected||this.client.currentState===Mt.RECONNECTING,l=[Pt.FAILED,Pt.CLOSING,Pt.CLOSED].includes(r);c&&l&&!this._isClosed&&this.emit(de.Offline)}),this.pcManager.onTrack=r=>{this.emit(de.MediaTrackAdded,r.track,r.streams[0],r.receiver)},Bb((n=e.serverInfo)===null||n===void 0?void 0:n.protocol)||this.createDataChannels()})}setupSignalClientCallbacks(){this.client.onAnswer=(e,t)=>P(this,void 0,void 0,function*(){this.pcManager&&(this.log.debug("received server answer",Object.assign(Object.assign({},this.logContext),{RTCSdpType:e.type})),yield this.pcManager.setPublisherAnswer(e,t))}),this.client.onTrickle=(e,t)=>{this.pcManager&&(this.log.debug("got ICE candidate from peer",Object.assign(Object.assign({},this.logContext),{candidate:e,target:t})),this.pcManager.addIceCandidate(e,t))},this.client.onOffer=(e,t)=>P(this,void 0,void 0,function*(){if(this.latestRemoteOfferId=t,!this.pcManager)return;const n=yield this.pcManager.createSubscriberAnswerFromOffer(e,t);n&&this.client.sendAnswer(n,t)}),this.client.onLocalTrackPublished=e=>{var t;if(this.log.debug("received trackPublishedResponse",Object.assign(Object.assign({},this.logContext),{cid:e.cid,track:(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),Object.assign(Object.assign({},this.logContext),{cid:e.cid}));return}const{resolve:n}=this.pendingTrackResolvers[e.cid];delete this.pendingTrackResolvers[e.cid],n(e.track)},this.client.onLocalTrackUnpublished=e=>{this.emit(de.LocalTrackUnpublished,e)},this.client.onLocalTrackSubscribed=e=>{this.emit(de.LocalTrackSubscribed,e)},this.client.onTokenRefresh=e=>{this.token=e},this.client.onRemoteMuteChanged=(e,t)=>{this.emit(de.RemoteMute,e,t)},this.client.onSubscribedQualityUpdate=e=>{this.emit(de.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(de.RoomMoved,e)},this.client.onClose=()=>{this.handleDisconnect("signal",Is.RR_SIGNAL_DISCONNECTED)},this.client.onLeave=e=>{switch(this.log.debug("client leave request",Object.assign(Object.assign({},this.logContext),{reason:e==null?void 0:e.reason})),e.regions&&this.regionUrlProvider&&(this.log.debug("updating regions",this.logContext),this.regionUrlProvider.setServerReportedRegions(e.regions)),e.action){case Us.DISCONNECT:this.emit(de.Disconnected,e==null?void 0:e.reason),this.close();break;case Us.RECONNECT:this.fullReconnectOnNext=!0,this.handleDisconnect(rl);break;case Us.RESUME:this.handleDisconnect(rl)}}}makeRTCConfiguration(e){var t;const n=Object.assign({},this.rtcConfig);if(!((t=this.signalOpts)===null||t===void 0)&&t.e2eeEnabled&&(this.log.debug("E2EE - setting up transports with insertable streams",this.logContext),n.encodedInsertableStreams=!0),e.iceServers&&!n.iceServers){const s=[];e.iceServers.forEach(r=>{const a={urls:r.urls};r.username&&(a.username=r.username),r.credential&&(a.credential=r.credential),s.push(a)}),n.iceServers=s}return e.clientConfiguration&&e.clientConfiguration.forceRelay===kr.ENABLED&&(n.iceTransportPolicy="relay"),n.sdpSemantics="unified-plan",n.continualGatheringPolicy="gather_continually",n}createDataChannels(){this.pcManager&&(this.lossyDC&&(this.lossyDC.onmessage=null,this.lossyDC.onerror=null),this.reliableDC&&(this.reliableDC.onmessage=null,this.reliableDC.onerror=null),this.lossyDC=this.pcManager.createPublisherDataChannel(tp,{ordered:!1,maxRetransmits:0}),this.reliableDC=this.pcManager.createPublisherDataChannel(np,{ordered:!0}),this.lossyDC.onmessage=this.handleDataMessage,this.reliableDC.onmessage=this.handleDataMessage,this.lossyDC.onerror=this.handleDataError,this.reliableDC.onerror=this.handleDataError,this.lossyDC.bufferedAmountLowThreshold=65535,this.reliableDC.bufferedAmountLowThreshold=65535,this.lossyDC.onbufferedamountlow=this.handleBufferedAmountLow,this.reliableDC.onbufferedamountlow=this.handleBufferedAmountLow)}createSender(e,t,n){return P(this,void 0,void 0,function*(){if(kc())return yield this.createTransceiverRTCRtpSender(e,t,n);if(Ic())return this.log.warn("using add-track fallback",this.logContext),yield this.createRTCRtpSender(e.mediaStreamTrack);throw new Gt("Required webRTC APIs not supported on this device")})}createSimulcastSender(e,t,n,s){return P(this,void 0,void 0,function*(){if(kc())return this.createSimulcastTransceiverSender(e,t,n,s);if(Ic())return this.log.debug("using add-track fallback",this.logContext),this.createRTCRtpSender(e.mediaStreamTrack);throw new Gt("Cannot stream on this device")})}createTransceiverRTCRtpSender(e,t,n){return P(this,void 0,void 0,function*(){if(!this.pcManager)throw new Gt("publisher is closed");const s=[];e.mediaStream&&s.push(e.mediaStream),Gi(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 P(this,void 0,void 0,function*(){if(!this.pcManager)throw new Gt("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 P(this,void 0,void 0,function*(){if(!this.pcManager)throw new Gt("publisher is closed");return this.pcManager.addPublisherTrack(e)})}attemptReconnect(e){return P(this,void 0,void 0,function*(){var t,n,s;if(!this._isClosed){if(this.attemptingReconnect){Ke.warn("already attempting reconnect, returning early",this.logContext);return}(((t=this.clientConfiguration)===null||t===void 0?void 0:t.resumeConnection)===kr.DISABLED||((s=(n=this.pcManager)===null||n===void 0?void 0:n.currentState)!==null&&s!==void 0?s:Pt.NEW)===Pt.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 Gt?(this.log.debug("received unrecoverable error",Object.assign(Object.assign({},this.logContext),{error:r})),a=!1):r instanceof Vs||(this.fullReconnectOnNext=!0),a?this.handleDisconnect("reconnect",Is.RR_UNKNOWN):(this.log.info("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(Date.now()-this.reconnectStart,"ms. giving up"),this.logContext),this.emit(de.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",Object.assign(Object.assign({},this.logContext),{error:t}))}return null}restartConnection(e){return P(this,void 0,void 0,function*(){var t,n,s;try{if(!this.url||!this.token)throw new Gt("could not reconnect, url or token not saved");this.log.info("reconnecting, attempt: ".concat(this.reconnectAttempts),this.logContext),this.emit(de.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",this.logContext),new Vs;r=yield this.join(e??this.url,this.token,this.signalOpts)}catch(a){throw a instanceof _t&&a.reason===tt.NotAllowed?new Gt("could not reconnect, token might be expired"):new Vs}if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(this.client.setReconnected(),this.emit(de.SignalRestarted,r),yield this.waitForPCReconnected(),this.client.currentState!==Mt.CONNECTED)throw new Vs("Signal connection got severed during reconnect");(t=this.regionUrlProvider)===null||t===void 0||t.resetAttempts(),this.emit(de.Restarted)}catch(r){const a=yield(n=this.regionUrlProvider)===null||n===void 0?void 0:n.getNextBestRegionUrl();if(a){yield this.restartConnection(a);return}else throw(s=this.regionUrlProvider)===null||s===void 0||s.resetAttempts(),r}})}resumeConnection(e){return P(this,void 0,void 0,function*(){var t;if(!this.url||!this.token)throw new Gt("could not reconnect, url or token not saved");if(!this.pcManager)throw new Gt("publisher and subscriber connections unset");this.log.info("resuming signal connection, attempt ".concat(this.reconnectAttempts),this.logContext),this.emit(de.Resuming);let n;try{this.setupSignalClientCallbacks(),n=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,Object.assign(Object.assign({},this.logContext),{error:s}))),s instanceof _t&&s.reason===tt.NotAllowed?new Gt("could not reconnect, token might be expired"):s instanceof _t&&s.reason===tt.LeaveRequest?s:new Vs(r)}if(this.emit(de.SignalResumed),n){const s=this.makeRTCConfiguration(n);this.pcManager.updateConfiguration(s),this.latestJoinResponse&&(this.latestJoinResponse.serverInfo=n.serverInfo)}else this.log.warn("Did not receive reconnect response",this.logContext);if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(yield this.pcManager.triggerIceRestart(),yield this.waitForPCReconnected(),this.client.currentState!==Mt.CONNECTED)throw new Vs("Signal connection got severed during reconnect");this.client.setReconnected(),((t=this.reliableDC)===null||t===void 0?void 0:t.readyState)==="open"&&this.reliableDC.id===null&&this.createDataChannels(),n!=null&&n.lastMessageSeq&&this.resendReliableMessagesForResume(n.lastMessageSeq),this.emit(de.Resumed)})}waitForPCInitialConnection(e,t){return P(this,void 0,void 0,function*(){if(!this.pcManager)throw new Gt("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(t,e)})}waitForPCReconnected(){return P(this,void 0,void 0,function*(){this.pcState=On.Reconnecting,this.log.debug("waiting for peer connection to reconnect",this.logContext);try{if(yield un(Nb),!this.pcManager)throw new Gt("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(void 0,this.peerConnectionTimeout),this.pcState=On.Connected}catch(e){throw this.pcState=On.Disconnected,new _t("could not establish PC connection, ".concat(e.message),tt.InternalError)}})}publishRpcResponse(e,t,n,s){return P(this,void 0,void 0,function*(){const r=new dn({destinationIdentities:[e],kind:We.RELIABLE,value:{case:"rpcResponse",value:new nh({requestId:t,value:s?{case:"error",value:s.toProto()}:{case:"payload",value:n??""}})}});yield this.sendDataPacket(r,We.RELIABLE)})}publishRpcAck(e,t){return P(this,void 0,void 0,function*(){const n=new dn({destinationIdentities:[e],kind:We.RELIABLE,value:{case:"rpcAck",value:new th({requestId:t})}});yield this.sendDataPacket(n,We.RELIABLE)})}sendDataPacket(e,t){return P(this,void 0,void 0,function*(){yield this.ensurePublisherConnected(t),t===We.RELIABLE&&(e.sequence=this.reliableDataSequence,this.reliableDataSequence+=1);const n=e.toBinary(),s=this.dataChannelForKind(t);if(s){if(t===We.RELIABLE&&this.reliableMessageBuffer.push({data:n,sequence:e.sequence}),this.attemptingReconnect)return;s.send(n)}this.updateAndEmitDCBufferStatus(t)})}resendReliableMessagesForResume(e){return P(this,void 0,void 0,function*(){yield this.ensurePublisherConnected(We.RELIABLE);const t=this.dataChannelForKind(We.RELIABLE);t&&(this.reliableMessageBuffer.popToSequence(e),this.reliableMessageBuffer.getAll().forEach(n=>{t.send(n.data)})),this.updateAndEmitDCBufferStatus(We.RELIABLE)})}waitForBufferStatusLow(e){return new Promise((t,n)=>P(this,void 0,void 0,function*(){if(this.isBufferStatusLow(e))t();else{const s=()=>n("Engine closed");for(this.once(de.Closing,s);!this.dcBufferStatus.get(e);)yield un(10);this.off(de.Closing,s),t()}}))}ensureDataTransportConnected(e){return P(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 Gt("PC manager is closed");const a=s?n.pcManager.subscriber:n.pcManager.publisher,o=s?"Subscriber":"Publisher";if(!a)throw new _t("".concat(o," connection not set"),tt.InternalError);let c=!1;!s&&!n.dataChannelForKind(t,s)&&(n.createDataChannels(),c=!0),!c&&!s&&!n.pcManager.publisher.isICEConnected&&n.pcManager.publisher.getICEConnectionState()!=="checking"&&(c=!0),c&&n.negotiate();const l=n.dataChannelForKind(t,s);if((l==null?void 0:l.readyState)==="open")return;const d=new Date().getTime()+n.peerConnectionTimeout;for(;new Date().getTime()<d;){if(a.isICEConnected&&((r=n.dataChannelForKind(t,s))===null||r===void 0?void 0:r.readyState)==="open")return;yield un(50)}throw new _t("could not establish ".concat(o," connection, state: ").concat(a.getICEConnectionState()),tt.InternalError)}()})}ensurePublisherConnected(e){return P(this,void 0,void 0,function*(){this.publisherConnectionPromise||(this.publisherConnectionPromise=this.ensureDataTransportConnected(e,!1)),yield this.publisherConnectionPromise})}verifyTransport(){return!(!this.pcManager||this.pcManager.currentState!==Pt.CONNECTED||!this.client.ws||this.client.ws.readyState===WebSocket.CLOSED)}negotiate(){return P(this,void 0,void 0,function*(){return new Promise((e,t)=>P(this,void 0,void 0,function*(){if(!this.pcManager){t(new Ec("PC manager is closed"));return}this.pcManager.requirePublisher(),this.pcManager.publisher.getTransceivers().length==0&&!this.lossyDC&&!this.reliableDC&&this.createDataChannels();const n=new AbortController,s=()=>{n.abort(),this.log.debug("engine disconnected while negotiation was ongoing",this.logContext),e()};this.isClosed&&t("cannot negotiate on closed engine"),this.on(de.Closing,s),this.pcManager.publisher.once(zs.RTPVideoPayloadTypes,r=>{const a=new Map;r.forEach(o=>{const c=o.codec.toLowerCase();z0(c)&&a.set(o.payload,c)}),this.emit(de.RTPVideoMapUpdate,a)});try{yield this.pcManager.negotiate(n),e()}catch(r){r instanceof Ec&&(this.fullReconnectOnNext=!0),this.handleDisconnect("negotiation",Is.RR_UNKNOWN),t(r)}finally{this.off(de.Closing,s)}}))})}dataChannelForKind(e,t){if(t){if(e===We.LOSSY)return this.lossyDCSub;if(e===We.RELIABLE)return this.reliableDCSub}else{if(e===We.LOSSY)return this.lossyDC;if(e===We.RELIABLE)return this.reliableDC}}sendSyncState(e,t){var n,s;if(!this.pcManager){this.log.warn("sync state cannot be sent without peer connection setup",this.logContext);return}const r=this.pcManager.subscriber.getLocalDescription(),a=this.pcManager.subscriber.getRemoteDescription(),o=(s=(n=this.signalOpts)===null||n===void 0?void 0:n.autoSubscribe)!==null&&s!==void 0?s:!0,c=new Array,l=new Array;e.forEach(d=>{d.isDesired!==o&&c.push(d.trackSid),d.isEnabled||l.push(d.trackSid)}),this.client.sendSyncState(new Sh({answer:r?Ga({sdp:r.sdp,type:r.type}):void 0,offer:a?Ga({sdp:a.sdp,type:a.type}):void 0,subscription:new Ra({trackSids:c,subscribe:!o,participantTracks:[]}),publishTracks:Y0(t),dataChannels:this.dataChannelsInfo(),trackSidsDisabled:l,datachannelReceiveStates:this.reliableReceivedState.map((d,u)=>new xh({publisherSid:u,lastSeq:d}))}))}failNext(){this.shouldFailNext=!0}dataChannelsInfo(){const e=[],t=(n,s)=>{(n==null?void 0:n.id)!==void 0&&n.id!==null&&e.push(new Th({label:n.label,id:n.id,target:s}))};return t(this.dataChannelForKind(We.LOSSY),Dn.PUBLISHER),t(this.dataChannelForKind(We.RELIABLE),Dn.PUBLISHER),t(this.dataChannelForKind(We.LOSSY,!0),Dn.SUBSCRIBER),t(this.dataChannelForKind(We.RELIABLE,!0),Dn.SUBSCRIBER),e}clearReconnectTimeout(){this.reconnectTimeout&&Yt.clearTimeout(this.reconnectTimeout)}clearPendingReconnect(){this.clearReconnectTimeout(),this.reconnectAttempts=0}registerOnLineListener(){hn()&&window.addEventListener("online",this.handleBrowserOnLine)}deregisterOnLineListener(){hn()&&window.removeEventListener("online",this.handleBrowserOnLine)}}class Vs extends Error{}function Bb(i){return i!==void 0&&i>13}function zb(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}class al{constructor(e,t){this.lastUpdateAt=0,this.settingsCacheTime=3e3,this.attemptedRegions=[],this.serverUrl=new URL(e),this.token=t}updateToken(e){this.token=e}isCloud(){return Lc(this.serverUrl)}getServerUrl(){return this.serverUrl}getNextBestRegionUrl(e){return P(this,void 0,void 0,function*(){if(!this.isCloud())throw Error("region availability is only supported for LiveKit Cloud domains");(!this.regionSettings||Date.now()-this.lastUpdateAt>this.settingsCacheTime)&&(this.regionSettings=yield this.fetchRegionSettings(e));const t=this.regionSettings.regions.filter(n=>!this.attemptedRegions.find(s=>s.url===n.url));if(t.length>0){const n=t[0];return this.attemptedRegions.push(n),Ke.debug("next region: ".concat(n.region)),n.url}else return null})}resetAttempts(){this.attemptedRegions=[]}fetchRegionSettings(e){return P(this,void 0,void 0,function*(){const t=yield fetch("".concat(Vb(this.serverUrl),"/regions"),{headers:{authorization:"Bearer ".concat(this.token)},signal:e});if(t.ok){const n=yield t.json();return this.lastUpdateAt=Date.now(),n}else throw new _t("Could not fetch region settings: ".concat(t.statusText),t.status===401?tt.NotAllowed:tt.InternalError,t.status)})}setServerReportedRegions(e){this.regionSettings=e,this.lastUpdateAt=Date.now()}}function Vb(i){return"".concat(i.protocol.replace("ws","http"),"//").concat(i.host,"/settings")}class ip{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 zi("Not enough chunk(s) received - expected ".concat(this.totalByteSize," bytes of data total, only received ").concat(this.bytesReceived," bytes"),Un.Incomplete);if(this.bytesReceived>this.totalByteSize)throw new zi("Extra chunk(s) received - expected ".concat(this.totalByteSize," bytes of data total, received ").concat(this.bytesReceived," bytes"),Un.LengthExceeded)}}constructor(e,t,n,s){this.reader=t,this.totalByteSize=n,this._info=e,this.bytesReceived=0,this.outOfBandFailureRejectingFuture=s}}class Gb extends ip{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();let t=new Zn,n=null,s=null;if(this.signal){const a=this.signal;s=()=>{var o;(o=t.reject)===null||o===void 0||o.call(t,a.reason)},a.addEventListener("abort",s),n=a}const r=()=>{e.releaseLock(),n&&s&&n.removeEventListener("abort",s),this.signal=void 0};return{next:()=>P(this,void 0,void 0,function*(){var a,o;try{const{done:c,value:l}=yield Promise.race([e.read(),t.promise,(o=(a=this.outOfBandFailureRejectingFuture)===null||a===void 0?void 0:a.promise)!==null&&o!==void 0?o:new Promise(()=>{})]);return c?(this.validateBytesReceived(!0),{done:!0,value:void 0}):(this.handleChunkReceived(l),{done:!1,value:l.content})}catch(c){throw r(),c}}),return(){return P(this,void 0,void 0,function*(){return r(),{done:!0,value:void 0}})}}}withAbortSignal(e){return this.signal=e,this}readAll(){return P(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return function*(){var n,s,r,a;let o=new Set;const c=t.signal?e.withAbortSignal(t.signal):e;try{for(var l=!0,d=pi(c),u;u=yield d.next(),n=u.done,!n;l=!0){a=u.value,l=!1;const h=a;o.add(h)}}catch(h){s={error:h}}finally{try{!l&&!n&&(r=d.return)&&(yield r.call(d))}finally{if(s)throw s.error}}return Array.from(o)}()})}}class Hb extends ip{constructor(e,t,n,s){super(e,t,n,s),this.receivedChunks=new Map}handleChunkReceived(e){var t;const n=Va(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(),t=new TextDecoder("utf-8",{fatal:!0});let n=new Zn,s=null,r=null;if(this.signal){const o=this.signal;r=()=>{var c;(c=n.reject)===null||c===void 0||c.call(n,o.reason)},o.addEventListener("abort",r),s=o}const a=()=>{e.releaseLock(),s&&r&&s.removeEventListener("abort",r),this.signal=void 0};return{next:()=>P(this,void 0,void 0,function*(){var o,c;try{const{done:l,value:d}=yield Promise.race([e.read(),n.promise,(c=(o=this.outOfBandFailureRejectingFuture)===null||o===void 0?void 0:o.promise)!==null&&c!==void 0?c:new Promise(()=>{})]);if(l)return this.validateBytesReceived(!0),{done:!0,value:void 0};{this.handleChunkReceived(d);let u;try{u=t.decode(d.content)}catch(h){throw new zi("Cannot decode datastream chunk ".concat(d.chunkIndex," as text: ").concat(h),Un.DecodeFailed)}return{done:!1,value:u}}}catch(l){throw a(),l}}),return(){return P(this,void 0,void 0,function*(){return a(),{done:!0,value:void 0}})}}}withAbortSignal(e){return this.signal=e,this}readAll(){return P(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return function*(){var n,s,r,a;let o="";const c=t.signal?e.withAbortSignal(t.signal):e;try{for(var l=!0,d=pi(c),u;u=yield d.next(),n=u.done,!n;l=!0)a=u.value,l=!1,o+=a}catch(h){s={error:h}}finally{try{!l&&!n&&(r=d.return)&&(yield r.call(d))}finally{if(s)throw s.error}}return o}()})}}class Wb{constructor(){this.log=Ke,this.byteStreamControllers=new Map,this.textStreamControllers=new Map,this.byteStreamHandlers=new Map,this.textStreamHandlers=new Map}registerTextStreamHandler(e,t){if(this.textStreamHandlers.has(e))throw new zi('A text stream handler for topic "'.concat(e,'" has already been set.'),Un.HandlerAlreadyRegistered);this.textStreamHandlers.set(e,t)}unregisterTextStreamHandler(e){this.textStreamHandlers.delete(e)}registerByteStreamHandler(e,t){if(this.byteStreamHandlers.has(e))throw new zi('A byte stream handler for topic "'.concat(e,'" has already been set.'),Un.HandlerAlreadyRegistered);this.byteStreamHandlers.set(e,t)}unregisterByteStreamHandler(e){this.byteStreamHandlers.delete(e)}clearHandlersAndControllers(){this.byteStreamControllers.clear(),this.textStreamControllers.clear(),this.byteStreamHandlers.clear(),this.textStreamHandlers.clear()}validateParticipantHasNoActiveDataStreams(e){var t,n,s,r;const a=Array.from(this.textStreamControllers.entries()).filter(c=>c[1].sendingParticipantIdentity===e),o=Array.from(this.byteStreamControllers.entries()).filter(c=>c[1].sendingParticipantIdentity===e);if(a.length>0||o.length>0){const c=new zi("Participant ".concat(e," unexpectedly disconnected in the middle of sending data"),Un.AbnormalEnd);for(const[l,d]of o)(n=(t=d.outOfBandFailureRejectingFuture).reject)===null||n===void 0||n.call(t,c),this.byteStreamControllers.delete(l);for(const[l,d]of a)(r=(s=d.outOfBandFailureRejectingFuture).reject)===null||r===void 0||r.call(s,c),this.textStreamControllers.delete(l)}}handleDataStreamPacket(e){return P(this,void 0,void 0,function*(){switch(e.value.case){case"streamHeader":return this.handleStreamHeader(e.value.value,e.participantIdentity);case"streamChunk":return this.handleStreamChunk(e.value.value);case"streamTrailer":return this.handleStreamTrailer(e.value.value);default:throw new Error('DataPacket of value "'.concat(e.value.case,'" is not data stream related!'))}})}handleStreamHeader(e,t){return P(this,void 0,void 0,function*(){var n;if(e.contentHeader.case==="byteHeader"){const s=this.byteStreamHandlers.get(e.topic);if(!s){this.log.debug("ignoring incoming byte stream due to no handler for topic",e.topic);return}let r;const a=new Zn,o={id:e.streamId,name:(n=e.contentHeader.value.name)!==null&&n!==void 0?n:"unknown",mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:Va(e.timestamp),attributes:e.attributes},c=new ReadableStream({start:l=>{if(r=l,this.textStreamControllers.has(e.streamId))throw new zi("A data stream read is already in progress for a stream with id ".concat(e.streamId,"."),Un.AlreadyOpened);this.byteStreamControllers.set(e.streamId,{info:o,controller:r,startTime:Date.now(),sendingParticipantIdentity:t,outOfBandFailureRejectingFuture:a})}});s(new Gb(o,c,Va(e.totalLength),a),{identity:t})}else if(e.contentHeader.case==="textHeader"){const s=this.textStreamHandlers.get(e.topic);if(!s){this.log.debug("ignoring incoming text stream due to no handler for topic",e.topic);return}let r;const a=new Zn,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},c=new ReadableStream({start:l=>{if(r=l,this.textStreamControllers.has(e.streamId))throw new zi("A data stream read is already in progress for a stream with id ".concat(e.streamId,"."),Un.AlreadyOpened);this.textStreamControllers.set(e.streamId,{info:o,controller:r,startTime:Date.now(),sendingParticipantIdentity:t,outOfBandFailureRejectingFuture:a})}});s(new Hb(o,c,Va(e.totalLength),a),{identity:t})}})}handleStreamChunk(e){const t=this.byteStreamControllers.get(e.streamId);t&&e.content.length>0&&t.controller.enqueue(e);const n=this.textStreamControllers.get(e.streamId);n&&e.content.length>0&&n.controller.enqueue(e)}handleStreamTrailer(e){const t=this.textStreamControllers.get(e.streamId);t&&(t.info.attributes=Object.assign(Object.assign({},t.info.attributes),e.attributes),t.controller.close(),this.textStreamControllers.delete(e.streamId));const n=this.byteStreamControllers.get(e.streamId);n&&(n.info.attributes=Object.assign(Object.assign({},n.info.attributes),e.attributes),n.controller.close(),this.byteStreamControllers.delete(e.streamId))}}class sp{constructor(e,t,n){this.writableStream=e,this.defaultWriter=e.getWriter(),this.onClose=n,this.info=t}write(e){return this.defaultWriter.write(e)}close(){return P(this,void 0,void 0,function*(){var e;yield this.defaultWriter.close(),this.defaultWriter.releaseLock(),(e=this.onClose)===null||e===void 0||e.call(this)})}}class qb extends sp{}class $b extends sp{}const rp=15e3;class jb{constructor(e,t){this.engine=e,this.log=t}setupEngine(e){this.engine=e}sendText(e,t){return P(this,void 0,void 0,function*(){var n;const s=crypto.randomUUID(),a=new TextEncoder().encode(e).byteLength,o=(n=t==null?void 0:t.attachments)===null||n===void 0?void 0:n.map(()=>crypto.randomUUID()),c=new Array(o?o.length+1:1).fill(0),l=(u,h)=>{var f;c[h]=u;const g=c.reduce((v,m)=>v+m,0);(f=t==null?void 0:t.onProgress)===null||f===void 0||f.call(t,g)},d=yield this.streamText({streamId:s,totalSize:a,destinationIdentities:t==null?void 0:t.destinationIdentities,topic:t==null?void 0:t.topic,attachedStreamIds:o,attributes:t==null?void 0:t.attributes});return yield d.write(e),l(1,0),yield d.close(),t!=null&&t.attachments&&o&&(yield Promise.all(t.attachments.map((u,h)=>P(this,void 0,void 0,function*(){return this._sendFile(o[h],u,{topic:t.topic,mimeType:u.type,onProgress:f=>{l(f,h+1)}})})))),d.info})}streamText(e){return P(this,void 0,void 0,function*(){var t,n;const s=(t=e==null?void 0:e.streamId)!==null&&t!==void 0?t:crypto.randomUUID(),r={id:s,mimeType:"text/plain",timestamp:Date.now(),topic:(n=e==null?void 0:e.topic)!==null&&n!==void 0?n:"",size:e==null?void 0:e.totalSize,attributes:e==null?void 0:e.attributes},a=new ic({streamId:s,mimeType:r.mimeType,topic:r.topic,timestamp:ds(r.timestamp),totalLength:ds(e==null?void 0:e.totalSize),attributes:r.attributes,contentHeader:{case:"textHeader",value:new uh({version:e==null?void 0:e.version,attachedStreamIds:e==null?void 0:e.attachedStreamIds,replyToStreamId:e==null?void 0:e.replyToStreamId,operationType:(e==null?void 0:e.type)==="update"?nc.UPDATE:nc.CREATE})}}),o=e==null?void 0:e.destinationIdentities,c=new dn({destinationIdentities:o,value:{case:"streamHeader",value:a}});yield this.engine.sendDataPacket(c,We.RELIABLE);let l=0;const d=this.engine,u=new WritableStream({write(g){return P(this,void 0,void 0,function*(){for(const v of $0(g,rp)){yield d.waitForBufferStatusLow(We.RELIABLE);const m=new sc({content:v,streamId:s,chunkIndex:ds(l)}),p=new dn({destinationIdentities:o,value:{case:"streamChunk",value:m}});yield d.sendDataPacket(p,We.RELIABLE),l+=1}})},close(){return P(this,void 0,void 0,function*(){const g=new rc({streamId:s}),v=new dn({destinationIdentities:o,value:{case:"streamTrailer",value:g}});yield d.sendDataPacket(v,We.RELIABLE)})},abort(g){console.log("Sink error:",g)}});let h=()=>P(this,void 0,void 0,function*(){yield f.close()});d.once(de.Closing,h);const f=new qb(u,r,()=>this.engine.off(de.Closing,h));return f})}sendFile(e,t){return P(this,void 0,void 0,function*(){const n=crypto.randomUUID();return yield this._sendFile(n,e,t),{id:n}})}_sendFile(e,t,n){return P(this,void 0,void 0,function*(){var s;const r=yield this.streamBytes({streamId:e,totalSize:t.size,name:t.name,mimeType:(s=n==null?void 0:n.mimeType)!==null&&s!==void 0?s:t.type,topic:n==null?void 0:n.topic,destinationIdentities:n==null?void 0:n.destinationIdentities}),a=t.stream().getReader();for(;;){const{done:o,value:c}=yield a.read();if(o)break;yield r.write(c)}return yield r.close(),r.info})}streamBytes(e){return P(this,void 0,void 0,function*(){var t,n,s,r,a;const o=(t=e==null?void 0:e.streamId)!==null&&t!==void 0?t:crypto.randomUUID(),c=e==null?void 0:e.destinationIdentities,l={id:o,mimeType:(n=e==null?void 0:e.mimeType)!==null&&n!==void 0?n:"application/octet-stream",topic:(s=e==null?void 0:e.topic)!==null&&s!==void 0?s:"",timestamp:Date.now(),attributes:e==null?void 0:e.attributes,size:e==null?void 0:e.totalSize,name:(r=e==null?void 0:e.name)!==null&&r!==void 0?r:"unknown"},d=new ic({totalLength:ds((a=l.size)!==null&&a!==void 0?a:0),mimeType:l.mimeType,streamId:o,topic:l.topic,timestamp:ds(Date.now()),attributes:l.attributes,contentHeader:{case:"byteHeader",value:new hh({name:l.name})}}),u=new dn({destinationIdentities:c,value:{case:"streamHeader",value:d}});yield this.engine.sendDataPacket(u,We.RELIABLE);let h=0;const f=new cn,g=this.engine,v=this.log,m=new WritableStream({write(x){return P(this,void 0,void 0,function*(){const C=yield f.lock();let b=0;try{for(;b<x.byteLength;){const S=x.slice(b,b+rp);yield g.waitForBufferStatusLow(We.RELIABLE);const M=new dn({destinationIdentities:c,value:{case:"streamChunk",value:new sc({content:S,streamId:o,chunkIndex:ds(h)})}});yield g.sendDataPacket(M,We.RELIABLE),h+=1,b+=S.byteLength}}finally{C()}})},close(){return P(this,void 0,void 0,function*(){const x=new rc({streamId:o}),C=new dn({destinationIdentities:c,value:{case:"streamTrailer",value:x}});yield g.sendDataPacket(C,We.RELIABLE)})},abort(x){v.error("Sink error:",x)}});return new $b(m,l)})}}class ap extends Q{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?oe.Muted:oe.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(oe.Ended,this))};e.addEventListener("removetrack",t)}start(){this.startMonitor(),super.enable()}stop(){this.stopMonitor(),super.disable()}getRTCStatsReport(){return P(this,void 0,void 0,function*(){var e;return!((e=this.receiver)===null||e===void 0)&&e.getStats?yield this.receiver.getStats():void 0})}setPlayoutDelay(e){this.receiver?"playoutDelayHint"in this.receiver?this.receiver.playoutDelayHint=e:this.log.warn("Playout delay not supported in this browser"):this.log.warn("Cannot set playout delay, track already ended")}getPlayoutDelay(){if(this.receiver){if("playoutDelayHint"in this.receiver)return this.receiver.playoutDelayHint;this.log.warn("Playout delay not supported in this browser")}else this.log.warn("Cannot get playout delay, track already ended");return 0}startMonitor(){this.monitorInterval||(this.monitorInterval=setInterval(()=>this.monitorReceiver(),el)),K0()&&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{timestamp:s,rtpTimestamp:r}=n;r&&this.rtpTimestamp!==r&&(this.emit(oe.TimeSyncUpdate,{timestamp:s,rtpTimestamp:r}),this.rtpTimestamp=r)}};e()}}class Xb extends ap{constructor(e,t,n,s,r,a){super(e,t,Q.Kind.Audio,n,a),this.monitorReceiver=()=>P(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=Ha(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;Kn()&&this._mediaStreamTrack._setVolume(e),this.elementVolume=e}getVolume(){if(this.elementVolume)return this.elementVolume;if(Kn())return 1;let e=0;return this.attachedElements.forEach(t=>{t.volume>e&&(e=t.volume)}),e}setSinkId(e){return P(this,void 0,void 0,function*(){this.sinkId=e,yield Promise.all(this.attachedElements.map(t=>{if(Dc(t))return t.setSinkId(e)}))})}attach(e){const t=this.attachedElements.length===0;return e?super.attach(e):e=super.attach(),this.sinkId&&Dc(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(oe.AudioPlaybackFailed,new Error("Audio Context couldn't be started automatically"))}).catch(s=>{this.emit(oe.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 P(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})}}const ol=100;class Yb extends ap{constructor(e,t,n,s,r){super(e,t,Q.Kind.Video,n,r),this.elementInfos=[],this.monitorReceiver=()=>P(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=Ha(a,this.prevStats)),this.prevStats=a}),this.debouncedHandleResize=Kc(()=>{this.updateDimensions()},ol),this.adaptiveStreamSettings=s}get isAdaptiveStream(){return this.adaptiveStreamSettings!==void 0}setStreamState(e){super.setStreamState(e),console.log("setStreamState",e),e===Q.StreamState.Active&&this.updateVisibility()}get mediaStreamTrack(){return this._mediaStreamTrack}setMuted(e){super.setMuted(e),this.attachedElements.forEach(t=>{e?Fs(this._mediaStreamTrack,t):Os(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 Kb(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){let t=[];if(e)return this.stopObservingElement(e),super.detach(e);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 P(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 P(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((c,l)=>Math.max(c,l.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(c=>c.pictureInPicture),o=this.elementInfos.some(c=>c.visible)&&!r||a;if(!(this.lastVisible===o&&!e)){if(!o&&Date.now()-s<ol){Yt.setTimeout(()=>{this.updateVisibility()},ol);return}this.lastVisible=o,this.emit(oe.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,c=a.height()*r;o+c>n+s&&(n=o,s=c)}((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},this.emit(oe.VideoDimensionsChanged,this.lastDimensions,this))}getPixelDensity(){var e;const t=(e=this.adaptiveStreamSettings)===null||e===void 0?void 0:e.pixelDensity;return t==="screen"?Cf():t||(Cf()>2?2:1)}}class Kb{get visible(){return this.isPiP||this.isIntersecting}get pictureInPicture(){return this.isPiP}constructor(e,t){this.onVisibilityChanged=n=>{var s;const{target:r,isIntersecting:a}=n;r===this.element&&(this.isIntersecting=a,this.isPiP=Gr(this.element),this.visibilityChangedAt=Date.now(),(s=this.handleVisibilityChanged)===null||s===void 0||s.call(this))},this.onEnterPiP=()=>{var n,s,r;(s=(n=window.documentPictureInPicture)===null||n===void 0?void 0:n.window)===null||s===void 0||s.addEventListener("pagehide",this.onLeavePiP),this.isPiP=Gr(this.element),(r=this.handleVisibilityChanged)===null||r===void 0||r.call(this)},this.onLeavePiP=()=>{var n;this.isPiP=Gr(this.element),(n=this.handleVisibilityChanged)===null||n===void 0||n.call(this)},this.element=e,this.isIntersecting=t??cl(e),this.isPiP=hn()&&Gr(e),this.visibilityChangedAt=0}width(){return this.element.clientWidth}height(){return this.element.clientHeight}observe(){var e,t,n;this.isIntersecting=cl(this.element),this.isPiP=Gr(this.element),this.element.handleResize=()=>{var s;(s=this.handleResize)===null||s===void 0||s.call(this)},this.element.handleVisibilityChanged=this.onVisibilityChanged,Mf().observe(this.element),Ef().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=Mf())===null||e===void 0||e.unobserve(this.element),(t=Ef())===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 Gr(i){var e,t;return document.pictureInPictureElement===i?!0:!((e=window.documentPictureInPicture)===null||e===void 0)&&e.window?cl(i,(t=window.documentPictureInPicture)===null||t===void 0?void 0:t.window):!1}function cl(i,e){const t=e||window;let n=i.offsetTop,s=i.offsetLeft;const r=i.offsetWidth,a=i.offsetHeight,{hidden:o}=i,{display:c}=getComputedStyle(i);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&&!o&&c!=="none"}class bi extends Xn.EventEmitter{constructor(e,t,n,s){var r;super(),this.metadataMuted=!1,this.encryption=vn.NONE,this.log=Ke,this.handleMuted=()=>{this.emit(oe.Muted)},this.handleUnmuted=()=>{this.emit(oe.Unmuted)},this.log=fi((r=s==null?void 0:s.loggerName)!==null&&r!==void 0?r:Ln.Publication),this.loggerContextCb=this.loggerContextCb,this.setMaxListeners(100),this.kind=e,this.trackSid=t,this.trackName=n,this.source=Q.Source.Unknown}setTrack(e){this.track&&(this.track.off(oe.Muted,this.handleMuted),this.track.off(oe.Unmuted,this.handleUnmuted)),this.track=e,e&&(e.on(oe.Muted,this.handleMuted),e.on(oe.Unmuted,this.handleUnmuted))}get logContext(){var e;return Object.assign(Object.assign({},(e=this.loggerContextCb)===null||e===void 0?void 0:e.call(this)),Xe(this))}get isMuted(){return this.metadataMuted}get isEnabled(){return!0}get isSubscribed(){return this.track!==void 0}get isEncrypted(){return this.encryption!==vn.NONE}get audioTrack(){if(Qn(this.track))return this.track}get videoTrack(){if(Gi(this.track))return this.track}updateInfo(e){this.trackSid=e.sid,this.trackName=e.name,this.source=Q.sourceFromProto(e.source),this.mimeType=e.mimeType,this.kind===Q.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={}))})(bi||(bi={}));class ll extends bi{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=()=>{this.emit(oe.Ended)},this.handleCpuConstrained=()=>{this.track&&Gi(this.track)&&this.emit(oe.CpuConstrained,this.track)},this.updateInfo(t),this.setTrack(n)}setTrack(e){this.track&&(this.track.off(oe.Ended,this.handleTrackEnded),this.track.off(oe.CpuConstrained,this.handleCpuConstrained)),super.setTrack(e),e&&(e.on(oe.Ended,this.handleTrackEnded),e.on(oe.CpuConstrained,this.handleCpuConstrained))}get isMuted(){return this.track?this.track.isMuted:super.isMuted}get audioTrack(){return super.audioTrack}get videoTrack(){return super.videoTrack}get isLocal(){return!0}mute(){return P(this,void 0,void 0,function*(){var e;return(e=this.track)===null||e===void 0?void 0:e.mute()})}unmute(){return P(this,void 0,void 0,function*(){var e;return(e=this.track)===null||e===void 0?void 0:e.unmute()})}pauseUpstream(){return P(this,void 0,void 0,function*(){var e;yield(e=this.track)===null||e===void 0?void 0:e.pauseUpstream()})}resumeUpstream(){return P(this,void 0,void 0,function*(){var e;yield(e=this.track)===null||e===void 0?void 0:e.resumeUpstream()})}getTrackFeatures(){var e;if(Qn(this.track)){const t=this.track.getSourceTrackSettings(),n=new Set;return t.autoGainControl&&n.add(qt.TF_AUTO_GAIN_CONTROL),t.echoCancellation&&n.add(qt.TF_ECHO_CANCELLATION),t.noiseSuppression&&n.add(qt.TF_NOISE_SUPPRESSION),t.channelCount&&t.channelCount>1&&n.add(qt.TF_STEREO),!((e=this.options)===null||e===void 0)&&e.dtx||n.add(qt.TF_NO_DTX),this.track.enhancedNoiseCancellation&&n.add(qt.TF_ENHANCED_NOISE_CANCELLATION),Array.from(n.values())}else return[]}}function $a(i,e){return P(this,void 0,void 0,function*(){i??(i={});let t=!1;const{audioProcessor:n,videoProcessor:s,optionsWithoutProcessor:r}=If(i);let a=r.audio,o=r.video;if(n&&typeof r.audio=="object"&&(r.audio.processor=n),s&&typeof r.video=="object"&&(r.video.processor=s),i.audio&&typeof r.audio=="object"&&typeof r.audio.deviceId=="string"){const u=r.audio.deviceId;r.audio.deviceId={exact:u},t=!0,a=Object.assign(Object.assign({},r.audio),{deviceId:{ideal:u}})}if(r.video&&typeof r.video=="object"&&typeof r.video.deviceId=="string"){const u=r.video.deviceId;r.video.deviceId={exact:u},t=!0,o=Object.assign(Object.assign({},r.video),{deviceId:{ideal:u}})}(r.audio===!0||typeof r.audio=="object"&&!r.audio.deviceId)&&(r.audio={deviceId:"default"}),r.video===!0?r.video={deviceId:"default"}:typeof r.video=="object"&&!r.video.deviceId&&(r.video.deviceId="default");const c=Rf(r,Wf,qf),l=Gc(c),d=navigator.mediaDevices.getUserMedia(l);r.audio&&($t.userMediaPromiseMap.set("audioinput",d),d.catch(()=>$t.userMediaPromiseMap.delete("audioinput"))),r.video&&($t.userMediaPromiseMap.set("videoinput",d),d.catch(()=>$t.userMediaPromiseMap.delete("videoinput")));try{const u=yield d;return yield Promise.all(u.getTracks().map(h=>P(this,void 0,void 0,function*(){const f=h.kind==="audio";let g=f?c.audio:c.video;(typeof g=="boolean"||!g)&&(g={});let v;const m=f?l.audio:l.video;typeof m!="boolean"&&(v=m);const p=h.getSettings().deviceId;v!=null&&v.deviceId&&Vi(v.deviceId)!==p?v.deviceId=p:v||(v={deviceId:p});const x=Cb(h,v,e);return x.kind===Q.Kind.Video?x.source=Q.Source.Camera:x.kind===Q.Kind.Audio&&(x.source=Q.Source.Microphone),x.mediaStream=u,Qn(x)&&n?yield x.setProcessor(n):Gi(x)&&s&&(yield x.setProcessor(s)),x})))}catch(u){if(!t)throw u;return $a(Object.assign(Object.assign({},i),{audio:a,video:o}),e)}})}function Jb(i){return P(this,void 0,void 0,function*(){return(yield $a({audio:!1,video:!0}))[0]})}function Zb(i){return P(this,void 0,void 0,function*(){return(yield $a({audio:!0,video:!1}))[0]})}var qi;(function(i){i.Excellent="excellent",i.Good="good",i.Poor="poor",i.Lost="lost",i.Unknown="unknown"})(qi||(qi={}));function Qb(i){switch(i){case Pr.EXCELLENT:return qi.Excellent;case Pr.GOOD:return qi.Good;case Pr.POOR:return qi.Poor;case Pr.LOST:return qi.Lost;default:return qi.Unknown}}class op extends Xn.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===Ir.AGENT}get isActive(){var e;return((e=this.participantInfo)===null||e===void 0?void 0:e.state)===Ds.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]:Ir.STANDARD;var c;super(),this.audioLevel=0,this.isSpeaking=!1,this._connectionQuality=qi.Unknown,this.log=Ke,this.log=fi((c=a==null?void 0:a.loggerName)!==null&&c!==void 0?c:Ln.Participant),this.loggerOptions=a,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[,t]of this.trackPublications)if(t.source===e)return t}getTrackPublicationByName(e){for(const[,t]of this.trackPublications)if(t.trackName===e)return t}waitUntilActive(){return this.isActive?Promise.resolve():this.activeFuture?this.activeFuture.promise:(this.activeFuture=new Zn,this.once(le.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(Q.Source.Camera);return!(!((e=t==null?void 0:t.isMuted)!==null&&e!==void 0)||e)}get isMicrophoneEnabled(){var e;const t=this.getTrackPublication(Q.Source.Microphone);return!(!((e=t==null?void 0:t.isMuted)!==null&&e!==void 0)||e)}get isScreenShareEnabled(){return!!this.getTrackPublication(Q.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===Ds.ACTIVE&&((t=this.participantInfo)===null||t===void 0?void 0:t.state)!==Ds.ACTIVE&&this.emit(le.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(le.ParticipantMetadataChanged,n)}_setName(e){const t=this.name!==e;this.name=e,t&&this.emit(le.ParticipantNameChanged,e)}_setAttributes(e){const t=J0(this.attributes,e);this._attributes=e,Object.keys(t).length>0&&this.emit(le.AttributesChanged,t)}setPermissions(e){var t,n,s,r,a,o;const c=this.permissions,l=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((d,u)=>{var h;return d!==((h=this.permissions)===null||h===void 0?void 0:h.canPublishSources[u])})||e.canSubscribeMetrics!==((o=this.permissions)===null||o===void 0?void 0:o.canSubscribeMetrics);return this.permissions=e,l&&this.emit(le.ParticipantPermissionsChanged,c),l}setIsSpeaking(e){e!==this.isSpeaking&&(this.isSpeaking=e,e&&(this.lastSpokeAt=new Date),this.emit(le.IsSpeakingChanged,e))}setConnectionQuality(e){const t=this._connectionQuality;this._connectionQuality=Qb(e),t!==this._connectionQuality&&this.emit(le.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=>Qn(t.track)&&t.track.setAudioContext(e))}addTrackPublication(e){e.on(oe.Muted,()=>{this.emit(le.TrackMuted,e)}),e.on(oe.Unmuted,()=>{this.emit(le.TrackUnmuted,e)});const t=e;switch(t.track&&(t.track.sid=e.trackSid),this.trackPublications.set(e.trackSid,e),e.kind){case Q.Kind.Audio:this.audioTrackPublications.set(e.trackSid,e);break;case Q.Kind.Video:this.videoTrackPublications.set(e.trackSid,e);break}}}function ey(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 yh({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 ty extends op{constructor(e,t,n,s,r,a){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=vn.NONE,this.enabledPublishVideoCodecs=[],this.pendingAcks=new Map,this.pendingResponses=new Map,this.handleReconnecting=()=>{this.reconnectFuture||(this.reconnectFuture=new Zn)},this.handleReconnected=()=>{var o,c;(c=(o=this.reconnectFuture)===null||o===void 0?void 0:o.resolve)===null||c===void 0||c.call(o),this.reconnectFuture=void 0,this.updateTrackSubscriptionPermissions()},this.handleClosing=()=>{var o,c,l,d,u,h;this.reconnectFuture&&(this.reconnectFuture.promise.catch(f=>this.log.warn(f.message,this.logContext)),(c=(o=this.reconnectFuture)===null||o===void 0?void 0:o.reject)===null||c===void 0||c.call(o,"Got disconnected during reconnection attempt"),this.reconnectFuture=void 0),this.signalConnectedFuture&&((d=(l=this.signalConnectedFuture).reject)===null||d===void 0||d.call(l,"Got disconnected without signal connected"),this.signalConnectedFuture=void 0),(h=(u=this.activeAgentFuture)===null||u===void 0?void 0:u.reject)===null||h===void 0||h.call(u,"Got disconnected without active agent present"),this.activeAgentFuture=void 0,this.firstActiveAgent=void 0},this.handleSignalConnected=o=>{var c,l;o.participant&&this.updateInfo(o.participant),this.signalConnectedFuture||(this.signalConnectedFuture=new Zn),(l=(c=this.signalConnectedFuture).resolve)===null||l===void 0||l.call(c)},this.handleSignalRequestResponse=o=>{const{requestId:c,reason:l,message:d}=o,u=this.pendingSignalRequests.get(c);u&&(l!==fc.OK&&u.reject(new vf(d,l)),this.pendingSignalRequests.delete(c))},this.handleDataPacket=o=>{switch(o.value.case){case"rpcResponse":let c=o.value.value,l=null,d=null;c.value.case==="payload"?l=c.value.value:c.value.case==="error"&&(d=kt.fromProto(c.value.value)),this.handleIncomingRpcResponse(c.requestId,l,d);break;case"rpcAck":let u=o.value.value;this.handleIncomingRpcAck(u.requestId);break}},this.updateTrackSubscriptionPermissions=()=>{this.log.debug("updating track subscription permissions",Object.assign(Object.assign({},this.logContext),{allParticipantsAllowed:this.allParticipantsAllowedToSubscribe,participantTrackPermissions:this.participantTrackPermissions})),this.engine.client.sendUpdateSubscriptionPermissions(this.allParticipantsAllowedToSubscribe,this.participantTrackPermissions.map(o=>ey(o)))},this.onTrackUnmuted=o=>{this.onTrackMuted(o,o.isUpstreamPaused)},this.onTrackMuted=(o,c)=>{if(c===void 0&&(c=!0),!o.sid){this.log.error("could not update mute status for unpublished track",Object.assign(Object.assign({},this.logContext),Xe(o)));return}this.engine.updateMuteStatus(o.sid,c)},this.onTrackUpstreamPaused=o=>{this.log.debug("upstream paused",Object.assign(Object.assign({},this.logContext),Xe(o))),this.onTrackMuted(o,!0)},this.onTrackUpstreamResumed=o=>{this.log.debug("upstream resumed",Object.assign(Object.assign({},this.logContext),Xe(o))),this.onTrackMuted(o,o.isMuted)},this.onTrackFeatureUpdate=o=>{const c=this.audioTrackPublications.get(o.sid);if(!c){this.log.warn("Could not update local audio track settings, missing publication for track ".concat(o.sid),this.logContext);return}this.engine.client.sendUpdateLocalAudioTrack(c.trackSid,c.getTrackFeatures())},this.onTrackCpuConstrained=(o,c)=>{this.log.debug("track cpu constrained",Object.assign(Object.assign({},this.logContext),Xe(c))),this.emit(le.LocalTrackCpuConstrained,o,c)},this.handleSubscribedQualityUpdate=o=>P(this,void 0,void 0,function*(){var c,l,d,u,h;if(!(!((h=this.roomOptions)===null||h===void 0)&&h.dynacast))return;const f=this.videoTrackPublications.get(o.trackSid);if(!f){this.log.warn("received subscribed quality update for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:o.trackSid}));return}if(!f.videoTrack)return;const g=yield f.videoTrack.setPublishingCodecs(o.subscribedCodecs);try{for(var v=!0,m=pi(g),p;p=yield m.next(),c=p.done,!c;v=!0){u=p.value,v=!1;const x=u;A0(x)&&(this.log.debug("publish ".concat(x," for ").concat(f.videoTrack.sid),Object.assign(Object.assign({},this.logContext),Xe(f))),yield this.publishAdditionalCodecForTrack(f.videoTrack,x,f.options))}}catch(x){l={error:x}}finally{try{!v&&!c&&(d=m.return)&&(yield d.call(m))}finally{if(l)throw l.error}}}),this.handleLocalTrackUnpublished=o=>{const c=this.trackPublications.get(o.trackSid);if(!c){this.log.warn("received unpublished event for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:o.trackSid}));return}this.unpublishTrack(c.track)},this.handleTrackEnded=o=>P(this,void 0,void 0,function*(){if(o.source===Q.Source.ScreenShare||o.source===Q.Source.ScreenShareAudio)this.log.debug("unpublishing local track due to TrackEnded",Object.assign(Object.assign({},this.logContext),Xe(o))),this.unpublishTrack(o);else if(o.isUserProvided)yield o.mute();else if(vi(o)||Hi(o))try{if(hn())try{const c=yield navigator==null?void 0:navigator.permissions.query({name:o.source===Q.Source.Camera?"camera":"microphone"});if(c&&c.state==="denied")throw this.log.warn("user has revoked access to ".concat(o.source),Object.assign(Object.assign({},this.logContext),Xe(o))),c.onchange=()=>{c.state!=="denied"&&(o.isMuted||o.restartTrack(),c.onchange=null)},new Error("GetUserMedia Permission denied")}catch{}o.isMuted||(this.log.debug("track ended, attempting to use a different device",Object.assign(Object.assign({},this.logContext),Xe(o))),vi(o)?yield o.restartTrack({deviceId:"default"}):yield o.restartTrack())}catch{this.log.warn("could not restart track, muting instead",Object.assign(Object.assign({},this.logContext),Xe(o))),yield o.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.rpcHandlers=r,this.roomOutgoingDataStreamManager=a}get lastCameraError(){return this.cameraError}get lastMicrophoneError(){return this.microphoneError}get isE2EEEnabled(){return this.encryptionType!==vn.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(de.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(de.Connected,this.handleReconnected).on(de.SignalConnected,this.handleSignalConnected).on(de.SignalRestarted,this.handleReconnected).on(de.SignalResumed,this.handleReconnected).on(de.Restarting,this.handleReconnecting).on(de.Resuming,this.handleReconnecting).on(de.LocalTrackUnpublished,this.handleLocalTrackUnpublished).on(de.SubscribedQualityUpdate,this.handleSubscribedQualityUpdate).on(de.Closing,this.handleClosing).on(de.SignalRequestResponse,this.handleSignalRequestResponse).on(de.DataPacketReceived,this.handleDataPacket)}setMetadata(e){return P(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({metadata:e})})}setName(e){return P(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({name:e})})}setAttributes(e){return P(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({attributes:e})})}requestMetadataUpdate(e){return P(this,arguments,void 0,function(t){var n=this;let{metadata:s,name:r,attributes:a}=t;return function*(){return new Promise((o,c)=>P(n,void 0,void 0,function*(){var l,d;try{let u=!1;const h=yield this.engine.client.sendUpdateLocalMetadata((l=s??this.metadata)!==null&&l!==void 0?l:"",(d=r??this.name)!==null&&d!==void 0?d:"",a),f=performance.now();for(this.pendingSignalRequests.set(h,{resolve:o,reject:g=>{c(g),u=!0},values:{name:r,metadata:s,attributes:a}});performance.now()-f<5e3&&!u;){if((!r||this.name===r)&&(!s||this.metadata===s)&&(!a||Object.entries(a).every(g=>{let[v,m]=g;return this.attributes[v]===m||m===""&&!this.attributes[v]}))){this.pendingSignalRequests.delete(h),o();return}yield un(50)}c(new vf("Request to update local metadata timed out","TimeoutError"))}catch(u){u instanceof Error&&c(u)}}))}()})}setCameraEnabled(e,t,n){return this.setTrackEnabled(Q.Source.Camera,e,t,n)}setMicrophoneEnabled(e,t,n){return this.setTrackEnabled(Q.Source.Microphone,e,t,n)}setScreenShareEnabled(e,t,n){return this.setTrackEnabled(Q.Source.ScreenShare,e,t,n)}setPermissions(e){const t=this.permissions,n=super.setPermissions(e);return n&&t&&this.emit(le.ParticipantPermissionsChanged,t),n}setE2EEEnabled(e){return P(this,void 0,void 0,function*(){this.encryptionType=e?vn.GCM:vn.NONE,yield this.republishAllTracks(void 0,!1)})}setTrackEnabled(e,t,n,s){return P(this,void 0,void 0,function*(){var r,a;this.log.debug("setTrackEnabled",Object.assign(Object.assign({},this.logContext),{source:e,enabled:t})),this.republishPromise&&(yield this.republishPromise);let o=this.getTrackPublication(e);if(t)if(o)yield o.unmute();else{let c;if(this.pendingPublishing.has(e)){const l=yield this.waitForPendingPublicationOfSource(e);return l||this.log.info("waiting for pending publication promise timed out",Object.assign(Object.assign({},this.logContext),{source:e})),yield l==null?void 0:l.unmute(),l}this.pendingPublishing.add(e);try{switch(e){case Q.Source.Camera:c=yield this.createTracks({video:(r=n)!==null&&r!==void 0?r:!0});break;case Q.Source.Microphone:c=yield this.createTracks({audio:(a=n)!==null&&a!==void 0?a:!0});break;case Q.Source.ScreenShare:c=yield this.createScreenTracks(Object.assign({},n));break;default:throw new gi(e)}}catch(l){throw c==null||c.forEach(d=>{d.stop()}),l instanceof Error&&this.emit(le.MediaDevicesError,l,Hc(e)),this.pendingPublishing.delete(e),l}for(const l of c){const d=Object.assign(Object.assign({},this.roomOptions.publishDefaults),n);e===Q.Source.Microphone&&Qn(l)&&d.preConnectBuffer&&(this.log.info("starting preconnect buffer for microphone",Object.assign({},this.logContext)),l.startPreConnectBuffer())}try{const l=[];for(const u of c)this.log.info("publishing track",Object.assign(Object.assign({},this.logContext),Xe(u))),l.push(this.publishTrack(u,s));[o]=yield Promise.all(l)}catch(l){throw c==null||c.forEach(d=>{d.stop()}),l}finally{this.pendingPublishing.delete(e)}}else if(!(o!=null&&o.track)&&this.pendingPublishing.has(e)&&(o=yield this.waitForPendingPublicationOfSource(e),o||this.log.info("waiting for pending publication promise timed out",Object.assign(Object.assign({},this.logContext),{source:e}))),o&&o.track)if(e===Q.Source.ScreenShare){o=yield this.unpublishTrack(o.track);const c=this.getTrackPublication(Q.Source.ScreenShareAudio);c&&c.track&&this.unpublishTrack(c.track)}else yield o.mute();return o})}enableCameraAndMicrophone(){return P(this,void 0,void 0,function*(){if(!(this.pendingPublishing.has(Q.Source.Camera)||this.pendingPublishing.has(Q.Source.Microphone))){this.pendingPublishing.add(Q.Source.Camera),this.pendingPublishing.add(Q.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(Q.Source.Camera),this.pendingPublishing.delete(Q.Source.Microphone)}}})}createTracks(e){return P(this,void 0,void 0,function*(){var t,n;e??(e={});const s=Rf(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 $a(s,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext})).map(o=>(Qn(o)&&(this.microphoneError=void 0,o.setAudioContext(this.audioContext),o.source=Q.Source.Microphone,this.emit(le.AudioStreamAcquired)),Gi(o)&&(this.cameraError=void 0,o.source=Q.Source.Camera),o))}catch(r){throw r instanceof Error&&(e.audio&&(this.microphoneError=r),e.video&&(this.cameraError=r)),r}})}createScreenTracks(e){return P(this,void 0,void 0,function*(){if(e===void 0&&(e={}),navigator.mediaDevices.getDisplayMedia===void 0)throw new Cc("getDisplayMedia not supported");e.resolution===void 0&&!L0()&&(e.resolution=Pc.h1080fps30.resolution);const t=X0(e),n=yield navigator.mediaDevices.getDisplayMedia(t),s=n.getVideoTracks();if(s.length===0)throw new gi("no video track found");const r=new qa(s[0],void 0,!1,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});r.source=Q.Source.ScreenShare,e.contentHint&&(r.mediaStreamTrack.contentHint=e.contentHint);const a=[r];if(n.getAudioTracks().length>0){this.emit(le.AudioStreamAcquired);const o=new Wa(n.getAudioTracks()[0],void 0,!1,this.audioContext,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});o.source=Q.Source.ScreenShareAudio,a.push(o)}return a})}publishTrack(e,t){return P(this,void 0,void 0,function*(){return this.publishOrRepublishTrack(e,t)})}publishOrRepublishTrack(e,t){return P(this,arguments,void 0,function(n,s){var r=this;let a=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1;return function*(){var o,c,l,d;vi(n)&&n.setAudioContext(r.audioContext),yield(o=r.reconnectFuture)===null||o===void 0?void 0:o.promise,r.republishPromise&&!a&&(yield r.republishPromise),Bs(n)&&r.pendingPublishPromises.has(n)&&(yield r.pendingPublishPromises.get(n));let u;if(n instanceof MediaStreamTrack)u=n.getConstraints();else{u=n.constraints;let p;switch(n.source){case Q.Source.Microphone:p="audioinput";break;case Q.Source.Camera:p="videoinput"}p&&r.activeDeviceMap.has(p)&&(u=Object.assign(Object.assign({},u),{deviceId:r.activeDeviceMap.get(p)}))}if(n instanceof MediaStreamTrack)switch(n.kind){case"audio":n=new Wa(n,u,!0,r.audioContext,{loggerName:r.roomOptions.loggerName,loggerContextCb:()=>r.logContext});break;case"video":n=new qa(n,u,!0,{loggerName:r.roomOptions.loggerName,loggerContextCb:()=>r.logContext});break;default:throw new gi("unsupported MediaStreamTrack kind ".concat(n.kind))}else n.updateLoggerOptions({loggerName:r.roomOptions.loggerName,loggerContextCb:()=>r.logContext});let h;if(r.trackPublications.forEach(p=>{p.track&&p.track===n&&(h=p)}),h)return r.log.warn("track has already been published, skipping",Object.assign(Object.assign({},r.logContext),Xe(h))),h;const f="channelCount"in n.mediaStreamTrack.getSettings()&&n.mediaStreamTrack.getSettings().channelCount===2||n.mediaStreamTrack.getConstraints().channelCount===2,g=(c=s==null?void 0:s.forceStereo)!==null&&c!==void 0?c:f;g&&(s||(s={}),s.dtx===void 0&&r.log.info("Opus DTX will be disabled for stereo tracks by default. Enable them explicitly to make it work.",Object.assign(Object.assign({},r.logContext),Xe(n))),s.red===void 0&&r.log.info("Opus RED will be disabled for stereo tracks by default. Enable them explicitly to make it work."),(l=s.dtx)!==null&&l!==void 0||(s.dtx=!1),(d=s.red)!==null&&d!==void 0||(s.red=!1));const v=Object.assign(Object.assign({},r.roomOptions.publishDefaults),s);!N0()&&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",Object.assign({},r.logContext)),v.simulcast=!1),v.source&&(n.source=v.source);const m=new Promise((p,x)=>P(r,void 0,void 0,function*(){try{if(this.engine.client.currentState!==Mt.CONNECTED){this.log.debug("deferring track publication until signal is connected",Object.assign(Object.assign({},this.logContext),{track:Xe(n)}));const C=setTimeout(()=>{x(new gf("publishing rejected as engine not connected within timeout",408))},15e3);yield this.waitUntilEngineConnected(),clearTimeout(C);const b=yield this.publish(n,v,g);p(b)}else try{const C=yield this.publish(n,v,g);p(C)}catch(C){x(C)}}catch(C){x(C)}}));r.pendingPublishPromises.set(n,m);try{return yield m}catch(p){throw p}finally{r.pendingPublishPromises.delete(n)}}()})}waitUntilEngineConnected(){return this.signalConnectedFuture||(this.signalConnectedFuture=new Zn),this.signalConnectedFuture.promise}hasPermissionsToPublish(e){if(!this.permissions)return this.log.warn("no permissions present for publishing track",Object.assign(Object.assign({},this.logContext),Xe(e))),!1;const{canPublish:t,canPublishSources:n}=this.permissions;return t&&(n.length===0||n.map(s=>Z0(s)).includes(e.source))?!0:(this.log.warn("insufficient permissions to publish",Object.assign(Object.assign({},this.logContext),Xe(e))),!1)}publish(e,t,n){return P(this,void 0,void 0,function*(){var s,r,a,o,c,l,d,u,h,f;if(!this.hasPermissionsToPublish(e))throw new gf("failed to publish track, insufficient permissions",403);Array.from(this.trackPublications.values()).find(_=>Bs(e)&&_.source===e.source)&&e.source!==Q.Source.Unknown&&this.log.info("publishing a second track with the same source: ".concat(e.source),Object.assign(Object.assign({},this.logContext),Xe(e))),t.stopMicTrackOnMute&&Qn(e)&&(e.stopOnMute=!0),e.source===Q.Source.ScreenShare&&cs()&&(t.simulcast=!1),t.videoCodec==="av1"&&!k0()&&(t.videoCodec=void 0),t.videoCodec==="vp9"&&!I0()&&(t.videoCodec=void 0),t.videoCodec===void 0&&(t.videoCodec=Jc),this.enabledPublishVideoCodecs.length>0&&(this.enabledPublishVideoCodecs.some(_=>t.videoCodec===zr(_.mime))||(t.videoCodec=zr(this.enabledPublishVideoCodecs[0].mime)));const v=t.videoCodec;e.on(oe.Muted,this.onTrackMuted),e.on(oe.Unmuted,this.onTrackUnmuted),e.on(oe.Ended,this.handleTrackEnded),e.on(oe.UpstreamPaused,this.onTrackUpstreamPaused),e.on(oe.UpstreamResumed,this.onTrackUpstreamResumed),e.on(oe.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate);const m=[],p=!(!((s=t.dtx)!==null&&s!==void 0)||s),x=e.getSourceTrackSettings();x.autoGainControl&&m.push(qt.TF_AUTO_GAIN_CONTROL),x.echoCancellation&&m.push(qt.TF_ECHO_CANCELLATION),x.noiseSuppression&&m.push(qt.TF_NOISE_SUPPRESSION),x.channelCount&&x.channelCount>1&&m.push(qt.TF_STEREO),p&&m.push(qt.TF_NO_DTX),vi(e)&&e.hasPreConnectBuffer&&m.push(qt.TF_PRECONNECT_BUFFER);const C=new cc({cid:e.mediaStreamTrack.id,name:t.name,type:Q.kindToProto(e.kind),muted:e.isMuted,source:Q.sourceToProto(e.source),disableDtx:p,encryption:this.encryptionType,stereo:n,disableRed:this.isE2EEEnabled||!(!((r=t.red)!==null&&r!==void 0)||r),stream:t==null?void 0:t.stream,backupCodecPolicy:t==null?void 0:t.backupCodecPolicy,audioFeatures:m});let b;if(e.kind===Q.Kind.Video){let _={width:0,height:0};try{_=yield e.waitForDimensions()}catch{const R=(o=(a=this.roomOptions.videoCaptureDefaults)===null||a===void 0?void 0:a.resolution)!==null&&o!==void 0?o:Or.h720.resolution;_={width:R.width,height:R.height},this.log.error("could not determine track dimensions, using defaults",Object.assign(Object.assign(Object.assign({},this.logContext),Xe(e)),{dims:_}))}C.width=_.width,C.height=_.height,Hi(e)&&(Yn(v)&&(e.source===Q.Source.ScreenShare&&(t.scalabilityMode="L1T3","contentHint"in e.mediaStreamTrack&&(e.mediaStreamTrack.contentHint="motion",this.log.info("forcing contentHint to motion for screenshare with SVC codecs",Object.assign(Object.assign({},this.logContext),Xe(e))))),t.scalabilityMode=(c=t.scalabilityMode)!==null&&c!==void 0?c:"L3T3_KEY"),C.simulcastCodecs=[new oc({codec:v,cid:e.mediaStreamTrack.id})],t.backupCodec===!0&&(t.backupCodec={codec:Jc}),t.backupCodec&&v!==t.backupCodec.codec&&C.encryption===vn.NONE&&(this.roomOptions.dynacast||(this.roomOptions.dynacast=!0),C.simulcastCodecs.push(new oc({codec:t.backupCodec.codec,cid:""})))),b=il(e.source===Q.Source.ScreenShare,C.width,C.height,t),C.layers=ep(C.width,C.height,b,Yn(t.videoCodec))}else e.kind===Q.Kind.Audio&&(b=[{maxBitrate:(l=t.audioPreset)===null||l===void 0?void 0:l.maxBitrate,priority:(u=(d=t.audioPreset)===null||d===void 0?void 0:d.priority)!==null&&u!==void 0?u:"high",networkPriority:(f=(h=t.audioPreset)===null||h===void 0?void 0:h.priority)!==null&&f!==void 0?f:"high"}]);if(!this.engine||this.engine.isClosed)throw new Gt("cannot publish track when not connected");const S=()=>P(this,void 0,void 0,function*(){var _,T,R;if(!this.engine.pcManager)throw new Gt("pcManager is not ready");if(e.sender=yield this.engine.createSender(e,t,b),this.emit(le.LocalSenderCreated,e.sender,e),Hi(e)&&((_=t.degradationPreference)!==null&&_!==void 0||(t.degradationPreference=Lb(e)),e.setDegradationPreference(t.degradationPreference)),b)if(cs()&&e.kind===Q.Kind.Audio){let O;for(const z of this.engine.pcManager.publisher.getTransceivers())if(z.sender===e.sender){O=z;break}O&&this.engine.pcManager.publisher.setTrackCodecBitrate({transceiver:O,codec:"opus",maxbr:!((T=b[0])===null||T===void 0)&&T.maxBitrate?b[0].maxBitrate/1e3:0})}else e.codec&&Yn(e.codec)&&(!((R=b[0])===null||R===void 0)&&R.maxBitrate)&&this.engine.pcManager.publisher.setTrackCodecBitrate({cid:C.cid,codec:e.codec,maxbr:b[0].maxBitrate/1e3});yield this.engine.negotiate()});let M;const A=new Promise((_,T)=>P(this,void 0,void 0,function*(){var R;try{M=yield this.engine.addTrack(C),_(M)}catch(O){e.sender&&(!((R=this.engine.pcManager)===null||R===void 0)&&R.publisher)&&(this.engine.pcManager.publisher.removeTrack(e.sender),yield this.engine.negotiate().catch(z=>{this.log.error("failed to negotiate after removing track due to failed add track request",Object.assign(Object.assign(Object.assign({},this.logContext),Xe(e)),{error:z}))})),T(O)}}));if(this.enabledPublishVideoCodecs.length>0)M=(yield Promise.all([A,S()]))[0];else{M=yield A;let _;if(M.codecs.forEach(T=>{_===void 0&&(_=T.mimeType)}),_&&e.kind===Q.Kind.Video){const T=zr(_);T!==v&&(this.log.debug("falling back to server selected codec",Object.assign(Object.assign(Object.assign({},this.logContext),Xe(e)),{codec:T})),t.videoCodec=T,b=il(e.source===Q.Source.ScreenShare,C.width,C.height,t))}yield S()}const k=new ll(e.kind,M,e,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});if(k.on(oe.CpuConstrained,_=>this.onTrackCpuConstrained(_,k)),k.options=t,e.sid=M.sid,this.log.debug("publishing ".concat(e.kind," with encodings"),Object.assign(Object.assign({},this.logContext),{encodings:b,trackInfo:M})),Hi(e)?e.startMonitor(this.engine.client):vi(e)&&e.startMonitor(),this.addTrackPublication(k),this.emit(le.LocalTrackPublished,k),vi(e)&&M.audioFeatures.includes(qt.TF_PRECONNECT_BUFFER)){const _=e.getPreConnectBuffer(),T=e.getPreConnectBufferMimeType();this.on(le.LocalTrackSubscribed,R=>{if(R.trackSid===M.sid){if(!e.hasPreConnectBuffer){this.log.warn("subscribe event came to late, buffer already closed",this.logContext);return}this.log.debug("finished recording preconnect buffer",Object.assign(Object.assign({},this.logContext),Xe(e))),e.stopPreConnectBuffer()}}),_&&new Promise((O,z)=>P(this,void 0,void 0,function*(){var $,J,W,q,ne,be;try{this.log.debug("waiting for agent",Object.assign(Object.assign({},this.logContext),Xe(e)));const Be=setTimeout(()=>{z(new Error("agent not active within 10 seconds"))},1e4),wt=yield this.waitUntilActiveAgentPresent();clearTimeout(Be),this.log.debug("sending preconnect buffer",Object.assign(Object.assign({},this.logContext),Xe(e)));const vt=yield this.streamBytes({name:"preconnect-buffer",mimeType:T,topic:"lk.agent.pre-connect-audio-buffer",destinationIdentities:[wt.identity],attributes:{trackId:k.trackSid,sampleRate:String((ne=x.sampleRate)!==null&&ne!==void 0?ne:"48000"),channels:String((be=x.channelCount)!==null&&be!==void 0?be:"1")}});try{for(var ue=!0,_e=pi(_),ze;ze=yield _e.next(),$=ze.done,!$;ue=!0){q=ze.value,ue=!1;const K=q;yield vt.write(K)}}catch(K){J={error:K}}finally{try{!ue&&!$&&(W=_e.return)&&(yield W.call(_e))}finally{if(J)throw J.error}}yield vt.close(),O()}catch(Be){z(Be)}})).then(()=>{this.log.debug("preconnect buffer sent successfully",Object.assign(Object.assign({},this.logContext),Xe(e)))}).catch(O=>{this.log.error("error sending preconnect buffer",Object.assign(Object.assign(Object.assign({},this.logContext),Xe(e)),{error:O}))})}return k})}get isLocal(){return!0}publishAdditionalCodecForTrack(e,t,n){return P(this,void 0,void 0,function*(){var s;if(this.encryptionType!==vn.NONE)return;let r;if(this.trackPublications.forEach(f=>{f.track&&f.track===e&&(r=f)}),!r)throw new gi("track is not published");if(!Hi(e))throw new gi("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=kb(e,t,a);if(!o){this.log.info("backup codec has been disabled, ignoring request to add additional codec for track",Object.assign(Object.assign({},this.logContext),Xe(e)));return}const c=e.addSimulcastTrack(t,o);if(!c)return;const l=new cc({cid:c.mediaStreamTrack.id,type:Q.kindToProto(e.kind),muted:e.isMuted,source:Q.sourceToProto(e.source),sid:e.sid,simulcastCodecs:[{codec:a.videoCodec,cid:c.mediaStreamTrack.id}]});if(l.layers=ep(l.width,l.height,o),!this.engine||this.engine.isClosed)throw new Gt("cannot publish track when not connected");const d=()=>P(this,void 0,void 0,function*(){yield this.engine.createSimulcastSender(e,c,a,o),yield this.engine.negotiate()}),h=(yield Promise.all([this.engine.addTrack(l),d()]))[0];this.log.debug("published ".concat(t," for track ").concat(e.sid),Object.assign(Object.assign({},this.logContext),{encodings:o,trackInfo:h}))})}unpublishTrack(e,t){return P(this,void 0,void 0,function*(){var n,s;if(Bs(e)){const l=this.pendingPublishPromises.get(e);l&&(this.log.info("awaiting publish promise before attempting to unpublish",Object.assign(Object.assign({},this.logContext),Xe(e))),yield l)}const r=this.getPublicationForTrack(e),a=r?Xe(r):void 0;if(this.log.debug("unpublishing track",Object.assign(Object.assign({},this.logContext),a)),!r||!r.track){this.log.warn("track was not unpublished because no publication was found",Object.assign(Object.assign({},this.logContext),a));return}e=r.track,e.off(oe.Muted,this.onTrackMuted),e.off(oe.Unmuted,this.onTrackUnmuted),e.off(oe.Ended,this.handleTrackEnded),e.off(oe.UpstreamPaused,this.onTrackUpstreamPaused),e.off(oe.UpstreamResumed,this.onTrackUpstreamResumed),e.off(oe.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 c=e.sender;if(e.sender=void 0,this.engine.pcManager&&this.engine.pcManager.currentState<Pt.FAILED&&c)try{for(const l of this.engine.pcManager.publisher.getTransceivers())l.sender===c&&(l.direction="inactive",o=!0);if(this.engine.removeTrack(c)&&(o=!0),Hi(e)){for(const[,l]of e.simulcastCodecs)l.sender&&(this.engine.removeTrack(l.sender)&&(o=!0),l.sender=void 0);e.simulcastCodecs.clear()}}catch(l){this.log.warn("failed to unpublish track",Object.assign(Object.assign(Object.assign({},this.logContext),a),{error:l}))}switch(this.trackPublications.delete(r.trackSid),r.kind){case Q.Kind.Audio:this.audioTrackPublications.delete(r.trackSid);break;case Q.Kind.Video:this.videoTrackPublications.delete(r.trackSid);break}return this.emit(le.LocalTrackUnpublished,r),r.setTrack(void 0),o&&(yield this.engine.negotiate()),r})}unpublishTracks(e){return P(this,void 0,void 0,function*(){return(yield Promise.all(e.map(n=>this.unpublishTrack(n)))).filter(n=>!!n)})}republishAllTracks(e){return P(this,arguments,void 0,function(t){var n=this;let s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){n.republishPromise&&(yield n.republishPromise),n.republishPromise=new Promise((r,a)=>P(n,void 0,void 0,function*(){try{const o=[];this.trackPublications.forEach(c=>{c.track&&(t&&(c.options=Object.assign(Object.assign({},c.options),t)),o.push(c))}),yield Promise.all(o.map(c=>P(this,void 0,void 0,function*(){const l=c.track;yield this.unpublishTrack(l,!1),s&&!l.isMuted&&l.source!==Q.Source.ScreenShare&&l.source!==Q.Source.ScreenShareAudio&&(vi(l)||Hi(l))&&!l.isUserProvided&&(this.log.debug("restarting existing track",Object.assign(Object.assign({},this.logContext),{track:c.trackSid})),yield l.restartTrack()),yield this.publishOrRepublishTrack(l,c.options,!0)}))),r()}catch(o){a(o)}finally{this.republishPromise=void 0}})),yield n.republishPromise}()})}publishData(e){return P(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?We.RELIABLE:We.LOSSY,a=s.destinationIdentities,o=s.topic,c=new dn({kind:r,value:{case:"user",value:new Zu({participantIdentity:n.identity,payload:t,destinationIdentities:a,topic:o})}});yield n.engine.sendDataPacket(c,r)}()})}publishDtmf(e,t){return P(this,void 0,void 0,function*(){const n=new dn({kind:We.RELIABLE,value:{case:"sipDtmf",value:new Qu({code:e,digit:t})}});yield this.engine.sendDataPacket(n,We.RELIABLE)})}sendChatMessage(e,t){return P(this,void 0,void 0,function*(){const n={id:crypto.randomUUID(),message:e,timestamp:Date.now(),attachedFiles:t==null?void 0:t.attachments},s=new dn({value:{case:"chatMessage",value:new tc(Object.assign(Object.assign({},n),{timestamp:At.parse(n.timestamp)}))}});return yield this.engine.sendDataPacket(s,We.RELIABLE),this.emit(le.ChatMessage,n),n})}editChatMessage(e,t){return P(this,void 0,void 0,function*(){const n=Object.assign(Object.assign({},t),{message:e,editTimestamp:Date.now()}),s=new dn({value:{case:"chatMessage",value:new tc(Object.assign(Object.assign({},n),{timestamp:At.parse(n.timestamp),editTimestamp:At.parse(n.editTimestamp)}))}});return yield this.engine.sendDataPacket(s,We.RELIABLE),this.emit(le.ChatMessage,n),n})}sendText(e,t){return P(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.sendText(e,t)})}streamText(e){return P(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.streamText(e)})}sendFile(e,t){return P(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.sendFile(e,t)})}streamBytes(e){return P(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.streamBytes(e)})}performRpc(e){return P(this,arguments,void 0,function(t){var n=this;let{destinationIdentity:s,method:r,payload:a,responseTimeout:o=1e4}=t;return function*(){return new Promise((l,d)=>P(n,void 0,void 0,function*(){var u,h,f,g;if(Qc(a)>$f){d(kt.builtIn("REQUEST_PAYLOAD_TOO_LARGE"));return}if(!((h=(u=this.engine.latestJoinResponse)===null||u===void 0?void 0:u.serverInfo)===null||h===void 0)&&h.version&&Jn((g=(f=this.engine.latestJoinResponse)===null||f===void 0?void 0:f.serverInfo)===null||g===void 0?void 0:g.version,"1.8.0")<0){d(kt.builtIn("UNSUPPORTED_SERVER"));return}const v=crypto.randomUUID();yield this.publishRpcRequest(s,v,r,a,o-2e3);const m=setTimeout(()=>{this.pendingAcks.delete(v),d(kt.builtIn("CONNECTION_TIMEOUT")),this.pendingResponses.delete(v),clearTimeout(p)},2e3);this.pendingAcks.set(v,{resolve:()=>{clearTimeout(m)},participantIdentity:s});const p=setTimeout(()=>{this.pendingResponses.delete(v),d(kt.builtIn("RESPONSE_TIMEOUT"))},o);this.pendingResponses.set(v,{resolve:(x,C)=>{clearTimeout(p),this.pendingAcks.has(v)&&(console.warn("RPC response received before ack",v),this.pendingAcks.delete(v),clearTimeout(m)),C?d(C):l(x??"")},participantIdentity:s})}))}()})}registerRpcMethod(e,t){this.rpcHandlers.has(e)&&this.log.warn("you're overriding the RPC handler for method ".concat(e,", in the future this will throw an error")),this.rpcHandlers.set(e,t)}unregisterRpcMethod(e){this.rpcHandlers.delete(e)}setTrackSubscriptionPermissions(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:[];this.participantTrackPermissions=t,this.allParticipantsAllowedToSubscribe=e,this.engine.client.isDisconnected||this.updateTrackSubscriptionPermissions()}handleIncomingRpcAck(e){const t=this.pendingAcks.get(e);t?(t.resolve(),this.pendingAcks.delete(e)):console.error("Ack received for unexpected RPC request",e)}handleIncomingRpcResponse(e,t,n){const s=this.pendingResponses.get(e);s?(s.resolve(t,n),this.pendingResponses.delete(e)):console.error("Response received for unexpected RPC request",e)}publishRpcRequest(e,t,n,s,r){return P(this,void 0,void 0,function*(){const a=new dn({destinationIdentities:[e],kind:We.RELIABLE,value:{case:"rpcRequest",value:new eh({id:t,method:n,payload:s,responseTimeoutMs:r,version:1})}});yield this.engine.sendDataPacket(a,We.RELIABLE)})}handleParticipantDisconnected(e){for(const[t,{participantIdentity:n}]of this.pendingAcks)n===e&&this.pendingAcks.delete(t);for(const[t,{participantIdentity:n,resolve:s}]of this.pendingResponses)n===e&&(s(null,kt.builtIn("RECIPIENT_DISCONNECTED")),this.pendingResponses.delete(t))}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(Object.assign({},this.logContext),Xe(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,"Agent disconnected"),this.activeAgentFuture=void 0}waitUntilActiveAgentPresent(){return this.firstActiveAgent?Promise.resolve(this.firstActiveAgent):(this.activeAgentFuture||(this.activeAgentFuture=new Zn),this.activeAgentFuture.promise)}getPublicationForTrack(e){let t;return this.trackPublications.forEach(n=>{const s=n.track;s&&(e instanceof MediaStreamTrack?(vi(s)||Hi(s))&&s.mediaStreamTrack===e&&(t=n):e===s&&(t=n))}),t}waitForPendingPublicationOfSource(e){return P(this,void 0,void 0,function*(){const n=Date.now();for(;Date.now()<n+1e4;){const s=Array.from(this.pendingPublishPromises.entries()).find(r=>{let[a]=r;return a.source===e});if(s)return s[1];yield un(20)}})}}class ny extends bi{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(oe.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 Ra({trackSids:[this.trackSid],subscribe:this.subscribed,participantTracks:[new sh({participantSid:"",trackSids:[this.trackSid]})]});this.emit(oe.UpdateSubscription,s),this.emitSubscriptionUpdateIfChanged(t),this.emitPermissionUpdateIfChanged(n)}get subscriptionStatus(){return this.subscribed===!1?bi.SubscriptionStatus.Unsubscribed:super.isSubscribed?bi.SubscriptionStatus.Subscribed:bi.SubscriptionStatus.Desired}get permissionStatus(){return this.allowed?bi.PermissionStatus.Allowed:bi.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||(zc(this.track)&&(this.requestedVideoDimensions=e),this.requestedMaxQuality=void 0,this.emitTrackUpdate()))}setVideoFPS(e){this.isManualOperationAllowed()&&zc(this.track)&&this.fps!==e&&(this.fps=e,this.emitTrackUpdate())}get videoQuality(){var e;return(e=this.requestedMaxQuality)!==null&&e!==void 0?e:yn.HIGH}setTrack(e){const t=this.subscriptionStatus,n=this.permissionStatus,s=this.track;s!==e&&(s&&(s.off(oe.VideoDimensionsChanged,this.handleVideoDimensionsChange),s.off(oe.VisibilityChanged,this.handleVisibilityChange),s.off(oe.Ended,this.handleEnded),s.detach(),s.stopMonitor(),this.emit(oe.Unsubscribed,s)),super.setTrack(e),e&&(e.sid=this.trackSid,e.on(oe.VideoDimensionsChanged,this.handleVideoDimensionsChange),e.on(oe.VisibilityChanged,this.handleVisibilityChange),e.on(oe.Ended,this.handleEnded),this.emit(oe.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(oe.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?oe.Muted:oe.Unmuted)}emitSubscriptionUpdateIfChanged(e){const t=this.subscriptionStatus;e!==t&&this.emit(oe.SubscriptionStatusChanged,t,e)}emitPermissionUpdateIfChanged(e){this.permissionStatus!==e&&this.emit(oe.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 zc(this.track)&&this.track.isAdaptiveStream}emitTrackUpdate(){const e=new ph({trackSids:[this.trackSid],disabled:!this.isEnabled,fps:this.fps});if(this.kind===Q.Kind.Video){let t=this.requestedVideoDimensions;if(this.videoDimensionsAdaptiveStream!==void 0)if(t)Df(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=Q0(this.trackInfo,this.requestedMaxQuality);n&&Df(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:yn.HIGH})),e.quality=yn.HIGH)}this.emit(oe.UpdateSettings,e)}}class ja extends op{static fromParticipantInfo(e,t,n){return new ja(e,t.sid,t.identity,t.name,t.metadata,t.attributes,n,t.kind)}get logContext(){return Object.assign(Object.assign({},super.logContext),{rpID:this.sid,remoteParticipant:this.identity})}constructor(e,t,n,s,r,a,o){let c=arguments.length>7&&arguments[7]!==void 0?arguments[7]:Ir.STANDARD;super(t,n||"",s,r,a,o,c),this.signalClient=e,this.trackPublications=new Map,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.volumeMap=new Map}addTrackPublication(e){super.addTrackPublication(e),e.on(oe.UpdateSettings,t=>{this.log.debug("send update settings",Object.assign(Object.assign(Object.assign({},this.logContext),Xe(e)),{settings:t})),this.signalClient.sendUpdateTrackSettings(t)}),e.on(oe.UpdateSubscription,t=>{t.participantTracks.forEach(n=>{n.participantSid=this.sid}),this.signalClient.sendUpdateSubscription(t)}),e.on(oe.SubscriptionPermissionChanged,t=>{this.emit(le.TrackSubscriptionPermissionChanged,e,t)}),e.on(oe.SubscriptionStatusChanged,t=>{this.emit(le.TrackSubscriptionStatusChanged,e,t)}),e.on(oe.Subscribed,t=>{this.emit(le.TrackSubscribed,t,e)}),e.on(oe.Unsubscribed,t=>{this.emit(le.TrackUnsubscribed,t,e)}),e.on(oe.SubscriptionFailed,t=>{this.emit(le.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]:Q.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]:Q.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(d=>{!o&&e.kind===d.kind.toString()&&(o=d)}),!o){if(a===0){this.log.error("could not find published track",Object.assign(Object.assign({},this.logContext),{trackSid:t})),this.emit(le.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),Xe(o))),this.emit(le.TrackSubscriptionFailed,t);return}const c=e.kind==="video";let l;return c?l=new Yb(e,t,s,r):l=new Xb(e,t,s,this.audioContext,this.audioOutput),l.source=o.source,l.isMuted=o.isMuted,l.setMediaStream(n),l.start(),o.setTrack(l),this.volumeMap.has(o.source)&&Bc(l)&&Qn(l)&&l.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 c=Q.kindFromProto(s.type);if(!c)return;o=new ny(c,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 l=Array.from(this.trackPublications.values()).find(d=>d.source===(o==null?void 0:o.source));l&&o.source!==Q.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:Xe(l),newTrack:Xe(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),Xe(s))),this.unpublishTrack(s.trackSid,!0))}),n.forEach(s=>{this.emit(le.TrackPublished,s)}),!0}unpublishTrack(e,t){const n=this.trackPublications.get(e);if(!n)return;const{track:s}=n;switch(s&&(s.stop(),n.setTrack(void 0)),this.trackPublications.delete(e),n.kind){case Q.Kind.Audio:this.audioTrackPublications.delete(e);break;case Q.Kind.Video:this.videoTrackPublications.delete(e);break}t&&this.emit(le.TrackUnpublished,n)}setAudioOutput(e){return P(this,void 0,void 0,function*(){this.audioOutput=e;const t=[];this.audioTrackPublications.forEach(n=>{var s;Qn(n.track)&&Bc(n.track)&&t.push(n.track.setSinkId((s=e.deviceId)!==null&&s!==void 0?s:"default"))}),yield Promise.all(t)})}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 ct;(function(i){i.Disconnected="disconnected",i.Connecting="connecting",i.Connected="connected",i.Reconnecting="reconnecting",i.SignalReconnecting="signalReconnecting"})(ct||(ct={}));const iy=4*1e3;class Gs extends Xn.EventEmitter{constructor(e){var t,n,s,r;if(super(),t=this,this.state=ct.Disconnected,this.activeSpeakers=[],this.isE2EEEnabled=!1,this.audioEnabled=!0,this.isVideoPlaybackBlocked=!1,this.log=Ke,this.bufferedEvents=[],this.isResuming=!1,this.rpcHandlers=new Map,this.connect=(a,o,c)=>P(this,void 0,void 0,function*(){var l;if(!D0())throw Kn()?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 d=yield this.disconnectLock.lock();if(this.state===ct.Connected)return this.log.info("already connected to room ".concat(this.name),this.logContext),d(),Promise.resolve();if(this.connectFuture)return d(),this.connectFuture.promise;this.setAndEmitConnectionState(ct.Connecting),((l=this.regionUrlProvider)===null||l===void 0?void 0:l.getServerUrl().toString())!==a&&(this.regionUrl=void 0,this.regionUrlProvider=void 0),Lc(new URL(a))&&(this.regionUrlProvider===void 0?this.regionUrlProvider=new al(a,o):this.regionUrlProvider.updateToken(o),this.regionUrlProvider.fetchRegionSettings().then(f=>{var g;(g=this.regionUrlProvider)===null||g===void 0||g.setServerReportedRegions(f)}).catch(f=>{this.log.warn("could not fetch region settings",Object.assign(Object.assign({},this.logContext),{error:f}))}));const u=(f,g,v)=>P(this,void 0,void 0,function*(){var m,p;this.abortController&&this.abortController.abort();const x=new AbortController;this.abortController=x,d==null||d();try{yield this.attemptConnection(v??a,o,c,x),this.abortController=void 0,f()}catch(C){if(this.regionUrlProvider&&C instanceof _t&&C.reason!==tt.Cancelled&&C.reason!==tt.NotAllowed){let b=null;try{b=yield this.regionUrlProvider.getNextBestRegionUrl((m=this.abortController)===null||m===void 0?void 0:m.signal)}catch(S){if(S instanceof _t&&(S.status===401||S.reason===tt.Cancelled)){this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),g(S);return}}b&&!(!((p=this.abortController)===null||p===void 0)&&p.signal.aborted)?(this.log.info("Initial connection failed with ConnectionError: ".concat(C.message,". Retrying with another region: ").concat(b),this.logContext),this.recreateEngine(),yield u(f,g,b)):(this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,Af(C)),g(C))}else{let b=In.UNKNOWN_REASON;C instanceof _t&&(b=Af(C)),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,b),g(C)}}}),h=this.regionUrl;return this.regionUrl=void 0,this.connectFuture=new Zn((f,g)=>{u(f,g,h)},()=>{this.clearConnectionFutures()}),this.connectFuture.promise}),this.connectSignal=(a,o,c,l,d,u)=>P(this,void 0,void 0,function*(){var h,f,g;const v=yield c.join(a,o,{autoSubscribe:l.autoSubscribe,adaptiveStream:typeof d.adaptiveStream=="object"?!0:d.adaptiveStream,maxRetries:l.maxRetries,e2eeEnabled:!!this.e2eeManager,websocketTimeout:l.websocketTimeout},u.signal);let m=v.serverInfo;if(m||(m={version:v.serverVersion,region:v.serverRegion}),this.serverInfo=m,this.log.debug("connected to Livekit Server ".concat(Object.entries(m).map(p=>{let[x,C]=p;return"".concat(x,": ").concat(C)}).join(", ")),{room:(h=v.room)===null||h===void 0?void 0:h.name,roomSid:(f=v.room)===null||f===void 0?void 0:f.sid,identity:(g=v.participant)===null||g===void 0?void 0:g.identity}),!m.version)throw new b0("unknown server version");return m.version==="0.15.1"&&this.options.dynacast&&(this.log.debug("disabling dynacast due to server version",this.logContext),d.dynacast=!1),v}),this.applyJoinResponse=a=>{const o=a.participant;if(this.localParticipant.sid=o.sid,this.localParticipant.identity=o.identity,this.localParticipant.setEnabledPublishCodecs(a.enabledPublishCodecs),this.options.e2ee&&this.e2eeManager)try{this.e2eeManager.setSifTrailer(a.sifTrailer)}catch(c){this.log.error(c instanceof Error?c.message:"Could not set SifTrailer",Object.assign(Object.assign({},this.logContext),{error:c}))}this.handleParticipantUpdates([o,...a.otherParticipants]),a.room&&this.handleRoomUpdate(a.room)},this.attemptConnection=(a,o,c,l)=>P(this,void 0,void 0,function*(){var d,u;this.state===ct.Reconnecting||this.isResuming||!((d=this.engine)===null||d===void 0)&&d.pendingReconnect?(this.log.info("Reconnection attempt replaced by new connection attempt",this.logContext),this.recreateEngine()):this.maybeCreateEngine(),!((u=this.regionUrlProvider)===null||u===void 0)&&u.isCloud()&&this.engine.setRegionUrlProvider(this.regionUrlProvider),this.acquireAudioContext(),this.connOptions=Object.assign(Object.assign({},Zc),c),this.connOptions.rtcConfig&&(this.engine.rtcConfig=this.connOptions.rtcConfig),this.connOptions.peerConnectionTimeout&&(this.engine.peerConnectionTimeout=this.connOptions.peerConnectionTimeout);try{const h=yield this.connectSignal(a,o,this.engine,this.connOptions,this.options,l);this.applyJoinResponse(h),this.setupLocalParticipantEvents(),this.emit(ie.SignalConnected)}catch(h){yield this.engine.close(),this.recreateEngine();const f=new _t("could not establish signal connection",tt.ServerUnreachable);throw h instanceof Error&&(f.message="".concat(f.message,": ").concat(h.message)),h instanceof _t&&(f.reason=h.reason,f.status=h.status),this.log.debug("error trying to establish signal connection",Object.assign(Object.assign({},this.logContext),{error:h})),f}if(l.signal.aborted)throw yield this.engine.close(),this.recreateEngine(),new _t("Connection attempt aborted",tt.Cancelled);try{yield this.engine.waitForPCInitialConnection(this.connOptions.peerConnectionTimeout,l)}catch(h){throw yield this.engine.close(),this.recreateEngine(),h}hn()&&this.options.disconnectOnPageLeave&&(window.addEventListener("pagehide",this.onPageLeave),window.addEventListener("beforeunload",this.onPageLeave)),hn()&&document.addEventListener("freeze",this.onPageLeave),this.setAndEmitConnectionState(ct.Connected),this.emit(ie.Connected),this.registerConnectionReconcile()}),this.disconnect=function(){for(var a=arguments.length,o=new Array(a),c=0;c<a;c++)o[c]=arguments[c];return P(t,[...o],void 0,function(){var l=this;let d=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){var u,h,f,g;const v=yield l.disconnectLock.lock();try{if(l.state===ct.Disconnected){l.log.debug("already disconnected",l.logContext);return}l.log.info("disconnect from room",Object.assign({},l.logContext)),(l.state===ct.Connecting||l.state===ct.Reconnecting||l.isResuming)&&(l.log.warn("abort connection attempt",l.logContext),(u=l.abortController)===null||u===void 0||u.abort(),(f=(h=l.connectFuture)===null||h===void 0?void 0:h.reject)===null||f===void 0||f.call(h,new _t("Client initiated disconnect",tt.Cancelled)),l.connectFuture=void 0),!((g=l.engine)===null||g===void 0)&&g.client.isDisconnected||(yield l.engine.client.sendLeave()),l.engine&&(yield l.engine.close()),l.handleDisconnect(d,In.CLIENT_INITIATED),l.engine=void 0}finally{v()}}()})},this.onPageLeave=()=>P(this,void 0,void 0,function*(){this.log.info("Page leave detected, disconnecting",this.logContext),yield this.disconnect()}),this.startAudio=()=>P(this,void 0,void 0,function*(){const a=[],o=bn();if(o&&o.os==="iOS"){const c="livekit-dummy-audio-el";let l=document.getElementById(c);if(!l){l=document.createElement("audio"),l.id=c,l.autoplay=!0,l.hidden=!0;const d=Oc();d.enabled=!0;const u=new MediaStream([d]);l.srcObject=u,document.addEventListener("visibilitychange",()=>{l&&(l.srcObject=document.hidden?null:u,document.hidden||(this.log.debug("page visible again, triggering startAudio to resume playback and update playback status",this.logContext),this.startAudio()))}),document.body.append(l),this.once(ie.Disconnected,()=>{l==null||l.remove(),l=null})}a.push(l)}this.remoteParticipants.forEach(c=>{c.audioTrackPublications.forEach(l=>{l.track&&l.track.attachedElements.forEach(d=>{a.push(d)})})});try{yield Promise.all([this.acquireAudioContext(),...a.map(c=>(c.muted=!1,c.play()))]),this.handleAudioPlaybackStarted()}catch(c){throw this.handleAudioPlaybackFailed(c),c}}),this.startVideo=()=>P(this,void 0,void 0,function*(){const a=[];for(const o of this.remoteParticipants.values())o.videoTrackPublications.forEach(c=>{var l;(l=c.track)===null||l===void 0||l.attachedElements.forEach(d=>{a.includes(d)||a.push(d)})});yield Promise.all(a.map(o=>o.play())).then(()=>{this.handleVideoPlaybackStarted()}).catch(o=>{o.name==="NotAllowedError"?this.handleVideoPlaybackFailed():this.log.warn("Resuming video playback failed, make sure you call `startVideo` directly in a user gesture handler",this.logContext)})}),this.handleRestarting=()=>{this.clearConnectionReconcile(),this.isResuming=!1;for(const a of this.remoteParticipants.values())this.handleParticipantDisconnected(a.identity,a);this.setAndEmitConnectionState(ct.Reconnecting)&&this.emit(ie.Reconnecting)},this.handleSignalRestarted=a=>P(this,void 0,void 0,function*(){this.log.debug("signal reconnected to server, region ".concat(a.serverRegion),Object.assign(Object.assign({},this.logContext),{region:a.serverRegion})),this.bufferedEvents=[],this.applyJoinResponse(a);try{yield this.localParticipant.republishAllTracks(void 0,!0)}catch(o){this.log.error("error trying to re-publish tracks after reconnection",Object.assign(Object.assign({},this.logContext),{error:o}))}try{yield this.engine.waitForRestarted(),this.log.debug("fully reconnected to server",Object.assign(Object.assign({},this.logContext),{region:a.serverRegion}))}catch{return}this.setAndEmitConnectionState(ct.Connected),this.emit(ie.Reconnected),this.registerConnectionReconcile(),this.emitBufferedEvents()}),this.handleParticipantUpdates=a=>{a.forEach(o=>{var c;if(o.identity===this.localParticipant.identity){this.localParticipant.updateInfo(o);return}o.identity===""&&(o.identity=(c=this.sidToIdentity.get(o.sid))!==null&&c!==void 0?c:"");let l=this.remoteParticipants.get(o.identity);o.state===Ds.DISCONNECTED?this.handleParticipantDisconnected(o.identity,l):l=this.getOrCreateParticipant(o.identity,o)})},this.handleActiveSpeakersUpdate=a=>{const o=[],c={};a.forEach(l=>{if(c[l.sid]=!0,l.sid===this.localParticipant.sid)this.localParticipant.audioLevel=l.level,this.localParticipant.setIsSpeaking(!0),o.push(this.localParticipant);else{const d=this.getRemoteParticipantBySid(l.sid);d&&(d.audioLevel=l.level,d.setIsSpeaking(!0),o.push(d))}}),c[this.localParticipant.sid]||(this.localParticipant.audioLevel=0,this.localParticipant.setIsSpeaking(!1)),this.remoteParticipants.forEach(l=>{c[l.sid]||(l.audioLevel=0,l.setIsSpeaking(!1))}),this.activeSpeakers=o,this.emitWhenConnected(ie.ActiveSpeakersChanged,o)},this.handleSpeakersChanged=a=>{const o=new Map;this.activeSpeakers.forEach(l=>{const d=this.remoteParticipants.get(l.identity);d&&d.sid!==l.sid||o.set(l.sid,l)}),a.forEach(l=>{let d=this.getRemoteParticipantBySid(l.sid);l.sid===this.localParticipant.sid&&(d=this.localParticipant),d&&(d.audioLevel=l.level,d.setIsSpeaking(l.active),l.active?o.set(l.sid,d):o.delete(l.sid))});const c=Array.from(o.values());c.sort((l,d)=>d.audioLevel-l.audioLevel),this.activeSpeakers=c,this.emitWhenConnected(ie.ActiveSpeakersChanged,c)},this.handleStreamStateUpdate=a=>{a.streamStates.forEach(o=>{const c=this.getRemoteParticipantBySid(o.participantSid);if(!c)return;const l=c.getTrackPublicationBySid(o.trackSid);if(!l||!l.track)return;const d=Q.streamStateFromProto(o.state);l.track.setStreamState(d),d!==l.track.streamState&&(c.emit(le.TrackStreamStateChanged,l,l.track.streamState),this.emitWhenConnected(ie.TrackStreamStateChanged,l,l.track.streamState,c))})},this.handleSubscriptionPermissionUpdate=a=>{const o=this.getRemoteParticipantBySid(a.participantSid);if(!o)return;const c=o.getTrackPublicationBySid(a.trackSid);c&&c.setAllowed(a.allowed)},this.handleSubscriptionError=a=>{const o=Array.from(this.remoteParticipants.values()).find(l=>l.trackPublications.has(a.trackSid));if(!o)return;const c=o.getTrackPublicationBySid(a.trackSid);c&&c.setSubscriptionError(a.err)},this.handleDataPacket=a=>{const o=this.remoteParticipants.get(a.participantIdentity);if(a.value.case==="user")this.handleUserPacket(o,a.value.value,a.kind);else if(a.value.case==="transcription")this.handleTranscription(o,a.value.value);else if(a.value.case==="sipDtmf")this.handleSipDtmf(o,a.value.value);else if(a.value.case==="chatMessage")this.handleChatMessage(o,a.value.value);else if(a.value.case==="metrics")this.handleMetrics(a.value.value,o);else if(a.value.case==="streamHeader"||a.value.case==="streamChunk"||a.value.case==="streamTrailer")this.handleDataStream(a);else if(a.value.case==="rpcRequest"){const c=a.value.value;this.handleIncomingRpcRequest(a.participantIdentity,c.id,c.method,c.payload,c.responseTimeoutMs,c.version)}},this.handleUserPacket=(a,o,c)=>{this.emit(ie.DataReceived,o.payload,a,c,o.topic),a==null||a.emit(le.DataReceived,o.payload,c)},this.handleSipDtmf=(a,o)=>{this.emit(ie.SipDTMFReceived,o,a),a==null||a.emit(le.SipDTMFReceived,o)},this.handleTranscription=(a,o)=>{const c=o.transcribedParticipantIdentity===this.localParticipant.identity?this.localParticipant:this.getParticipantByIdentity(o.transcribedParticipantIdentity),l=c==null?void 0:c.trackPublications.get(o.trackId),d=G0(o,this.transcriptionReceivedTimes);l==null||l.emit(oe.TranscriptionReceived,d),c==null||c.emit(le.TranscriptionReceived,d,l),this.emit(ie.TranscriptionReceived,d,c,l)},this.handleChatMessage=(a,o)=>{const c=H0(o);this.emit(ie.ChatMessage,c,a)},this.handleMetrics=(a,o)=>{this.emit(ie.MetricsReceived,a,o)},this.handleDataStream=a=>{this.incomingDataStreamManager.handleDataStreamPacket(a)},this.bufferedSegments=new Map,this.handleAudioPlaybackStarted=()=>{this.canPlaybackAudio||(this.audioEnabled=!0,this.emit(ie.AudioPlaybackStatusChanged,!0))},this.handleAudioPlaybackFailed=a=>{this.log.warn("could not playback audio",Object.assign(Object.assign({},this.logContext),{error:a})),this.canPlaybackAudio&&(this.audioEnabled=!1,this.emit(ie.AudioPlaybackStatusChanged,!1))},this.handleVideoPlaybackStarted=()=>{this.isVideoPlaybackBlocked&&(this.isVideoPlaybackBlocked=!1,this.emit(ie.VideoPlaybackStatusChanged,!0))},this.handleVideoPlaybackFailed=()=>{this.isVideoPlaybackBlocked||(this.isVideoPlaybackBlocked=!0,this.emit(ie.VideoPlaybackStatusChanged,!1))},this.handleDeviceChange=()=>P(this,void 0,void 0,function*(){var a;((a=bn())===null||a===void 0?void 0:a.os)!=="iOS"&&(yield this.selectDefaultDevices()),this.emit(ie.MediaDevicesChanged)}),this.handleRoomUpdate=a=>{const o=this.roomInfo;this.roomInfo=a,o&&o.metadata!==a.metadata&&this.emitWhenConnected(ie.RoomMetadataChanged,a.metadata),(o==null?void 0:o.activeRecording)!==a.activeRecording&&this.emitWhenConnected(ie.RecordingStatusChanged,a.activeRecording)},this.handleConnectionQualityUpdate=a=>{a.updates.forEach(o=>{if(o.participantSid===this.localParticipant.sid){this.localParticipant.setConnectionQuality(o.quality);return}const c=this.getRemoteParticipantBySid(o.participantSid);c&&c.setConnectionQuality(o.quality)})},this.onLocalParticipantMetadataChanged=a=>{this.emit(ie.ParticipantMetadataChanged,a,this.localParticipant)},this.onLocalParticipantNameChanged=a=>{this.emit(ie.ParticipantNameChanged,a,this.localParticipant)},this.onLocalAttributesChanged=a=>{this.emit(ie.ParticipantAttributesChanged,a,this.localParticipant)},this.onLocalTrackMuted=a=>{this.emit(ie.TrackMuted,a,this.localParticipant)},this.onLocalTrackUnmuted=a=>{this.emit(ie.TrackUnmuted,a,this.localParticipant)},this.onTrackProcessorUpdate=a=>{var o;(o=a==null?void 0:a.onPublish)===null||o===void 0||o.call(a,this)},this.onLocalTrackPublished=a=>P(this,void 0,void 0,function*(){var o,c,l,d,u,h;(o=a.track)===null||o===void 0||o.on(oe.TrackProcessorUpdate,this.onTrackProcessorUpdate),(c=a.track)===null||c===void 0||c.on(oe.Restarted,this.onLocalTrackRestarted),(u=(d=(l=a.track)===null||l===void 0?void 0:l.getProcessor())===null||d===void 0?void 0:d.onPublish)===null||u===void 0||u.call(d,this),this.emit(ie.LocalTrackPublished,a,this.localParticipant),vi(a.track)&&(yield a.track.checkForSilence())&&this.emit(ie.LocalAudioSilenceDetected,a);const f=yield(h=a.track)===null||h===void 0?void 0:h.getDeviceId(!1),g=Hc(a.source);g&&f&&f!==this.localParticipant.activeDeviceMap.get(g)&&(this.localParticipant.activeDeviceMap.set(g,f),this.emit(ie.ActiveDeviceChanged,g,f))}),this.onLocalTrackUnpublished=a=>{var o,c;(o=a.track)===null||o===void 0||o.off(oe.TrackProcessorUpdate,this.onTrackProcessorUpdate),(c=a.track)===null||c===void 0||c.off(oe.Restarted,this.onLocalTrackRestarted),this.emit(ie.LocalTrackUnpublished,a,this.localParticipant)},this.onLocalTrackRestarted=a=>P(this,void 0,void 0,function*(){const o=yield a.getDeviceId(!1),c=Hc(a.source);c&&o&&o!==this.localParticipant.activeDeviceMap.get(c)&&(this.log.debug("local track restarted, setting ".concat(c," ").concat(o," active"),this.logContext),this.localParticipant.activeDeviceMap.set(c,o),this.emit(ie.ActiveDeviceChanged,c,o))}),this.onLocalConnectionQualityChanged=a=>{this.emit(ie.ConnectionQualityChanged,a,this.localParticipant)},this.onMediaDevicesError=(a,o)=>{this.emit(ie.MediaDevicesError,a,o)},this.onLocalParticipantPermissionsChanged=a=>{this.emit(ie.ParticipantPermissionsChanged,a,this.localParticipant)},this.onLocalChatMessageSent=a=>{this.emit(ie.ChatMessage,a,this.localParticipant)},this.setMaxListeners(100),this.remoteParticipants=new Map,this.sidToIdentity=new Map,this.options=Object.assign(Object.assign({},gb),e),this.log=fi((n=this.options.loggerName)!==null&&n!==void 0?n:Ln.Room),this.transcriptionReceivedTimes=new Map,this.options.audioCaptureDefaults=Object.assign(Object.assign({},Wf),e==null?void 0:e.audioCaptureDefaults),this.options.videoCaptureDefaults=Object.assign(Object.assign({},qf),e==null?void 0:e.videoCaptureDefaults),this.options.publishDefaults=Object.assign(Object.assign({},mb),e==null?void 0:e.publishDefaults),this.maybeCreateEngine(),this.incomingDataStreamManager=new Wb,this.outgoingDataStreamManager=new jb(this.engine,this.log),this.disconnectLock=new cn,this.localParticipant=new ty("","",this.engine,this.options,this.rpcHandlers,this.outgoingDataStreamManager),this.options.videoCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("videoinput",Vi(this.options.videoCaptureDefaults.deviceId)),this.options.audioCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("audioinput",Vi(this.options.audioCaptureDefaults.deviceId)),!((s=this.options.audioOutput)===null||s===void 0)&&s.deviceId&&this.switchActiveDevice("audiooutput",Vi(this.options.audioOutput.deviceId)).catch(a=>this.log.warn("Could not set audio output: ".concat(a.message),this.logContext)),this.options.e2ee&&this.setupE2EE(),hn()){const a=new AbortController;(r=navigator.mediaDevices)===null||r===void 0||r.addEventListener("devicechange",this.handleDeviceChange,{signal:a.signal}),Gs.cleanupRegistry&&Gs.cleanupRegistry.register(this,()=>{a.abort()})}}registerTextStreamHandler(e,t){return this.incomingDataStreamManager.registerTextStreamHandler(e,t)}unregisterTextStreamHandler(e){return this.incomingDataStreamManager.unregisterTextStreamHandler(e)}registerByteStreamHandler(e,t){return this.incomingDataStreamManager.registerByteStreamHandler(e,t)}unregisterByteStreamHandler(e){return this.incomingDataStreamManager.unregisterByteStreamHandler(e)}registerRpcMethod(e,t){if(this.rpcHandlers.has(e))throw Error("RPC handler already registered for method ".concat(e,", unregisterRpcMethod before trying to register again"));this.rpcHandlers.set(e,t)}unregisterRpcMethod(e){this.rpcHandlers.delete(e)}setE2EEEnabled(e){return P(this,void 0,void 0,function*(){if(this.e2eeManager)yield Promise.all([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")})}setupE2EE(){var e;this.options.e2ee&&("e2eeManager"in this.options.e2ee?this.e2eeManager=this.options.e2ee.e2eeManager:this.e2eeManager=new eb(this.options.e2ee),this.e2eeManager.on(Bi.ParticipantEncryptionStatusChanged,(t,n)=>{q0(n)&&(this.isE2EEEnabled=t),this.emit(ie.ParticipantEncryptionStatusChanged,t,n)}),this.e2eeManager.on(Bi.EncryptionError,t=>this.emit(ie.EncryptionError,t)),(e=this.e2eeManager)===null||e===void 0||e.setup(this))}get logContext(){var e;return{room:this.name,roomID:(e=this.roomInfo)===null||e===void 0?void 0:e.sid,participant:this.localParticipant.identity,pID:this.localParticipant.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 P(this,void 0,void 0,function*(){return this.state===ct.Disconnected?"":this.roomInfo&&this.roomInfo.sid!==""?this.roomInfo.sid:new Promise((e,t)=>{const n=s=>{s.sid!==""&&(this.engine.off(de.RoomUpdate,n),e(s.sid))};this.engine.on(de.RoomUpdate,n),this.once(ie.Disconnected,()=>{this.engine.off(de.RoomUpdate,n),t("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.isClosed||(this.engine=new Fb(this.options),this.engine.on(de.ParticipantUpdate,this.handleParticipantUpdates).on(de.RoomUpdate,this.handleRoomUpdate).on(de.SpeakersChanged,this.handleSpeakersChanged).on(de.StreamStateChanged,this.handleStreamStateUpdate).on(de.ConnectionQualityUpdate,this.handleConnectionQualityUpdate).on(de.SubscriptionError,this.handleSubscriptionError).on(de.SubscriptionPermissionUpdate,this.handleSubscriptionPermissionUpdate).on(de.MediaTrackAdded,(e,t,n)=>{this.onTrackAdded(e,t,n)}).on(de.Disconnected,e=>{this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e)}).on(de.ActiveSpeakersUpdate,this.handleActiveSpeakersUpdate).on(de.DataPacketReceived,this.handleDataPacket).on(de.Resuming,()=>{this.clearConnectionReconcile(),this.isResuming=!0,this.log.info("Resuming signal connection",this.logContext),this.setAndEmitConnectionState(ct.SignalReconnecting)&&this.emit(ie.SignalReconnecting)}).on(de.Resumed,()=>{this.registerConnectionReconcile(),this.isResuming=!1,this.log.info("Resumed signal connection",this.logContext),this.updateSubscriptions(),this.emitBufferedEvents(),this.setAndEmitConnectionState(ct.Connected)&&this.emit(ie.Reconnected)}).on(de.SignalResumed,()=>{this.bufferedEvents=[],(this.state===ct.Reconnecting||this.isResuming)&&this.sendSyncState()}).on(de.Restarting,this.handleRestarting).on(de.SignalRestarted,this.handleSignalRestarted).on(de.Offline,()=>{this.setAndEmitConnectionState(ct.Reconnecting)&&this.emit(ie.Reconnecting)}).on(de.DCBufferStatusChanged,(e,t)=>{this.emit(ie.DCBufferStatusChanged,e,t)}).on(de.LocalTrackSubscribed,e=>{const t=this.localParticipant.getTrackPublications().find(n=>{let{trackSid:s}=n;return s===e});if(!t){this.log.warn("could not find local track subscription for subscribed event",this.logContext);return}this.localParticipant.emit(le.LocalTrackSubscribed,t),this.emitWhenConnected(ie.LocalTrackSubscribed,t,this.localParticipant)}).on(de.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(ie.Moved,e.room.name),e.participant?this.handleParticipantUpdates([e.participant,...e.otherParticipants]):this.handleParticipantUpdates(e.otherParticipants)}),this.localParticipant&&this.localParticipant.setupEngine(this.engine),this.e2eeManager&&this.e2eeManager.setupEngine(this.engine),this.outgoingDataStreamManager&&this.outgoingDataStreamManager.setupEngine(this.engine))}static getLocalDevices(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return $t.getInstance().getDevices(e,t)}prepareConnection(e,t){return P(this,void 0,void 0,function*(){if(this.state===ct.Disconnected){this.log.debug("prepareConnection to ".concat(e),this.logContext);try{if(Lc(new URL(e))&&t){this.regionUrlProvider=new al(e,t);const n=yield this.regionUrlProvider.getNextBestRegionUrl();n&&this.state===ct.Disconnected&&(this.regionUrl=n,yield fetch(Fc(n),{method:"HEAD"}),this.log.debug("prepared connection to ".concat(n),this.logContext))}else yield fetch(Fc(e),{method:"HEAD"})}catch(n){this.log.warn("could not prepare connection",Object.assign(Object.assign({},this.logContext),{error:n}))}}})}getParticipantByIdentity(e){return this.localParticipant.identity===e?this.localParticipant:this.remoteParticipants.get(e)}clearConnectionFutures(){this.connectFuture=void 0}simulateScenario(e,t){return P(this,void 0,void 0,function*(){let n=()=>{},s;switch(e){case"signal-reconnect":yield this.engine.client.handleOnClose("simulate disconnect");break;case"speaker":s=new jn({scenario:{case:"speakerUpdate",value:3}});break;case"node-failure":s=new jn({scenario:{case:"nodeFailure",value:!0}});break;case"server-leave":s=new jn({scenario:{case:"serverLeave",value:!0}});break;case"migration":s=new jn({scenario:{case:"migration",value:!0}});break;case"resume-reconnect":this.engine.failNext(),yield this.engine.client.handleOnClose("simulate resume-disconnect");break;case"disconnect-signal-on-resume":n=()=>P(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),s=new jn({scenario:{case:"disconnectSignalOnResume",value:!0}});break;case"disconnect-signal-on-resume-no-messages":n=()=>P(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),s=new jn({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 jn({scenario:{case:"switchCandidateProtocol",value:e==="force-tls"?2:1}}),n=()=>P(this,void 0,void 0,function*(){const r=this.engine.client.onLeave;r&&r(new Pa({reason:In.CLIENT_INITIATED,action:Us.RECONNECT}))});break;case"subscriber-bandwidth":if(t===void 0||typeof t!="number")throw new Error("subscriber-bandwidth requires a number as argument");s=new jn({scenario:{case:"subscriberBandwidth",value:ds(t)}});break;case"leave-full-reconnect":s=new jn({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 P(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,c,l,d,u,h,f;let g=!0,v=!1;const m=a?{exact:s}:s;if(n==="audioinput"){v=r.localParticipant.audioTrackPublications.size===0;const p=(o=r.getActiveDevice(n))!==null&&o!==void 0?o:r.options.audioCaptureDefaults.deviceId;r.options.audioCaptureDefaults.deviceId=m;const x=Array.from(r.localParticipant.audioTrackPublications.values()).filter(b=>b.source===Q.Source.Microphone);try{g=(yield Promise.all(x.map(b=>{var S;return(S=b.audioTrack)===null||S===void 0?void 0:S.setDeviceId(m)}))).every(b=>b===!0)}catch(b){throw r.options.audioCaptureDefaults.deviceId=p,b}const C=x.some(b=>{var S,M;return(M=(S=b.track)===null||S===void 0?void 0:S.isMuted)!==null&&M!==void 0?M:!1});g&&C&&(v=!0)}else if(n==="videoinput"){v=r.localParticipant.videoTrackPublications.size===0;const p=(c=r.getActiveDevice(n))!==null&&c!==void 0?c:r.options.videoCaptureDefaults.deviceId;r.options.videoCaptureDefaults.deviceId=m;const x=Array.from(r.localParticipant.videoTrackPublications.values()).filter(b=>b.source===Q.Source.Camera);try{g=(yield Promise.all(x.map(b=>{var S;return(S=b.videoTrack)===null||S===void 0?void 0:S.setDeviceId(m)}))).every(b=>b===!0)}catch(b){throw r.options.videoCaptureDefaults.deviceId=p,b}const C=x.some(b=>{var S,M;return(M=(S=b.track)===null||S===void 0?void 0:S.isMuted)!==null&&M!==void 0?M:!1});g&&C&&(v=!0)}else if(n==="audiooutput"){if(v=!0,!Dc()&&!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=(l=yield $t.getInstance().normalizeDeviceId("audiooutput",s))!==null&&l!==void 0?l:""),(d=(f=r.options).audioOutput)!==null&&d!==void 0||(f.audioOutput={});const p=(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(x=>x.setAudioOutput({deviceId:s})))}catch(x){throw r.options.audioOutput.deviceId=p,x}}return v&&(r.localParticipant.activeDeviceMap.set(n,s),r.emit(ie.ActiveDeviceChanged,n,s)),g}()})}setupLocalParticipantEvents(){this.localParticipant.on(le.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).on(le.ParticipantNameChanged,this.onLocalParticipantNameChanged).on(le.AttributesChanged,this.onLocalAttributesChanged).on(le.TrackMuted,this.onLocalTrackMuted).on(le.TrackUnmuted,this.onLocalTrackUnmuted).on(le.LocalTrackPublished,this.onLocalTrackPublished).on(le.LocalTrackUnpublished,this.onLocalTrackUnpublished).on(le.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).on(le.MediaDevicesError,this.onMediaDevicesError).on(le.AudioStreamAcquired,this.startAudio).on(le.ChatMessage,this.onLocalChatMessageSent).on(le.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged)}recreateEngine(){var e;(e=this.engine)===null||e===void 0||e.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===ct.Connecting||this.state===ct.Reconnecting){const u=()=>{this.onTrackAdded(e,t,n),h()},h=()=>{this.off(ie.Reconnected,u),this.off(ie.Connected,u),this.off(ie.Disconnected,h)};this.once(ie.Reconnected,u),this.once(ie.Connected,u),this.once(ie.Disconnected,h);return}if(this.state===ct.Disconnected){this.log.warn("skipping incoming track after Room disconnected",this.logContext);return}if(e.readyState==="ended"){this.log.info("skipping incoming track as it already ended",this.logContext);return}const s=P0(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",this.logContext);return}const c=Array.from(this.remoteParticipants.values()).find(u=>u.sid===r);if(!c){this.log.error("Tried to add a track for a participant, that's not present. Sid: ".concat(r),this.logContext);return}let l;this.options.adaptiveStream&&(typeof this.options.adaptiveStream=="object"?l=this.options.adaptiveStream:l={});const d=c.addSubscribedMediaTrack(e,o,t,n,l);d!=null&&d.isEncrypted&&!this.e2eeManager&&this.emit(ie.EncryptionError,new Error("Encrypted ".concat(d.source," track received from participant ").concat(c.sid,", but room does not have encryption enabled!")))}handleDisconnect(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0,t=arguments.length>1?arguments[1]:void 0;var n;if(this.clearConnectionReconcile(),this.isResuming=!1,this.bufferedEvents=[],this.transcriptionReceivedTimes.clear(),this.incomingDataStreamManager.clearHandlersAndControllers(),this.state!==ct.Disconnected){this.regionUrl=void 0;try{this.remoteParticipants.forEach(s=>{s.trackPublications.forEach(r=>{s.unpublishTrack(r.trackSid)})}),this.localParticipant.trackPublications.forEach(s=>{var r,a,o;s.track&&this.localParticipant.unpublishTrack(s.track,e),e?((r=s.track)===null||r===void 0||r.detach(),(a=s.track)===null||a===void 0||a.stop()):(o=s.track)===null||o===void 0||o.stopMonitor()}),this.localParticipant.off(le.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).off(le.ParticipantNameChanged,this.onLocalParticipantNameChanged).off(le.AttributesChanged,this.onLocalAttributesChanged).off(le.TrackMuted,this.onLocalTrackMuted).off(le.TrackUnmuted,this.onLocalTrackUnmuted).off(le.LocalTrackPublished,this.onLocalTrackPublished).off(le.LocalTrackUnpublished,this.onLocalTrackUnpublished).off(le.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).off(le.MediaDevicesError,this.onMediaDevicesError).off(le.AudioStreamAcquired,this.startAudio).off(le.ChatMessage,this.onLocalChatMessageSent).off(le.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),hn()&&(window.removeEventListener("beforeunload",this.onPageLeave),window.removeEventListener("pagehide",this.onPageLeave),window.removeEventListener("freeze",this.onPageLeave),(n=navigator.mediaDevices)===null||n===void 0||n.removeEventListener("devicechange",this.handleDeviceChange))}finally{this.setAndEmitConnectionState(ct.Disconnected),this.emit(ie.Disconnected,t)}}}handleParticipantDisconnected(e,t){var n;this.remoteParticipants.delete(e),t&&(this.incomingDataStreamManager.validateParticipantHasNoActiveDataStreams(e),t.trackPublications.forEach(s=>{t.unpublishTrack(s.trackSid,!0)}),this.emit(ie.ParticipantDisconnected,t),t.setDisconnected(),(n=this.localParticipant)===null||n===void 0||n.handleParticipantDisconnected(t.identity))}handleIncomingRpcRequest(e,t,n,s,r,a){return P(this,void 0,void 0,function*(){if(yield this.engine.publishRpcAck(e,t),a!==1){yield this.engine.publishRpcResponse(e,t,null,kt.builtIn("UNSUPPORTED_VERSION"));return}const o=this.rpcHandlers.get(n);if(!o){yield this.engine.publishRpcResponse(e,t,null,kt.builtIn("UNSUPPORTED_METHOD"));return}let c=null,l=null;try{const d=yield o({requestId:t,callerIdentity:e,payload:s,responseTimeout:r});Qc(d)>$f?(c=kt.builtIn("RESPONSE_PAYLOAD_TOO_LARGE"),console.warn("RPC Response payload too large for ".concat(n))):l=d}catch(d){d instanceof kt?c=d:(console.warn("Uncaught error returned by RPC handler for ".concat(n,". Returning APPLICATION_ERROR instead."),d),c=kt.builtIn("APPLICATION_ERROR"))}yield this.engine.publishRpcResponse(e,t,l,c)})}selectDefaultDevices(){return P(this,void 0,void 0,function*(){var e,t,n;const s=$t.getInstance().previousDevices,r=yield $t.getInstance().getDevices(void 0,!1),a=bn();if((a==null?void 0:a.name)==="Chrome"&&a.os!=="iOS")for(let c of r){const l=s.find(d=>d.deviceId===c.deviceId);l&&l.label!==""&&l.kind===c.kind&&l.label!==c.label&&this.getActiveDevice(c.kind)==="default"&&this.emit(ie.ActiveDeviceChanged,c.kind,c.deviceId)}const o=["audiooutput","audioinput","videoinput"];for(let c of o){const l=j0(c),d=this.localParticipant.getTrackPublication(l);if(d&&(!((e=d.track)===null||e===void 0)&&e.isUserProvided))continue;const u=r.filter(f=>f.kind===c),h=this.getActiveDevice(c);if(h===((t=s.filter(f=>f.kind===c)[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(c,u[0].deviceId);continue}c==="audioinput"&&!Fr()||c==="videoinput"||u.length>0&&!u.find(f=>f.deviceId===this.getActiveDevice(c))&&(c!=="audiooutput"||!Fr())&&(yield this.switchActiveDevice(c,u[0].deviceId))}})}acquireAudioContext(){return P(this,void 0,void 0,function*(){var e,t;if(typeof this.options.webAudioMix!="boolean"&&this.options.webAudioMix.audioContext?this.audioContext=this.options.webAudioMix.audioContext:(!this.audioContext||this.audioContext.state==="closed")&&(this.audioContext=(e=kf())!==null&&e!==void 0?e:void 0),this.options.webAudioMix&&this.remoteParticipants.forEach(s=>s.setAudioContext(this.audioContext)),this.localParticipant.setAudioContext(this.audioContext),this.audioContext&&this.audioContext.state==="suspended")try{yield Promise.race([this.audioContext.resume(),un(200)])}catch(s){this.log.warn("Could not resume audio context",Object.assign(Object.assign({},this.logContext),{error:s}))}const n=((t=this.audioContext)===null||t===void 0?void 0:t.state)==="running";n!==this.canPlaybackAudio&&(this.audioEnabled=n,this.emit(ie.AudioPlaybackStatusChanged,n))})}createParticipant(e,t){var n;let s;return t?s=ja.fromParticipantInfo(this.engine.client,t,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}):s=new ja(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),this.logContext)),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(ie.ParticipantConnected,n),n.on(le.TrackPublished,s=>{this.emitWhenConnected(ie.TrackPublished,s,n)}).on(le.TrackSubscribed,(s,r)=>{s.kind===Q.Kind.Audio?(s.on(oe.AudioPlaybackStarted,this.handleAudioPlaybackStarted),s.on(oe.AudioPlaybackFailed,this.handleAudioPlaybackFailed)):s.kind===Q.Kind.Video&&(s.on(oe.VideoPlaybackFailed,this.handleVideoPlaybackFailed),s.on(oe.VideoPlaybackStarted,this.handleVideoPlaybackStarted)),this.emit(ie.TrackSubscribed,s,r,n)}).on(le.TrackUnpublished,s=>{this.emit(ie.TrackUnpublished,s,n)}).on(le.TrackUnsubscribed,(s,r)=>{this.emit(ie.TrackUnsubscribed,s,r,n)}).on(le.TrackMuted,s=>{this.emitWhenConnected(ie.TrackMuted,s,n)}).on(le.TrackUnmuted,s=>{this.emitWhenConnected(ie.TrackUnmuted,s,n)}).on(le.ParticipantMetadataChanged,s=>{this.emitWhenConnected(ie.ParticipantMetadataChanged,s,n)}).on(le.ParticipantNameChanged,s=>{this.emitWhenConnected(ie.ParticipantNameChanged,s,n)}).on(le.AttributesChanged,s=>{this.emitWhenConnected(ie.ParticipantAttributesChanged,s,n)}).on(le.ConnectionQualityChanged,s=>{this.emitWhenConnected(ie.ConnectionQualityChanged,s,n)}).on(le.ParticipantPermissionsChanged,s=>{this.emitWhenConnected(ie.ParticipantPermissionsChanged,s,n)}).on(le.TrackSubscriptionStatusChanged,(s,r)=>{this.emitWhenConnected(ie.TrackSubscriptionStatusChanged,s,r,n)}).on(le.TrackSubscriptionFailed,(s,r)=>{this.emit(ie.TrackSubscriptionFailed,s,n,r)}).on(le.TrackSubscriptionPermissionChanged,(s,r)=>{this.emitWhenConnected(ie.TrackSubscriptionPermissionChanged,s,r,n)}).on(le.Active,()=>{this.emitWhenConnected(ie.ParticipantActive,n),n.kind===Ir.AGENT&&this.localParticipant.setActiveAgent(n)}),t&&n.updateInfo(t),n}sendSyncState(){const e=Array.from(this.remoteParticipants.values()).reduce((n,s)=>(n.push(...s.getTrackPublications()),n),[]),t=this.localParticipant.getTrackPublications();this.engine.sendSyncState(e,t)}updateSubscriptions(){for(const e of this.remoteParticipants.values())for(const t of e.videoTrackPublications.values())t.isSubscribed&&W0(t)&&t.emitTrackUpdate()}getRemoteParticipantBySid(e){const t=this.sidToIdentity.get(e);if(t)return this.remoteParticipants.get(t)}registerConnectionReconcile(){this.clearConnectionReconcile();let e=0;this.connectionReconcileInterval=Yt.setInterval(()=>{!this.engine||this.engine.isClosed||!this.engine.verifyTransport()?(e++,this.log.warn("detected connection state mismatch",Object.assign(Object.assign({},this.logContext),{numFailures:e,engine:this.engine?{closed:this.engine.isClosed,transportsConnected:this.engine.verifyTransport()}:void 0})),e>=3&&(this.recreateEngine(),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,In.STATE_MISMATCH))):e=0},iy)}clearConnectionReconcile(){this.connectionReconcileInterval&&Yt.clearInterval(this.connectionReconcileInterval)}setAndEmitConnectionState(e){return e===this.state?!1:(this.state=e,this.emit(ie.ConnectionStateChanged,this.state),!0)}emitBufferedEvents(){this.bufferedEvents.forEach(e=>{let[t,n]=e;this.emit(t,...n)}),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===ct.Reconnecting||this.isResuming||!this.engine||this.engine.pendingReconnect)this.bufferedEvents.push([e,n]);else if(this.state===ct.Connected)return this.emit(e,...n);return!1}simulateParticipants(e){return P(this,void 0,void 0,function*(){var t,n;const s=Object.assign({audio:!0,video:!0,useRealTracks:!1},e.publish),r=Object.assign({count:9,audio:!1,video:!0,aspectRatios:[1.66,1.7,1.3]},e.participants);if(this.handleDisconnect(),this.roomInfo=new wa({sid:"RM_SIMULATED",name:"simulated-room",emptyTimeout:0,maxParticipants:0,creationTime:At.parse(new Date().getTime()),metadata:"",numParticipants:1,numPublishers:1,turnPassword:"",enabledCodecs:[],activeRecording:!1}),this.localParticipant.updateInfo(new ss({identity:"simulated-local",name:"local-name"})),this.setupLocalParticipantEvents(),this.emit(ie.SignalConnected),this.emit(ie.Connected),this.setAndEmitConnectionState(ct.Connected),s.video){const a=new ll(Q.Kind.Video,new Ls({source:Ot.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:kn.AUDIO,name:"video-dummy"}),new qa(s.useRealTracks?(yield window.navigator.mediaDevices.getUserMedia({video:!0})).getVideoTracks()[0]:wf(160*((t=r.aspectRatios[0])!==null&&t!==void 0?t:1),160,!0,!0),void 0,!1,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(a),this.localParticipant.emit(le.LocalTrackPublished,a)}if(s.audio){const a=new ll(Q.Kind.Audio,new Ls({source:Ot.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:kn.AUDIO}),new Wa(s.useRealTracks?(yield navigator.mediaDevices.getUserMedia({audio:!0})).getAudioTracks()[0]:Oc(),void 0,!1,this.audioContext,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(a),this.localParticipant.emit(le.LocalTrackPublished,a)}for(let a=0;a<r.count-1;a+=1){let o=new ss({sid:Math.floor(Math.random()*1e4).toString(),identity:"simulated-".concat(a),state:Ds.ACTIVE,tracks:[],joinedAt:At.parse(Date.now())});const c=this.getOrCreateParticipant(o.identity,o);if(r.video){const l=wf(160*((n=r.aspectRatios[a%r.aspectRatios.length])!==null&&n!==void 0?n:1),160,!1,!0),d=new Ls({source:Ot.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:kn.AUDIO});c.addSubscribedMediaTrack(l,d.sid,new MediaStream([l]),new RTCRtpReceiver),o.tracks=[...o.tracks,d]}if(r.audio){const l=Oc(),d=new Ls({source:Ot.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:kn.AUDIO});c.addSubscribedMediaTrack(l,d.sid,new MediaStream([l]),new RTCRtpReceiver),o.tracks=[...o.tracks,d]}c.updateInfo(o)}})}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!==ie.ActiveSpeakersChanged&&e!==ie.TranscriptionReceived){const r=cp(n).filter(a=>a!==void 0);this.log.debug("room event ".concat(e),Object.assign(Object.assign({},this.logContext),{event:e,args:r}))}return super.emit(e,...n)}}Gs.cleanupRegistry=typeof FinalizationRegistry<"u"&&new FinalizationRegistry(i=>{i()});function cp(i){return i.map(e=>{if(e)return Array.isArray(e)?cp(e):typeof e=="object"?"logContext"in e?e.logContext:void 0:e})}var Fn;(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"})(Fn||(Fn={}));class $i extends Xn.EventEmitter{constructor(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.status=Fn.IDLE,this.logs=[],this.options={},this.url=e,this.token=t,this.name=this.constructor.name,this.room=new Gs(n.roomOptions),this.connectOptions=n.connectOptions,this.options=n}run(e){return P(this,void 0,void 0,function*(){if(this.status!==Fn.IDLE)throw Error("check is running already");this.setStatus(Fn.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!==Fn.SKIPPED&&this.setStatus(this.isSuccess()?Fn.SUCCESS:Fn.FAILED),e&&e(),this.getInfo()})}isSuccess(){return!this.logs.some(e=>e.level==="error")}connect(e){return P(this,void 0,void 0,function*(){return this.room.state===ct.Connected?this.room:(e||(e=this.url),yield this.room.connect(e,this.token,this.connectOptions),this.room)})}disconnect(){return P(this,void 0,void 0,function*(){this.room&&this.room.state!==ct.Disconnected&&(yield this.room.disconnect(),yield new Promise(e=>setTimeout(e,500)))})}skip(){this.setStatus(Fn.SKIPPED)}switchProtocol(e){return P(this,void 0,void 0,function*(){let t=!1,n=!1;if(this.room.on(ie.Reconnecting,()=>{t=!0}),this.room.once(ie.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 un(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 sy extends $i{get description(){return"Cloud regions"}perform(){return P(this,void 0,void 0,function*(){const e=new al(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 P(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,c=1e6/a,l="A".repeat(a),d=Date.now();for(let g=0;g<c;g++)yield r.write(l);yield r.close();const u=Date.now(),h=yield(n=this.room.engine.pcManager)===null||n===void 0?void 0:n.publisher.getStats(),f={region:s,rtt:1e4,duration:u-d};return h==null||h.forEach(g=>{g.type==="candidate-pair"&&g.nominated&&(f.rtt=g.currentRoundTripTime*1e3)}),yield this.disconnect(),f})}}const dl=1e4;class ry extends $i{get description(){return"Connection via UDP vs TCP"}perform(){return P(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/(dl/1e3)*100).toFixed(2),"%")),n.qualityLimitationDurations.cpu>0&&this.appendWarning("cpu limited ".concat((n.qualityLimitationDurations.cpu/(dl/1e3)*100).toFixed(2),"%"))})}getInfo(){const e=super.getInfo();return e.data=this.bestStats,e}checkConnectionProtocol(e){return P(this,void 0,void 0,function*(){yield this.connect(),e==="tcp"?yield this.switchProtocol("tcp"):yield this.switchProtocol("udp");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],l=(yield this.room.localParticipant.publishTrack(o,{simulcast:!1,degradationPreference:"maintain-resolution",videoEncoding:{maxBitrate:2e6}})).track,d={protocol:e,packetsLost:0,packetsSent:0,qualityLimitationDurations:{},rttTotal:0,jitterTotal:0,bitrateTotal:0,count:0},u=setInterval(()=>P(this,void 0,void 0,function*(){const h=yield l.getRTCStatsReport();h==null||h.forEach(f=>{f.type==="outbound-rtp"?(d.packetsSent=f.packetsSent,d.qualityLimitationDurations=f.qualityLimitationDurations,d.bitrateTotal+=f.targetBitrate,d.count++):f.type==="remote-inbound-rtp"&&(d.packetsLost=f.packetsLost,d.rttTotal+=f.roundTripTime,d.jitterTotal+=f.jitter)})}),1e3);return yield new Promise(h=>setTimeout(h,dl)),clearInterval(u),o.stop(),t.remove(),yield this.disconnect(),d})}}class ay extends $i{get description(){return"Can publish audio"}perform(){return P(this,void 0,void 0,function*(){var e;const t=yield this.connect(),n=yield Zb();if(yield Pf(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 oy extends $i{get description(){return"Can publish video"}perform(){return P(this,void 0,void 0,function*(){var e;const t=yield this.connect(),n=yield Jb();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=>{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 P(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,yield new Promise(s=>{n.onplay=()=>{setTimeout(()=>{var r,a,o,c;const l=document.createElement("canvas"),d=e.getSettings(),u=(a=(r=d.width)!==null&&r!==void 0?r:n.videoWidth)!==null&&a!==void 0?a:1280,h=(c=(o=d.height)!==null&&o!==void 0?o:n.videoHeight)!==null&&c!==void 0?c:720;l.width=u,l.height=h;const f=l.getContext("2d");f.drawImage(n,0,0);const v=f.getImageData(0,0,l.width,l.height).data;let m=!0;for(let p=0;p<v.length;p+=4)if(v[p]!==0||v[p+1]!==0||v[p+2]!==0){m=!1;break}m?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 cy extends $i{get description(){return"Resuming connection after interruption"}perform(){return P(this,void 0,void 0,function*(){var e;const t=yield this.connect();let n=!1,s=!1,r;const a=new Promise(l=>{setTimeout(l,5e3),r=l}),o=()=>{n=!0};t.on(ie.SignalReconnecting,o).on(ie.Reconnecting,o).on(ie.Reconnected,()=>{s=!0,r(!0)}),(e=t.engine.client.ws)===null||e===void 0||e.close();const c=t.engine.client.onClose;if(c&&c(""),yield a,n){if(!s||t.state!==ct.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 ly extends $i{get description(){return"Can connect via TURN"}perform(){return P(this,void 0,void 0,function*(){var e,t;const n=new qc,s=yield n.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3});let r=!1,a=!1,o=!1;for(let c of s.iceServers)for(let l of c.urls)l.startsWith("turn:")?(a=!0,o=!0):l.startsWith("turns:")&&(a=!0,o=!0,r=!0),l.startsWith("stun:")&&(o=!0);o?a&&!r&&this.appendWarning("TURN is configured server side, but TURN/TLS is unavailable."):this.appendWarning("No STUN servers configured on server side."),yield n.close(),!((t=(e=this.connectOptions)===null||e===void 0?void 0:e.rtcConfig)===null||t===void 0)&&t.iceServers||a?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 dy extends $i{get description(){return"Establishing WebRTC connection"}perform(){return P(this,void 0,void 0,function*(){let e=!1,t=!1;this.room.on(ie.SignalConnected,()=>{const n=this.room.engine.client.onTrickle;this.room.engine.client.onTrickle=(s,r)=>{if(s.candidate){const a=new RTCIceCandidate(s);let o="".concat(a.protocol," ").concat(a.address,":").concat(a.port," ").concat(a.type);a.address&&(uy(a.address)?o+=" (private)":a.protocol==="tcp"&&a.tcpType==="passive"?(e=!0,o+=" (passive)"):a.protocol==="udp"&&(t=!0)),this.appendMessage(o)}n&&n(s,r)},this.room.engine.pcManager&&(this.room.engine.pcManager.subscriber.onIceCandidateError=s=>{s instanceof RTCPeerConnectionIceErrorEvent&&this.appendWarning("error with ICE candidate: ".concat(s.errorCode," ").concat(s.errorText," ").concat(s.url))})});try{yield this.connect(),Ke.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 uy(i){const e=i.split(".");if(e.length===4){if(e[0]==="10")return!0;if(e[0]==="192"&&e[1]==="168")return!0;if(e[0]==="172"){const t=parseInt(e[1],10);if(t>=16&&t<=31)return!0}}return!1}class hy extends $i{get description(){return"Connecting to signal connection via WebSocket"}perform(){return P(this,void 0,void 0,function*(){var e,t,n;(this.url.startsWith("ws:")||this.url.startsWith("http:"))&&this.appendWarning("Server is insecure, clients may block connections to it");let s=new qc;const r=yield s.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3});this.appendMessage("Connected to server, version ".concat(r.serverVersion,".")),((e=r.serverInfo)===null||e===void 0?void 0:e.edition)===ah.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)),yield s.close()})}}class wE extends Xn.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:Fn.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!==Fn.FAILED)}getResults(){return Array.from(this.checkResults.values())}createAndRunCheck(e){return P(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 P(this,void 0,void 0,function*(){return this.createAndRunCheck(hy)})}checkWebRTC(){return P(this,void 0,void 0,function*(){return this.createAndRunCheck(dy)})}checkTURN(){return P(this,void 0,void 0,function*(){return this.createAndRunCheck(ly)})}checkReconnect(){return P(this,void 0,void 0,function*(){return this.createAndRunCheck(cy)})}checkPublishAudio(){return P(this,void 0,void 0,function*(){return this.createAndRunCheck(ay)})}checkPublishVideo(){return P(this,void 0,void 0,function*(){return this.createAndRunCheck(oy)})}checkConnectionProtocol(){return P(this,void 0,void 0,function*(){const e=yield this.createAndRunCheck(ry);if(e.data&&"protocol"in e.data){const t=e.data;this.options.protocol=t.protocol}return e})}checkCloudRegion(){return P(this,void 0,void 0,function*(){return this.createAndRunCheck(sy)})}}class Hs{constructor(){this.audioContext=null,this.refCount=0,this.resumePromise=null}static getInstance(){return Hs.instance||(Hs.instance=new Hs),Hs.instance}async acquire(){if(this.refCount++,!this.audioContext)try{const e=window.AudioContext||window.webkitAudioContext;if(!e)return console.warn("[SharedAudioContext] Web Audio API not supported"),null;this.audioContext=new e,console.log("[SharedAudioContext] Created shared AudioContext")}catch(e){return console.warn("[SharedAudioContext] Failed to create AudioContext:",e),null}return await this.ensureResumed(),this.audioContext}release(){this.refCount=Math.max(0,this.refCount-1),this.refCount===0&&console.log("[SharedAudioContext] All references released, context kept alive for reuse")}forceClose(){if(this.audioContext){try{this.audioContext.close()}catch{}this.audioContext=null,this.refCount=0,console.log("[SharedAudioContext] Force closed")}}getContext(){return this.audioContext}async ensureResumed(){if(!this.audioContext)return!1;if(this.audioContext.state==="suspended"){this.resumePromise||(this.resumePromise=this.audioContext.resume().finally(()=>{this.resumePromise=null}));try{await this.resumePromise}catch{return!1}}return this.audioContext.state==="running"}isRunning(){return this.audioContext!==null&&this.audioContext.state==="running"}getState(){var e;return((e=this.audioContext)==null?void 0:e.state)??null}getSampleRate(){var e;return((e=this.audioContext)==null?void 0:e.sampleRate)??44100}getCurrentTime(){var e;return((e=this.audioContext)==null?void 0:e.currentTime)??0}getDestination(){var e;return((e=this.audioContext)==null?void 0:e.destination)??null}}const ei=Hs.getInstance();typeof window<"u"&&window.addEventListener("pagehide",()=>{ei.forceClose()});const pn=class pn extends EventTarget{constructor(){super(...arguments),this.room=null,this.callStatus="idle",this.isReady=!1,this.error=null,this.microphoneEnabled=!1,this.connectedParticipants=[],this.userIdentity="",this.roomName="",this.audioPlaybackPrompt=!1,this.isAppleDevice=/iPhone|iPad|iPod|Macintosh|Mac OS/i.test(navigator.userAgent),this.agentAudioElements=[],this.unmuteTimer=null,this.speakingHandler=null,this.fadeContext=null,this.fadeContextAcquired=!1,this.fadeGains=new Map,this.fadeSetupPromise=null}static isAgentIdentity(e){return e.includes("agent")||e.includes("voice-assistant")||e.includes("AJ_")}set serviceUrl(e){this._serviceUrl=e}get serviceUrl(){return this._serviceUrl??"https://voice.hanc.ai"}get status(){return this.callStatus}get ready(){return this.isReady}get currentError(){return this.error}get currentRoom(){return this.room}get isMicrophoneEnabled(){return this.microphoneEnabled}get participants(){return this.connectedParticipants}get identity(){return this.userIdentity}get roomNameValue(){return this.roomName}get showAudioPrompt(){return this.audioPlaybackPrompt}updateStatus(e){this.callStatus=e,this.dispatchEvent(new CustomEvent("status-changed",{detail:e}))}async makeCall({agentId:e,user_identity:t}){var n;if(!(this.room&&this.room.state==="connected")){this.updateStatus("connecting"),this.error=null,this.isReady=!1,this.room&&(await this.room.disconnect(),this.room=null);try{const s=new Gs({webAudioMix:!1,dynacast:!0,adaptiveStream:!0});this.room=s,this.setupRoomEventListeners(s);const r=await fetch(`${this.serviceUrl}/create-room-token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({metadata:{user_identity:t,agent_id:e,timestamp:Date.now(),is_apple_device:this.isAppleDevice}})});if(!r.ok){const u=await r.text();throw new Error(`Failed to get room token: ${r.status} ${u}`)}const{token:a,url:o,room_name:c,user_identity:l}=await r.json();this.roomName=c,this.userIdentity=l;const d={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0};await Promise.all([s.localParticipant.setMicrophoneEnabled(!0,d).then(()=>{this.microphoneEnabled=!0,this.dispatchEvent(new CustomEvent("microphone-enabled"))}).catch(u=>{console.warn("Could not enable microphone:",u),this.microphoneEnabled=!1,this.dispatchEvent(new CustomEvent("microphone-disabled"))}),s.connect(o,a)]),await new Promise(u=>{const h=setTimeout(()=>{s.off(ie.ParticipantConnected,f),u()},2e3),f=g=>{pn.isAgentIdentity(g.identity)&&(clearTimeout(h),s.off(ie.ParticipantConnected,f),u())};for(const g of s.remoteParticipants.values())if(pn.isAgentIdentity(g.identity)){clearTimeout(h),u();return}s.on(ie.ParticipantConnected,f)}),this.updateStatus("connected"),this.isReady=!0;for(const u of s.localParticipant.audioTrackPublications.values())(n=u.track)!=null&&n.mediaStreamTrack&&this.dispatchEvent(new CustomEvent("local-audio-track",{detail:u.track.mediaStreamTrack}));this.dispatchEvent(new CustomEvent("room-connected",{detail:{roomName:c,identity:l}}))}catch(s){this.error=`Connection failed: ${s instanceof Error?s.message:String(s)}`,this.updateStatus("error"),this.isReady=!1,this.room=null,this.dispatchEvent(new CustomEvent("error",{detail:{error:this.error}}))}}}setupRoomEventListeners(e){e.on(ie.Disconnected,()=>{this.callStatus!=="disconnected"&&this.updateStatus("disconnected"),this.connectedParticipants=[],this.microphoneEnabled=!1,this.audioPlaybackPrompt=!1,this.isReady=!1,this.cleanupFadeContext(),this.unmuteTimer&&(clearTimeout(this.unmuteTimer),this.unmuteTimer=null),this.speakingHandler&&(e.localParticipant.off("isSpeakingChanged",this.speakingHandler),this.speakingHandler=null),this.room=null,this.dispatchEvent(new CustomEvent("disconnected"))}),e.on(ie.ParticipantConnected,t=>{this.connectedParticipants=[...this.connectedParticipants,t.identity];const n=pn.isAgentIdentity(t.identity);n&&(this.updateStatus("agent-connected"),this.audioPlaybackPrompt=!0,this.dispatchEvent(new CustomEvent("agent-connected",{detail:{participant:t.identity}}))),this.dispatchEvent(new CustomEvent("participant-connected",{detail:{participant:t.identity,isAgent:n}}))}),e.on(ie.ParticipantDisconnected,t=>{this.connectedParticipants=this.connectedParticipants.filter(s=>s!==t.identity);const n=pn.isAgentIdentity(t.identity);n&&(this.audioPlaybackPrompt=!1,this.updateStatus("connected"),this.dispatchEvent(new CustomEvent("agent-disconnected",{detail:{participant:t.identity}}))),this.dispatchEvent(new CustomEvent("participant-disconnected",{detail:{participant:t.identity,isAgent:n}}))}),e.on(ie.TrackSubscribed,(t,n,s)=>{if(t.kind==="audio"){const r=t.attach();document.body.appendChild(r),pn.isAgentIdentity(s.identity)&&(this.agentAudioElements.push(r),this.setupAgentAudioFade(r)),this.dispatchEvent(new CustomEvent("audio-track-added",{detail:{participant:s.identity,element:r}}));const a=t.mediaStreamTrack;a&&this.dispatchEvent(new CustomEvent("audio-track",{detail:a}))}}),e.on(ie.TrackUnsubscribed,(t,n,s)=>{const r=t.detach();for(const a of r){const o=this.fadeGains.get(a);if(o){try{o.source.disconnect()}catch{}try{o.gain.disconnect()}catch{}this.fadeGains.delete(a)}}this.agentAudioElements=this.agentAudioElements.filter(a=>!r.includes(a)),this.dispatchEvent(new CustomEvent("audio-track-removed",{detail:{participant:s.identity}}))}),e.on(ie.MediaDevicesError,t=>{this.error=`Media device error: ${t.message}`,this.updateStatus("error"),this.dispatchEvent(new CustomEvent("error",{detail:{error:this.error}}))}),e.on(ie.AudioPlaybackStatusChanged,async()=>{e.canPlaybackAudio||this.connectedParticipants.some(n=>pn.isAgentIdentity(n))&&!this.audioPlaybackPrompt&&(this.updateStatus("agent-connected"),this.audioPlaybackPrompt=!0),this.dispatchEvent(new CustomEvent("audio-playback-status-changed",{detail:{canPlayback:e.canPlaybackAudio}}))}),this.speakingHandler=t=>{t?(this.unmuteTimer&&(clearTimeout(this.unmuteTimer),this.unmuteTimer=null),this.rampAgentGain(0,pn.FADEOUT_TC)):this.unmuteTimer=setTimeout(()=>{this.unmuteTimer=null,this.rampAgentGain(1,pn.FADEIN_TC)},pn.UNMUTE_HOLDOVER_MS)},e.localParticipant.on("isSpeakingChanged",this.speakingHandler)}async toggleMicrophone(){if(this.room)try{this.microphoneEnabled?(await this.room.localParticipant.setMicrophoneEnabled(!1),this.microphoneEnabled=!1,this.dispatchEvent(new CustomEvent("microphone-disabled"))):(await this.room.localParticipant.setMicrophoneEnabled(!0,{echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0}),this.microphoneEnabled=!0,this.dispatchEvent(new CustomEvent("microphone-enabled")))}catch(e){this.error=`Failed to toggle microphone: ${e instanceof Error?e.message:String(e)}`,this.dispatchEvent(new CustomEvent("error",{detail:{error:this.error}}))}}setupAgentAudioFade(e){const t=(async()=>{try{if(this.fadeContext)await ei.ensureResumed();else{const r=await ei.acquire();if(!r){console.warn("[CallManager] Could not acquire shared AudioContext for fade");return}this.fadeContext=r,this.fadeContextAcquired=!0}const n=this.fadeContext.createMediaElementSource(e),s=this.fadeContext.createGain();n.connect(s),s.connect(this.fadeContext.destination),this.fadeGains.set(e,{source:n,gain:s})}catch(n){console.warn("[CallManager] Audio fade setup failed:",n)}})();this.fadeSetupPromise=t,t.then(()=>{this.fadeSetupPromise=null})}rampAgentGain(e,t,n=!1){const s=this.fadeContext;if(s&&s.state==="running"&&this.fadeGains.size>0)for(const{gain:r}of this.fadeGains.values())r.gain.cancelScheduledValues(s.currentTime),r.gain.setValueAtTime(r.gain.value,s.currentTime),r.gain.setTargetAtTime(e,s.currentTime,t);else if(this.fadeSetupPromise)this.fadeSetupPromise.then(()=>this.rampAgentGain(e,t));else if(!n&&s&&s.state==="suspended"&&this.fadeGains.size>0)ei.ensureResumed().then(r=>{if(r)this.rampAgentGain(e,t,!0);else for(const a of this.agentAudioElements)a.volume=e});else for(const r of this.agentAudioElements)r.volume=e}cleanupFadeContext(){this.agentAudioElements=[];for(const{source:e,gain:t}of this.fadeGains.values()){try{e.disconnect()}catch{}try{t.disconnect()}catch{}}this.fadeGains.clear(),this.fadeSetupPromise=null,this.fadeContextAcquired&&(ei.release(),this.fadeContextAcquired=!1),this.fadeContext=null}async enableAudio(){if(this.room)try{await this.room.startAudio(),this.audioPlaybackPrompt=!1;const e=JSON.stringify({type:"audio_enabled"}),n=new TextEncoder().encode(e);await this.room.localParticipant.publishData(n,{reliable:!0}),this.dispatchEvent(new CustomEvent("audio-enabled"))}catch(e){this.error=`Failed to enable audio: ${e instanceof Error?e.message:String(e)}`,this.dispatchEvent(new CustomEvent("error",{detail:{error:this.error}}))}}async hangUp(){if(!this.room){this.error="No active connection to end.";return}this.updateStatus("disconnecting");const e=this.room;this.room=null,this.connectedParticipants=[],this.microphoneEnabled=!1,this.audioPlaybackPrompt=!1,this.isReady=!1,this.cleanupFadeContext(),this.unmuteTimer&&(clearTimeout(this.unmuteTimer),this.unmuteTimer=null),this.speakingHandler&&(e.localParticipant.off("isSpeakingChanged",this.speakingHandler),this.speakingHandler=null),this.updateStatus("disconnected"),this.dispatchEvent(new CustomEvent("call-ended")),requestAnimationFrame(()=>{setTimeout(async()=>{try{await e.disconnect()}catch(t){console.warn("Error during room disconnect:",t)}},0)})}};pn.UNMUTE_HOLDOVER_MS=350,pn.FADEOUT_TC=.045,pn.FADEIN_TC=.03;let Ws=pn;/**
|
|
85
85
|
* @license
|
|
86
86
|
* Copyright 2010-2025 Three.js Authors
|
|
87
87
|
* SPDX-License-Identifier: MIT
|
|
88
|
-
*/const ul="182",fy=0,lp=1,py=2,Xa=1,my=2,Hr=3,yi=0,en=1,_i=2,Si=0,qs=1,hl=2,dp=3,up=4,gy=5,us=100,vy=101,by=102,yy=103,_y=104,Sy=200,xy=201,Ty=202,Cy=203,fl=204,pl=205,Ey=206,My=207,wy=208,Ay=209,Ry=210,Py=211,ky=212,Iy=213,Dy=214,ml=0,gl=1,vl=2,$s=3,bl=4,yl=5,_l=6,Sl=7,hp=0,Ly=1,Uy=2,ti=0,fp=1,pp=2,mp=3,gp=4,vp=5,bp=6,yp=7,_p=300,hs=301,js=302,xl=303,Tl=304,Ya=306,Cl=1e3,xi=1001,El=1002,Kt=1003,Ny=1004,Ka=1005,Jt=1006,Ml=1007,fs=1008,En=1009,Sp=1010,xp=1011,Wr=1012,wl=1013,ni=1014,ii=1015,Ti=1016,Al=1017,Rl=1018,qr=1020,Tp=35902,Cp=35899,Ep=1021,Mp=1022,Bn=1023,Ci=1026,ps=1027,wp=1028,Pl=1029,Xs=1030,kl=1031,Il=1033,Ja=33776,Za=33777,Qa=33778,eo=33779,Dl=35840,Ll=35841,Ul=35842,Nl=35843,Ol=36196,Fl=37492,Bl=37496,zl=37488,Vl=37489,Gl=37490,Hl=37491,Wl=37808,ql=37809,$l=37810,jl=37811,Xl=37812,Yl=37813,Kl=37814,Jl=37815,Zl=37816,Ql=37817,ed=37818,td=37819,nd=37820,id=37821,sd=36492,rd=36494,ad=36495,od=36283,cd=36284,ld=36285,dd=36286,Oy=3200,Fy=0,By=1,ji="",Mn="srgb",Ys="srgb-linear",to="linear",ut="srgb",Ks=7680,Ap=519,zy=512,Vy=513,Gy=514,ud=515,Hy=516,Wy=517,hd=518,qy=519,Rp=35044,Pp="300 es",si=2e3,no=2001;function kp(i){for(let e=i.length-1;e>=0;--e)if(i[e]>=65535)return!0;return!1}function io(i){return document.createElementNS("http://www.w3.org/1999/xhtml",i)}function $y(){const i=io("canvas");return i.style.display="block",i}const Ip={};function Dp(...i){const e="THREE."+i.shift();console.log(e,...i)}function Oe(...i){const e="THREE."+i.shift();console.warn(e,...i)}function rt(...i){const e="THREE."+i.shift();console.error(e,...i)}function $r(...i){const e=i.join(" ");e in Ip||(Ip[e]=!0,Oe(...i))}function jy(i,e,t){return new Promise(function(n,s){function r(){switch(i.clientWaitSync(e,i.SYNC_FLUSH_COMMANDS_BIT,0)){case i.WAIT_FAILED:s();break;case i.TIMEOUT_EXPIRED:setTimeout(r,t);break;default:n()}}setTimeout(r,t)})}class Js{addEventListener(e,t){this._listeners===void 0&&(this._listeners={});const n=this._listeners;n[e]===void 0&&(n[e]=[]),n[e].indexOf(t)===-1&&n[e].push(t)}hasEventListener(e,t){const n=this._listeners;return n===void 0?!1:n[e]!==void 0&&n[e].indexOf(t)!==-1}removeEventListener(e,t){const n=this._listeners;if(n===void 0)return;const s=n[e];if(s!==void 0){const r=s.indexOf(t);r!==-1&&s.splice(r,1)}}dispatchEvent(e){const t=this._listeners;if(t===void 0)return;const n=t[e.type];if(n!==void 0){e.target=this;const s=n.slice(0);for(let r=0,a=s.length;r<a;r++)s[r].call(this,e);e.target=null}}}const Zt=["00","01","02","03","04","05","06","07","08","09","0a","0b","0c","0d","0e","0f","10","11","12","13","14","15","16","17","18","19","1a","1b","1c","1d","1e","1f","20","21","22","23","24","25","26","27","28","29","2a","2b","2c","2d","2e","2f","30","31","32","33","34","35","36","37","38","39","3a","3b","3c","3d","3e","3f","40","41","42","43","44","45","46","47","48","49","4a","4b","4c","4d","4e","4f","50","51","52","53","54","55","56","57","58","59","5a","5b","5c","5d","5e","5f","60","61","62","63","64","65","66","67","68","69","6a","6b","6c","6d","6e","6f","70","71","72","73","74","75","76","77","78","79","7a","7b","7c","7d","7e","7f","80","81","82","83","84","85","86","87","88","89","8a","8b","8c","8d","8e","8f","90","91","92","93","94","95","96","97","98","99","9a","9b","9c","9d","9e","9f","a0","a1","a2","a3","a4","a5","a6","a7","a8","a9","aa","ab","ac","ad","ae","af","b0","b1","b2","b3","b4","b5","b6","b7","b8","b9","ba","bb","bc","bd","be","bf","c0","c1","c2","c3","c4","c5","c6","c7","c8","c9","ca","cb","cc","cd","ce","cf","d0","d1","d2","d3","d4","d5","d6","d7","d8","d9","da","db","dc","dd","de","df","e0","e1","e2","e3","e4","e5","e6","e7","e8","e9","ea","eb","ec","ed","ee","ef","f0","f1","f2","f3","f4","f5","f6","f7","f8","f9","fa","fb","fc","fd","fe","ff"],fd=Math.PI/180,pd=180/Math.PI;function jr(){const i=Math.random()*4294967295|0,e=Math.random()*4294967295|0,t=Math.random()*4294967295|0,n=Math.random()*4294967295|0;return(Zt[i&255]+Zt[i>>8&255]+Zt[i>>16&255]+Zt[i>>24&255]+"-"+Zt[e&255]+Zt[e>>8&255]+"-"+Zt[e>>16&15|64]+Zt[e>>24&255]+"-"+Zt[t&63|128]+Zt[t>>8&255]+"-"+Zt[t>>16&255]+Zt[t>>24&255]+Zt[n&255]+Zt[n>>8&255]+Zt[n>>16&255]+Zt[n>>24&255]).toLowerCase()}function et(i,e,t){return Math.max(e,Math.min(t,i))}function Xy(i,e){return(i%e+e)%e}function md(i,e,t){return(1-t)*i+t*e}function Xr(i,e){switch(e.constructor){case Float32Array:return i;case Uint32Array:return i/4294967295;case Uint16Array:return i/65535;case Uint8Array:return i/255;case Int32Array:return Math.max(i/2147483647,-1);case Int16Array:return Math.max(i/32767,-1);case Int8Array:return Math.max(i/127,-1);default:throw new Error("Invalid component type.")}}function un(i,e){switch(e.constructor){case Float32Array:return i;case Uint32Array:return Math.round(i*4294967295);case Uint16Array:return Math.round(i*65535);case Uint8Array:return Math.round(i*255);case Int32Array:return Math.round(i*2147483647);case Int16Array:return Math.round(i*32767);case Int8Array:return Math.round(i*127);default:throw new Error("Invalid component type.")}}class lt{constructor(e=0,t=0){lt.prototype.isVector2=!0,this.x=e,this.y=t}get width(){return this.x}set width(e){this.x=e}get height(){return this.y}set height(e){this.y=e}set(e,t){return this.x=e,this.y=t,this}setScalar(e){return this.x=e,this.y=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y)}copy(e){return this.x=e.x,this.y=e.y,this}add(e){return this.x+=e.x,this.y+=e.y,this}addScalar(e){return this.x+=e,this.y+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this}subScalar(e){return this.x-=e,this.y-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this}multiply(e){return this.x*=e.x,this.y*=e.y,this}multiplyScalar(e){return this.x*=e,this.y*=e,this}divide(e){return this.x/=e.x,this.y/=e.y,this}divideScalar(e){return this.multiplyScalar(1/e)}applyMatrix3(e){const t=this.x,n=this.y,s=e.elements;return this.x=s[0]*t+s[3]*n+s[6],this.y=s[1]*t+s[4]*n+s[7],this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this}clamp(e,t){return this.x=et(this.x,e.x,t.x),this.y=et(this.y,e.y,t.y),this}clampScalar(e,t){return this.x=et(this.x,e,t),this.y=et(this.y,e,t),this}clampLength(e,t){const n=this.length();return this.divideScalar(n||1).multiplyScalar(et(n,e,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this}negate(){return this.x=-this.x,this.y=-this.y,this}dot(e){return this.x*e.x+this.y*e.y}cross(e){return this.x*e.y-this.y*e.x}lengthSq(){return this.x*this.x+this.y*this.y}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)}normalize(){return this.divideScalar(this.length()||1)}angle(){return Math.atan2(-this.y,-this.x)+Math.PI}angleTo(e){const t=Math.sqrt(this.lengthSq()*e.lengthSq());if(t===0)return Math.PI/2;const n=this.dot(e)/t;return Math.acos(et(n,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){const t=this.x-e.x,n=this.y-e.y;return t*t+n*n}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this}lerpVectors(e,t,n){return this.x=e.x+(t.x-e.x)*n,this.y=e.y+(t.y-e.y)*n,this}equals(e){return e.x===this.x&&e.y===this.y}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this}rotateAround(e,t){const n=Math.cos(t),s=Math.sin(t),r=this.x-e.x,a=this.y-e.y;return this.x=r*n-a*s+e.x,this.y=r*s+a*n+e.y,this}random(){return this.x=Math.random(),this.y=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y}}class Yr{constructor(e=0,t=0,n=0,s=1){this.isQuaternion=!0,this._x=e,this._y=t,this._z=n,this._w=s}static slerpFlat(e,t,n,s,r,a,o){let c=n[s+0],l=n[s+1],d=n[s+2],u=n[s+3],h=r[a+0],f=r[a+1],g=r[a+2],v=r[a+3];if(o<=0){e[t+0]=c,e[t+1]=l,e[t+2]=d,e[t+3]=u;return}if(o>=1){e[t+0]=h,e[t+1]=f,e[t+2]=g,e[t+3]=v;return}if(u!==v||c!==h||l!==f||d!==g){let m=c*h+l*f+d*g+u*v;m<0&&(h=-h,f=-f,g=-g,v=-v,m=-m);let p=1-o;if(m<.9995){const x=Math.acos(m),C=Math.sin(x);p=Math.sin(p*x)/C,o=Math.sin(o*x)/C,c=c*p+h*o,l=l*p+f*o,d=d*p+g*o,u=u*p+v*o}else{c=c*p+h*o,l=l*p+f*o,d=d*p+g*o,u=u*p+v*o;const x=1/Math.sqrt(c*c+l*l+d*d+u*u);c*=x,l*=x,d*=x,u*=x}}e[t]=c,e[t+1]=l,e[t+2]=d,e[t+3]=u}static multiplyQuaternionsFlat(e,t,n,s,r,a){const o=n[s],c=n[s+1],l=n[s+2],d=n[s+3],u=r[a],h=r[a+1],f=r[a+2],g=r[a+3];return e[t]=o*g+d*u+c*f-l*h,e[t+1]=c*g+d*h+l*u-o*f,e[t+2]=l*g+d*f+o*h-c*u,e[t+3]=d*g-o*u-c*h-l*f,e}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get w(){return this._w}set w(e){this._w=e,this._onChangeCallback()}set(e,t,n,s){return this._x=e,this._y=t,this._z=n,this._w=s,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._w)}copy(e){return this._x=e.x,this._y=e.y,this._z=e.z,this._w=e.w,this._onChangeCallback(),this}setFromEuler(e,t=!0){const n=e._x,s=e._y,r=e._z,a=e._order,o=Math.cos,c=Math.sin,l=o(n/2),d=o(s/2),u=o(r/2),h=c(n/2),f=c(s/2),g=c(r/2);switch(a){case"XYZ":this._x=h*d*u+l*f*g,this._y=l*f*u-h*d*g,this._z=l*d*g+h*f*u,this._w=l*d*u-h*f*g;break;case"YXZ":this._x=h*d*u+l*f*g,this._y=l*f*u-h*d*g,this._z=l*d*g-h*f*u,this._w=l*d*u+h*f*g;break;case"ZXY":this._x=h*d*u-l*f*g,this._y=l*f*u+h*d*g,this._z=l*d*g+h*f*u,this._w=l*d*u-h*f*g;break;case"ZYX":this._x=h*d*u-l*f*g,this._y=l*f*u+h*d*g,this._z=l*d*g-h*f*u,this._w=l*d*u+h*f*g;break;case"YZX":this._x=h*d*u+l*f*g,this._y=l*f*u+h*d*g,this._z=l*d*g-h*f*u,this._w=l*d*u-h*f*g;break;case"XZY":this._x=h*d*u-l*f*g,this._y=l*f*u-h*d*g,this._z=l*d*g+h*f*u,this._w=l*d*u+h*f*g;break;default:Oe("Quaternion: .setFromEuler() encountered an unknown order: "+a)}return t===!0&&this._onChangeCallback(),this}setFromAxisAngle(e,t){const n=t/2,s=Math.sin(n);return this._x=e.x*s,this._y=e.y*s,this._z=e.z*s,this._w=Math.cos(n),this._onChangeCallback(),this}setFromRotationMatrix(e){const t=e.elements,n=t[0],s=t[4],r=t[8],a=t[1],o=t[5],c=t[9],l=t[2],d=t[6],u=t[10],h=n+o+u;if(h>0){const f=.5/Math.sqrt(h+1);this._w=.25/f,this._x=(d-c)*f,this._y=(r-l)*f,this._z=(a-s)*f}else if(n>o&&n>u){const f=2*Math.sqrt(1+n-o-u);this._w=(d-c)/f,this._x=.25*f,this._y=(s+a)/f,this._z=(r+l)/f}else if(o>u){const f=2*Math.sqrt(1+o-n-u);this._w=(r-l)/f,this._x=(s+a)/f,this._y=.25*f,this._z=(c+d)/f}else{const f=2*Math.sqrt(1+u-n-o);this._w=(a-s)/f,this._x=(r+l)/f,this._y=(c+d)/f,this._z=.25*f}return this._onChangeCallback(),this}setFromUnitVectors(e,t){let n=e.dot(t)+1;return n<1e-8?(n=0,Math.abs(e.x)>Math.abs(e.z)?(this._x=-e.y,this._y=e.x,this._z=0,this._w=n):(this._x=0,this._y=-e.z,this._z=e.y,this._w=n)):(this._x=e.y*t.z-e.z*t.y,this._y=e.z*t.x-e.x*t.z,this._z=e.x*t.y-e.y*t.x,this._w=n),this.normalize()}angleTo(e){return 2*Math.acos(Math.abs(et(this.dot(e),-1,1)))}rotateTowards(e,t){const n=this.angleTo(e);if(n===0)return this;const s=Math.min(1,t/n);return this.slerp(e,s),this}identity(){return this.set(0,0,0,1)}invert(){return this.conjugate()}conjugate(){return this._x*=-1,this._y*=-1,this._z*=-1,this._onChangeCallback(),this}dot(e){return this._x*e._x+this._y*e._y+this._z*e._z+this._w*e._w}lengthSq(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w}length(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)}normalize(){let e=this.length();return e===0?(this._x=0,this._y=0,this._z=0,this._w=1):(e=1/e,this._x=this._x*e,this._y=this._y*e,this._z=this._z*e,this._w=this._w*e),this._onChangeCallback(),this}multiply(e){return this.multiplyQuaternions(this,e)}premultiply(e){return this.multiplyQuaternions(e,this)}multiplyQuaternions(e,t){const n=e._x,s=e._y,r=e._z,a=e._w,o=t._x,c=t._y,l=t._z,d=t._w;return this._x=n*d+a*o+s*l-r*c,this._y=s*d+a*c+r*o-n*l,this._z=r*d+a*l+n*c-s*o,this._w=a*d-n*o-s*c-r*l,this._onChangeCallback(),this}slerp(e,t){if(t<=0)return this;if(t>=1)return this.copy(e);let n=e._x,s=e._y,r=e._z,a=e._w,o=this.dot(e);o<0&&(n=-n,s=-s,r=-r,a=-a,o=-o);let c=1-t;if(o<.9995){const l=Math.acos(o),d=Math.sin(l);c=Math.sin(c*l)/d,t=Math.sin(t*l)/d,this._x=this._x*c+n*t,this._y=this._y*c+s*t,this._z=this._z*c+r*t,this._w=this._w*c+a*t,this._onChangeCallback()}else this._x=this._x*c+n*t,this._y=this._y*c+s*t,this._z=this._z*c+r*t,this._w=this._w*c+a*t,this.normalize();return this}slerpQuaternions(e,t,n){return this.copy(e).slerp(t,n)}random(){const e=2*Math.PI*Math.random(),t=2*Math.PI*Math.random(),n=Math.random(),s=Math.sqrt(1-n),r=Math.sqrt(n);return this.set(s*Math.sin(e),s*Math.cos(e),r*Math.sin(t),r*Math.cos(t))}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._w===this._w}fromArray(e,t=0){return this._x=e[t],this._y=e[t+1],this._z=e[t+2],this._w=e[t+3],this._onChangeCallback(),this}toArray(e=[],t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._w,e}fromBufferAttribute(e,t){return this._x=e.getX(t),this._y=e.getY(t),this._z=e.getZ(t),this._w=e.getW(t),this._onChangeCallback(),this}toJSON(){return this.toArray()}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._w}}class B{constructor(e=0,t=0,n=0){B.prototype.isVector3=!0,this.x=e,this.y=t,this.z=n}set(e,t,n){return n===void 0&&(n=this.z),this.x=e,this.y=t,this.z=n,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y,this.z)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this}multiplyVectors(e,t){return this.x=e.x*t.x,this.y=e.y*t.y,this.z=e.z*t.z,this}applyEuler(e){return this.applyQuaternion(Lp.setFromEuler(e))}applyAxisAngle(e,t){return this.applyQuaternion(Lp.setFromAxisAngle(e,t))}applyMatrix3(e){const t=this.x,n=this.y,s=this.z,r=e.elements;return this.x=r[0]*t+r[3]*n+r[6]*s,this.y=r[1]*t+r[4]*n+r[7]*s,this.z=r[2]*t+r[5]*n+r[8]*s,this}applyNormalMatrix(e){return this.applyMatrix3(e).normalize()}applyMatrix4(e){const t=this.x,n=this.y,s=this.z,r=e.elements,a=1/(r[3]*t+r[7]*n+r[11]*s+r[15]);return this.x=(r[0]*t+r[4]*n+r[8]*s+r[12])*a,this.y=(r[1]*t+r[5]*n+r[9]*s+r[13])*a,this.z=(r[2]*t+r[6]*n+r[10]*s+r[14])*a,this}applyQuaternion(e){const t=this.x,n=this.y,s=this.z,r=e.x,a=e.y,o=e.z,c=e.w,l=2*(a*s-o*n),d=2*(o*t-r*s),u=2*(r*n-a*t);return this.x=t+c*l+a*u-o*d,this.y=n+c*d+o*l-r*u,this.z=s+c*u+r*d-a*l,this}project(e){return this.applyMatrix4(e.matrixWorldInverse).applyMatrix4(e.projectionMatrix)}unproject(e){return this.applyMatrix4(e.projectionMatrixInverse).applyMatrix4(e.matrixWorld)}transformDirection(e){const t=this.x,n=this.y,s=this.z,r=e.elements;return this.x=r[0]*t+r[4]*n+r[8]*s,this.y=r[1]*t+r[5]*n+r[9]*s,this.z=r[2]*t+r[6]*n+r[10]*s,this.normalize()}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this}divideScalar(e){return this.multiplyScalar(1/e)}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this}clamp(e,t){return this.x=et(this.x,e.x,t.x),this.y=et(this.y,e.y,t.y),this.z=et(this.z,e.z,t.z),this}clampScalar(e,t){return this.x=et(this.x,e,t),this.y=et(this.y,e,t),this.z=et(this.z,e,t),this}clampLength(e,t){const n=this.length();return this.divideScalar(n||1).multiplyScalar(et(n,e,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)}normalize(){return this.divideScalar(this.length()||1)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this.z+=(e.z-this.z)*t,this}lerpVectors(e,t,n){return this.x=e.x+(t.x-e.x)*n,this.y=e.y+(t.y-e.y)*n,this.z=e.z+(t.z-e.z)*n,this}cross(e){return this.crossVectors(this,e)}crossVectors(e,t){const n=e.x,s=e.y,r=e.z,a=t.x,o=t.y,c=t.z;return this.x=s*c-r*o,this.y=r*a-n*c,this.z=n*o-s*a,this}projectOnVector(e){const t=e.lengthSq();if(t===0)return this.set(0,0,0);const n=e.dot(this)/t;return this.copy(e).multiplyScalar(n)}projectOnPlane(e){return gd.copy(this).projectOnVector(e),this.sub(gd)}reflect(e){return this.sub(gd.copy(e).multiplyScalar(2*this.dot(e)))}angleTo(e){const t=Math.sqrt(this.lengthSq()*e.lengthSq());if(t===0)return Math.PI/2;const n=this.dot(e)/t;return Math.acos(et(n,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){const t=this.x-e.x,n=this.y-e.y,s=this.z-e.z;return t*t+n*n+s*s}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)+Math.abs(this.z-e.z)}setFromSpherical(e){return this.setFromSphericalCoords(e.radius,e.phi,e.theta)}setFromSphericalCoords(e,t,n){const s=Math.sin(t)*e;return this.x=s*Math.sin(n),this.y=Math.cos(t)*e,this.z=s*Math.cos(n),this}setFromCylindrical(e){return this.setFromCylindricalCoords(e.radius,e.theta,e.y)}setFromCylindricalCoords(e,t,n){return this.x=e*Math.sin(t),this.y=n,this.z=e*Math.cos(t),this}setFromMatrixPosition(e){const t=e.elements;return this.x=t[12],this.y=t[13],this.z=t[14],this}setFromMatrixScale(e){const t=this.setFromMatrixColumn(e,0).length(),n=this.setFromMatrixColumn(e,1).length(),s=this.setFromMatrixColumn(e,2).length();return this.x=t,this.y=n,this.z=s,this}setFromMatrixColumn(e,t){return this.fromArray(e.elements,t*4)}setFromMatrix3Column(e,t){return this.fromArray(e.elements,t*3)}setFromEuler(e){return this.x=e._x,this.y=e._y,this.z=e._z,this}setFromColor(e){return this.x=e.r,this.y=e.g,this.z=e.b,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this.z=e[t+2],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this.z=e.getZ(t),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this}randomDirection(){const e=Math.random()*Math.PI*2,t=Math.random()*2-1,n=Math.sqrt(1-t*t);return this.x=n*Math.cos(e),this.y=t,this.z=n*Math.sin(e),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z}}const gd=new B,Lp=new Yr;class Ve{constructor(e,t,n,s,r,a,o,c,l){Ve.prototype.isMatrix3=!0,this.elements=[1,0,0,0,1,0,0,0,1],e!==void 0&&this.set(e,t,n,s,r,a,o,c,l)}set(e,t,n,s,r,a,o,c,l){const d=this.elements;return d[0]=e,d[1]=s,d[2]=o,d[3]=t,d[4]=r,d[5]=c,d[6]=n,d[7]=a,d[8]=l,this}identity(){return this.set(1,0,0,0,1,0,0,0,1),this}copy(e){const t=this.elements,n=e.elements;return t[0]=n[0],t[1]=n[1],t[2]=n[2],t[3]=n[3],t[4]=n[4],t[5]=n[5],t[6]=n[6],t[7]=n[7],t[8]=n[8],this}extractBasis(e,t,n){return e.setFromMatrix3Column(this,0),t.setFromMatrix3Column(this,1),n.setFromMatrix3Column(this,2),this}setFromMatrix4(e){const t=e.elements;return this.set(t[0],t[4],t[8],t[1],t[5],t[9],t[2],t[6],t[10]),this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){const n=e.elements,s=t.elements,r=this.elements,a=n[0],o=n[3],c=n[6],l=n[1],d=n[4],u=n[7],h=n[2],f=n[5],g=n[8],v=s[0],m=s[3],p=s[6],x=s[1],C=s[4],b=s[7],S=s[2],M=s[5],A=s[8];return r[0]=a*v+o*x+c*S,r[3]=a*m+o*C+c*M,r[6]=a*p+o*b+c*A,r[1]=l*v+d*x+u*S,r[4]=l*m+d*C+u*M,r[7]=l*p+d*b+u*A,r[2]=h*v+f*x+g*S,r[5]=h*m+f*C+g*M,r[8]=h*p+f*b+g*A,this}multiplyScalar(e){const t=this.elements;return t[0]*=e,t[3]*=e,t[6]*=e,t[1]*=e,t[4]*=e,t[7]*=e,t[2]*=e,t[5]*=e,t[8]*=e,this}determinant(){const e=this.elements,t=e[0],n=e[1],s=e[2],r=e[3],a=e[4],o=e[5],c=e[6],l=e[7],d=e[8];return t*a*d-t*o*l-n*r*d+n*o*c+s*r*l-s*a*c}invert(){const e=this.elements,t=e[0],n=e[1],s=e[2],r=e[3],a=e[4],o=e[5],c=e[6],l=e[7],d=e[8],u=d*a-o*l,h=o*c-d*r,f=l*r-a*c,g=t*u+n*h+s*f;if(g===0)return this.set(0,0,0,0,0,0,0,0,0);const v=1/g;return e[0]=u*v,e[1]=(s*l-d*n)*v,e[2]=(o*n-s*a)*v,e[3]=h*v,e[4]=(d*t-s*c)*v,e[5]=(s*r-o*t)*v,e[6]=f*v,e[7]=(n*c-l*t)*v,e[8]=(a*t-n*r)*v,this}transpose(){let e;const t=this.elements;return e=t[1],t[1]=t[3],t[3]=e,e=t[2],t[2]=t[6],t[6]=e,e=t[5],t[5]=t[7],t[7]=e,this}getNormalMatrix(e){return this.setFromMatrix4(e).invert().transpose()}transposeIntoArray(e){const t=this.elements;return e[0]=t[0],e[1]=t[3],e[2]=t[6],e[3]=t[1],e[4]=t[4],e[5]=t[7],e[6]=t[2],e[7]=t[5],e[8]=t[8],this}setUvTransform(e,t,n,s,r,a,o){const c=Math.cos(r),l=Math.sin(r);return this.set(n*c,n*l,-n*(c*a+l*o)+a+e,-s*l,s*c,-s*(-l*a+c*o)+o+t,0,0,1),this}scale(e,t){return this.premultiply(vd.makeScale(e,t)),this}rotate(e){return this.premultiply(vd.makeRotation(-e)),this}translate(e,t){return this.premultiply(vd.makeTranslation(e,t)),this}makeTranslation(e,t){return e.isVector2?this.set(1,0,e.x,0,1,e.y,0,0,1):this.set(1,0,e,0,1,t,0,0,1),this}makeRotation(e){const t=Math.cos(e),n=Math.sin(e);return this.set(t,-n,0,n,t,0,0,0,1),this}makeScale(e,t){return this.set(e,0,0,0,t,0,0,0,1),this}equals(e){const t=this.elements,n=e.elements;for(let s=0;s<9;s++)if(t[s]!==n[s])return!1;return!0}fromArray(e,t=0){for(let n=0;n<9;n++)this.elements[n]=e[n+t];return this}toArray(e=[],t=0){const n=this.elements;return e[t]=n[0],e[t+1]=n[1],e[t+2]=n[2],e[t+3]=n[3],e[t+4]=n[4],e[t+5]=n[5],e[t+6]=n[6],e[t+7]=n[7],e[t+8]=n[8],e}clone(){return new this.constructor().fromArray(this.elements)}}const vd=new Ve,Up=new Ve().set(.4123908,.3575843,.1804808,.212639,.7151687,.0721923,.0193308,.1191948,.9505322),Np=new Ve().set(3.2409699,-1.5373832,-.4986108,-.9692436,1.8759675,.0415551,.0556301,-.203977,1.0569715);function Yy(){const i={enabled:!0,workingColorSpace:Ys,spaces:{},convert:function(s,r,a){return this.enabled===!1||r===a||!r||!a||(this.spaces[r].transfer===ut&&(s.r=Ei(s.r),s.g=Ei(s.g),s.b=Ei(s.b)),this.spaces[r].primaries!==this.spaces[a].primaries&&(s.applyMatrix3(this.spaces[r].toXYZ),s.applyMatrix3(this.spaces[a].fromXYZ)),this.spaces[a].transfer===ut&&(s.r=Zs(s.r),s.g=Zs(s.g),s.b=Zs(s.b))),s},workingToColorSpace:function(s,r){return this.convert(s,this.workingColorSpace,r)},colorSpaceToWorking:function(s,r){return this.convert(s,r,this.workingColorSpace)},getPrimaries:function(s){return this.spaces[s].primaries},getTransfer:function(s){return s===ji?to:this.spaces[s].transfer},getToneMappingMode:function(s){return this.spaces[s].outputColorSpaceConfig.toneMappingMode||"standard"},getLuminanceCoefficients:function(s,r=this.workingColorSpace){return s.fromArray(this.spaces[r].luminanceCoefficients)},define:function(s){Object.assign(this.spaces,s)},_getMatrix:function(s,r,a){return s.copy(this.spaces[r].toXYZ).multiply(this.spaces[a].fromXYZ)},_getDrawingBufferColorSpace:function(s){return this.spaces[s].outputColorSpaceConfig.drawingBufferColorSpace},_getUnpackColorSpace:function(s=this.workingColorSpace){return this.spaces[s].workingColorSpaceConfig.unpackColorSpace},fromWorkingColorSpace:function(s,r){return $r("ColorManagement: .fromWorkingColorSpace() has been renamed to .workingToColorSpace()."),i.workingToColorSpace(s,r)},toWorkingColorSpace:function(s,r){return $r("ColorManagement: .toWorkingColorSpace() has been renamed to .colorSpaceToWorking()."),i.colorSpaceToWorking(s,r)}},e=[.64,.33,.3,.6,.15,.06],t=[.2126,.7152,.0722],n=[.3127,.329];return i.define({[Ys]:{primaries:e,whitePoint:n,transfer:to,toXYZ:Up,fromXYZ:Np,luminanceCoefficients:t,workingColorSpaceConfig:{unpackColorSpace:Mn},outputColorSpaceConfig:{drawingBufferColorSpace:Mn}},[Mn]:{primaries:e,whitePoint:n,transfer:ut,toXYZ:Up,fromXYZ:Np,luminanceCoefficients:t,outputColorSpaceConfig:{drawingBufferColorSpace:Mn}}}),i}const it=Yy();function Ei(i){return i<.04045?i*.0773993808:Math.pow(i*.9478672986+.0521327014,2.4)}function Zs(i){return i<.0031308?i*12.92:1.055*Math.pow(i,.41666)-.055}let Qs;class Ky{static getDataURL(e,t="image/png"){if(/^data:/i.test(e.src)||typeof HTMLCanvasElement>"u")return e.src;let n;if(e instanceof HTMLCanvasElement)n=e;else{Qs===void 0&&(Qs=io("canvas")),Qs.width=e.width,Qs.height=e.height;const s=Qs.getContext("2d");e instanceof ImageData?s.putImageData(e,0,0):s.drawImage(e,0,0,e.width,e.height),n=Qs}return n.toDataURL(t)}static sRGBToLinear(e){if(typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&e instanceof ImageBitmap){const t=io("canvas");t.width=e.width,t.height=e.height;const n=t.getContext("2d");n.drawImage(e,0,0,e.width,e.height);const s=n.getImageData(0,0,e.width,e.height),r=s.data;for(let a=0;a<r.length;a++)r[a]=Ei(r[a]/255)*255;return n.putImageData(s,0,0),t}else if(e.data){const t=e.data.slice(0);for(let n=0;n<t.length;n++)t instanceof Uint8Array||t instanceof Uint8ClampedArray?t[n]=Math.floor(Ei(t[n]/255)*255):t[n]=Ei(t[n]);return{data:t,width:e.width,height:e.height}}else return Oe("ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied."),e}}let Jy=0;class bd{constructor(e=null){this.isSource=!0,Object.defineProperty(this,"id",{value:Jy++}),this.uuid=jr(),this.data=e,this.dataReady=!0,this.version=0}getSize(e){const t=this.data;return typeof HTMLVideoElement<"u"&&t instanceof HTMLVideoElement?e.set(t.videoWidth,t.videoHeight,0):typeof VideoFrame<"u"&&t instanceof VideoFrame?e.set(t.displayHeight,t.displayWidth,0):t!==null?e.set(t.width,t.height,t.depth||0):e.set(0,0,0),e}set needsUpdate(e){e===!0&&this.version++}toJSON(e){const t=e===void 0||typeof e=="string";if(!t&&e.images[this.uuid]!==void 0)return e.images[this.uuid];const n={uuid:this.uuid,url:""},s=this.data;if(s!==null){let r;if(Array.isArray(s)){r=[];for(let a=0,o=s.length;a<o;a++)s[a].isDataTexture?r.push(yd(s[a].image)):r.push(yd(s[a]))}else r=yd(s);n.url=r}return t||(e.images[this.uuid]=n),n}}function yd(i){return typeof HTMLImageElement<"u"&&i instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&i instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&i instanceof ImageBitmap?Ky.getDataURL(i):i.data?{data:Array.from(i.data),width:i.width,height:i.height,type:i.data.constructor.name}:(Oe("Texture: Unable to serialize Texture."),{})}let Zy=0;const _d=new B;class tn extends Js{constructor(e=tn.DEFAULT_IMAGE,t=tn.DEFAULT_MAPPING,n=xi,s=xi,r=Jt,a=fs,o=Bn,c=En,l=tn.DEFAULT_ANISOTROPY,d=ji){super(),this.isTexture=!0,Object.defineProperty(this,"id",{value:Zy++}),this.uuid=jr(),this.name="",this.source=new bd(e),this.mipmaps=[],this.mapping=t,this.channel=0,this.wrapS=n,this.wrapT=s,this.magFilter=r,this.minFilter=a,this.anisotropy=l,this.format=o,this.internalFormat=null,this.type=c,this.offset=new lt(0,0),this.repeat=new lt(1,1),this.center=new lt(0,0),this.rotation=0,this.matrixAutoUpdate=!0,this.matrix=new Ve,this.generateMipmaps=!0,this.premultiplyAlpha=!1,this.flipY=!0,this.unpackAlignment=4,this.colorSpace=d,this.userData={},this.updateRanges=[],this.version=0,this.onUpdate=null,this.renderTarget=null,this.isRenderTargetTexture=!1,this.isArrayTexture=!!(e&&e.depth&&e.depth>1),this.pmremVersion=0}get width(){return this.source.getSize(_d).x}get height(){return this.source.getSize(_d).y}get depth(){return this.source.getSize(_d).z}get image(){return this.source.data}set image(e=null){this.source.data=e}updateMatrix(){this.matrix.setUvTransform(this.offset.x,this.offset.y,this.repeat.x,this.repeat.y,this.rotation,this.center.x,this.center.y)}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}clone(){return new this.constructor().copy(this)}copy(e){return this.name=e.name,this.source=e.source,this.mipmaps=e.mipmaps.slice(0),this.mapping=e.mapping,this.channel=e.channel,this.wrapS=e.wrapS,this.wrapT=e.wrapT,this.magFilter=e.magFilter,this.minFilter=e.minFilter,this.anisotropy=e.anisotropy,this.format=e.format,this.internalFormat=e.internalFormat,this.type=e.type,this.offset.copy(e.offset),this.repeat.copy(e.repeat),this.center.copy(e.center),this.rotation=e.rotation,this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrix.copy(e.matrix),this.generateMipmaps=e.generateMipmaps,this.premultiplyAlpha=e.premultiplyAlpha,this.flipY=e.flipY,this.unpackAlignment=e.unpackAlignment,this.colorSpace=e.colorSpace,this.renderTarget=e.renderTarget,this.isRenderTargetTexture=e.isRenderTargetTexture,this.isArrayTexture=e.isArrayTexture,this.userData=JSON.parse(JSON.stringify(e.userData)),this.needsUpdate=!0,this}setValues(e){for(const t in e){const n=e[t];if(n===void 0){Oe(`Texture.setValues(): parameter '${t}' has value of undefined.`);continue}const s=this[t];if(s===void 0){Oe(`Texture.setValues(): property '${t}' does not exist.`);continue}s&&n&&s.isVector2&&n.isVector2||s&&n&&s.isVector3&&n.isVector3||s&&n&&s.isMatrix3&&n.isMatrix3?s.copy(n):this[t]=n}}toJSON(e){const t=e===void 0||typeof e=="string";if(!t&&e.textures[this.uuid]!==void 0)return e.textures[this.uuid];const n={metadata:{version:4.7,type:"Texture",generator:"Texture.toJSON"},uuid:this.uuid,name:this.name,image:this.source.toJSON(e).uuid,mapping:this.mapping,channel:this.channel,repeat:[this.repeat.x,this.repeat.y],offset:[this.offset.x,this.offset.y],center:[this.center.x,this.center.y],rotation:this.rotation,wrap:[this.wrapS,this.wrapT],format:this.format,internalFormat:this.internalFormat,type:this.type,colorSpace:this.colorSpace,minFilter:this.minFilter,magFilter:this.magFilter,anisotropy:this.anisotropy,flipY:this.flipY,generateMipmaps:this.generateMipmaps,premultiplyAlpha:this.premultiplyAlpha,unpackAlignment:this.unpackAlignment};return Object.keys(this.userData).length>0&&(n.userData=this.userData),t||(e.textures[this.uuid]=n),n}dispose(){this.dispatchEvent({type:"dispose"})}transformUv(e){if(this.mapping!==_p)return e;if(e.applyMatrix3(this.matrix),e.x<0||e.x>1)switch(this.wrapS){case Cl:e.x=e.x-Math.floor(e.x);break;case xi:e.x=e.x<0?0:1;break;case El:Math.abs(Math.floor(e.x)%2)===1?e.x=Math.ceil(e.x)-e.x:e.x=e.x-Math.floor(e.x);break}if(e.y<0||e.y>1)switch(this.wrapT){case Cl:e.y=e.y-Math.floor(e.y);break;case xi:e.y=e.y<0?0:1;break;case El:Math.abs(Math.floor(e.y)%2)===1?e.y=Math.ceil(e.y)-e.y:e.y=e.y-Math.floor(e.y);break}return this.flipY&&(e.y=1-e.y),e}set needsUpdate(e){e===!0&&(this.version++,this.source.needsUpdate=!0)}set needsPMREMUpdate(e){e===!0&&this.pmremVersion++}}tn.DEFAULT_IMAGE=null,tn.DEFAULT_MAPPING=_p,tn.DEFAULT_ANISOTROPY=1;class Ut{constructor(e=0,t=0,n=0,s=1){Ut.prototype.isVector4=!0,this.x=e,this.y=t,this.z=n,this.w=s}get width(){return this.z}set width(e){this.z=e}get height(){return this.w}set height(e){this.w=e}set(e,t,n,s){return this.x=e,this.y=t,this.z=n,this.w=s,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this.w=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setW(e){return this.w=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;case 3:this.w=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;case 3:return this.w;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y,this.z,this.w)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this.w=e.w!==void 0?e.w:1,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this.w+=e.w,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this.w+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this.w=e.w+t.w,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this.w+=e.w*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this.w-=e.w,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this.w-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this.w=e.w-t.w,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this.w*=e.w,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this.w*=e,this}applyMatrix4(e){const t=this.x,n=this.y,s=this.z,r=this.w,a=e.elements;return this.x=a[0]*t+a[4]*n+a[8]*s+a[12]*r,this.y=a[1]*t+a[5]*n+a[9]*s+a[13]*r,this.z=a[2]*t+a[6]*n+a[10]*s+a[14]*r,this.w=a[3]*t+a[7]*n+a[11]*s+a[15]*r,this}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this.w/=e.w,this}divideScalar(e){return this.multiplyScalar(1/e)}setAxisAngleFromQuaternion(e){this.w=2*Math.acos(e.w);const t=Math.sqrt(1-e.w*e.w);return t<1e-4?(this.x=1,this.y=0,this.z=0):(this.x=e.x/t,this.y=e.y/t,this.z=e.z/t),this}setAxisAngleFromRotationMatrix(e){let t,n,s,r;const c=e.elements,l=c[0],d=c[4],u=c[8],h=c[1],f=c[5],g=c[9],v=c[2],m=c[6],p=c[10];if(Math.abs(d-h)<.01&&Math.abs(u-v)<.01&&Math.abs(g-m)<.01){if(Math.abs(d+h)<.1&&Math.abs(u+v)<.1&&Math.abs(g+m)<.1&&Math.abs(l+f+p-3)<.1)return this.set(1,0,0,0),this;t=Math.PI;const C=(l+1)/2,b=(f+1)/2,S=(p+1)/2,M=(d+h)/4,A=(u+v)/4,k=(g+m)/4;return C>b&&C>S?C<.01?(n=0,s=.707106781,r=.707106781):(n=Math.sqrt(C),s=M/n,r=A/n):b>S?b<.01?(n=.707106781,s=0,r=.707106781):(s=Math.sqrt(b),n=M/s,r=k/s):S<.01?(n=.707106781,s=.707106781,r=0):(r=Math.sqrt(S),n=A/r,s=k/r),this.set(n,s,r,t),this}let x=Math.sqrt((m-g)*(m-g)+(u-v)*(u-v)+(h-d)*(h-d));return Math.abs(x)<.001&&(x=1),this.x=(m-g)/x,this.y=(u-v)/x,this.z=(h-d)/x,this.w=Math.acos((l+f+p-1)/2),this}setFromMatrixPosition(e){const t=e.elements;return this.x=t[12],this.y=t[13],this.z=t[14],this.w=t[15],this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this.w=Math.min(this.w,e.w),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this.w=Math.max(this.w,e.w),this}clamp(e,t){return this.x=et(this.x,e.x,t.x),this.y=et(this.y,e.y,t.y),this.z=et(this.z,e.z,t.z),this.w=et(this.w,e.w,t.w),this}clampScalar(e,t){return this.x=et(this.x,e,t),this.y=et(this.y,e,t),this.z=et(this.z,e,t),this.w=et(this.w,e,t),this}clampLength(e,t){const n=this.length();return this.divideScalar(n||1).multiplyScalar(et(n,e,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this.w=Math.floor(this.w),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this.w=Math.ceil(this.w),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this.w=Math.round(this.w),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this.w=Math.trunc(this.w),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this.w=-this.w,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z+this.w*e.w}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)+Math.abs(this.w)}normalize(){return this.divideScalar(this.length()||1)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this.z+=(e.z-this.z)*t,this.w+=(e.w-this.w)*t,this}lerpVectors(e,t,n){return this.x=e.x+(t.x-e.x)*n,this.y=e.y+(t.y-e.y)*n,this.z=e.z+(t.z-e.z)*n,this.w=e.w+(t.w-e.w)*n,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z&&e.w===this.w}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this.z=e[t+2],this.w=e[t+3],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e[t+3]=this.w,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this.z=e.getZ(t),this.w=e.getW(t),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this.w=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z,yield this.w}}class Qy extends Js{constructor(e=1,t=1,n={}){super(),n=Object.assign({generateMipmaps:!1,internalFormat:null,minFilter:Jt,depthBuffer:!0,stencilBuffer:!1,resolveDepthBuffer:!0,resolveStencilBuffer:!0,depthTexture:null,samples:0,count:1,depth:1,multiview:!1},n),this.isRenderTarget=!0,this.width=e,this.height=t,this.depth=n.depth,this.scissor=new Ut(0,0,e,t),this.scissorTest=!1,this.viewport=new Ut(0,0,e,t);const s={width:e,height:t,depth:n.depth},r=new tn(s);this.textures=[];const a=n.count;for(let o=0;o<a;o++)this.textures[o]=r.clone(),this.textures[o].isRenderTargetTexture=!0,this.textures[o].renderTarget=this;this._setTextureOptions(n),this.depthBuffer=n.depthBuffer,this.stencilBuffer=n.stencilBuffer,this.resolveDepthBuffer=n.resolveDepthBuffer,this.resolveStencilBuffer=n.resolveStencilBuffer,this._depthTexture=null,this.depthTexture=n.depthTexture,this.samples=n.samples,this.multiview=n.multiview}_setTextureOptions(e={}){const t={minFilter:Jt,generateMipmaps:!1,flipY:!1,internalFormat:null};e.mapping!==void 0&&(t.mapping=e.mapping),e.wrapS!==void 0&&(t.wrapS=e.wrapS),e.wrapT!==void 0&&(t.wrapT=e.wrapT),e.wrapR!==void 0&&(t.wrapR=e.wrapR),e.magFilter!==void 0&&(t.magFilter=e.magFilter),e.minFilter!==void 0&&(t.minFilter=e.minFilter),e.format!==void 0&&(t.format=e.format),e.type!==void 0&&(t.type=e.type),e.anisotropy!==void 0&&(t.anisotropy=e.anisotropy),e.colorSpace!==void 0&&(t.colorSpace=e.colorSpace),e.flipY!==void 0&&(t.flipY=e.flipY),e.generateMipmaps!==void 0&&(t.generateMipmaps=e.generateMipmaps),e.internalFormat!==void 0&&(t.internalFormat=e.internalFormat);for(let n=0;n<this.textures.length;n++)this.textures[n].setValues(t)}get texture(){return this.textures[0]}set texture(e){this.textures[0]=e}set depthTexture(e){this._depthTexture!==null&&(this._depthTexture.renderTarget=null),e!==null&&(e.renderTarget=this),this._depthTexture=e}get depthTexture(){return this._depthTexture}setSize(e,t,n=1){if(this.width!==e||this.height!==t||this.depth!==n){this.width=e,this.height=t,this.depth=n;for(let s=0,r=this.textures.length;s<r;s++)this.textures[s].image.width=e,this.textures[s].image.height=t,this.textures[s].image.depth=n,this.textures[s].isData3DTexture!==!0&&(this.textures[s].isArrayTexture=this.textures[s].image.depth>1);this.dispose()}this.viewport.set(0,0,e,t),this.scissor.set(0,0,e,t)}clone(){return new this.constructor().copy(this)}copy(e){this.width=e.width,this.height=e.height,this.depth=e.depth,this.scissor.copy(e.scissor),this.scissorTest=e.scissorTest,this.viewport.copy(e.viewport),this.textures.length=0;for(let t=0,n=e.textures.length;t<n;t++){this.textures[t]=e.textures[t].clone(),this.textures[t].isRenderTargetTexture=!0,this.textures[t].renderTarget=this;const s=Object.assign({},e.textures[t].image);this.textures[t].source=new bd(s)}return this.depthBuffer=e.depthBuffer,this.stencilBuffer=e.stencilBuffer,this.resolveDepthBuffer=e.resolveDepthBuffer,this.resolveStencilBuffer=e.resolveStencilBuffer,e.depthTexture!==null&&(this.depthTexture=e.depthTexture.clone()),this.samples=e.samples,this}dispose(){this.dispatchEvent({type:"dispose"})}}class ri extends Qy{constructor(e=1,t=1,n={}){super(e,t,n),this.isWebGLRenderTarget=!0}}class Op extends tn{constructor(e=null,t=1,n=1,s=1){super(null),this.isDataArrayTexture=!0,this.image={data:e,width:t,height:n,depth:s},this.magFilter=Kt,this.minFilter=Kt,this.wrapR=xi,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1,this.layerUpdates=new Set}addLayerUpdate(e){this.layerUpdates.add(e)}clearLayerUpdates(){this.layerUpdates.clear()}}class e_ extends tn{constructor(e=null,t=1,n=1,s=1){super(null),this.isData3DTexture=!0,this.image={data:e,width:t,height:n,depth:s},this.magFilter=Kt,this.minFilter=Kt,this.wrapR=xi,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}}class Kr{constructor(e=new B(1/0,1/0,1/0),t=new B(-1/0,-1/0,-1/0)){this.isBox3=!0,this.min=e,this.max=t}set(e,t){return this.min.copy(e),this.max.copy(t),this}setFromArray(e){this.makeEmpty();for(let t=0,n=e.length;t<n;t+=3)this.expandByPoint(zn.fromArray(e,t));return this}setFromBufferAttribute(e){this.makeEmpty();for(let t=0,n=e.count;t<n;t++)this.expandByPoint(zn.fromBufferAttribute(e,t));return this}setFromPoints(e){this.makeEmpty();for(let t=0,n=e.length;t<n;t++)this.expandByPoint(e[t]);return this}setFromCenterAndSize(e,t){const n=zn.copy(t).multiplyScalar(.5);return this.min.copy(e).sub(n),this.max.copy(e).add(n),this}setFromObject(e,t=!1){return this.makeEmpty(),this.expandByObject(e,t)}clone(){return new this.constructor().copy(this)}copy(e){return this.min.copy(e.min),this.max.copy(e.max),this}makeEmpty(){return this.min.x=this.min.y=this.min.z=1/0,this.max.x=this.max.y=this.max.z=-1/0,this}isEmpty(){return this.max.x<this.min.x||this.max.y<this.min.y||this.max.z<this.min.z}getCenter(e){return this.isEmpty()?e.set(0,0,0):e.addVectors(this.min,this.max).multiplyScalar(.5)}getSize(e){return this.isEmpty()?e.set(0,0,0):e.subVectors(this.max,this.min)}expandByPoint(e){return this.min.min(e),this.max.max(e),this}expandByVector(e){return this.min.sub(e),this.max.add(e),this}expandByScalar(e){return this.min.addScalar(-e),this.max.addScalar(e),this}expandByObject(e,t=!1){e.updateWorldMatrix(!1,!1);const n=e.geometry;if(n!==void 0){const r=n.getAttribute("position");if(t===!0&&r!==void 0&&e.isInstancedMesh!==!0)for(let a=0,o=r.count;a<o;a++)e.isMesh===!0?e.getVertexPosition(a,zn):zn.fromBufferAttribute(r,a),zn.applyMatrix4(e.matrixWorld),this.expandByPoint(zn);else e.boundingBox!==void 0?(e.boundingBox===null&&e.computeBoundingBox(),so.copy(e.boundingBox)):(n.boundingBox===null&&n.computeBoundingBox(),so.copy(n.boundingBox)),so.applyMatrix4(e.matrixWorld),this.union(so)}const s=e.children;for(let r=0,a=s.length;r<a;r++)this.expandByObject(s[r],t);return this}containsPoint(e){return e.x>=this.min.x&&e.x<=this.max.x&&e.y>=this.min.y&&e.y<=this.max.y&&e.z>=this.min.z&&e.z<=this.max.z}containsBox(e){return this.min.x<=e.min.x&&e.max.x<=this.max.x&&this.min.y<=e.min.y&&e.max.y<=this.max.y&&this.min.z<=e.min.z&&e.max.z<=this.max.z}getParameter(e,t){return t.set((e.x-this.min.x)/(this.max.x-this.min.x),(e.y-this.min.y)/(this.max.y-this.min.y),(e.z-this.min.z)/(this.max.z-this.min.z))}intersectsBox(e){return e.max.x>=this.min.x&&e.min.x<=this.max.x&&e.max.y>=this.min.y&&e.min.y<=this.max.y&&e.max.z>=this.min.z&&e.min.z<=this.max.z}intersectsSphere(e){return this.clampPoint(e.center,zn),zn.distanceToSquared(e.center)<=e.radius*e.radius}intersectsPlane(e){let t,n;return e.normal.x>0?(t=e.normal.x*this.min.x,n=e.normal.x*this.max.x):(t=e.normal.x*this.max.x,n=e.normal.x*this.min.x),e.normal.y>0?(t+=e.normal.y*this.min.y,n+=e.normal.y*this.max.y):(t+=e.normal.y*this.max.y,n+=e.normal.y*this.min.y),e.normal.z>0?(t+=e.normal.z*this.min.z,n+=e.normal.z*this.max.z):(t+=e.normal.z*this.max.z,n+=e.normal.z*this.min.z),t<=-e.constant&&n>=-e.constant}intersectsTriangle(e){if(this.isEmpty())return!1;this.getCenter(Jr),ro.subVectors(this.max,Jr),er.subVectors(e.a,Jr),tr.subVectors(e.b,Jr),nr.subVectors(e.c,Jr),Xi.subVectors(tr,er),Yi.subVectors(nr,tr),ms.subVectors(er,nr);let t=[0,-Xi.z,Xi.y,0,-Yi.z,Yi.y,0,-ms.z,ms.y,Xi.z,0,-Xi.x,Yi.z,0,-Yi.x,ms.z,0,-ms.x,-Xi.y,Xi.x,0,-Yi.y,Yi.x,0,-ms.y,ms.x,0];return!Sd(t,er,tr,nr,ro)||(t=[1,0,0,0,1,0,0,0,1],!Sd(t,er,tr,nr,ro))?!1:(ao.crossVectors(Xi,Yi),t=[ao.x,ao.y,ao.z],Sd(t,er,tr,nr,ro))}clampPoint(e,t){return t.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,zn).distanceTo(e)}getBoundingSphere(e){return this.isEmpty()?e.makeEmpty():(this.getCenter(e.center),e.radius=this.getSize(zn).length()*.5),e}intersect(e){return this.min.max(e.min),this.max.min(e.max),this.isEmpty()&&this.makeEmpty(),this}union(e){return this.min.min(e.min),this.max.max(e.max),this}applyMatrix4(e){return this.isEmpty()?this:(Mi[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(e),Mi[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(e),Mi[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(e),Mi[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(e),Mi[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(e),Mi[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(e),Mi[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(e),Mi[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(e),this.setFromPoints(Mi),this)}translate(e){return this.min.add(e),this.max.add(e),this}equals(e){return e.min.equals(this.min)&&e.max.equals(this.max)}toJSON(){return{min:this.min.toArray(),max:this.max.toArray()}}fromJSON(e){return this.min.fromArray(e.min),this.max.fromArray(e.max),this}}const Mi=[new B,new B,new B,new B,new B,new B,new B,new B],zn=new B,so=new Kr,er=new B,tr=new B,nr=new B,Xi=new B,Yi=new B,ms=new B,Jr=new B,ro=new B,ao=new B,gs=new B;function Sd(i,e,t,n,s){for(let r=0,a=i.length-3;r<=a;r+=3){gs.fromArray(i,r);const o=s.x*Math.abs(gs.x)+s.y*Math.abs(gs.y)+s.z*Math.abs(gs.z),c=e.dot(gs),l=t.dot(gs),d=n.dot(gs);if(Math.max(-Math.max(c,l,d),Math.min(c,l,d))>o)return!1}return!0}const t_=new Kr,Zr=new B,xd=new B;class Td{constructor(e=new B,t=-1){this.isSphere=!0,this.center=e,this.radius=t}set(e,t){return this.center.copy(e),this.radius=t,this}setFromPoints(e,t){const n=this.center;t!==void 0?n.copy(t):t_.setFromPoints(e).getCenter(n);let s=0;for(let r=0,a=e.length;r<a;r++)s=Math.max(s,n.distanceToSquared(e[r]));return this.radius=Math.sqrt(s),this}copy(e){return this.center.copy(e.center),this.radius=e.radius,this}isEmpty(){return this.radius<0}makeEmpty(){return this.center.set(0,0,0),this.radius=-1,this}containsPoint(e){return e.distanceToSquared(this.center)<=this.radius*this.radius}distanceToPoint(e){return e.distanceTo(this.center)-this.radius}intersectsSphere(e){const t=this.radius+e.radius;return e.center.distanceToSquared(this.center)<=t*t}intersectsBox(e){return e.intersectsSphere(this)}intersectsPlane(e){return Math.abs(e.distanceToPoint(this.center))<=this.radius}clampPoint(e,t){const n=this.center.distanceToSquared(e);return t.copy(e),n>this.radius*this.radius&&(t.sub(this.center).normalize(),t.multiplyScalar(this.radius).add(this.center)),t}getBoundingBox(e){return this.isEmpty()?(e.makeEmpty(),e):(e.set(this.center,this.center),e.expandByScalar(this.radius),e)}applyMatrix4(e){return this.center.applyMatrix4(e),this.radius=this.radius*e.getMaxScaleOnAxis(),this}translate(e){return this.center.add(e),this}expandByPoint(e){if(this.isEmpty())return this.center.copy(e),this.radius=0,this;Zr.subVectors(e,this.center);const t=Zr.lengthSq();if(t>this.radius*this.radius){const n=Math.sqrt(t),s=(n-this.radius)*.5;this.center.addScaledVector(Zr,s/n),this.radius+=s}return this}union(e){return e.isEmpty()?this:this.isEmpty()?(this.copy(e),this):(this.center.equals(e.center)===!0?this.radius=Math.max(this.radius,e.radius):(xd.subVectors(e.center,this.center).setLength(e.radius),this.expandByPoint(Zr.copy(e.center).add(xd)),this.expandByPoint(Zr.copy(e.center).sub(xd))),this)}equals(e){return e.center.equals(this.center)&&e.radius===this.radius}clone(){return new this.constructor().copy(this)}toJSON(){return{radius:this.radius,center:this.center.toArray()}}fromJSON(e){return this.radius=e.radius,this.center.fromArray(e.center),this}}const wi=new B,Cd=new B,oo=new B,Ki=new B,Ed=new B,co=new B,Md=new B;class n_{constructor(e=new B,t=new B(0,0,-1)){this.origin=e,this.direction=t}set(e,t){return this.origin.copy(e),this.direction.copy(t),this}copy(e){return this.origin.copy(e.origin),this.direction.copy(e.direction),this}at(e,t){return t.copy(this.origin).addScaledVector(this.direction,e)}lookAt(e){return this.direction.copy(e).sub(this.origin).normalize(),this}recast(e){return this.origin.copy(this.at(e,wi)),this}closestPointToPoint(e,t){t.subVectors(e,this.origin);const n=t.dot(this.direction);return n<0?t.copy(this.origin):t.copy(this.origin).addScaledVector(this.direction,n)}distanceToPoint(e){return Math.sqrt(this.distanceSqToPoint(e))}distanceSqToPoint(e){const t=wi.subVectors(e,this.origin).dot(this.direction);return t<0?this.origin.distanceToSquared(e):(wi.copy(this.origin).addScaledVector(this.direction,t),wi.distanceToSquared(e))}distanceSqToSegment(e,t,n,s){Cd.copy(e).add(t).multiplyScalar(.5),oo.copy(t).sub(e).normalize(),Ki.copy(this.origin).sub(Cd);const r=e.distanceTo(t)*.5,a=-this.direction.dot(oo),o=Ki.dot(this.direction),c=-Ki.dot(oo),l=Ki.lengthSq(),d=Math.abs(1-a*a);let u,h,f,g;if(d>0)if(u=a*c-o,h=a*o-c,g=r*d,u>=0)if(h>=-g)if(h<=g){const v=1/d;u*=v,h*=v,f=u*(u+a*h+2*o)+h*(a*u+h+2*c)+l}else h=r,u=Math.max(0,-(a*h+o)),f=-u*u+h*(h+2*c)+l;else h=-r,u=Math.max(0,-(a*h+o)),f=-u*u+h*(h+2*c)+l;else h<=-g?(u=Math.max(0,-(-a*r+o)),h=u>0?-r:Math.min(Math.max(-r,-c),r),f=-u*u+h*(h+2*c)+l):h<=g?(u=0,h=Math.min(Math.max(-r,-c),r),f=h*(h+2*c)+l):(u=Math.max(0,-(a*r+o)),h=u>0?r:Math.min(Math.max(-r,-c),r),f=-u*u+h*(h+2*c)+l);else h=a>0?-r:r,u=Math.max(0,-(a*h+o)),f=-u*u+h*(h+2*c)+l;return n&&n.copy(this.origin).addScaledVector(this.direction,u),s&&s.copy(Cd).addScaledVector(oo,h),f}intersectSphere(e,t){wi.subVectors(e.center,this.origin);const n=wi.dot(this.direction),s=wi.dot(wi)-n*n,r=e.radius*e.radius;if(s>r)return null;const a=Math.sqrt(r-s),o=n-a,c=n+a;return c<0?null:o<0?this.at(c,t):this.at(o,t)}intersectsSphere(e){return e.radius<0?!1:this.distanceSqToPoint(e.center)<=e.radius*e.radius}distanceToPlane(e){const t=e.normal.dot(this.direction);if(t===0)return e.distanceToPoint(this.origin)===0?0:null;const n=-(this.origin.dot(e.normal)+e.constant)/t;return n>=0?n:null}intersectPlane(e,t){const n=this.distanceToPlane(e);return n===null?null:this.at(n,t)}intersectsPlane(e){const t=e.distanceToPoint(this.origin);return t===0||e.normal.dot(this.direction)*t<0}intersectBox(e,t){let n,s,r,a,o,c;const l=1/this.direction.x,d=1/this.direction.y,u=1/this.direction.z,h=this.origin;return l>=0?(n=(e.min.x-h.x)*l,s=(e.max.x-h.x)*l):(n=(e.max.x-h.x)*l,s=(e.min.x-h.x)*l),d>=0?(r=(e.min.y-h.y)*d,a=(e.max.y-h.y)*d):(r=(e.max.y-h.y)*d,a=(e.min.y-h.y)*d),n>a||r>s||((r>n||isNaN(n))&&(n=r),(a<s||isNaN(s))&&(s=a),u>=0?(o=(e.min.z-h.z)*u,c=(e.max.z-h.z)*u):(o=(e.max.z-h.z)*u,c=(e.min.z-h.z)*u),n>c||o>s)||((o>n||n!==n)&&(n=o),(c<s||s!==s)&&(s=c),s<0)?null:this.at(n>=0?n:s,t)}intersectsBox(e){return this.intersectBox(e,wi)!==null}intersectTriangle(e,t,n,s,r){Ed.subVectors(t,e),co.subVectors(n,e),Md.crossVectors(Ed,co);let a=this.direction.dot(Md),o;if(a>0){if(s)return null;o=1}else if(a<0)o=-1,a=-a;else return null;Ki.subVectors(this.origin,e);const c=o*this.direction.dot(co.crossVectors(Ki,co));if(c<0)return null;const l=o*this.direction.dot(Ed.cross(Ki));if(l<0||c+l>a)return null;const d=-o*Ki.dot(Md);return d<0?null:this.at(d/a,r)}applyMatrix4(e){return this.origin.applyMatrix4(e),this.direction.transformDirection(e),this}equals(e){return e.origin.equals(this.origin)&&e.direction.equals(this.direction)}clone(){return new this.constructor().copy(this)}}class Ft{constructor(e,t,n,s,r,a,o,c,l,d,u,h,f,g,v,m){Ft.prototype.isMatrix4=!0,this.elements=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],e!==void 0&&this.set(e,t,n,s,r,a,o,c,l,d,u,h,f,g,v,m)}set(e,t,n,s,r,a,o,c,l,d,u,h,f,g,v,m){const p=this.elements;return p[0]=e,p[4]=t,p[8]=n,p[12]=s,p[1]=r,p[5]=a,p[9]=o,p[13]=c,p[2]=l,p[6]=d,p[10]=u,p[14]=h,p[3]=f,p[7]=g,p[11]=v,p[15]=m,this}identity(){return this.set(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1),this}clone(){return new Ft().fromArray(this.elements)}copy(e){const t=this.elements,n=e.elements;return t[0]=n[0],t[1]=n[1],t[2]=n[2],t[3]=n[3],t[4]=n[4],t[5]=n[5],t[6]=n[6],t[7]=n[7],t[8]=n[8],t[9]=n[9],t[10]=n[10],t[11]=n[11],t[12]=n[12],t[13]=n[13],t[14]=n[14],t[15]=n[15],this}copyPosition(e){const t=this.elements,n=e.elements;return t[12]=n[12],t[13]=n[13],t[14]=n[14],this}setFromMatrix3(e){const t=e.elements;return this.set(t[0],t[3],t[6],0,t[1],t[4],t[7],0,t[2],t[5],t[8],0,0,0,0,1),this}extractBasis(e,t,n){return this.determinant()===0?(e.set(1,0,0),t.set(0,1,0),n.set(0,0,1),this):(e.setFromMatrixColumn(this,0),t.setFromMatrixColumn(this,1),n.setFromMatrixColumn(this,2),this)}makeBasis(e,t,n){return this.set(e.x,t.x,n.x,0,e.y,t.y,n.y,0,e.z,t.z,n.z,0,0,0,0,1),this}extractRotation(e){if(e.determinant()===0)return this.identity();const t=this.elements,n=e.elements,s=1/ir.setFromMatrixColumn(e,0).length(),r=1/ir.setFromMatrixColumn(e,1).length(),a=1/ir.setFromMatrixColumn(e,2).length();return t[0]=n[0]*s,t[1]=n[1]*s,t[2]=n[2]*s,t[3]=0,t[4]=n[4]*r,t[5]=n[5]*r,t[6]=n[6]*r,t[7]=0,t[8]=n[8]*a,t[9]=n[9]*a,t[10]=n[10]*a,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromEuler(e){const t=this.elements,n=e.x,s=e.y,r=e.z,a=Math.cos(n),o=Math.sin(n),c=Math.cos(s),l=Math.sin(s),d=Math.cos(r),u=Math.sin(r);if(e.order==="XYZ"){const h=a*d,f=a*u,g=o*d,v=o*u;t[0]=c*d,t[4]=-c*u,t[8]=l,t[1]=f+g*l,t[5]=h-v*l,t[9]=-o*c,t[2]=v-h*l,t[6]=g+f*l,t[10]=a*c}else if(e.order==="YXZ"){const h=c*d,f=c*u,g=l*d,v=l*u;t[0]=h+v*o,t[4]=g*o-f,t[8]=a*l,t[1]=a*u,t[5]=a*d,t[9]=-o,t[2]=f*o-g,t[6]=v+h*o,t[10]=a*c}else if(e.order==="ZXY"){const h=c*d,f=c*u,g=l*d,v=l*u;t[0]=h-v*o,t[4]=-a*u,t[8]=g+f*o,t[1]=f+g*o,t[5]=a*d,t[9]=v-h*o,t[2]=-a*l,t[6]=o,t[10]=a*c}else if(e.order==="ZYX"){const h=a*d,f=a*u,g=o*d,v=o*u;t[0]=c*d,t[4]=g*l-f,t[8]=h*l+v,t[1]=c*u,t[5]=v*l+h,t[9]=f*l-g,t[2]=-l,t[6]=o*c,t[10]=a*c}else if(e.order==="YZX"){const h=a*c,f=a*l,g=o*c,v=o*l;t[0]=c*d,t[4]=v-h*u,t[8]=g*u+f,t[1]=u,t[5]=a*d,t[9]=-o*d,t[2]=-l*d,t[6]=f*u+g,t[10]=h-v*u}else if(e.order==="XZY"){const h=a*c,f=a*l,g=o*c,v=o*l;t[0]=c*d,t[4]=-u,t[8]=l*d,t[1]=h*u+v,t[5]=a*d,t[9]=f*u-g,t[2]=g*u-f,t[6]=o*d,t[10]=v*u+h}return t[3]=0,t[7]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromQuaternion(e){return this.compose(i_,e,s_)}lookAt(e,t,n){const s=this.elements;return _n.subVectors(e,t),_n.lengthSq()===0&&(_n.z=1),_n.normalize(),Ji.crossVectors(n,_n),Ji.lengthSq()===0&&(Math.abs(n.z)===1?_n.x+=1e-4:_n.z+=1e-4,_n.normalize(),Ji.crossVectors(n,_n)),Ji.normalize(),lo.crossVectors(_n,Ji),s[0]=Ji.x,s[4]=lo.x,s[8]=_n.x,s[1]=Ji.y,s[5]=lo.y,s[9]=_n.y,s[2]=Ji.z,s[6]=lo.z,s[10]=_n.z,this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){const n=e.elements,s=t.elements,r=this.elements,a=n[0],o=n[4],c=n[8],l=n[12],d=n[1],u=n[5],h=n[9],f=n[13],g=n[2],v=n[6],m=n[10],p=n[14],x=n[3],C=n[7],b=n[11],S=n[15],M=s[0],A=s[4],k=s[8],_=s[12],T=s[1],R=s[5],O=s[9],z=s[13],$=s[2],J=s[6],W=s[10],q=s[14],ne=s[3],be=s[7],ue=s[11],_e=s[15];return r[0]=a*M+o*T+c*$+l*ne,r[4]=a*A+o*R+c*J+l*be,r[8]=a*k+o*O+c*W+l*ue,r[12]=a*_+o*z+c*q+l*_e,r[1]=d*M+u*T+h*$+f*ne,r[5]=d*A+u*R+h*J+f*be,r[9]=d*k+u*O+h*W+f*ue,r[13]=d*_+u*z+h*q+f*_e,r[2]=g*M+v*T+m*$+p*ne,r[6]=g*A+v*R+m*J+p*be,r[10]=g*k+v*O+m*W+p*ue,r[14]=g*_+v*z+m*q+p*_e,r[3]=x*M+C*T+b*$+S*ne,r[7]=x*A+C*R+b*J+S*be,r[11]=x*k+C*O+b*W+S*ue,r[15]=x*_+C*z+b*q+S*_e,this}multiplyScalar(e){const t=this.elements;return t[0]*=e,t[4]*=e,t[8]*=e,t[12]*=e,t[1]*=e,t[5]*=e,t[9]*=e,t[13]*=e,t[2]*=e,t[6]*=e,t[10]*=e,t[14]*=e,t[3]*=e,t[7]*=e,t[11]*=e,t[15]*=e,this}determinant(){const e=this.elements,t=e[0],n=e[4],s=e[8],r=e[12],a=e[1],o=e[5],c=e[9],l=e[13],d=e[2],u=e[6],h=e[10],f=e[14],g=e[3],v=e[7],m=e[11],p=e[15],x=c*f-l*h,C=o*f-l*u,b=o*h-c*u,S=a*f-l*d,M=a*h-c*d,A=a*u-o*d;return t*(v*x-m*C+p*b)-n*(g*x-m*S+p*M)+s*(g*C-v*S+p*A)-r*(g*b-v*M+m*A)}transpose(){const e=this.elements;let t;return t=e[1],e[1]=e[4],e[4]=t,t=e[2],e[2]=e[8],e[8]=t,t=e[6],e[6]=e[9],e[9]=t,t=e[3],e[3]=e[12],e[12]=t,t=e[7],e[7]=e[13],e[13]=t,t=e[11],e[11]=e[14],e[14]=t,this}setPosition(e,t,n){const s=this.elements;return e.isVector3?(s[12]=e.x,s[13]=e.y,s[14]=e.z):(s[12]=e,s[13]=t,s[14]=n),this}invert(){const e=this.elements,t=e[0],n=e[1],s=e[2],r=e[3],a=e[4],o=e[5],c=e[6],l=e[7],d=e[8],u=e[9],h=e[10],f=e[11],g=e[12],v=e[13],m=e[14],p=e[15],x=u*m*l-v*h*l+v*c*f-o*m*f-u*c*p+o*h*p,C=g*h*l-d*m*l-g*c*f+a*m*f+d*c*p-a*h*p,b=d*v*l-g*u*l+g*o*f-a*v*f-d*o*p+a*u*p,S=g*u*c-d*v*c-g*o*h+a*v*h+d*o*m-a*u*m,M=t*x+n*C+s*b+r*S;if(M===0)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);const A=1/M;return e[0]=x*A,e[1]=(v*h*r-u*m*r-v*s*f+n*m*f+u*s*p-n*h*p)*A,e[2]=(o*m*r-v*c*r+v*s*l-n*m*l-o*s*p+n*c*p)*A,e[3]=(u*c*r-o*h*r-u*s*l+n*h*l+o*s*f-n*c*f)*A,e[4]=C*A,e[5]=(d*m*r-g*h*r+g*s*f-t*m*f-d*s*p+t*h*p)*A,e[6]=(g*c*r-a*m*r-g*s*l+t*m*l+a*s*p-t*c*p)*A,e[7]=(a*h*r-d*c*r+d*s*l-t*h*l-a*s*f+t*c*f)*A,e[8]=b*A,e[9]=(g*u*r-d*v*r-g*n*f+t*v*f+d*n*p-t*u*p)*A,e[10]=(a*v*r-g*o*r+g*n*l-t*v*l-a*n*p+t*o*p)*A,e[11]=(d*o*r-a*u*r-d*n*l+t*u*l+a*n*f-t*o*f)*A,e[12]=S*A,e[13]=(d*v*s-g*u*s+g*n*h-t*v*h-d*n*m+t*u*m)*A,e[14]=(g*o*s-a*v*s-g*n*c+t*v*c+a*n*m-t*o*m)*A,e[15]=(a*u*s-d*o*s+d*n*c-t*u*c-a*n*h+t*o*h)*A,this}scale(e){const t=this.elements,n=e.x,s=e.y,r=e.z;return t[0]*=n,t[4]*=s,t[8]*=r,t[1]*=n,t[5]*=s,t[9]*=r,t[2]*=n,t[6]*=s,t[10]*=r,t[3]*=n,t[7]*=s,t[11]*=r,this}getMaxScaleOnAxis(){const e=this.elements,t=e[0]*e[0]+e[1]*e[1]+e[2]*e[2],n=e[4]*e[4]+e[5]*e[5]+e[6]*e[6],s=e[8]*e[8]+e[9]*e[9]+e[10]*e[10];return Math.sqrt(Math.max(t,n,s))}makeTranslation(e,t,n){return e.isVector3?this.set(1,0,0,e.x,0,1,0,e.y,0,0,1,e.z,0,0,0,1):this.set(1,0,0,e,0,1,0,t,0,0,1,n,0,0,0,1),this}makeRotationX(e){const t=Math.cos(e),n=Math.sin(e);return this.set(1,0,0,0,0,t,-n,0,0,n,t,0,0,0,0,1),this}makeRotationY(e){const t=Math.cos(e),n=Math.sin(e);return this.set(t,0,n,0,0,1,0,0,-n,0,t,0,0,0,0,1),this}makeRotationZ(e){const t=Math.cos(e),n=Math.sin(e);return this.set(t,-n,0,0,n,t,0,0,0,0,1,0,0,0,0,1),this}makeRotationAxis(e,t){const n=Math.cos(t),s=Math.sin(t),r=1-n,a=e.x,o=e.y,c=e.z,l=r*a,d=r*o;return this.set(l*a+n,l*o-s*c,l*c+s*o,0,l*o+s*c,d*o+n,d*c-s*a,0,l*c-s*o,d*c+s*a,r*c*c+n,0,0,0,0,1),this}makeScale(e,t,n){return this.set(e,0,0,0,0,t,0,0,0,0,n,0,0,0,0,1),this}makeShear(e,t,n,s,r,a){return this.set(1,n,r,0,e,1,a,0,t,s,1,0,0,0,0,1),this}compose(e,t,n){const s=this.elements,r=t._x,a=t._y,o=t._z,c=t._w,l=r+r,d=a+a,u=o+o,h=r*l,f=r*d,g=r*u,v=a*d,m=a*u,p=o*u,x=c*l,C=c*d,b=c*u,S=n.x,M=n.y,A=n.z;return s[0]=(1-(v+p))*S,s[1]=(f+b)*S,s[2]=(g-C)*S,s[3]=0,s[4]=(f-b)*M,s[5]=(1-(h+p))*M,s[6]=(m+x)*M,s[7]=0,s[8]=(g+C)*A,s[9]=(m-x)*A,s[10]=(1-(h+v))*A,s[11]=0,s[12]=e.x,s[13]=e.y,s[14]=e.z,s[15]=1,this}decompose(e,t,n){const s=this.elements;if(e.x=s[12],e.y=s[13],e.z=s[14],this.determinant()===0)return n.set(1,1,1),t.identity(),this;let r=ir.set(s[0],s[1],s[2]).length();const a=ir.set(s[4],s[5],s[6]).length(),o=ir.set(s[8],s[9],s[10]).length();this.determinant()<0&&(r=-r),Vn.copy(this);const l=1/r,d=1/a,u=1/o;return Vn.elements[0]*=l,Vn.elements[1]*=l,Vn.elements[2]*=l,Vn.elements[4]*=d,Vn.elements[5]*=d,Vn.elements[6]*=d,Vn.elements[8]*=u,Vn.elements[9]*=u,Vn.elements[10]*=u,t.setFromRotationMatrix(Vn),n.x=r,n.y=a,n.z=o,this}makePerspective(e,t,n,s,r,a,o=si,c=!1){const l=this.elements,d=2*r/(t-e),u=2*r/(n-s),h=(t+e)/(t-e),f=(n+s)/(n-s);let g,v;if(c)g=r/(a-r),v=a*r/(a-r);else if(o===si)g=-(a+r)/(a-r),v=-2*a*r/(a-r);else if(o===no)g=-a/(a-r),v=-a*r/(a-r);else throw new Error("THREE.Matrix4.makePerspective(): Invalid coordinate system: "+o);return l[0]=d,l[4]=0,l[8]=h,l[12]=0,l[1]=0,l[5]=u,l[9]=f,l[13]=0,l[2]=0,l[6]=0,l[10]=g,l[14]=v,l[3]=0,l[7]=0,l[11]=-1,l[15]=0,this}makeOrthographic(e,t,n,s,r,a,o=si,c=!1){const l=this.elements,d=2/(t-e),u=2/(n-s),h=-(t+e)/(t-e),f=-(n+s)/(n-s);let g,v;if(c)g=1/(a-r),v=a/(a-r);else if(o===si)g=-2/(a-r),v=-(a+r)/(a-r);else if(o===no)g=-1/(a-r),v=-r/(a-r);else throw new Error("THREE.Matrix4.makeOrthographic(): Invalid coordinate system: "+o);return l[0]=d,l[4]=0,l[8]=0,l[12]=h,l[1]=0,l[5]=u,l[9]=0,l[13]=f,l[2]=0,l[6]=0,l[10]=g,l[14]=v,l[3]=0,l[7]=0,l[11]=0,l[15]=1,this}equals(e){const t=this.elements,n=e.elements;for(let s=0;s<16;s++)if(t[s]!==n[s])return!1;return!0}fromArray(e,t=0){for(let n=0;n<16;n++)this.elements[n]=e[n+t];return this}toArray(e=[],t=0){const n=this.elements;return e[t]=n[0],e[t+1]=n[1],e[t+2]=n[2],e[t+3]=n[3],e[t+4]=n[4],e[t+5]=n[5],e[t+6]=n[6],e[t+7]=n[7],e[t+8]=n[8],e[t+9]=n[9],e[t+10]=n[10],e[t+11]=n[11],e[t+12]=n[12],e[t+13]=n[13],e[t+14]=n[14],e[t+15]=n[15],e}}const ir=new B,Vn=new Ft,i_=new B(0,0,0),s_=new B(1,1,1),Ji=new B,lo=new B,_n=new B,Fp=new Ft,Bp=new Yr;class Ai{constructor(e=0,t=0,n=0,s=Ai.DEFAULT_ORDER){this.isEuler=!0,this._x=e,this._y=t,this._z=n,this._order=s}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get order(){return this._order}set order(e){this._order=e,this._onChangeCallback()}set(e,t,n,s=this._order){return this._x=e,this._y=t,this._z=n,this._order=s,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._order)}copy(e){return this._x=e._x,this._y=e._y,this._z=e._z,this._order=e._order,this._onChangeCallback(),this}setFromRotationMatrix(e,t=this._order,n=!0){const s=e.elements,r=s[0],a=s[4],o=s[8],c=s[1],l=s[5],d=s[9],u=s[2],h=s[6],f=s[10];switch(t){case"XYZ":this._y=Math.asin(et(o,-1,1)),Math.abs(o)<.9999999?(this._x=Math.atan2(-d,f),this._z=Math.atan2(-a,r)):(this._x=Math.atan2(h,l),this._z=0);break;case"YXZ":this._x=Math.asin(-et(d,-1,1)),Math.abs(d)<.9999999?(this._y=Math.atan2(o,f),this._z=Math.atan2(c,l)):(this._y=Math.atan2(-u,r),this._z=0);break;case"ZXY":this._x=Math.asin(et(h,-1,1)),Math.abs(h)<.9999999?(this._y=Math.atan2(-u,f),this._z=Math.atan2(-a,l)):(this._y=0,this._z=Math.atan2(c,r));break;case"ZYX":this._y=Math.asin(-et(u,-1,1)),Math.abs(u)<.9999999?(this._x=Math.atan2(h,f),this._z=Math.atan2(c,r)):(this._x=0,this._z=Math.atan2(-a,l));break;case"YZX":this._z=Math.asin(et(c,-1,1)),Math.abs(c)<.9999999?(this._x=Math.atan2(-d,l),this._y=Math.atan2(-u,r)):(this._x=0,this._y=Math.atan2(o,f));break;case"XZY":this._z=Math.asin(-et(a,-1,1)),Math.abs(a)<.9999999?(this._x=Math.atan2(h,l),this._y=Math.atan2(o,r)):(this._x=Math.atan2(-d,f),this._y=0);break;default:Oe("Euler: .setFromRotationMatrix() encountered an unknown order: "+t)}return this._order=t,n===!0&&this._onChangeCallback(),this}setFromQuaternion(e,t,n){return Fp.makeRotationFromQuaternion(e),this.setFromRotationMatrix(Fp,t,n)}setFromVector3(e,t=this._order){return this.set(e.x,e.y,e.z,t)}reorder(e){return Bp.setFromEuler(this),this.setFromQuaternion(Bp,e)}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._order===this._order}fromArray(e){return this._x=e[0],this._y=e[1],this._z=e[2],e[3]!==void 0&&(this._order=e[3]),this._onChangeCallback(),this}toArray(e=[],t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._order,e}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._order}}Ai.DEFAULT_ORDER="XYZ";class zp{constructor(){this.mask=1}set(e){this.mask=(1<<e|0)>>>0}enable(e){this.mask|=1<<e|0}enableAll(){this.mask=-1}toggle(e){this.mask^=1<<e|0}disable(e){this.mask&=~(1<<e|0)}disableAll(){this.mask=0}test(e){return(this.mask&e.mask)!==0}isEnabled(e){return(this.mask&(1<<e|0))!==0}}let r_=0;const Vp=new B,sr=new Yr,Ri=new Ft,uo=new B,Qr=new B,a_=new B,o_=new Yr,Gp=new B(1,0,0),Hp=new B(0,1,0),Wp=new B(0,0,1),qp={type:"added"},c_={type:"removed"},rr={type:"childadded",child:null},wd={type:"childremoved",child:null};class Sn extends Js{constructor(){super(),this.isObject3D=!0,Object.defineProperty(this,"id",{value:r_++}),this.uuid=jr(),this.name="",this.type="Object3D",this.parent=null,this.children=[],this.up=Sn.DEFAULT_UP.clone();const e=new B,t=new Ai,n=new Yr,s=new B(1,1,1);function r(){n.setFromEuler(t,!1)}function a(){t.setFromQuaternion(n,void 0,!1)}t._onChange(r),n._onChange(a),Object.defineProperties(this,{position:{configurable:!0,enumerable:!0,value:e},rotation:{configurable:!0,enumerable:!0,value:t},quaternion:{configurable:!0,enumerable:!0,value:n},scale:{configurable:!0,enumerable:!0,value:s},modelViewMatrix:{value:new Ft},normalMatrix:{value:new Ve}}),this.matrix=new Ft,this.matrixWorld=new Ft,this.matrixAutoUpdate=Sn.DEFAULT_MATRIX_AUTO_UPDATE,this.matrixWorldAutoUpdate=Sn.DEFAULT_MATRIX_WORLD_AUTO_UPDATE,this.matrixWorldNeedsUpdate=!1,this.layers=new zp,this.visible=!0,this.castShadow=!1,this.receiveShadow=!1,this.frustumCulled=!0,this.renderOrder=0,this.animations=[],this.customDepthMaterial=void 0,this.customDistanceMaterial=void 0,this.userData={}}onBeforeShadow(){}onAfterShadow(){}onBeforeRender(){}onAfterRender(){}applyMatrix4(e){this.matrixAutoUpdate&&this.updateMatrix(),this.matrix.premultiply(e),this.matrix.decompose(this.position,this.quaternion,this.scale)}applyQuaternion(e){return this.quaternion.premultiply(e),this}setRotationFromAxisAngle(e,t){this.quaternion.setFromAxisAngle(e,t)}setRotationFromEuler(e){this.quaternion.setFromEuler(e,!0)}setRotationFromMatrix(e){this.quaternion.setFromRotationMatrix(e)}setRotationFromQuaternion(e){this.quaternion.copy(e)}rotateOnAxis(e,t){return sr.setFromAxisAngle(e,t),this.quaternion.multiply(sr),this}rotateOnWorldAxis(e,t){return sr.setFromAxisAngle(e,t),this.quaternion.premultiply(sr),this}rotateX(e){return this.rotateOnAxis(Gp,e)}rotateY(e){return this.rotateOnAxis(Hp,e)}rotateZ(e){return this.rotateOnAxis(Wp,e)}translateOnAxis(e,t){return Vp.copy(e).applyQuaternion(this.quaternion),this.position.add(Vp.multiplyScalar(t)),this}translateX(e){return this.translateOnAxis(Gp,e)}translateY(e){return this.translateOnAxis(Hp,e)}translateZ(e){return this.translateOnAxis(Wp,e)}localToWorld(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(this.matrixWorld)}worldToLocal(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(Ri.copy(this.matrixWorld).invert())}lookAt(e,t,n){e.isVector3?uo.copy(e):uo.set(e,t,n);const s=this.parent;this.updateWorldMatrix(!0,!1),Qr.setFromMatrixPosition(this.matrixWorld),this.isCamera||this.isLight?Ri.lookAt(Qr,uo,this.up):Ri.lookAt(uo,Qr,this.up),this.quaternion.setFromRotationMatrix(Ri),s&&(Ri.extractRotation(s.matrixWorld),sr.setFromRotationMatrix(Ri),this.quaternion.premultiply(sr.invert()))}add(e){if(arguments.length>1){for(let t=0;t<arguments.length;t++)this.add(arguments[t]);return this}return e===this?(rt("Object3D.add: object can't be added as a child of itself.",e),this):(e&&e.isObject3D?(e.removeFromParent(),e.parent=this,this.children.push(e),e.dispatchEvent(qp),rr.child=e,this.dispatchEvent(rr),rr.child=null):rt("Object3D.add: object not an instance of THREE.Object3D.",e),this)}remove(e){if(arguments.length>1){for(let n=0;n<arguments.length;n++)this.remove(arguments[n]);return this}const t=this.children.indexOf(e);return t!==-1&&(e.parent=null,this.children.splice(t,1),e.dispatchEvent(c_),wd.child=e,this.dispatchEvent(wd),wd.child=null),this}removeFromParent(){const e=this.parent;return e!==null&&e.remove(this),this}clear(){return this.remove(...this.children)}attach(e){return this.updateWorldMatrix(!0,!1),Ri.copy(this.matrixWorld).invert(),e.parent!==null&&(e.parent.updateWorldMatrix(!0,!1),Ri.multiply(e.parent.matrixWorld)),e.applyMatrix4(Ri),e.removeFromParent(),e.parent=this,this.children.push(e),e.updateWorldMatrix(!1,!0),e.dispatchEvent(qp),rr.child=e,this.dispatchEvent(rr),rr.child=null,this}getObjectById(e){return this.getObjectByProperty("id",e)}getObjectByName(e){return this.getObjectByProperty("name",e)}getObjectByProperty(e,t){if(this[e]===t)return this;for(let n=0,s=this.children.length;n<s;n++){const a=this.children[n].getObjectByProperty(e,t);if(a!==void 0)return a}}getObjectsByProperty(e,t,n=[]){this[e]===t&&n.push(this);const s=this.children;for(let r=0,a=s.length;r<a;r++)s[r].getObjectsByProperty(e,t,n);return n}getWorldPosition(e){return this.updateWorldMatrix(!0,!1),e.setFromMatrixPosition(this.matrixWorld)}getWorldQuaternion(e){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(Qr,e,a_),e}getWorldScale(e){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(Qr,o_,e),e}getWorldDirection(e){this.updateWorldMatrix(!0,!1);const t=this.matrixWorld.elements;return e.set(t[8],t[9],t[10]).normalize()}raycast(){}traverse(e){e(this);const t=this.children;for(let n=0,s=t.length;n<s;n++)t[n].traverse(e)}traverseVisible(e){if(this.visible===!1)return;e(this);const t=this.children;for(let n=0,s=t.length;n<s;n++)t[n].traverseVisible(e)}traverseAncestors(e){const t=this.parent;t!==null&&(e(t),t.traverseAncestors(e))}updateMatrix(){this.matrix.compose(this.position,this.quaternion,this.scale),this.matrixWorldNeedsUpdate=!0}updateMatrixWorld(e){this.matrixAutoUpdate&&this.updateMatrix(),(this.matrixWorldNeedsUpdate||e)&&(this.matrixWorldAutoUpdate===!0&&(this.parent===null?this.matrixWorld.copy(this.matrix):this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix)),this.matrixWorldNeedsUpdate=!1,e=!0);const t=this.children;for(let n=0,s=t.length;n<s;n++)t[n].updateMatrixWorld(e)}updateWorldMatrix(e,t){const n=this.parent;if(e===!0&&n!==null&&n.updateWorldMatrix(!0,!1),this.matrixAutoUpdate&&this.updateMatrix(),this.matrixWorldAutoUpdate===!0&&(this.parent===null?this.matrixWorld.copy(this.matrix):this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix)),t===!0){const s=this.children;for(let r=0,a=s.length;r<a;r++)s[r].updateWorldMatrix(!1,!0)}}toJSON(e){const t=e===void 0||typeof e=="string",n={};t&&(e={geometries:{},materials:{},textures:{},images:{},shapes:{},skeletons:{},animations:{},nodes:{}},n.metadata={version:4.7,type:"Object",generator:"Object3D.toJSON"});const s={};s.uuid=this.uuid,s.type=this.type,this.name!==""&&(s.name=this.name),this.castShadow===!0&&(s.castShadow=!0),this.receiveShadow===!0&&(s.receiveShadow=!0),this.visible===!1&&(s.visible=!1),this.frustumCulled===!1&&(s.frustumCulled=!1),this.renderOrder!==0&&(s.renderOrder=this.renderOrder),Object.keys(this.userData).length>0&&(s.userData=this.userData),s.layers=this.layers.mask,s.matrix=this.matrix.toArray(),s.up=this.up.toArray(),this.matrixAutoUpdate===!1&&(s.matrixAutoUpdate=!1),this.isInstancedMesh&&(s.type="InstancedMesh",s.count=this.count,s.instanceMatrix=this.instanceMatrix.toJSON(),this.instanceColor!==null&&(s.instanceColor=this.instanceColor.toJSON())),this.isBatchedMesh&&(s.type="BatchedMesh",s.perObjectFrustumCulled=this.perObjectFrustumCulled,s.sortObjects=this.sortObjects,s.drawRanges=this._drawRanges,s.reservedRanges=this._reservedRanges,s.geometryInfo=this._geometryInfo.map(o=>({...o,boundingBox:o.boundingBox?o.boundingBox.toJSON():void 0,boundingSphere:o.boundingSphere?o.boundingSphere.toJSON():void 0})),s.instanceInfo=this._instanceInfo.map(o=>({...o})),s.availableInstanceIds=this._availableInstanceIds.slice(),s.availableGeometryIds=this._availableGeometryIds.slice(),s.nextIndexStart=this._nextIndexStart,s.nextVertexStart=this._nextVertexStart,s.geometryCount=this._geometryCount,s.maxInstanceCount=this._maxInstanceCount,s.maxVertexCount=this._maxVertexCount,s.maxIndexCount=this._maxIndexCount,s.geometryInitialized=this._geometryInitialized,s.matricesTexture=this._matricesTexture.toJSON(e),s.indirectTexture=this._indirectTexture.toJSON(e),this._colorsTexture!==null&&(s.colorsTexture=this._colorsTexture.toJSON(e)),this.boundingSphere!==null&&(s.boundingSphere=this.boundingSphere.toJSON()),this.boundingBox!==null&&(s.boundingBox=this.boundingBox.toJSON()));function r(o,c){return o[c.uuid]===void 0&&(o[c.uuid]=c.toJSON(e)),c.uuid}if(this.isScene)this.background&&(this.background.isColor?s.background=this.background.toJSON():this.background.isTexture&&(s.background=this.background.toJSON(e).uuid)),this.environment&&this.environment.isTexture&&this.environment.isRenderTargetTexture!==!0&&(s.environment=this.environment.toJSON(e).uuid);else if(this.isMesh||this.isLine||this.isPoints){s.geometry=r(e.geometries,this.geometry);const o=this.geometry.parameters;if(o!==void 0&&o.shapes!==void 0){const c=o.shapes;if(Array.isArray(c))for(let l=0,d=c.length;l<d;l++){const u=c[l];r(e.shapes,u)}else r(e.shapes,c)}}if(this.isSkinnedMesh&&(s.bindMode=this.bindMode,s.bindMatrix=this.bindMatrix.toArray(),this.skeleton!==void 0&&(r(e.skeletons,this.skeleton),s.skeleton=this.skeleton.uuid)),this.material!==void 0)if(Array.isArray(this.material)){const o=[];for(let c=0,l=this.material.length;c<l;c++)o.push(r(e.materials,this.material[c]));s.material=o}else s.material=r(e.materials,this.material);if(this.children.length>0){s.children=[];for(let o=0;o<this.children.length;o++)s.children.push(this.children[o].toJSON(e).object)}if(this.animations.length>0){s.animations=[];for(let o=0;o<this.animations.length;o++){const c=this.animations[o];s.animations.push(r(e.animations,c))}}if(t){const o=a(e.geometries),c=a(e.materials),l=a(e.textures),d=a(e.images),u=a(e.shapes),h=a(e.skeletons),f=a(e.animations),g=a(e.nodes);o.length>0&&(n.geometries=o),c.length>0&&(n.materials=c),l.length>0&&(n.textures=l),d.length>0&&(n.images=d),u.length>0&&(n.shapes=u),h.length>0&&(n.skeletons=h),f.length>0&&(n.animations=f),g.length>0&&(n.nodes=g)}return n.object=s,n;function a(o){const c=[];for(const l in o){const d=o[l];delete d.metadata,c.push(d)}return c}}clone(e){return new this.constructor().copy(this,e)}copy(e,t=!0){if(this.name=e.name,this.up.copy(e.up),this.position.copy(e.position),this.rotation.order=e.rotation.order,this.quaternion.copy(e.quaternion),this.scale.copy(e.scale),this.matrix.copy(e.matrix),this.matrixWorld.copy(e.matrixWorld),this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrixWorldAutoUpdate=e.matrixWorldAutoUpdate,this.matrixWorldNeedsUpdate=e.matrixWorldNeedsUpdate,this.layers.mask=e.layers.mask,this.visible=e.visible,this.castShadow=e.castShadow,this.receiveShadow=e.receiveShadow,this.frustumCulled=e.frustumCulled,this.renderOrder=e.renderOrder,this.animations=e.animations.slice(),this.userData=JSON.parse(JSON.stringify(e.userData)),t===!0)for(let n=0;n<e.children.length;n++){const s=e.children[n];this.add(s.clone())}return this}}Sn.DEFAULT_UP=new B(0,1,0),Sn.DEFAULT_MATRIX_AUTO_UPDATE=!0,Sn.DEFAULT_MATRIX_WORLD_AUTO_UPDATE=!0;const Gn=new B,Pi=new B,Ad=new B,ki=new B,ar=new B,or=new B,$p=new B,Rd=new B,Pd=new B,kd=new B,Id=new Ut,Dd=new Ut,Ld=new Ut;class Hn{constructor(e=new B,t=new B,n=new B){this.a=e,this.b=t,this.c=n}static getNormal(e,t,n,s){s.subVectors(n,t),Gn.subVectors(e,t),s.cross(Gn);const r=s.lengthSq();return r>0?s.multiplyScalar(1/Math.sqrt(r)):s.set(0,0,0)}static getBarycoord(e,t,n,s,r){Gn.subVectors(s,t),Pi.subVectors(n,t),Ad.subVectors(e,t);const a=Gn.dot(Gn),o=Gn.dot(Pi),c=Gn.dot(Ad),l=Pi.dot(Pi),d=Pi.dot(Ad),u=a*l-o*o;if(u===0)return r.set(0,0,0),null;const h=1/u,f=(l*c-o*d)*h,g=(a*d-o*c)*h;return r.set(1-f-g,g,f)}static containsPoint(e,t,n,s){return this.getBarycoord(e,t,n,s,ki)===null?!1:ki.x>=0&&ki.y>=0&&ki.x+ki.y<=1}static getInterpolation(e,t,n,s,r,a,o,c){return this.getBarycoord(e,t,n,s,ki)===null?(c.x=0,c.y=0,"z"in c&&(c.z=0),"w"in c&&(c.w=0),null):(c.setScalar(0),c.addScaledVector(r,ki.x),c.addScaledVector(a,ki.y),c.addScaledVector(o,ki.z),c)}static getInterpolatedAttribute(e,t,n,s,r,a){return Id.setScalar(0),Dd.setScalar(0),Ld.setScalar(0),Id.fromBufferAttribute(e,t),Dd.fromBufferAttribute(e,n),Ld.fromBufferAttribute(e,s),a.setScalar(0),a.addScaledVector(Id,r.x),a.addScaledVector(Dd,r.y),a.addScaledVector(Ld,r.z),a}static isFrontFacing(e,t,n,s){return Gn.subVectors(n,t),Pi.subVectors(e,t),Gn.cross(Pi).dot(s)<0}set(e,t,n){return this.a.copy(e),this.b.copy(t),this.c.copy(n),this}setFromPointsAndIndices(e,t,n,s){return this.a.copy(e[t]),this.b.copy(e[n]),this.c.copy(e[s]),this}setFromAttributeAndIndices(e,t,n,s){return this.a.fromBufferAttribute(e,t),this.b.fromBufferAttribute(e,n),this.c.fromBufferAttribute(e,s),this}clone(){return new this.constructor().copy(this)}copy(e){return this.a.copy(e.a),this.b.copy(e.b),this.c.copy(e.c),this}getArea(){return Gn.subVectors(this.c,this.b),Pi.subVectors(this.a,this.b),Gn.cross(Pi).length()*.5}getMidpoint(e){return e.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(e){return Hn.getNormal(this.a,this.b,this.c,e)}getPlane(e){return e.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(e,t){return Hn.getBarycoord(e,this.a,this.b,this.c,t)}getInterpolation(e,t,n,s,r){return Hn.getInterpolation(e,this.a,this.b,this.c,t,n,s,r)}containsPoint(e){return Hn.containsPoint(e,this.a,this.b,this.c)}isFrontFacing(e){return Hn.isFrontFacing(this.a,this.b,this.c,e)}intersectsBox(e){return e.intersectsTriangle(this)}closestPointToPoint(e,t){const n=this.a,s=this.b,r=this.c;let a,o;ar.subVectors(s,n),or.subVectors(r,n),Rd.subVectors(e,n);const c=ar.dot(Rd),l=or.dot(Rd);if(c<=0&&l<=0)return t.copy(n);Pd.subVectors(e,s);const d=ar.dot(Pd),u=or.dot(Pd);if(d>=0&&u<=d)return t.copy(s);const h=c*u-d*l;if(h<=0&&c>=0&&d<=0)return a=c/(c-d),t.copy(n).addScaledVector(ar,a);kd.subVectors(e,r);const f=ar.dot(kd),g=or.dot(kd);if(g>=0&&f<=g)return t.copy(r);const v=f*l-c*g;if(v<=0&&l>=0&&g<=0)return o=l/(l-g),t.copy(n).addScaledVector(or,o);const m=d*g-f*u;if(m<=0&&u-d>=0&&f-g>=0)return $p.subVectors(r,s),o=(u-d)/(u-d+(f-g)),t.copy(s).addScaledVector($p,o);const p=1/(m+v+h);return a=v*p,o=h*p,t.copy(n).addScaledVector(ar,a).addScaledVector(or,o)}equals(e){return e.a.equals(this.a)&&e.b.equals(this.b)&&e.c.equals(this.c)}}const jp={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074},Zi={h:0,s:0,l:0},ho={h:0,s:0,l:0};function Ud(i,e,t){return t<0&&(t+=1),t>1&&(t-=1),t<1/6?i+(e-i)*6*t:t<1/2?e:t<2/3?i+(e-i)*6*(2/3-t):i}class nt{constructor(e,t,n){return this.isColor=!0,this.r=1,this.g=1,this.b=1,this.set(e,t,n)}set(e,t,n){if(t===void 0&&n===void 0){const s=e;s&&s.isColor?this.copy(s):typeof s=="number"?this.setHex(s):typeof s=="string"&&this.setStyle(s)}else this.setRGB(e,t,n);return this}setScalar(e){return this.r=e,this.g=e,this.b=e,this}setHex(e,t=Mn){return e=Math.floor(e),this.r=(e>>16&255)/255,this.g=(e>>8&255)/255,this.b=(e&255)/255,it.colorSpaceToWorking(this,t),this}setRGB(e,t,n,s=it.workingColorSpace){return this.r=e,this.g=t,this.b=n,it.colorSpaceToWorking(this,s),this}setHSL(e,t,n,s=it.workingColorSpace){if(e=Xy(e,1),t=et(t,0,1),n=et(n,0,1),t===0)this.r=this.g=this.b=n;else{const r=n<=.5?n*(1+t):n+t-n*t,a=2*n-r;this.r=Ud(a,r,e+1/3),this.g=Ud(a,r,e),this.b=Ud(a,r,e-1/3)}return it.colorSpaceToWorking(this,s),this}setStyle(e,t=Mn){function n(r){r!==void 0&&parseFloat(r)<1&&Oe("Color: Alpha component of "+e+" will be ignored.")}let s;if(s=/^(\w+)\(([^\)]*)\)/.exec(e)){let r;const a=s[1],o=s[2];switch(a){case"rgb":case"rgba":if(r=/^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return n(r[4]),this.setRGB(Math.min(255,parseInt(r[1],10))/255,Math.min(255,parseInt(r[2],10))/255,Math.min(255,parseInt(r[3],10))/255,t);if(r=/^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return n(r[4]),this.setRGB(Math.min(100,parseInt(r[1],10))/100,Math.min(100,parseInt(r[2],10))/100,Math.min(100,parseInt(r[3],10))/100,t);break;case"hsl":case"hsla":if(r=/^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return n(r[4]),this.setHSL(parseFloat(r[1])/360,parseFloat(r[2])/100,parseFloat(r[3])/100,t);break;default:Oe("Color: Unknown color model "+e)}}else if(s=/^\#([A-Fa-f\d]+)$/.exec(e)){const r=s[1],a=r.length;if(a===3)return this.setRGB(parseInt(r.charAt(0),16)/15,parseInt(r.charAt(1),16)/15,parseInt(r.charAt(2),16)/15,t);if(a===6)return this.setHex(parseInt(r,16),t);Oe("Color: Invalid hex color "+e)}else if(e&&e.length>0)return this.setColorName(e,t);return this}setColorName(e,t=Mn){const n=jp[e.toLowerCase()];return n!==void 0?this.setHex(n,t):Oe("Color: Unknown color "+e),this}clone(){return new this.constructor(this.r,this.g,this.b)}copy(e){return this.r=e.r,this.g=e.g,this.b=e.b,this}copySRGBToLinear(e){return this.r=Ei(e.r),this.g=Ei(e.g),this.b=Ei(e.b),this}copyLinearToSRGB(e){return this.r=Zs(e.r),this.g=Zs(e.g),this.b=Zs(e.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(e=Mn){return it.workingToColorSpace(Qt.copy(this),e),Math.round(et(Qt.r*255,0,255))*65536+Math.round(et(Qt.g*255,0,255))*256+Math.round(et(Qt.b*255,0,255))}getHexString(e=Mn){return("000000"+this.getHex(e).toString(16)).slice(-6)}getHSL(e,t=it.workingColorSpace){it.workingToColorSpace(Qt.copy(this),t);const n=Qt.r,s=Qt.g,r=Qt.b,a=Math.max(n,s,r),o=Math.min(n,s,r);let c,l;const d=(o+a)/2;if(o===a)c=0,l=0;else{const u=a-o;switch(l=d<=.5?u/(a+o):u/(2-a-o),a){case n:c=(s-r)/u+(s<r?6:0);break;case s:c=(r-n)/u+2;break;case r:c=(n-s)/u+4;break}c/=6}return e.h=c,e.s=l,e.l=d,e}getRGB(e,t=it.workingColorSpace){return it.workingToColorSpace(Qt.copy(this),t),e.r=Qt.r,e.g=Qt.g,e.b=Qt.b,e}getStyle(e=Mn){it.workingToColorSpace(Qt.copy(this),e);const t=Qt.r,n=Qt.g,s=Qt.b;return e!==Mn?`color(${e} ${t.toFixed(3)} ${n.toFixed(3)} ${s.toFixed(3)})`:`rgb(${Math.round(t*255)},${Math.round(n*255)},${Math.round(s*255)})`}offsetHSL(e,t,n){return this.getHSL(Zi),this.setHSL(Zi.h+e,Zi.s+t,Zi.l+n)}add(e){return this.r+=e.r,this.g+=e.g,this.b+=e.b,this}addColors(e,t){return this.r=e.r+t.r,this.g=e.g+t.g,this.b=e.b+t.b,this}addScalar(e){return this.r+=e,this.g+=e,this.b+=e,this}sub(e){return this.r=Math.max(0,this.r-e.r),this.g=Math.max(0,this.g-e.g),this.b=Math.max(0,this.b-e.b),this}multiply(e){return this.r*=e.r,this.g*=e.g,this.b*=e.b,this}multiplyScalar(e){return this.r*=e,this.g*=e,this.b*=e,this}lerp(e,t){return this.r+=(e.r-this.r)*t,this.g+=(e.g-this.g)*t,this.b+=(e.b-this.b)*t,this}lerpColors(e,t,n){return this.r=e.r+(t.r-e.r)*n,this.g=e.g+(t.g-e.g)*n,this.b=e.b+(t.b-e.b)*n,this}lerpHSL(e,t){this.getHSL(Zi),e.getHSL(ho);const n=md(Zi.h,ho.h,t),s=md(Zi.s,ho.s,t),r=md(Zi.l,ho.l,t);return this.setHSL(n,s,r),this}setFromVector3(e){return this.r=e.x,this.g=e.y,this.b=e.z,this}applyMatrix3(e){const t=this.r,n=this.g,s=this.b,r=e.elements;return this.r=r[0]*t+r[3]*n+r[6]*s,this.g=r[1]*t+r[4]*n+r[7]*s,this.b=r[2]*t+r[5]*n+r[8]*s,this}equals(e){return e.r===this.r&&e.g===this.g&&e.b===this.b}fromArray(e,t=0){return this.r=e[t],this.g=e[t+1],this.b=e[t+2],this}toArray(e=[],t=0){return e[t]=this.r,e[t+1]=this.g,e[t+2]=this.b,e}fromBufferAttribute(e,t){return this.r=e.getX(t),this.g=e.getY(t),this.b=e.getZ(t),this}toJSON(){return this.getHex()}*[Symbol.iterator](){yield this.r,yield this.g,yield this.b}}const Qt=new nt;nt.NAMES=jp;let l_=0;class fo extends Js{constructor(){super(),this.isMaterial=!0,Object.defineProperty(this,"id",{value:l_++}),this.uuid=jr(),this.name="",this.type="Material",this.blending=qs,this.side=yi,this.vertexColors=!1,this.opacity=1,this.transparent=!1,this.alphaHash=!1,this.blendSrc=fl,this.blendDst=pl,this.blendEquation=us,this.blendSrcAlpha=null,this.blendDstAlpha=null,this.blendEquationAlpha=null,this.blendColor=new nt(0,0,0),this.blendAlpha=0,this.depthFunc=$s,this.depthTest=!0,this.depthWrite=!0,this.stencilWriteMask=255,this.stencilFunc=Ap,this.stencilRef=0,this.stencilFuncMask=255,this.stencilFail=Ks,this.stencilZFail=Ks,this.stencilZPass=Ks,this.stencilWrite=!1,this.clippingPlanes=null,this.clipIntersection=!1,this.clipShadows=!1,this.shadowSide=null,this.colorWrite=!0,this.precision=null,this.polygonOffset=!1,this.polygonOffsetFactor=0,this.polygonOffsetUnits=0,this.dithering=!1,this.alphaToCoverage=!1,this.premultipliedAlpha=!1,this.forceSinglePass=!1,this.allowOverride=!0,this.visible=!0,this.toneMapped=!0,this.userData={},this.version=0,this._alphaTest=0}get alphaTest(){return this._alphaTest}set alphaTest(e){this._alphaTest>0!=e>0&&this.version++,this._alphaTest=e}onBeforeRender(){}onBeforeCompile(){}customProgramCacheKey(){return this.onBeforeCompile.toString()}setValues(e){if(e!==void 0)for(const t in e){const n=e[t];if(n===void 0){Oe(`Material: parameter '${t}' has value of undefined.`);continue}const s=this[t];if(s===void 0){Oe(`Material: '${t}' is not a property of THREE.${this.type}.`);continue}s&&s.isColor?s.set(n):s&&s.isVector3&&n&&n.isVector3?s.copy(n):this[t]=n}}toJSON(e){const t=e===void 0||typeof e=="string";t&&(e={textures:{},images:{}});const n={metadata:{version:4.7,type:"Material",generator:"Material.toJSON"}};n.uuid=this.uuid,n.type=this.type,this.name!==""&&(n.name=this.name),this.color&&this.color.isColor&&(n.color=this.color.getHex()),this.roughness!==void 0&&(n.roughness=this.roughness),this.metalness!==void 0&&(n.metalness=this.metalness),this.sheen!==void 0&&(n.sheen=this.sheen),this.sheenColor&&this.sheenColor.isColor&&(n.sheenColor=this.sheenColor.getHex()),this.sheenRoughness!==void 0&&(n.sheenRoughness=this.sheenRoughness),this.emissive&&this.emissive.isColor&&(n.emissive=this.emissive.getHex()),this.emissiveIntensity!==void 0&&this.emissiveIntensity!==1&&(n.emissiveIntensity=this.emissiveIntensity),this.specular&&this.specular.isColor&&(n.specular=this.specular.getHex()),this.specularIntensity!==void 0&&(n.specularIntensity=this.specularIntensity),this.specularColor&&this.specularColor.isColor&&(n.specularColor=this.specularColor.getHex()),this.shininess!==void 0&&(n.shininess=this.shininess),this.clearcoat!==void 0&&(n.clearcoat=this.clearcoat),this.clearcoatRoughness!==void 0&&(n.clearcoatRoughness=this.clearcoatRoughness),this.clearcoatMap&&this.clearcoatMap.isTexture&&(n.clearcoatMap=this.clearcoatMap.toJSON(e).uuid),this.clearcoatRoughnessMap&&this.clearcoatRoughnessMap.isTexture&&(n.clearcoatRoughnessMap=this.clearcoatRoughnessMap.toJSON(e).uuid),this.clearcoatNormalMap&&this.clearcoatNormalMap.isTexture&&(n.clearcoatNormalMap=this.clearcoatNormalMap.toJSON(e).uuid,n.clearcoatNormalScale=this.clearcoatNormalScale.toArray()),this.sheenColorMap&&this.sheenColorMap.isTexture&&(n.sheenColorMap=this.sheenColorMap.toJSON(e).uuid),this.sheenRoughnessMap&&this.sheenRoughnessMap.isTexture&&(n.sheenRoughnessMap=this.sheenRoughnessMap.toJSON(e).uuid),this.dispersion!==void 0&&(n.dispersion=this.dispersion),this.iridescence!==void 0&&(n.iridescence=this.iridescence),this.iridescenceIOR!==void 0&&(n.iridescenceIOR=this.iridescenceIOR),this.iridescenceThicknessRange!==void 0&&(n.iridescenceThicknessRange=this.iridescenceThicknessRange),this.iridescenceMap&&this.iridescenceMap.isTexture&&(n.iridescenceMap=this.iridescenceMap.toJSON(e).uuid),this.iridescenceThicknessMap&&this.iridescenceThicknessMap.isTexture&&(n.iridescenceThicknessMap=this.iridescenceThicknessMap.toJSON(e).uuid),this.anisotropy!==void 0&&(n.anisotropy=this.anisotropy),this.anisotropyRotation!==void 0&&(n.anisotropyRotation=this.anisotropyRotation),this.anisotropyMap&&this.anisotropyMap.isTexture&&(n.anisotropyMap=this.anisotropyMap.toJSON(e).uuid),this.map&&this.map.isTexture&&(n.map=this.map.toJSON(e).uuid),this.matcap&&this.matcap.isTexture&&(n.matcap=this.matcap.toJSON(e).uuid),this.alphaMap&&this.alphaMap.isTexture&&(n.alphaMap=this.alphaMap.toJSON(e).uuid),this.lightMap&&this.lightMap.isTexture&&(n.lightMap=this.lightMap.toJSON(e).uuid,n.lightMapIntensity=this.lightMapIntensity),this.aoMap&&this.aoMap.isTexture&&(n.aoMap=this.aoMap.toJSON(e).uuid,n.aoMapIntensity=this.aoMapIntensity),this.bumpMap&&this.bumpMap.isTexture&&(n.bumpMap=this.bumpMap.toJSON(e).uuid,n.bumpScale=this.bumpScale),this.normalMap&&this.normalMap.isTexture&&(n.normalMap=this.normalMap.toJSON(e).uuid,n.normalMapType=this.normalMapType,n.normalScale=this.normalScale.toArray()),this.displacementMap&&this.displacementMap.isTexture&&(n.displacementMap=this.displacementMap.toJSON(e).uuid,n.displacementScale=this.displacementScale,n.displacementBias=this.displacementBias),this.roughnessMap&&this.roughnessMap.isTexture&&(n.roughnessMap=this.roughnessMap.toJSON(e).uuid),this.metalnessMap&&this.metalnessMap.isTexture&&(n.metalnessMap=this.metalnessMap.toJSON(e).uuid),this.emissiveMap&&this.emissiveMap.isTexture&&(n.emissiveMap=this.emissiveMap.toJSON(e).uuid),this.specularMap&&this.specularMap.isTexture&&(n.specularMap=this.specularMap.toJSON(e).uuid),this.specularIntensityMap&&this.specularIntensityMap.isTexture&&(n.specularIntensityMap=this.specularIntensityMap.toJSON(e).uuid),this.specularColorMap&&this.specularColorMap.isTexture&&(n.specularColorMap=this.specularColorMap.toJSON(e).uuid),this.envMap&&this.envMap.isTexture&&(n.envMap=this.envMap.toJSON(e).uuid,this.combine!==void 0&&(n.combine=this.combine)),this.envMapRotation!==void 0&&(n.envMapRotation=this.envMapRotation.toArray()),this.envMapIntensity!==void 0&&(n.envMapIntensity=this.envMapIntensity),this.reflectivity!==void 0&&(n.reflectivity=this.reflectivity),this.refractionRatio!==void 0&&(n.refractionRatio=this.refractionRatio),this.gradientMap&&this.gradientMap.isTexture&&(n.gradientMap=this.gradientMap.toJSON(e).uuid),this.transmission!==void 0&&(n.transmission=this.transmission),this.transmissionMap&&this.transmissionMap.isTexture&&(n.transmissionMap=this.transmissionMap.toJSON(e).uuid),this.thickness!==void 0&&(n.thickness=this.thickness),this.thicknessMap&&this.thicknessMap.isTexture&&(n.thicknessMap=this.thicknessMap.toJSON(e).uuid),this.attenuationDistance!==void 0&&this.attenuationDistance!==1/0&&(n.attenuationDistance=this.attenuationDistance),this.attenuationColor!==void 0&&(n.attenuationColor=this.attenuationColor.getHex()),this.size!==void 0&&(n.size=this.size),this.shadowSide!==null&&(n.shadowSide=this.shadowSide),this.sizeAttenuation!==void 0&&(n.sizeAttenuation=this.sizeAttenuation),this.blending!==qs&&(n.blending=this.blending),this.side!==yi&&(n.side=this.side),this.vertexColors===!0&&(n.vertexColors=!0),this.opacity<1&&(n.opacity=this.opacity),this.transparent===!0&&(n.transparent=!0),this.blendSrc!==fl&&(n.blendSrc=this.blendSrc),this.blendDst!==pl&&(n.blendDst=this.blendDst),this.blendEquation!==us&&(n.blendEquation=this.blendEquation),this.blendSrcAlpha!==null&&(n.blendSrcAlpha=this.blendSrcAlpha),this.blendDstAlpha!==null&&(n.blendDstAlpha=this.blendDstAlpha),this.blendEquationAlpha!==null&&(n.blendEquationAlpha=this.blendEquationAlpha),this.blendColor&&this.blendColor.isColor&&(n.blendColor=this.blendColor.getHex()),this.blendAlpha!==0&&(n.blendAlpha=this.blendAlpha),this.depthFunc!==$s&&(n.depthFunc=this.depthFunc),this.depthTest===!1&&(n.depthTest=this.depthTest),this.depthWrite===!1&&(n.depthWrite=this.depthWrite),this.colorWrite===!1&&(n.colorWrite=this.colorWrite),this.stencilWriteMask!==255&&(n.stencilWriteMask=this.stencilWriteMask),this.stencilFunc!==Ap&&(n.stencilFunc=this.stencilFunc),this.stencilRef!==0&&(n.stencilRef=this.stencilRef),this.stencilFuncMask!==255&&(n.stencilFuncMask=this.stencilFuncMask),this.stencilFail!==Ks&&(n.stencilFail=this.stencilFail),this.stencilZFail!==Ks&&(n.stencilZFail=this.stencilZFail),this.stencilZPass!==Ks&&(n.stencilZPass=this.stencilZPass),this.stencilWrite===!0&&(n.stencilWrite=this.stencilWrite),this.rotation!==void 0&&this.rotation!==0&&(n.rotation=this.rotation),this.polygonOffset===!0&&(n.polygonOffset=!0),this.polygonOffsetFactor!==0&&(n.polygonOffsetFactor=this.polygonOffsetFactor),this.polygonOffsetUnits!==0&&(n.polygonOffsetUnits=this.polygonOffsetUnits),this.linewidth!==void 0&&this.linewidth!==1&&(n.linewidth=this.linewidth),this.dashSize!==void 0&&(n.dashSize=this.dashSize),this.gapSize!==void 0&&(n.gapSize=this.gapSize),this.scale!==void 0&&(n.scale=this.scale),this.dithering===!0&&(n.dithering=!0),this.alphaTest>0&&(n.alphaTest=this.alphaTest),this.alphaHash===!0&&(n.alphaHash=!0),this.alphaToCoverage===!0&&(n.alphaToCoverage=!0),this.premultipliedAlpha===!0&&(n.premultipliedAlpha=!0),this.forceSinglePass===!0&&(n.forceSinglePass=!0),this.allowOverride===!1&&(n.allowOverride=!1),this.wireframe===!0&&(n.wireframe=!0),this.wireframeLinewidth>1&&(n.wireframeLinewidth=this.wireframeLinewidth),this.wireframeLinecap!=="round"&&(n.wireframeLinecap=this.wireframeLinecap),this.wireframeLinejoin!=="round"&&(n.wireframeLinejoin=this.wireframeLinejoin),this.flatShading===!0&&(n.flatShading=!0),this.visible===!1&&(n.visible=!1),this.toneMapped===!1&&(n.toneMapped=!1),this.fog===!1&&(n.fog=!1),Object.keys(this.userData).length>0&&(n.userData=this.userData);function s(r){const a=[];for(const o in r){const c=r[o];delete c.metadata,a.push(c)}return a}if(t){const r=s(e.textures),a=s(e.images);r.length>0&&(n.textures=r),a.length>0&&(n.images=a)}return n}clone(){return new this.constructor().copy(this)}copy(e){this.name=e.name,this.blending=e.blending,this.side=e.side,this.vertexColors=e.vertexColors,this.opacity=e.opacity,this.transparent=e.transparent,this.blendSrc=e.blendSrc,this.blendDst=e.blendDst,this.blendEquation=e.blendEquation,this.blendSrcAlpha=e.blendSrcAlpha,this.blendDstAlpha=e.blendDstAlpha,this.blendEquationAlpha=e.blendEquationAlpha,this.blendColor.copy(e.blendColor),this.blendAlpha=e.blendAlpha,this.depthFunc=e.depthFunc,this.depthTest=e.depthTest,this.depthWrite=e.depthWrite,this.stencilWriteMask=e.stencilWriteMask,this.stencilFunc=e.stencilFunc,this.stencilRef=e.stencilRef,this.stencilFuncMask=e.stencilFuncMask,this.stencilFail=e.stencilFail,this.stencilZFail=e.stencilZFail,this.stencilZPass=e.stencilZPass,this.stencilWrite=e.stencilWrite;const t=e.clippingPlanes;let n=null;if(t!==null){const s=t.length;n=new Array(s);for(let r=0;r!==s;++r)n[r]=t[r].clone()}return this.clippingPlanes=n,this.clipIntersection=e.clipIntersection,this.clipShadows=e.clipShadows,this.shadowSide=e.shadowSide,this.colorWrite=e.colorWrite,this.precision=e.precision,this.polygonOffset=e.polygonOffset,this.polygonOffsetFactor=e.polygonOffsetFactor,this.polygonOffsetUnits=e.polygonOffsetUnits,this.dithering=e.dithering,this.alphaTest=e.alphaTest,this.alphaHash=e.alphaHash,this.alphaToCoverage=e.alphaToCoverage,this.premultipliedAlpha=e.premultipliedAlpha,this.forceSinglePass=e.forceSinglePass,this.allowOverride=e.allowOverride,this.visible=e.visible,this.toneMapped=e.toneMapped,this.userData=JSON.parse(JSON.stringify(e.userData)),this}dispose(){this.dispatchEvent({type:"dispose"})}set needsUpdate(e){e===!0&&this.version++}}class Xp extends fo{constructor(e){super(),this.isMeshBasicMaterial=!0,this.type="MeshBasicMaterial",this.color=new nt(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new Ai,this.combine=hp,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.combine=e.combine,this.reflectivity=e.reflectivity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.fog=e.fog,this}}const Bt=new B,po=new lt;let d_=0;class ai{constructor(e,t,n=!1){if(Array.isArray(e))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");this.isBufferAttribute=!0,Object.defineProperty(this,"id",{value:d_++}),this.name="",this.array=e,this.itemSize=t,this.count=e!==void 0?e.length/t:0,this.normalized=n,this.usage=Rp,this.updateRanges=[],this.gpuType=ii,this.version=0}onUploadCallback(){}set needsUpdate(e){e===!0&&this.version++}setUsage(e){return this.usage=e,this}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}copy(e){return this.name=e.name,this.array=new e.array.constructor(e.array),this.itemSize=e.itemSize,this.count=e.count,this.normalized=e.normalized,this.usage=e.usage,this.gpuType=e.gpuType,this}copyAt(e,t,n){e*=this.itemSize,n*=t.itemSize;for(let s=0,r=this.itemSize;s<r;s++)this.array[e+s]=t.array[n+s];return this}copyArray(e){return this.array.set(e),this}applyMatrix3(e){if(this.itemSize===2)for(let t=0,n=this.count;t<n;t++)po.fromBufferAttribute(this,t),po.applyMatrix3(e),this.setXY(t,po.x,po.y);else if(this.itemSize===3)for(let t=0,n=this.count;t<n;t++)Bt.fromBufferAttribute(this,t),Bt.applyMatrix3(e),this.setXYZ(t,Bt.x,Bt.y,Bt.z);return this}applyMatrix4(e){for(let t=0,n=this.count;t<n;t++)Bt.fromBufferAttribute(this,t),Bt.applyMatrix4(e),this.setXYZ(t,Bt.x,Bt.y,Bt.z);return this}applyNormalMatrix(e){for(let t=0,n=this.count;t<n;t++)Bt.fromBufferAttribute(this,t),Bt.applyNormalMatrix(e),this.setXYZ(t,Bt.x,Bt.y,Bt.z);return this}transformDirection(e){for(let t=0,n=this.count;t<n;t++)Bt.fromBufferAttribute(this,t),Bt.transformDirection(e),this.setXYZ(t,Bt.x,Bt.y,Bt.z);return this}set(e,t=0){return this.array.set(e,t),this}getComponent(e,t){let n=this.array[e*this.itemSize+t];return this.normalized&&(n=Xr(n,this.array)),n}setComponent(e,t,n){return this.normalized&&(n=un(n,this.array)),this.array[e*this.itemSize+t]=n,this}getX(e){let t=this.array[e*this.itemSize];return this.normalized&&(t=Xr(t,this.array)),t}setX(e,t){return this.normalized&&(t=un(t,this.array)),this.array[e*this.itemSize]=t,this}getY(e){let t=this.array[e*this.itemSize+1];return this.normalized&&(t=Xr(t,this.array)),t}setY(e,t){return this.normalized&&(t=un(t,this.array)),this.array[e*this.itemSize+1]=t,this}getZ(e){let t=this.array[e*this.itemSize+2];return this.normalized&&(t=Xr(t,this.array)),t}setZ(e,t){return this.normalized&&(t=un(t,this.array)),this.array[e*this.itemSize+2]=t,this}getW(e){let t=this.array[e*this.itemSize+3];return this.normalized&&(t=Xr(t,this.array)),t}setW(e,t){return this.normalized&&(t=un(t,this.array)),this.array[e*this.itemSize+3]=t,this}setXY(e,t,n){return e*=this.itemSize,this.normalized&&(t=un(t,this.array),n=un(n,this.array)),this.array[e+0]=t,this.array[e+1]=n,this}setXYZ(e,t,n,s){return e*=this.itemSize,this.normalized&&(t=un(t,this.array),n=un(n,this.array),s=un(s,this.array)),this.array[e+0]=t,this.array[e+1]=n,this.array[e+2]=s,this}setXYZW(e,t,n,s,r){return e*=this.itemSize,this.normalized&&(t=un(t,this.array),n=un(n,this.array),s=un(s,this.array),r=un(r,this.array)),this.array[e+0]=t,this.array[e+1]=n,this.array[e+2]=s,this.array[e+3]=r,this}onUpload(e){return this.onUploadCallback=e,this}clone(){return new this.constructor(this.array,this.itemSize).copy(this)}toJSON(){const e={itemSize:this.itemSize,type:this.array.constructor.name,array:Array.from(this.array),normalized:this.normalized};return this.name!==""&&(e.name=this.name),this.usage!==Rp&&(e.usage=this.usage),e}}class Yp extends ai{constructor(e,t,n){super(new Uint16Array(e),t,n)}}class Kp extends ai{constructor(e,t,n){super(new Uint32Array(e),t,n)}}class nn extends ai{constructor(e,t,n){super(new Float32Array(e),t,n)}}let u_=0;const wn=new Ft,Nd=new Sn,cr=new B,xn=new Kr,ea=new Kr,jt=new B;class Wn extends Js{constructor(){super(),this.isBufferGeometry=!0,Object.defineProperty(this,"id",{value:u_++}),this.uuid=jr(),this.name="",this.type="BufferGeometry",this.index=null,this.indirect=null,this.indirectOffset=0,this.attributes={},this.morphAttributes={},this.morphTargetsRelative=!1,this.groups=[],this.boundingBox=null,this.boundingSphere=null,this.drawRange={start:0,count:1/0},this.userData={}}getIndex(){return this.index}setIndex(e){return Array.isArray(e)?this.index=new(kp(e)?Kp:Yp)(e,1):this.index=e,this}setIndirect(e,t=0){return this.indirect=e,this.indirectOffset=t,this}getIndirect(){return this.indirect}getAttribute(e){return this.attributes[e]}setAttribute(e,t){return this.attributes[e]=t,this}deleteAttribute(e){return delete this.attributes[e],this}hasAttribute(e){return this.attributes[e]!==void 0}addGroup(e,t,n=0){this.groups.push({start:e,count:t,materialIndex:n})}clearGroups(){this.groups=[]}setDrawRange(e,t){this.drawRange.start=e,this.drawRange.count=t}applyMatrix4(e){const t=this.attributes.position;t!==void 0&&(t.applyMatrix4(e),t.needsUpdate=!0);const n=this.attributes.normal;if(n!==void 0){const r=new Ve().getNormalMatrix(e);n.applyNormalMatrix(r),n.needsUpdate=!0}const s=this.attributes.tangent;return s!==void 0&&(s.transformDirection(e),s.needsUpdate=!0),this.boundingBox!==null&&this.computeBoundingBox(),this.boundingSphere!==null&&this.computeBoundingSphere(),this}applyQuaternion(e){return wn.makeRotationFromQuaternion(e),this.applyMatrix4(wn),this}rotateX(e){return wn.makeRotationX(e),this.applyMatrix4(wn),this}rotateY(e){return wn.makeRotationY(e),this.applyMatrix4(wn),this}rotateZ(e){return wn.makeRotationZ(e),this.applyMatrix4(wn),this}translate(e,t,n){return wn.makeTranslation(e,t,n),this.applyMatrix4(wn),this}scale(e,t,n){return wn.makeScale(e,t,n),this.applyMatrix4(wn),this}lookAt(e){return Nd.lookAt(e),Nd.updateMatrix(),this.applyMatrix4(Nd.matrix),this}center(){return this.computeBoundingBox(),this.boundingBox.getCenter(cr).negate(),this.translate(cr.x,cr.y,cr.z),this}setFromPoints(e){const t=this.getAttribute("position");if(t===void 0){const n=[];for(let s=0,r=e.length;s<r;s++){const a=e[s];n.push(a.x,a.y,a.z||0)}this.setAttribute("position",new nn(n,3))}else{const n=Math.min(e.length,t.count);for(let s=0;s<n;s++){const r=e[s];t.setXYZ(s,r.x,r.y,r.z||0)}e.length>t.count&&Oe("BufferGeometry: Buffer size too small for points data. Use .dispose() and create a new geometry."),t.needsUpdate=!0}return this}computeBoundingBox(){this.boundingBox===null&&(this.boundingBox=new Kr);const e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute){rt("BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.",this),this.boundingBox.set(new B(-1/0,-1/0,-1/0),new B(1/0,1/0,1/0));return}if(e!==void 0){if(this.boundingBox.setFromBufferAttribute(e),t)for(let n=0,s=t.length;n<s;n++){const r=t[n];xn.setFromBufferAttribute(r),this.morphTargetsRelative?(jt.addVectors(this.boundingBox.min,xn.min),this.boundingBox.expandByPoint(jt),jt.addVectors(this.boundingBox.max,xn.max),this.boundingBox.expandByPoint(jt)):(this.boundingBox.expandByPoint(xn.min),this.boundingBox.expandByPoint(xn.max))}}else this.boundingBox.makeEmpty();(isNaN(this.boundingBox.min.x)||isNaN(this.boundingBox.min.y)||isNaN(this.boundingBox.min.z))&&rt('BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.',this)}computeBoundingSphere(){this.boundingSphere===null&&(this.boundingSphere=new Td);const e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute){rt("BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.",this),this.boundingSphere.set(new B,1/0);return}if(e){const n=this.boundingSphere.center;if(xn.setFromBufferAttribute(e),t)for(let r=0,a=t.length;r<a;r++){const o=t[r];ea.setFromBufferAttribute(o),this.morphTargetsRelative?(jt.addVectors(xn.min,ea.min),xn.expandByPoint(jt),jt.addVectors(xn.max,ea.max),xn.expandByPoint(jt)):(xn.expandByPoint(ea.min),xn.expandByPoint(ea.max))}xn.getCenter(n);let s=0;for(let r=0,a=e.count;r<a;r++)jt.fromBufferAttribute(e,r),s=Math.max(s,n.distanceToSquared(jt));if(t)for(let r=0,a=t.length;r<a;r++){const o=t[r],c=this.morphTargetsRelative;for(let l=0,d=o.count;l<d;l++)jt.fromBufferAttribute(o,l),c&&(cr.fromBufferAttribute(e,l),jt.add(cr)),s=Math.max(s,n.distanceToSquared(jt))}this.boundingSphere.radius=Math.sqrt(s),isNaN(this.boundingSphere.radius)&&rt('BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.',this)}}computeTangents(){const e=this.index,t=this.attributes;if(e===null||t.position===void 0||t.normal===void 0||t.uv===void 0){rt("BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)");return}const n=t.position,s=t.normal,r=t.uv;this.hasAttribute("tangent")===!1&&this.setAttribute("tangent",new ai(new Float32Array(4*n.count),4));const a=this.getAttribute("tangent"),o=[],c=[];for(let k=0;k<n.count;k++)o[k]=new B,c[k]=new B;const l=new B,d=new B,u=new B,h=new lt,f=new lt,g=new lt,v=new B,m=new B;function p(k,_,T){l.fromBufferAttribute(n,k),d.fromBufferAttribute(n,_),u.fromBufferAttribute(n,T),h.fromBufferAttribute(r,k),f.fromBufferAttribute(r,_),g.fromBufferAttribute(r,T),d.sub(l),u.sub(l),f.sub(h),g.sub(h);const R=1/(f.x*g.y-g.x*f.y);isFinite(R)&&(v.copy(d).multiplyScalar(g.y).addScaledVector(u,-f.y).multiplyScalar(R),m.copy(u).multiplyScalar(f.x).addScaledVector(d,-g.x).multiplyScalar(R),o[k].add(v),o[_].add(v),o[T].add(v),c[k].add(m),c[_].add(m),c[T].add(m))}let x=this.groups;x.length===0&&(x=[{start:0,count:e.count}]);for(let k=0,_=x.length;k<_;++k){const T=x[k],R=T.start,O=T.count;for(let z=R,$=R+O;z<$;z+=3)p(e.getX(z+0),e.getX(z+1),e.getX(z+2))}const C=new B,b=new B,S=new B,M=new B;function A(k){S.fromBufferAttribute(s,k),M.copy(S);const _=o[k];C.copy(_),C.sub(S.multiplyScalar(S.dot(_))).normalize(),b.crossVectors(M,_);const R=b.dot(c[k])<0?-1:1;a.setXYZW(k,C.x,C.y,C.z,R)}for(let k=0,_=x.length;k<_;++k){const T=x[k],R=T.start,O=T.count;for(let z=R,$=R+O;z<$;z+=3)A(e.getX(z+0)),A(e.getX(z+1)),A(e.getX(z+2))}}computeVertexNormals(){const e=this.index,t=this.getAttribute("position");if(t!==void 0){let n=this.getAttribute("normal");if(n===void 0)n=new ai(new Float32Array(t.count*3),3),this.setAttribute("normal",n);else for(let h=0,f=n.count;h<f;h++)n.setXYZ(h,0,0,0);const s=new B,r=new B,a=new B,o=new B,c=new B,l=new B,d=new B,u=new B;if(e)for(let h=0,f=e.count;h<f;h+=3){const g=e.getX(h+0),v=e.getX(h+1),m=e.getX(h+2);s.fromBufferAttribute(t,g),r.fromBufferAttribute(t,v),a.fromBufferAttribute(t,m),d.subVectors(a,r),u.subVectors(s,r),d.cross(u),o.fromBufferAttribute(n,g),c.fromBufferAttribute(n,v),l.fromBufferAttribute(n,m),o.add(d),c.add(d),l.add(d),n.setXYZ(g,o.x,o.y,o.z),n.setXYZ(v,c.x,c.y,c.z),n.setXYZ(m,l.x,l.y,l.z)}else for(let h=0,f=t.count;h<f;h+=3)s.fromBufferAttribute(t,h+0),r.fromBufferAttribute(t,h+1),a.fromBufferAttribute(t,h+2),d.subVectors(a,r),u.subVectors(s,r),d.cross(u),n.setXYZ(h+0,d.x,d.y,d.z),n.setXYZ(h+1,d.x,d.y,d.z),n.setXYZ(h+2,d.x,d.y,d.z);this.normalizeNormals(),n.needsUpdate=!0}}normalizeNormals(){const e=this.attributes.normal;for(let t=0,n=e.count;t<n;t++)jt.fromBufferAttribute(e,t),jt.normalize(),e.setXYZ(t,jt.x,jt.y,jt.z)}toNonIndexed(){function e(o,c){const l=o.array,d=o.itemSize,u=o.normalized,h=new l.constructor(c.length*d);let f=0,g=0;for(let v=0,m=c.length;v<m;v++){o.isInterleavedBufferAttribute?f=c[v]*o.data.stride+o.offset:f=c[v]*d;for(let p=0;p<d;p++)h[g++]=l[f++]}return new ai(h,d,u)}if(this.index===null)return Oe("BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed."),this;const t=new Wn,n=this.index.array,s=this.attributes;for(const o in s){const c=s[o],l=e(c,n);t.setAttribute(o,l)}const r=this.morphAttributes;for(const o in r){const c=[],l=r[o];for(let d=0,u=l.length;d<u;d++){const h=l[d],f=e(h,n);c.push(f)}t.morphAttributes[o]=c}t.morphTargetsRelative=this.morphTargetsRelative;const a=this.groups;for(let o=0,c=a.length;o<c;o++){const l=a[o];t.addGroup(l.start,l.count,l.materialIndex)}return t}toJSON(){const e={metadata:{version:4.7,type:"BufferGeometry",generator:"BufferGeometry.toJSON"}};if(e.uuid=this.uuid,e.type=this.type,this.name!==""&&(e.name=this.name),Object.keys(this.userData).length>0&&(e.userData=this.userData),this.parameters!==void 0){const c=this.parameters;for(const l in c)c[l]!==void 0&&(e[l]=c[l]);return e}e.data={attributes:{}};const t=this.index;t!==null&&(e.data.index={type:t.array.constructor.name,array:Array.prototype.slice.call(t.array)});const n=this.attributes;for(const c in n){const l=n[c];e.data.attributes[c]=l.toJSON(e.data)}const s={};let r=!1;for(const c in this.morphAttributes){const l=this.morphAttributes[c],d=[];for(let u=0,h=l.length;u<h;u++){const f=l[u];d.push(f.toJSON(e.data))}d.length>0&&(s[c]=d,r=!0)}r&&(e.data.morphAttributes=s,e.data.morphTargetsRelative=this.morphTargetsRelative);const a=this.groups;a.length>0&&(e.data.groups=JSON.parse(JSON.stringify(a)));const o=this.boundingSphere;return o!==null&&(e.data.boundingSphere=o.toJSON()),e}clone(){return new this.constructor().copy(this)}copy(e){this.index=null,this.attributes={},this.morphAttributes={},this.groups=[],this.boundingBox=null,this.boundingSphere=null;const t={};this.name=e.name;const n=e.index;n!==null&&this.setIndex(n.clone());const s=e.attributes;for(const l in s){const d=s[l];this.setAttribute(l,d.clone(t))}const r=e.morphAttributes;for(const l in r){const d=[],u=r[l];for(let h=0,f=u.length;h<f;h++)d.push(u[h].clone(t));this.morphAttributes[l]=d}this.morphTargetsRelative=e.morphTargetsRelative;const a=e.groups;for(let l=0,d=a.length;l<d;l++){const u=a[l];this.addGroup(u.start,u.count,u.materialIndex)}const o=e.boundingBox;o!==null&&(this.boundingBox=o.clone());const c=e.boundingSphere;return c!==null&&(this.boundingSphere=c.clone()),this.drawRange.start=e.drawRange.start,this.drawRange.count=e.drawRange.count,this.userData=e.userData,this}dispose(){this.dispatchEvent({type:"dispose"})}}const Jp=new Ft,vs=new n_,mo=new Td,Zp=new B,go=new B,vo=new B,bo=new B,Od=new B,yo=new B,Qp=new B,_o=new B;class qn extends Sn{constructor(e=new Wn,t=new Xp){super(),this.isMesh=!0,this.type="Mesh",this.geometry=e,this.material=t,this.morphTargetDictionary=void 0,this.morphTargetInfluences=void 0,this.count=1,this.updateMorphTargets()}copy(e,t){return super.copy(e,t),e.morphTargetInfluences!==void 0&&(this.morphTargetInfluences=e.morphTargetInfluences.slice()),e.morphTargetDictionary!==void 0&&(this.morphTargetDictionary=Object.assign({},e.morphTargetDictionary)),this.material=Array.isArray(e.material)?e.material.slice():e.material,this.geometry=e.geometry,this}updateMorphTargets(){const t=this.geometry.morphAttributes,n=Object.keys(t);if(n.length>0){const s=t[n[0]];if(s!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let r=0,a=s.length;r<a;r++){const o=s[r].name||String(r);this.morphTargetInfluences.push(0),this.morphTargetDictionary[o]=r}}}}getVertexPosition(e,t){const n=this.geometry,s=n.attributes.position,r=n.morphAttributes.position,a=n.morphTargetsRelative;t.fromBufferAttribute(s,e);const o=this.morphTargetInfluences;if(r&&o){yo.set(0,0,0);for(let c=0,l=r.length;c<l;c++){const d=o[c],u=r[c];d!==0&&(Od.fromBufferAttribute(u,e),a?yo.addScaledVector(Od,d):yo.addScaledVector(Od.sub(t),d))}t.add(yo)}return t}raycast(e,t){const n=this.geometry,s=this.material,r=this.matrixWorld;s!==void 0&&(n.boundingSphere===null&&n.computeBoundingSphere(),mo.copy(n.boundingSphere),mo.applyMatrix4(r),vs.copy(e.ray).recast(e.near),!(mo.containsPoint(vs.origin)===!1&&(vs.intersectSphere(mo,Zp)===null||vs.origin.distanceToSquared(Zp)>(e.far-e.near)**2))&&(Jp.copy(r).invert(),vs.copy(e.ray).applyMatrix4(Jp),!(n.boundingBox!==null&&vs.intersectsBox(n.boundingBox)===!1)&&this._computeIntersections(e,t,vs)))}_computeIntersections(e,t,n){let s;const r=this.geometry,a=this.material,o=r.index,c=r.attributes.position,l=r.attributes.uv,d=r.attributes.uv1,u=r.attributes.normal,h=r.groups,f=r.drawRange;if(o!==null)if(Array.isArray(a))for(let g=0,v=h.length;g<v;g++){const m=h[g],p=a[m.materialIndex],x=Math.max(m.start,f.start),C=Math.min(o.count,Math.min(m.start+m.count,f.start+f.count));for(let b=x,S=C;b<S;b+=3){const M=o.getX(b),A=o.getX(b+1),k=o.getX(b+2);s=So(this,p,e,n,l,d,u,M,A,k),s&&(s.faceIndex=Math.floor(b/3),s.face.materialIndex=m.materialIndex,t.push(s))}}else{const g=Math.max(0,f.start),v=Math.min(o.count,f.start+f.count);for(let m=g,p=v;m<p;m+=3){const x=o.getX(m),C=o.getX(m+1),b=o.getX(m+2);s=So(this,a,e,n,l,d,u,x,C,b),s&&(s.faceIndex=Math.floor(m/3),t.push(s))}}else if(c!==void 0)if(Array.isArray(a))for(let g=0,v=h.length;g<v;g++){const m=h[g],p=a[m.materialIndex],x=Math.max(m.start,f.start),C=Math.min(c.count,Math.min(m.start+m.count,f.start+f.count));for(let b=x,S=C;b<S;b+=3){const M=b,A=b+1,k=b+2;s=So(this,p,e,n,l,d,u,M,A,k),s&&(s.faceIndex=Math.floor(b/3),s.face.materialIndex=m.materialIndex,t.push(s))}}else{const g=Math.max(0,f.start),v=Math.min(c.count,f.start+f.count);for(let m=g,p=v;m<p;m+=3){const x=m,C=m+1,b=m+2;s=So(this,a,e,n,l,d,u,x,C,b),s&&(s.faceIndex=Math.floor(m/3),t.push(s))}}}}function h_(i,e,t,n,s,r,a,o){let c;if(e.side===en?c=n.intersectTriangle(a,r,s,!0,o):c=n.intersectTriangle(s,r,a,e.side===yi,o),c===null)return null;_o.copy(o),_o.applyMatrix4(i.matrixWorld);const l=t.ray.origin.distanceTo(_o);return l<t.near||l>t.far?null:{distance:l,point:_o.clone(),object:i}}function So(i,e,t,n,s,r,a,o,c,l){i.getVertexPosition(o,go),i.getVertexPosition(c,vo),i.getVertexPosition(l,bo);const d=h_(i,e,t,n,go,vo,bo,Qp);if(d){const u=new B;Hn.getBarycoord(Qp,go,vo,bo,u),s&&(d.uv=Hn.getInterpolatedAttribute(s,o,c,l,u,new lt)),r&&(d.uv1=Hn.getInterpolatedAttribute(r,o,c,l,u,new lt)),a&&(d.normal=Hn.getInterpolatedAttribute(a,o,c,l,u,new B),d.normal.dot(n.direction)>0&&d.normal.multiplyScalar(-1));const h={a:o,b:c,c:l,normal:new B,materialIndex:0};Hn.getNormal(go,vo,bo,h.normal),d.face=h,d.barycoord=u}return d}class ta extends Wn{constructor(e=1,t=1,n=1,s=1,r=1,a=1){super(),this.type="BoxGeometry",this.parameters={width:e,height:t,depth:n,widthSegments:s,heightSegments:r,depthSegments:a};const o=this;s=Math.floor(s),r=Math.floor(r),a=Math.floor(a);const c=[],l=[],d=[],u=[];let h=0,f=0;g("z","y","x",-1,-1,n,t,e,a,r,0),g("z","y","x",1,-1,n,t,-e,a,r,1),g("x","z","y",1,1,e,n,t,s,a,2),g("x","z","y",1,-1,e,n,-t,s,a,3),g("x","y","z",1,-1,e,t,n,s,r,4),g("x","y","z",-1,-1,e,t,-n,s,r,5),this.setIndex(c),this.setAttribute("position",new nn(l,3)),this.setAttribute("normal",new nn(d,3)),this.setAttribute("uv",new nn(u,2));function g(v,m,p,x,C,b,S,M,A,k,_){const T=b/A,R=S/k,O=b/2,z=S/2,$=M/2,J=A+1,W=k+1;let q=0,ne=0;const be=new B;for(let ue=0;ue<W;ue++){const _e=ue*R-z;for(let ze=0;ze<J;ze++){const Be=ze*T-O;be[v]=Be*x,be[m]=_e*C,be[p]=$,l.push(be.x,be.y,be.z),be[v]=0,be[m]=0,be[p]=M>0?1:-1,d.push(be.x,be.y,be.z),u.push(ze/A),u.push(1-ue/k),q+=1}}for(let ue=0;ue<k;ue++)for(let _e=0;_e<A;_e++){const ze=h+_e+J*ue,Be=h+_e+J*(ue+1),wt=h+(_e+1)+J*(ue+1),vt=h+(_e+1)+J*ue;c.push(ze,Be,vt),c.push(Be,wt,vt),ne+=6}o.addGroup(f,ne,_),f+=ne,h+=q}}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new ta(e.width,e.height,e.depth,e.widthSegments,e.heightSegments,e.depthSegments)}}function lr(i){const e={};for(const t in i){e[t]={};for(const n in i[t]){const s=i[t][n];s&&(s.isColor||s.isMatrix3||s.isMatrix4||s.isVector2||s.isVector3||s.isVector4||s.isTexture||s.isQuaternion)?s.isRenderTargetTexture?(Oe("UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms()."),e[t][n]=null):e[t][n]=s.clone():Array.isArray(s)?e[t][n]=s.slice():e[t][n]=s}}return e}function sn(i){const e={};for(let t=0;t<i.length;t++){const n=lr(i[t]);for(const s in n)e[s]=n[s]}return e}function f_(i){const e=[];for(let t=0;t<i.length;t++)e.push(i[t].clone());return e}function em(i){const e=i.getRenderTarget();return e===null?i.outputColorSpace:e.isXRRenderTarget===!0?e.texture.colorSpace:it.workingColorSpace}const p_={clone:lr,merge:sn};var m_=`void main() {
|
|
88
|
+
*/const ul="182",fy=0,lp=1,py=2,Xa=1,my=2,Hr=3,yi=0,en=1,_i=2,Si=0,qs=1,hl=2,dp=3,up=4,gy=5,us=100,vy=101,by=102,yy=103,_y=104,Sy=200,xy=201,Ty=202,Cy=203,fl=204,pl=205,Ey=206,My=207,wy=208,Ay=209,Ry=210,Py=211,ky=212,Iy=213,Dy=214,ml=0,gl=1,vl=2,$s=3,bl=4,yl=5,_l=6,Sl=7,hp=0,Ly=1,Uy=2,ti=0,fp=1,pp=2,mp=3,gp=4,vp=5,bp=6,yp=7,_p=300,hs=301,js=302,xl=303,Tl=304,Ya=306,Cl=1e3,xi=1001,El=1002,Kt=1003,Ny=1004,Ka=1005,Jt=1006,Ml=1007,fs=1008,En=1009,Sp=1010,xp=1011,Wr=1012,wl=1013,ni=1014,ii=1015,Ti=1016,Al=1017,Rl=1018,qr=1020,Tp=35902,Cp=35899,Ep=1021,Mp=1022,Bn=1023,Ci=1026,ps=1027,wp=1028,Pl=1029,Xs=1030,kl=1031,Il=1033,Ja=33776,Za=33777,Qa=33778,eo=33779,Dl=35840,Ll=35841,Ul=35842,Nl=35843,Ol=36196,Fl=37492,Bl=37496,zl=37488,Vl=37489,Gl=37490,Hl=37491,Wl=37808,ql=37809,$l=37810,jl=37811,Xl=37812,Yl=37813,Kl=37814,Jl=37815,Zl=37816,Ql=37817,ed=37818,td=37819,nd=37820,id=37821,sd=36492,rd=36494,ad=36495,od=36283,cd=36284,ld=36285,dd=36286,Oy=3200,Fy=0,By=1,ji="",Mn="srgb",Ys="srgb-linear",to="linear",ut="srgb",Ks=7680,Ap=519,zy=512,Vy=513,Gy=514,ud=515,Hy=516,Wy=517,hd=518,qy=519,Rp=35044,Pp="300 es",si=2e3,no=2001;function kp(i){for(let e=i.length-1;e>=0;--e)if(i[e]>=65535)return!0;return!1}function io(i){return document.createElementNS("http://www.w3.org/1999/xhtml",i)}function $y(){const i=io("canvas");return i.style.display="block",i}const Ip={};function Dp(...i){const e="THREE."+i.shift();console.log(e,...i)}function Oe(...i){const e="THREE."+i.shift();console.warn(e,...i)}function rt(...i){const e="THREE."+i.shift();console.error(e,...i)}function $r(...i){const e=i.join(" ");e in Ip||(Ip[e]=!0,Oe(...i))}function jy(i,e,t){return new Promise(function(n,s){function r(){switch(i.clientWaitSync(e,i.SYNC_FLUSH_COMMANDS_BIT,0)){case i.WAIT_FAILED:s();break;case i.TIMEOUT_EXPIRED:setTimeout(r,t);break;default:n()}}setTimeout(r,t)})}class Js{addEventListener(e,t){this._listeners===void 0&&(this._listeners={});const n=this._listeners;n[e]===void 0&&(n[e]=[]),n[e].indexOf(t)===-1&&n[e].push(t)}hasEventListener(e,t){const n=this._listeners;return n===void 0?!1:n[e]!==void 0&&n[e].indexOf(t)!==-1}removeEventListener(e,t){const n=this._listeners;if(n===void 0)return;const s=n[e];if(s!==void 0){const r=s.indexOf(t);r!==-1&&s.splice(r,1)}}dispatchEvent(e){const t=this._listeners;if(t===void 0)return;const n=t[e.type];if(n!==void 0){e.target=this;const s=n.slice(0);for(let r=0,a=s.length;r<a;r++)s[r].call(this,e);e.target=null}}}const Zt=["00","01","02","03","04","05","06","07","08","09","0a","0b","0c","0d","0e","0f","10","11","12","13","14","15","16","17","18","19","1a","1b","1c","1d","1e","1f","20","21","22","23","24","25","26","27","28","29","2a","2b","2c","2d","2e","2f","30","31","32","33","34","35","36","37","38","39","3a","3b","3c","3d","3e","3f","40","41","42","43","44","45","46","47","48","49","4a","4b","4c","4d","4e","4f","50","51","52","53","54","55","56","57","58","59","5a","5b","5c","5d","5e","5f","60","61","62","63","64","65","66","67","68","69","6a","6b","6c","6d","6e","6f","70","71","72","73","74","75","76","77","78","79","7a","7b","7c","7d","7e","7f","80","81","82","83","84","85","86","87","88","89","8a","8b","8c","8d","8e","8f","90","91","92","93","94","95","96","97","98","99","9a","9b","9c","9d","9e","9f","a0","a1","a2","a3","a4","a5","a6","a7","a8","a9","aa","ab","ac","ad","ae","af","b0","b1","b2","b3","b4","b5","b6","b7","b8","b9","ba","bb","bc","bd","be","bf","c0","c1","c2","c3","c4","c5","c6","c7","c8","c9","ca","cb","cc","cd","ce","cf","d0","d1","d2","d3","d4","d5","d6","d7","d8","d9","da","db","dc","dd","de","df","e0","e1","e2","e3","e4","e5","e6","e7","e8","e9","ea","eb","ec","ed","ee","ef","f0","f1","f2","f3","f4","f5","f6","f7","f8","f9","fa","fb","fc","fd","fe","ff"],fd=Math.PI/180,pd=180/Math.PI;function jr(){const i=Math.random()*4294967295|0,e=Math.random()*4294967295|0,t=Math.random()*4294967295|0,n=Math.random()*4294967295|0;return(Zt[i&255]+Zt[i>>8&255]+Zt[i>>16&255]+Zt[i>>24&255]+"-"+Zt[e&255]+Zt[e>>8&255]+"-"+Zt[e>>16&15|64]+Zt[e>>24&255]+"-"+Zt[t&63|128]+Zt[t>>8&255]+"-"+Zt[t>>16&255]+Zt[t>>24&255]+Zt[n&255]+Zt[n>>8&255]+Zt[n>>16&255]+Zt[n>>24&255]).toLowerCase()}function et(i,e,t){return Math.max(e,Math.min(t,i))}function Xy(i,e){return(i%e+e)%e}function md(i,e,t){return(1-t)*i+t*e}function Xr(i,e){switch(e.constructor){case Float32Array:return i;case Uint32Array:return i/4294967295;case Uint16Array:return i/65535;case Uint8Array:return i/255;case Int32Array:return Math.max(i/2147483647,-1);case Int16Array:return Math.max(i/32767,-1);case Int8Array:return Math.max(i/127,-1);default:throw new Error("Invalid component type.")}}function fn(i,e){switch(e.constructor){case Float32Array:return i;case Uint32Array:return Math.round(i*4294967295);case Uint16Array:return Math.round(i*65535);case Uint8Array:return Math.round(i*255);case Int32Array:return Math.round(i*2147483647);case Int16Array:return Math.round(i*32767);case Int8Array:return Math.round(i*127);default:throw new Error("Invalid component type.")}}class lt{constructor(e=0,t=0){lt.prototype.isVector2=!0,this.x=e,this.y=t}get width(){return this.x}set width(e){this.x=e}get height(){return this.y}set height(e){this.y=e}set(e,t){return this.x=e,this.y=t,this}setScalar(e){return this.x=e,this.y=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y)}copy(e){return this.x=e.x,this.y=e.y,this}add(e){return this.x+=e.x,this.y+=e.y,this}addScalar(e){return this.x+=e,this.y+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this}subScalar(e){return this.x-=e,this.y-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this}multiply(e){return this.x*=e.x,this.y*=e.y,this}multiplyScalar(e){return this.x*=e,this.y*=e,this}divide(e){return this.x/=e.x,this.y/=e.y,this}divideScalar(e){return this.multiplyScalar(1/e)}applyMatrix3(e){const t=this.x,n=this.y,s=e.elements;return this.x=s[0]*t+s[3]*n+s[6],this.y=s[1]*t+s[4]*n+s[7],this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this}clamp(e,t){return this.x=et(this.x,e.x,t.x),this.y=et(this.y,e.y,t.y),this}clampScalar(e,t){return this.x=et(this.x,e,t),this.y=et(this.y,e,t),this}clampLength(e,t){const n=this.length();return this.divideScalar(n||1).multiplyScalar(et(n,e,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this}negate(){return this.x=-this.x,this.y=-this.y,this}dot(e){return this.x*e.x+this.y*e.y}cross(e){return this.x*e.y-this.y*e.x}lengthSq(){return this.x*this.x+this.y*this.y}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)}normalize(){return this.divideScalar(this.length()||1)}angle(){return Math.atan2(-this.y,-this.x)+Math.PI}angleTo(e){const t=Math.sqrt(this.lengthSq()*e.lengthSq());if(t===0)return Math.PI/2;const n=this.dot(e)/t;return Math.acos(et(n,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){const t=this.x-e.x,n=this.y-e.y;return t*t+n*n}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this}lerpVectors(e,t,n){return this.x=e.x+(t.x-e.x)*n,this.y=e.y+(t.y-e.y)*n,this}equals(e){return e.x===this.x&&e.y===this.y}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this}rotateAround(e,t){const n=Math.cos(t),s=Math.sin(t),r=this.x-e.x,a=this.y-e.y;return this.x=r*n-a*s+e.x,this.y=r*s+a*n+e.y,this}random(){return this.x=Math.random(),this.y=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y}}class Yr{constructor(e=0,t=0,n=0,s=1){this.isQuaternion=!0,this._x=e,this._y=t,this._z=n,this._w=s}static slerpFlat(e,t,n,s,r,a,o){let c=n[s+0],l=n[s+1],d=n[s+2],u=n[s+3],h=r[a+0],f=r[a+1],g=r[a+2],v=r[a+3];if(o<=0){e[t+0]=c,e[t+1]=l,e[t+2]=d,e[t+3]=u;return}if(o>=1){e[t+0]=h,e[t+1]=f,e[t+2]=g,e[t+3]=v;return}if(u!==v||c!==h||l!==f||d!==g){let m=c*h+l*f+d*g+u*v;m<0&&(h=-h,f=-f,g=-g,v=-v,m=-m);let p=1-o;if(m<.9995){const x=Math.acos(m),C=Math.sin(x);p=Math.sin(p*x)/C,o=Math.sin(o*x)/C,c=c*p+h*o,l=l*p+f*o,d=d*p+g*o,u=u*p+v*o}else{c=c*p+h*o,l=l*p+f*o,d=d*p+g*o,u=u*p+v*o;const x=1/Math.sqrt(c*c+l*l+d*d+u*u);c*=x,l*=x,d*=x,u*=x}}e[t]=c,e[t+1]=l,e[t+2]=d,e[t+3]=u}static multiplyQuaternionsFlat(e,t,n,s,r,a){const o=n[s],c=n[s+1],l=n[s+2],d=n[s+3],u=r[a],h=r[a+1],f=r[a+2],g=r[a+3];return e[t]=o*g+d*u+c*f-l*h,e[t+1]=c*g+d*h+l*u-o*f,e[t+2]=l*g+d*f+o*h-c*u,e[t+3]=d*g-o*u-c*h-l*f,e}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get w(){return this._w}set w(e){this._w=e,this._onChangeCallback()}set(e,t,n,s){return this._x=e,this._y=t,this._z=n,this._w=s,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._w)}copy(e){return this._x=e.x,this._y=e.y,this._z=e.z,this._w=e.w,this._onChangeCallback(),this}setFromEuler(e,t=!0){const n=e._x,s=e._y,r=e._z,a=e._order,o=Math.cos,c=Math.sin,l=o(n/2),d=o(s/2),u=o(r/2),h=c(n/2),f=c(s/2),g=c(r/2);switch(a){case"XYZ":this._x=h*d*u+l*f*g,this._y=l*f*u-h*d*g,this._z=l*d*g+h*f*u,this._w=l*d*u-h*f*g;break;case"YXZ":this._x=h*d*u+l*f*g,this._y=l*f*u-h*d*g,this._z=l*d*g-h*f*u,this._w=l*d*u+h*f*g;break;case"ZXY":this._x=h*d*u-l*f*g,this._y=l*f*u+h*d*g,this._z=l*d*g+h*f*u,this._w=l*d*u-h*f*g;break;case"ZYX":this._x=h*d*u-l*f*g,this._y=l*f*u+h*d*g,this._z=l*d*g-h*f*u,this._w=l*d*u+h*f*g;break;case"YZX":this._x=h*d*u+l*f*g,this._y=l*f*u+h*d*g,this._z=l*d*g-h*f*u,this._w=l*d*u-h*f*g;break;case"XZY":this._x=h*d*u-l*f*g,this._y=l*f*u-h*d*g,this._z=l*d*g+h*f*u,this._w=l*d*u+h*f*g;break;default:Oe("Quaternion: .setFromEuler() encountered an unknown order: "+a)}return t===!0&&this._onChangeCallback(),this}setFromAxisAngle(e,t){const n=t/2,s=Math.sin(n);return this._x=e.x*s,this._y=e.y*s,this._z=e.z*s,this._w=Math.cos(n),this._onChangeCallback(),this}setFromRotationMatrix(e){const t=e.elements,n=t[0],s=t[4],r=t[8],a=t[1],o=t[5],c=t[9],l=t[2],d=t[6],u=t[10],h=n+o+u;if(h>0){const f=.5/Math.sqrt(h+1);this._w=.25/f,this._x=(d-c)*f,this._y=(r-l)*f,this._z=(a-s)*f}else if(n>o&&n>u){const f=2*Math.sqrt(1+n-o-u);this._w=(d-c)/f,this._x=.25*f,this._y=(s+a)/f,this._z=(r+l)/f}else if(o>u){const f=2*Math.sqrt(1+o-n-u);this._w=(r-l)/f,this._x=(s+a)/f,this._y=.25*f,this._z=(c+d)/f}else{const f=2*Math.sqrt(1+u-n-o);this._w=(a-s)/f,this._x=(r+l)/f,this._y=(c+d)/f,this._z=.25*f}return this._onChangeCallback(),this}setFromUnitVectors(e,t){let n=e.dot(t)+1;return n<1e-8?(n=0,Math.abs(e.x)>Math.abs(e.z)?(this._x=-e.y,this._y=e.x,this._z=0,this._w=n):(this._x=0,this._y=-e.z,this._z=e.y,this._w=n)):(this._x=e.y*t.z-e.z*t.y,this._y=e.z*t.x-e.x*t.z,this._z=e.x*t.y-e.y*t.x,this._w=n),this.normalize()}angleTo(e){return 2*Math.acos(Math.abs(et(this.dot(e),-1,1)))}rotateTowards(e,t){const n=this.angleTo(e);if(n===0)return this;const s=Math.min(1,t/n);return this.slerp(e,s),this}identity(){return this.set(0,0,0,1)}invert(){return this.conjugate()}conjugate(){return this._x*=-1,this._y*=-1,this._z*=-1,this._onChangeCallback(),this}dot(e){return this._x*e._x+this._y*e._y+this._z*e._z+this._w*e._w}lengthSq(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w}length(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)}normalize(){let e=this.length();return e===0?(this._x=0,this._y=0,this._z=0,this._w=1):(e=1/e,this._x=this._x*e,this._y=this._y*e,this._z=this._z*e,this._w=this._w*e),this._onChangeCallback(),this}multiply(e){return this.multiplyQuaternions(this,e)}premultiply(e){return this.multiplyQuaternions(e,this)}multiplyQuaternions(e,t){const n=e._x,s=e._y,r=e._z,a=e._w,o=t._x,c=t._y,l=t._z,d=t._w;return this._x=n*d+a*o+s*l-r*c,this._y=s*d+a*c+r*o-n*l,this._z=r*d+a*l+n*c-s*o,this._w=a*d-n*o-s*c-r*l,this._onChangeCallback(),this}slerp(e,t){if(t<=0)return this;if(t>=1)return this.copy(e);let n=e._x,s=e._y,r=e._z,a=e._w,o=this.dot(e);o<0&&(n=-n,s=-s,r=-r,a=-a,o=-o);let c=1-t;if(o<.9995){const l=Math.acos(o),d=Math.sin(l);c=Math.sin(c*l)/d,t=Math.sin(t*l)/d,this._x=this._x*c+n*t,this._y=this._y*c+s*t,this._z=this._z*c+r*t,this._w=this._w*c+a*t,this._onChangeCallback()}else this._x=this._x*c+n*t,this._y=this._y*c+s*t,this._z=this._z*c+r*t,this._w=this._w*c+a*t,this.normalize();return this}slerpQuaternions(e,t,n){return this.copy(e).slerp(t,n)}random(){const e=2*Math.PI*Math.random(),t=2*Math.PI*Math.random(),n=Math.random(),s=Math.sqrt(1-n),r=Math.sqrt(n);return this.set(s*Math.sin(e),s*Math.cos(e),r*Math.sin(t),r*Math.cos(t))}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._w===this._w}fromArray(e,t=0){return this._x=e[t],this._y=e[t+1],this._z=e[t+2],this._w=e[t+3],this._onChangeCallback(),this}toArray(e=[],t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._w,e}fromBufferAttribute(e,t){return this._x=e.getX(t),this._y=e.getY(t),this._z=e.getZ(t),this._w=e.getW(t),this._onChangeCallback(),this}toJSON(){return this.toArray()}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._w}}class B{constructor(e=0,t=0,n=0){B.prototype.isVector3=!0,this.x=e,this.y=t,this.z=n}set(e,t,n){return n===void 0&&(n=this.z),this.x=e,this.y=t,this.z=n,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y,this.z)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this}multiplyVectors(e,t){return this.x=e.x*t.x,this.y=e.y*t.y,this.z=e.z*t.z,this}applyEuler(e){return this.applyQuaternion(Lp.setFromEuler(e))}applyAxisAngle(e,t){return this.applyQuaternion(Lp.setFromAxisAngle(e,t))}applyMatrix3(e){const t=this.x,n=this.y,s=this.z,r=e.elements;return this.x=r[0]*t+r[3]*n+r[6]*s,this.y=r[1]*t+r[4]*n+r[7]*s,this.z=r[2]*t+r[5]*n+r[8]*s,this}applyNormalMatrix(e){return this.applyMatrix3(e).normalize()}applyMatrix4(e){const t=this.x,n=this.y,s=this.z,r=e.elements,a=1/(r[3]*t+r[7]*n+r[11]*s+r[15]);return this.x=(r[0]*t+r[4]*n+r[8]*s+r[12])*a,this.y=(r[1]*t+r[5]*n+r[9]*s+r[13])*a,this.z=(r[2]*t+r[6]*n+r[10]*s+r[14])*a,this}applyQuaternion(e){const t=this.x,n=this.y,s=this.z,r=e.x,a=e.y,o=e.z,c=e.w,l=2*(a*s-o*n),d=2*(o*t-r*s),u=2*(r*n-a*t);return this.x=t+c*l+a*u-o*d,this.y=n+c*d+o*l-r*u,this.z=s+c*u+r*d-a*l,this}project(e){return this.applyMatrix4(e.matrixWorldInverse).applyMatrix4(e.projectionMatrix)}unproject(e){return this.applyMatrix4(e.projectionMatrixInverse).applyMatrix4(e.matrixWorld)}transformDirection(e){const t=this.x,n=this.y,s=this.z,r=e.elements;return this.x=r[0]*t+r[4]*n+r[8]*s,this.y=r[1]*t+r[5]*n+r[9]*s,this.z=r[2]*t+r[6]*n+r[10]*s,this.normalize()}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this}divideScalar(e){return this.multiplyScalar(1/e)}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this}clamp(e,t){return this.x=et(this.x,e.x,t.x),this.y=et(this.y,e.y,t.y),this.z=et(this.z,e.z,t.z),this}clampScalar(e,t){return this.x=et(this.x,e,t),this.y=et(this.y,e,t),this.z=et(this.z,e,t),this}clampLength(e,t){const n=this.length();return this.divideScalar(n||1).multiplyScalar(et(n,e,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)}normalize(){return this.divideScalar(this.length()||1)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this.z+=(e.z-this.z)*t,this}lerpVectors(e,t,n){return this.x=e.x+(t.x-e.x)*n,this.y=e.y+(t.y-e.y)*n,this.z=e.z+(t.z-e.z)*n,this}cross(e){return this.crossVectors(this,e)}crossVectors(e,t){const n=e.x,s=e.y,r=e.z,a=t.x,o=t.y,c=t.z;return this.x=s*c-r*o,this.y=r*a-n*c,this.z=n*o-s*a,this}projectOnVector(e){const t=e.lengthSq();if(t===0)return this.set(0,0,0);const n=e.dot(this)/t;return this.copy(e).multiplyScalar(n)}projectOnPlane(e){return gd.copy(this).projectOnVector(e),this.sub(gd)}reflect(e){return this.sub(gd.copy(e).multiplyScalar(2*this.dot(e)))}angleTo(e){const t=Math.sqrt(this.lengthSq()*e.lengthSq());if(t===0)return Math.PI/2;const n=this.dot(e)/t;return Math.acos(et(n,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){const t=this.x-e.x,n=this.y-e.y,s=this.z-e.z;return t*t+n*n+s*s}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)+Math.abs(this.z-e.z)}setFromSpherical(e){return this.setFromSphericalCoords(e.radius,e.phi,e.theta)}setFromSphericalCoords(e,t,n){const s=Math.sin(t)*e;return this.x=s*Math.sin(n),this.y=Math.cos(t)*e,this.z=s*Math.cos(n),this}setFromCylindrical(e){return this.setFromCylindricalCoords(e.radius,e.theta,e.y)}setFromCylindricalCoords(e,t,n){return this.x=e*Math.sin(t),this.y=n,this.z=e*Math.cos(t),this}setFromMatrixPosition(e){const t=e.elements;return this.x=t[12],this.y=t[13],this.z=t[14],this}setFromMatrixScale(e){const t=this.setFromMatrixColumn(e,0).length(),n=this.setFromMatrixColumn(e,1).length(),s=this.setFromMatrixColumn(e,2).length();return this.x=t,this.y=n,this.z=s,this}setFromMatrixColumn(e,t){return this.fromArray(e.elements,t*4)}setFromMatrix3Column(e,t){return this.fromArray(e.elements,t*3)}setFromEuler(e){return this.x=e._x,this.y=e._y,this.z=e._z,this}setFromColor(e){return this.x=e.r,this.y=e.g,this.z=e.b,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this.z=e[t+2],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this.z=e.getZ(t),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this}randomDirection(){const e=Math.random()*Math.PI*2,t=Math.random()*2-1,n=Math.sqrt(1-t*t);return this.x=n*Math.cos(e),this.y=t,this.z=n*Math.sin(e),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z}}const gd=new B,Lp=new Yr;class Ve{constructor(e,t,n,s,r,a,o,c,l){Ve.prototype.isMatrix3=!0,this.elements=[1,0,0,0,1,0,0,0,1],e!==void 0&&this.set(e,t,n,s,r,a,o,c,l)}set(e,t,n,s,r,a,o,c,l){const d=this.elements;return d[0]=e,d[1]=s,d[2]=o,d[3]=t,d[4]=r,d[5]=c,d[6]=n,d[7]=a,d[8]=l,this}identity(){return this.set(1,0,0,0,1,0,0,0,1),this}copy(e){const t=this.elements,n=e.elements;return t[0]=n[0],t[1]=n[1],t[2]=n[2],t[3]=n[3],t[4]=n[4],t[5]=n[5],t[6]=n[6],t[7]=n[7],t[8]=n[8],this}extractBasis(e,t,n){return e.setFromMatrix3Column(this,0),t.setFromMatrix3Column(this,1),n.setFromMatrix3Column(this,2),this}setFromMatrix4(e){const t=e.elements;return this.set(t[0],t[4],t[8],t[1],t[5],t[9],t[2],t[6],t[10]),this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){const n=e.elements,s=t.elements,r=this.elements,a=n[0],o=n[3],c=n[6],l=n[1],d=n[4],u=n[7],h=n[2],f=n[5],g=n[8],v=s[0],m=s[3],p=s[6],x=s[1],C=s[4],b=s[7],S=s[2],M=s[5],A=s[8];return r[0]=a*v+o*x+c*S,r[3]=a*m+o*C+c*M,r[6]=a*p+o*b+c*A,r[1]=l*v+d*x+u*S,r[4]=l*m+d*C+u*M,r[7]=l*p+d*b+u*A,r[2]=h*v+f*x+g*S,r[5]=h*m+f*C+g*M,r[8]=h*p+f*b+g*A,this}multiplyScalar(e){const t=this.elements;return t[0]*=e,t[3]*=e,t[6]*=e,t[1]*=e,t[4]*=e,t[7]*=e,t[2]*=e,t[5]*=e,t[8]*=e,this}determinant(){const e=this.elements,t=e[0],n=e[1],s=e[2],r=e[3],a=e[4],o=e[5],c=e[6],l=e[7],d=e[8];return t*a*d-t*o*l-n*r*d+n*o*c+s*r*l-s*a*c}invert(){const e=this.elements,t=e[0],n=e[1],s=e[2],r=e[3],a=e[4],o=e[5],c=e[6],l=e[7],d=e[8],u=d*a-o*l,h=o*c-d*r,f=l*r-a*c,g=t*u+n*h+s*f;if(g===0)return this.set(0,0,0,0,0,0,0,0,0);const v=1/g;return e[0]=u*v,e[1]=(s*l-d*n)*v,e[2]=(o*n-s*a)*v,e[3]=h*v,e[4]=(d*t-s*c)*v,e[5]=(s*r-o*t)*v,e[6]=f*v,e[7]=(n*c-l*t)*v,e[8]=(a*t-n*r)*v,this}transpose(){let e;const t=this.elements;return e=t[1],t[1]=t[3],t[3]=e,e=t[2],t[2]=t[6],t[6]=e,e=t[5],t[5]=t[7],t[7]=e,this}getNormalMatrix(e){return this.setFromMatrix4(e).invert().transpose()}transposeIntoArray(e){const t=this.elements;return e[0]=t[0],e[1]=t[3],e[2]=t[6],e[3]=t[1],e[4]=t[4],e[5]=t[7],e[6]=t[2],e[7]=t[5],e[8]=t[8],this}setUvTransform(e,t,n,s,r,a,o){const c=Math.cos(r),l=Math.sin(r);return this.set(n*c,n*l,-n*(c*a+l*o)+a+e,-s*l,s*c,-s*(-l*a+c*o)+o+t,0,0,1),this}scale(e,t){return this.premultiply(vd.makeScale(e,t)),this}rotate(e){return this.premultiply(vd.makeRotation(-e)),this}translate(e,t){return this.premultiply(vd.makeTranslation(e,t)),this}makeTranslation(e,t){return e.isVector2?this.set(1,0,e.x,0,1,e.y,0,0,1):this.set(1,0,e,0,1,t,0,0,1),this}makeRotation(e){const t=Math.cos(e),n=Math.sin(e);return this.set(t,-n,0,n,t,0,0,0,1),this}makeScale(e,t){return this.set(e,0,0,0,t,0,0,0,1),this}equals(e){const t=this.elements,n=e.elements;for(let s=0;s<9;s++)if(t[s]!==n[s])return!1;return!0}fromArray(e,t=0){for(let n=0;n<9;n++)this.elements[n]=e[n+t];return this}toArray(e=[],t=0){const n=this.elements;return e[t]=n[0],e[t+1]=n[1],e[t+2]=n[2],e[t+3]=n[3],e[t+4]=n[4],e[t+5]=n[5],e[t+6]=n[6],e[t+7]=n[7],e[t+8]=n[8],e}clone(){return new this.constructor().fromArray(this.elements)}}const vd=new Ve,Up=new Ve().set(.4123908,.3575843,.1804808,.212639,.7151687,.0721923,.0193308,.1191948,.9505322),Np=new Ve().set(3.2409699,-1.5373832,-.4986108,-.9692436,1.8759675,.0415551,.0556301,-.203977,1.0569715);function Yy(){const i={enabled:!0,workingColorSpace:Ys,spaces:{},convert:function(s,r,a){return this.enabled===!1||r===a||!r||!a||(this.spaces[r].transfer===ut&&(s.r=Ei(s.r),s.g=Ei(s.g),s.b=Ei(s.b)),this.spaces[r].primaries!==this.spaces[a].primaries&&(s.applyMatrix3(this.spaces[r].toXYZ),s.applyMatrix3(this.spaces[a].fromXYZ)),this.spaces[a].transfer===ut&&(s.r=Zs(s.r),s.g=Zs(s.g),s.b=Zs(s.b))),s},workingToColorSpace:function(s,r){return this.convert(s,this.workingColorSpace,r)},colorSpaceToWorking:function(s,r){return this.convert(s,r,this.workingColorSpace)},getPrimaries:function(s){return this.spaces[s].primaries},getTransfer:function(s){return s===ji?to:this.spaces[s].transfer},getToneMappingMode:function(s){return this.spaces[s].outputColorSpaceConfig.toneMappingMode||"standard"},getLuminanceCoefficients:function(s,r=this.workingColorSpace){return s.fromArray(this.spaces[r].luminanceCoefficients)},define:function(s){Object.assign(this.spaces,s)},_getMatrix:function(s,r,a){return s.copy(this.spaces[r].toXYZ).multiply(this.spaces[a].fromXYZ)},_getDrawingBufferColorSpace:function(s){return this.spaces[s].outputColorSpaceConfig.drawingBufferColorSpace},_getUnpackColorSpace:function(s=this.workingColorSpace){return this.spaces[s].workingColorSpaceConfig.unpackColorSpace},fromWorkingColorSpace:function(s,r){return $r("ColorManagement: .fromWorkingColorSpace() has been renamed to .workingToColorSpace()."),i.workingToColorSpace(s,r)},toWorkingColorSpace:function(s,r){return $r("ColorManagement: .toWorkingColorSpace() has been renamed to .colorSpaceToWorking()."),i.colorSpaceToWorking(s,r)}},e=[.64,.33,.3,.6,.15,.06],t=[.2126,.7152,.0722],n=[.3127,.329];return i.define({[Ys]:{primaries:e,whitePoint:n,transfer:to,toXYZ:Up,fromXYZ:Np,luminanceCoefficients:t,workingColorSpaceConfig:{unpackColorSpace:Mn},outputColorSpaceConfig:{drawingBufferColorSpace:Mn}},[Mn]:{primaries:e,whitePoint:n,transfer:ut,toXYZ:Up,fromXYZ:Np,luminanceCoefficients:t,outputColorSpaceConfig:{drawingBufferColorSpace:Mn}}}),i}const it=Yy();function Ei(i){return i<.04045?i*.0773993808:Math.pow(i*.9478672986+.0521327014,2.4)}function Zs(i){return i<.0031308?i*12.92:1.055*Math.pow(i,.41666)-.055}let Qs;class Ky{static getDataURL(e,t="image/png"){if(/^data:/i.test(e.src)||typeof HTMLCanvasElement>"u")return e.src;let n;if(e instanceof HTMLCanvasElement)n=e;else{Qs===void 0&&(Qs=io("canvas")),Qs.width=e.width,Qs.height=e.height;const s=Qs.getContext("2d");e instanceof ImageData?s.putImageData(e,0,0):s.drawImage(e,0,0,e.width,e.height),n=Qs}return n.toDataURL(t)}static sRGBToLinear(e){if(typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&e instanceof ImageBitmap){const t=io("canvas");t.width=e.width,t.height=e.height;const n=t.getContext("2d");n.drawImage(e,0,0,e.width,e.height);const s=n.getImageData(0,0,e.width,e.height),r=s.data;for(let a=0;a<r.length;a++)r[a]=Ei(r[a]/255)*255;return n.putImageData(s,0,0),t}else if(e.data){const t=e.data.slice(0);for(let n=0;n<t.length;n++)t instanceof Uint8Array||t instanceof Uint8ClampedArray?t[n]=Math.floor(Ei(t[n]/255)*255):t[n]=Ei(t[n]);return{data:t,width:e.width,height:e.height}}else return Oe("ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied."),e}}let Jy=0;class bd{constructor(e=null){this.isSource=!0,Object.defineProperty(this,"id",{value:Jy++}),this.uuid=jr(),this.data=e,this.dataReady=!0,this.version=0}getSize(e){const t=this.data;return typeof HTMLVideoElement<"u"&&t instanceof HTMLVideoElement?e.set(t.videoWidth,t.videoHeight,0):typeof VideoFrame<"u"&&t instanceof VideoFrame?e.set(t.displayHeight,t.displayWidth,0):t!==null?e.set(t.width,t.height,t.depth||0):e.set(0,0,0),e}set needsUpdate(e){e===!0&&this.version++}toJSON(e){const t=e===void 0||typeof e=="string";if(!t&&e.images[this.uuid]!==void 0)return e.images[this.uuid];const n={uuid:this.uuid,url:""},s=this.data;if(s!==null){let r;if(Array.isArray(s)){r=[];for(let a=0,o=s.length;a<o;a++)s[a].isDataTexture?r.push(yd(s[a].image)):r.push(yd(s[a]))}else r=yd(s);n.url=r}return t||(e.images[this.uuid]=n),n}}function yd(i){return typeof HTMLImageElement<"u"&&i instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&i instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&i instanceof ImageBitmap?Ky.getDataURL(i):i.data?{data:Array.from(i.data),width:i.width,height:i.height,type:i.data.constructor.name}:(Oe("Texture: Unable to serialize Texture."),{})}let Zy=0;const _d=new B;class tn extends Js{constructor(e=tn.DEFAULT_IMAGE,t=tn.DEFAULT_MAPPING,n=xi,s=xi,r=Jt,a=fs,o=Bn,c=En,l=tn.DEFAULT_ANISOTROPY,d=ji){super(),this.isTexture=!0,Object.defineProperty(this,"id",{value:Zy++}),this.uuid=jr(),this.name="",this.source=new bd(e),this.mipmaps=[],this.mapping=t,this.channel=0,this.wrapS=n,this.wrapT=s,this.magFilter=r,this.minFilter=a,this.anisotropy=l,this.format=o,this.internalFormat=null,this.type=c,this.offset=new lt(0,0),this.repeat=new lt(1,1),this.center=new lt(0,0),this.rotation=0,this.matrixAutoUpdate=!0,this.matrix=new Ve,this.generateMipmaps=!0,this.premultiplyAlpha=!1,this.flipY=!0,this.unpackAlignment=4,this.colorSpace=d,this.userData={},this.updateRanges=[],this.version=0,this.onUpdate=null,this.renderTarget=null,this.isRenderTargetTexture=!1,this.isArrayTexture=!!(e&&e.depth&&e.depth>1),this.pmremVersion=0}get width(){return this.source.getSize(_d).x}get height(){return this.source.getSize(_d).y}get depth(){return this.source.getSize(_d).z}get image(){return this.source.data}set image(e=null){this.source.data=e}updateMatrix(){this.matrix.setUvTransform(this.offset.x,this.offset.y,this.repeat.x,this.repeat.y,this.rotation,this.center.x,this.center.y)}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}clone(){return new this.constructor().copy(this)}copy(e){return this.name=e.name,this.source=e.source,this.mipmaps=e.mipmaps.slice(0),this.mapping=e.mapping,this.channel=e.channel,this.wrapS=e.wrapS,this.wrapT=e.wrapT,this.magFilter=e.magFilter,this.minFilter=e.minFilter,this.anisotropy=e.anisotropy,this.format=e.format,this.internalFormat=e.internalFormat,this.type=e.type,this.offset.copy(e.offset),this.repeat.copy(e.repeat),this.center.copy(e.center),this.rotation=e.rotation,this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrix.copy(e.matrix),this.generateMipmaps=e.generateMipmaps,this.premultiplyAlpha=e.premultiplyAlpha,this.flipY=e.flipY,this.unpackAlignment=e.unpackAlignment,this.colorSpace=e.colorSpace,this.renderTarget=e.renderTarget,this.isRenderTargetTexture=e.isRenderTargetTexture,this.isArrayTexture=e.isArrayTexture,this.userData=JSON.parse(JSON.stringify(e.userData)),this.needsUpdate=!0,this}setValues(e){for(const t in e){const n=e[t];if(n===void 0){Oe(`Texture.setValues(): parameter '${t}' has value of undefined.`);continue}const s=this[t];if(s===void 0){Oe(`Texture.setValues(): property '${t}' does not exist.`);continue}s&&n&&s.isVector2&&n.isVector2||s&&n&&s.isVector3&&n.isVector3||s&&n&&s.isMatrix3&&n.isMatrix3?s.copy(n):this[t]=n}}toJSON(e){const t=e===void 0||typeof e=="string";if(!t&&e.textures[this.uuid]!==void 0)return e.textures[this.uuid];const n={metadata:{version:4.7,type:"Texture",generator:"Texture.toJSON"},uuid:this.uuid,name:this.name,image:this.source.toJSON(e).uuid,mapping:this.mapping,channel:this.channel,repeat:[this.repeat.x,this.repeat.y],offset:[this.offset.x,this.offset.y],center:[this.center.x,this.center.y],rotation:this.rotation,wrap:[this.wrapS,this.wrapT],format:this.format,internalFormat:this.internalFormat,type:this.type,colorSpace:this.colorSpace,minFilter:this.minFilter,magFilter:this.magFilter,anisotropy:this.anisotropy,flipY:this.flipY,generateMipmaps:this.generateMipmaps,premultiplyAlpha:this.premultiplyAlpha,unpackAlignment:this.unpackAlignment};return Object.keys(this.userData).length>0&&(n.userData=this.userData),t||(e.textures[this.uuid]=n),n}dispose(){this.dispatchEvent({type:"dispose"})}transformUv(e){if(this.mapping!==_p)return e;if(e.applyMatrix3(this.matrix),e.x<0||e.x>1)switch(this.wrapS){case Cl:e.x=e.x-Math.floor(e.x);break;case xi:e.x=e.x<0?0:1;break;case El:Math.abs(Math.floor(e.x)%2)===1?e.x=Math.ceil(e.x)-e.x:e.x=e.x-Math.floor(e.x);break}if(e.y<0||e.y>1)switch(this.wrapT){case Cl:e.y=e.y-Math.floor(e.y);break;case xi:e.y=e.y<0?0:1;break;case El:Math.abs(Math.floor(e.y)%2)===1?e.y=Math.ceil(e.y)-e.y:e.y=e.y-Math.floor(e.y);break}return this.flipY&&(e.y=1-e.y),e}set needsUpdate(e){e===!0&&(this.version++,this.source.needsUpdate=!0)}set needsPMREMUpdate(e){e===!0&&this.pmremVersion++}}tn.DEFAULT_IMAGE=null,tn.DEFAULT_MAPPING=_p,tn.DEFAULT_ANISOTROPY=1;class Ut{constructor(e=0,t=0,n=0,s=1){Ut.prototype.isVector4=!0,this.x=e,this.y=t,this.z=n,this.w=s}get width(){return this.z}set width(e){this.z=e}get height(){return this.w}set height(e){this.w=e}set(e,t,n,s){return this.x=e,this.y=t,this.z=n,this.w=s,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this.w=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setW(e){return this.w=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;case 3:this.w=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;case 3:return this.w;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y,this.z,this.w)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this.w=e.w!==void 0?e.w:1,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this.w+=e.w,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this.w+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this.w=e.w+t.w,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this.w+=e.w*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this.w-=e.w,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this.w-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this.w=e.w-t.w,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this.w*=e.w,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this.w*=e,this}applyMatrix4(e){const t=this.x,n=this.y,s=this.z,r=this.w,a=e.elements;return this.x=a[0]*t+a[4]*n+a[8]*s+a[12]*r,this.y=a[1]*t+a[5]*n+a[9]*s+a[13]*r,this.z=a[2]*t+a[6]*n+a[10]*s+a[14]*r,this.w=a[3]*t+a[7]*n+a[11]*s+a[15]*r,this}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this.w/=e.w,this}divideScalar(e){return this.multiplyScalar(1/e)}setAxisAngleFromQuaternion(e){this.w=2*Math.acos(e.w);const t=Math.sqrt(1-e.w*e.w);return t<1e-4?(this.x=1,this.y=0,this.z=0):(this.x=e.x/t,this.y=e.y/t,this.z=e.z/t),this}setAxisAngleFromRotationMatrix(e){let t,n,s,r;const c=e.elements,l=c[0],d=c[4],u=c[8],h=c[1],f=c[5],g=c[9],v=c[2],m=c[6],p=c[10];if(Math.abs(d-h)<.01&&Math.abs(u-v)<.01&&Math.abs(g-m)<.01){if(Math.abs(d+h)<.1&&Math.abs(u+v)<.1&&Math.abs(g+m)<.1&&Math.abs(l+f+p-3)<.1)return this.set(1,0,0,0),this;t=Math.PI;const C=(l+1)/2,b=(f+1)/2,S=(p+1)/2,M=(d+h)/4,A=(u+v)/4,k=(g+m)/4;return C>b&&C>S?C<.01?(n=0,s=.707106781,r=.707106781):(n=Math.sqrt(C),s=M/n,r=A/n):b>S?b<.01?(n=.707106781,s=0,r=.707106781):(s=Math.sqrt(b),n=M/s,r=k/s):S<.01?(n=.707106781,s=.707106781,r=0):(r=Math.sqrt(S),n=A/r,s=k/r),this.set(n,s,r,t),this}let x=Math.sqrt((m-g)*(m-g)+(u-v)*(u-v)+(h-d)*(h-d));return Math.abs(x)<.001&&(x=1),this.x=(m-g)/x,this.y=(u-v)/x,this.z=(h-d)/x,this.w=Math.acos((l+f+p-1)/2),this}setFromMatrixPosition(e){const t=e.elements;return this.x=t[12],this.y=t[13],this.z=t[14],this.w=t[15],this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this.w=Math.min(this.w,e.w),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this.w=Math.max(this.w,e.w),this}clamp(e,t){return this.x=et(this.x,e.x,t.x),this.y=et(this.y,e.y,t.y),this.z=et(this.z,e.z,t.z),this.w=et(this.w,e.w,t.w),this}clampScalar(e,t){return this.x=et(this.x,e,t),this.y=et(this.y,e,t),this.z=et(this.z,e,t),this.w=et(this.w,e,t),this}clampLength(e,t){const n=this.length();return this.divideScalar(n||1).multiplyScalar(et(n,e,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this.w=Math.floor(this.w),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this.w=Math.ceil(this.w),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this.w=Math.round(this.w),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this.w=Math.trunc(this.w),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this.w=-this.w,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z+this.w*e.w}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)+Math.abs(this.w)}normalize(){return this.divideScalar(this.length()||1)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this.z+=(e.z-this.z)*t,this.w+=(e.w-this.w)*t,this}lerpVectors(e,t,n){return this.x=e.x+(t.x-e.x)*n,this.y=e.y+(t.y-e.y)*n,this.z=e.z+(t.z-e.z)*n,this.w=e.w+(t.w-e.w)*n,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z&&e.w===this.w}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this.z=e[t+2],this.w=e[t+3],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e[t+3]=this.w,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this.z=e.getZ(t),this.w=e.getW(t),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this.w=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z,yield this.w}}class Qy extends Js{constructor(e=1,t=1,n={}){super(),n=Object.assign({generateMipmaps:!1,internalFormat:null,minFilter:Jt,depthBuffer:!0,stencilBuffer:!1,resolveDepthBuffer:!0,resolveStencilBuffer:!0,depthTexture:null,samples:0,count:1,depth:1,multiview:!1},n),this.isRenderTarget=!0,this.width=e,this.height=t,this.depth=n.depth,this.scissor=new Ut(0,0,e,t),this.scissorTest=!1,this.viewport=new Ut(0,0,e,t);const s={width:e,height:t,depth:n.depth},r=new tn(s);this.textures=[];const a=n.count;for(let o=0;o<a;o++)this.textures[o]=r.clone(),this.textures[o].isRenderTargetTexture=!0,this.textures[o].renderTarget=this;this._setTextureOptions(n),this.depthBuffer=n.depthBuffer,this.stencilBuffer=n.stencilBuffer,this.resolveDepthBuffer=n.resolveDepthBuffer,this.resolveStencilBuffer=n.resolveStencilBuffer,this._depthTexture=null,this.depthTexture=n.depthTexture,this.samples=n.samples,this.multiview=n.multiview}_setTextureOptions(e={}){const t={minFilter:Jt,generateMipmaps:!1,flipY:!1,internalFormat:null};e.mapping!==void 0&&(t.mapping=e.mapping),e.wrapS!==void 0&&(t.wrapS=e.wrapS),e.wrapT!==void 0&&(t.wrapT=e.wrapT),e.wrapR!==void 0&&(t.wrapR=e.wrapR),e.magFilter!==void 0&&(t.magFilter=e.magFilter),e.minFilter!==void 0&&(t.minFilter=e.minFilter),e.format!==void 0&&(t.format=e.format),e.type!==void 0&&(t.type=e.type),e.anisotropy!==void 0&&(t.anisotropy=e.anisotropy),e.colorSpace!==void 0&&(t.colorSpace=e.colorSpace),e.flipY!==void 0&&(t.flipY=e.flipY),e.generateMipmaps!==void 0&&(t.generateMipmaps=e.generateMipmaps),e.internalFormat!==void 0&&(t.internalFormat=e.internalFormat);for(let n=0;n<this.textures.length;n++)this.textures[n].setValues(t)}get texture(){return this.textures[0]}set texture(e){this.textures[0]=e}set depthTexture(e){this._depthTexture!==null&&(this._depthTexture.renderTarget=null),e!==null&&(e.renderTarget=this),this._depthTexture=e}get depthTexture(){return this._depthTexture}setSize(e,t,n=1){if(this.width!==e||this.height!==t||this.depth!==n){this.width=e,this.height=t,this.depth=n;for(let s=0,r=this.textures.length;s<r;s++)this.textures[s].image.width=e,this.textures[s].image.height=t,this.textures[s].image.depth=n,this.textures[s].isData3DTexture!==!0&&(this.textures[s].isArrayTexture=this.textures[s].image.depth>1);this.dispose()}this.viewport.set(0,0,e,t),this.scissor.set(0,0,e,t)}clone(){return new this.constructor().copy(this)}copy(e){this.width=e.width,this.height=e.height,this.depth=e.depth,this.scissor.copy(e.scissor),this.scissorTest=e.scissorTest,this.viewport.copy(e.viewport),this.textures.length=0;for(let t=0,n=e.textures.length;t<n;t++){this.textures[t]=e.textures[t].clone(),this.textures[t].isRenderTargetTexture=!0,this.textures[t].renderTarget=this;const s=Object.assign({},e.textures[t].image);this.textures[t].source=new bd(s)}return this.depthBuffer=e.depthBuffer,this.stencilBuffer=e.stencilBuffer,this.resolveDepthBuffer=e.resolveDepthBuffer,this.resolveStencilBuffer=e.resolveStencilBuffer,e.depthTexture!==null&&(this.depthTexture=e.depthTexture.clone()),this.samples=e.samples,this}dispose(){this.dispatchEvent({type:"dispose"})}}class ri extends Qy{constructor(e=1,t=1,n={}){super(e,t,n),this.isWebGLRenderTarget=!0}}class Op extends tn{constructor(e=null,t=1,n=1,s=1){super(null),this.isDataArrayTexture=!0,this.image={data:e,width:t,height:n,depth:s},this.magFilter=Kt,this.minFilter=Kt,this.wrapR=xi,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1,this.layerUpdates=new Set}addLayerUpdate(e){this.layerUpdates.add(e)}clearLayerUpdates(){this.layerUpdates.clear()}}class e_ extends tn{constructor(e=null,t=1,n=1,s=1){super(null),this.isData3DTexture=!0,this.image={data:e,width:t,height:n,depth:s},this.magFilter=Kt,this.minFilter=Kt,this.wrapR=xi,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}}class Kr{constructor(e=new B(1/0,1/0,1/0),t=new B(-1/0,-1/0,-1/0)){this.isBox3=!0,this.min=e,this.max=t}set(e,t){return this.min.copy(e),this.max.copy(t),this}setFromArray(e){this.makeEmpty();for(let t=0,n=e.length;t<n;t+=3)this.expandByPoint(zn.fromArray(e,t));return this}setFromBufferAttribute(e){this.makeEmpty();for(let t=0,n=e.count;t<n;t++)this.expandByPoint(zn.fromBufferAttribute(e,t));return this}setFromPoints(e){this.makeEmpty();for(let t=0,n=e.length;t<n;t++)this.expandByPoint(e[t]);return this}setFromCenterAndSize(e,t){const n=zn.copy(t).multiplyScalar(.5);return this.min.copy(e).sub(n),this.max.copy(e).add(n),this}setFromObject(e,t=!1){return this.makeEmpty(),this.expandByObject(e,t)}clone(){return new this.constructor().copy(this)}copy(e){return this.min.copy(e.min),this.max.copy(e.max),this}makeEmpty(){return this.min.x=this.min.y=this.min.z=1/0,this.max.x=this.max.y=this.max.z=-1/0,this}isEmpty(){return this.max.x<this.min.x||this.max.y<this.min.y||this.max.z<this.min.z}getCenter(e){return this.isEmpty()?e.set(0,0,0):e.addVectors(this.min,this.max).multiplyScalar(.5)}getSize(e){return this.isEmpty()?e.set(0,0,0):e.subVectors(this.max,this.min)}expandByPoint(e){return this.min.min(e),this.max.max(e),this}expandByVector(e){return this.min.sub(e),this.max.add(e),this}expandByScalar(e){return this.min.addScalar(-e),this.max.addScalar(e),this}expandByObject(e,t=!1){e.updateWorldMatrix(!1,!1);const n=e.geometry;if(n!==void 0){const r=n.getAttribute("position");if(t===!0&&r!==void 0&&e.isInstancedMesh!==!0)for(let a=0,o=r.count;a<o;a++)e.isMesh===!0?e.getVertexPosition(a,zn):zn.fromBufferAttribute(r,a),zn.applyMatrix4(e.matrixWorld),this.expandByPoint(zn);else e.boundingBox!==void 0?(e.boundingBox===null&&e.computeBoundingBox(),so.copy(e.boundingBox)):(n.boundingBox===null&&n.computeBoundingBox(),so.copy(n.boundingBox)),so.applyMatrix4(e.matrixWorld),this.union(so)}const s=e.children;for(let r=0,a=s.length;r<a;r++)this.expandByObject(s[r],t);return this}containsPoint(e){return e.x>=this.min.x&&e.x<=this.max.x&&e.y>=this.min.y&&e.y<=this.max.y&&e.z>=this.min.z&&e.z<=this.max.z}containsBox(e){return this.min.x<=e.min.x&&e.max.x<=this.max.x&&this.min.y<=e.min.y&&e.max.y<=this.max.y&&this.min.z<=e.min.z&&e.max.z<=this.max.z}getParameter(e,t){return t.set((e.x-this.min.x)/(this.max.x-this.min.x),(e.y-this.min.y)/(this.max.y-this.min.y),(e.z-this.min.z)/(this.max.z-this.min.z))}intersectsBox(e){return e.max.x>=this.min.x&&e.min.x<=this.max.x&&e.max.y>=this.min.y&&e.min.y<=this.max.y&&e.max.z>=this.min.z&&e.min.z<=this.max.z}intersectsSphere(e){return this.clampPoint(e.center,zn),zn.distanceToSquared(e.center)<=e.radius*e.radius}intersectsPlane(e){let t,n;return e.normal.x>0?(t=e.normal.x*this.min.x,n=e.normal.x*this.max.x):(t=e.normal.x*this.max.x,n=e.normal.x*this.min.x),e.normal.y>0?(t+=e.normal.y*this.min.y,n+=e.normal.y*this.max.y):(t+=e.normal.y*this.max.y,n+=e.normal.y*this.min.y),e.normal.z>0?(t+=e.normal.z*this.min.z,n+=e.normal.z*this.max.z):(t+=e.normal.z*this.max.z,n+=e.normal.z*this.min.z),t<=-e.constant&&n>=-e.constant}intersectsTriangle(e){if(this.isEmpty())return!1;this.getCenter(Jr),ro.subVectors(this.max,Jr),er.subVectors(e.a,Jr),tr.subVectors(e.b,Jr),nr.subVectors(e.c,Jr),Xi.subVectors(tr,er),Yi.subVectors(nr,tr),ms.subVectors(er,nr);let t=[0,-Xi.z,Xi.y,0,-Yi.z,Yi.y,0,-ms.z,ms.y,Xi.z,0,-Xi.x,Yi.z,0,-Yi.x,ms.z,0,-ms.x,-Xi.y,Xi.x,0,-Yi.y,Yi.x,0,-ms.y,ms.x,0];return!Sd(t,er,tr,nr,ro)||(t=[1,0,0,0,1,0,0,0,1],!Sd(t,er,tr,nr,ro))?!1:(ao.crossVectors(Xi,Yi),t=[ao.x,ao.y,ao.z],Sd(t,er,tr,nr,ro))}clampPoint(e,t){return t.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,zn).distanceTo(e)}getBoundingSphere(e){return this.isEmpty()?e.makeEmpty():(this.getCenter(e.center),e.radius=this.getSize(zn).length()*.5),e}intersect(e){return this.min.max(e.min),this.max.min(e.max),this.isEmpty()&&this.makeEmpty(),this}union(e){return this.min.min(e.min),this.max.max(e.max),this}applyMatrix4(e){return this.isEmpty()?this:(Mi[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(e),Mi[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(e),Mi[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(e),Mi[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(e),Mi[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(e),Mi[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(e),Mi[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(e),Mi[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(e),this.setFromPoints(Mi),this)}translate(e){return this.min.add(e),this.max.add(e),this}equals(e){return e.min.equals(this.min)&&e.max.equals(this.max)}toJSON(){return{min:this.min.toArray(),max:this.max.toArray()}}fromJSON(e){return this.min.fromArray(e.min),this.max.fromArray(e.max),this}}const Mi=[new B,new B,new B,new B,new B,new B,new B,new B],zn=new B,so=new Kr,er=new B,tr=new B,nr=new B,Xi=new B,Yi=new B,ms=new B,Jr=new B,ro=new B,ao=new B,gs=new B;function Sd(i,e,t,n,s){for(let r=0,a=i.length-3;r<=a;r+=3){gs.fromArray(i,r);const o=s.x*Math.abs(gs.x)+s.y*Math.abs(gs.y)+s.z*Math.abs(gs.z),c=e.dot(gs),l=t.dot(gs),d=n.dot(gs);if(Math.max(-Math.max(c,l,d),Math.min(c,l,d))>o)return!1}return!0}const t_=new Kr,Zr=new B,xd=new B;class Td{constructor(e=new B,t=-1){this.isSphere=!0,this.center=e,this.radius=t}set(e,t){return this.center.copy(e),this.radius=t,this}setFromPoints(e,t){const n=this.center;t!==void 0?n.copy(t):t_.setFromPoints(e).getCenter(n);let s=0;for(let r=0,a=e.length;r<a;r++)s=Math.max(s,n.distanceToSquared(e[r]));return this.radius=Math.sqrt(s),this}copy(e){return this.center.copy(e.center),this.radius=e.radius,this}isEmpty(){return this.radius<0}makeEmpty(){return this.center.set(0,0,0),this.radius=-1,this}containsPoint(e){return e.distanceToSquared(this.center)<=this.radius*this.radius}distanceToPoint(e){return e.distanceTo(this.center)-this.radius}intersectsSphere(e){const t=this.radius+e.radius;return e.center.distanceToSquared(this.center)<=t*t}intersectsBox(e){return e.intersectsSphere(this)}intersectsPlane(e){return Math.abs(e.distanceToPoint(this.center))<=this.radius}clampPoint(e,t){const n=this.center.distanceToSquared(e);return t.copy(e),n>this.radius*this.radius&&(t.sub(this.center).normalize(),t.multiplyScalar(this.radius).add(this.center)),t}getBoundingBox(e){return this.isEmpty()?(e.makeEmpty(),e):(e.set(this.center,this.center),e.expandByScalar(this.radius),e)}applyMatrix4(e){return this.center.applyMatrix4(e),this.radius=this.radius*e.getMaxScaleOnAxis(),this}translate(e){return this.center.add(e),this}expandByPoint(e){if(this.isEmpty())return this.center.copy(e),this.radius=0,this;Zr.subVectors(e,this.center);const t=Zr.lengthSq();if(t>this.radius*this.radius){const n=Math.sqrt(t),s=(n-this.radius)*.5;this.center.addScaledVector(Zr,s/n),this.radius+=s}return this}union(e){return e.isEmpty()?this:this.isEmpty()?(this.copy(e),this):(this.center.equals(e.center)===!0?this.radius=Math.max(this.radius,e.radius):(xd.subVectors(e.center,this.center).setLength(e.radius),this.expandByPoint(Zr.copy(e.center).add(xd)),this.expandByPoint(Zr.copy(e.center).sub(xd))),this)}equals(e){return e.center.equals(this.center)&&e.radius===this.radius}clone(){return new this.constructor().copy(this)}toJSON(){return{radius:this.radius,center:this.center.toArray()}}fromJSON(e){return this.radius=e.radius,this.center.fromArray(e.center),this}}const wi=new B,Cd=new B,oo=new B,Ki=new B,Ed=new B,co=new B,Md=new B;class n_{constructor(e=new B,t=new B(0,0,-1)){this.origin=e,this.direction=t}set(e,t){return this.origin.copy(e),this.direction.copy(t),this}copy(e){return this.origin.copy(e.origin),this.direction.copy(e.direction),this}at(e,t){return t.copy(this.origin).addScaledVector(this.direction,e)}lookAt(e){return this.direction.copy(e).sub(this.origin).normalize(),this}recast(e){return this.origin.copy(this.at(e,wi)),this}closestPointToPoint(e,t){t.subVectors(e,this.origin);const n=t.dot(this.direction);return n<0?t.copy(this.origin):t.copy(this.origin).addScaledVector(this.direction,n)}distanceToPoint(e){return Math.sqrt(this.distanceSqToPoint(e))}distanceSqToPoint(e){const t=wi.subVectors(e,this.origin).dot(this.direction);return t<0?this.origin.distanceToSquared(e):(wi.copy(this.origin).addScaledVector(this.direction,t),wi.distanceToSquared(e))}distanceSqToSegment(e,t,n,s){Cd.copy(e).add(t).multiplyScalar(.5),oo.copy(t).sub(e).normalize(),Ki.copy(this.origin).sub(Cd);const r=e.distanceTo(t)*.5,a=-this.direction.dot(oo),o=Ki.dot(this.direction),c=-Ki.dot(oo),l=Ki.lengthSq(),d=Math.abs(1-a*a);let u,h,f,g;if(d>0)if(u=a*c-o,h=a*o-c,g=r*d,u>=0)if(h>=-g)if(h<=g){const v=1/d;u*=v,h*=v,f=u*(u+a*h+2*o)+h*(a*u+h+2*c)+l}else h=r,u=Math.max(0,-(a*h+o)),f=-u*u+h*(h+2*c)+l;else h=-r,u=Math.max(0,-(a*h+o)),f=-u*u+h*(h+2*c)+l;else h<=-g?(u=Math.max(0,-(-a*r+o)),h=u>0?-r:Math.min(Math.max(-r,-c),r),f=-u*u+h*(h+2*c)+l):h<=g?(u=0,h=Math.min(Math.max(-r,-c),r),f=h*(h+2*c)+l):(u=Math.max(0,-(a*r+o)),h=u>0?r:Math.min(Math.max(-r,-c),r),f=-u*u+h*(h+2*c)+l);else h=a>0?-r:r,u=Math.max(0,-(a*h+o)),f=-u*u+h*(h+2*c)+l;return n&&n.copy(this.origin).addScaledVector(this.direction,u),s&&s.copy(Cd).addScaledVector(oo,h),f}intersectSphere(e,t){wi.subVectors(e.center,this.origin);const n=wi.dot(this.direction),s=wi.dot(wi)-n*n,r=e.radius*e.radius;if(s>r)return null;const a=Math.sqrt(r-s),o=n-a,c=n+a;return c<0?null:o<0?this.at(c,t):this.at(o,t)}intersectsSphere(e){return e.radius<0?!1:this.distanceSqToPoint(e.center)<=e.radius*e.radius}distanceToPlane(e){const t=e.normal.dot(this.direction);if(t===0)return e.distanceToPoint(this.origin)===0?0:null;const n=-(this.origin.dot(e.normal)+e.constant)/t;return n>=0?n:null}intersectPlane(e,t){const n=this.distanceToPlane(e);return n===null?null:this.at(n,t)}intersectsPlane(e){const t=e.distanceToPoint(this.origin);return t===0||e.normal.dot(this.direction)*t<0}intersectBox(e,t){let n,s,r,a,o,c;const l=1/this.direction.x,d=1/this.direction.y,u=1/this.direction.z,h=this.origin;return l>=0?(n=(e.min.x-h.x)*l,s=(e.max.x-h.x)*l):(n=(e.max.x-h.x)*l,s=(e.min.x-h.x)*l),d>=0?(r=(e.min.y-h.y)*d,a=(e.max.y-h.y)*d):(r=(e.max.y-h.y)*d,a=(e.min.y-h.y)*d),n>a||r>s||((r>n||isNaN(n))&&(n=r),(a<s||isNaN(s))&&(s=a),u>=0?(o=(e.min.z-h.z)*u,c=(e.max.z-h.z)*u):(o=(e.max.z-h.z)*u,c=(e.min.z-h.z)*u),n>c||o>s)||((o>n||n!==n)&&(n=o),(c<s||s!==s)&&(s=c),s<0)?null:this.at(n>=0?n:s,t)}intersectsBox(e){return this.intersectBox(e,wi)!==null}intersectTriangle(e,t,n,s,r){Ed.subVectors(t,e),co.subVectors(n,e),Md.crossVectors(Ed,co);let a=this.direction.dot(Md),o;if(a>0){if(s)return null;o=1}else if(a<0)o=-1,a=-a;else return null;Ki.subVectors(this.origin,e);const c=o*this.direction.dot(co.crossVectors(Ki,co));if(c<0)return null;const l=o*this.direction.dot(Ed.cross(Ki));if(l<0||c+l>a)return null;const d=-o*Ki.dot(Md);return d<0?null:this.at(d/a,r)}applyMatrix4(e){return this.origin.applyMatrix4(e),this.direction.transformDirection(e),this}equals(e){return e.origin.equals(this.origin)&&e.direction.equals(this.direction)}clone(){return new this.constructor().copy(this)}}class Ft{constructor(e,t,n,s,r,a,o,c,l,d,u,h,f,g,v,m){Ft.prototype.isMatrix4=!0,this.elements=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],e!==void 0&&this.set(e,t,n,s,r,a,o,c,l,d,u,h,f,g,v,m)}set(e,t,n,s,r,a,o,c,l,d,u,h,f,g,v,m){const p=this.elements;return p[0]=e,p[4]=t,p[8]=n,p[12]=s,p[1]=r,p[5]=a,p[9]=o,p[13]=c,p[2]=l,p[6]=d,p[10]=u,p[14]=h,p[3]=f,p[7]=g,p[11]=v,p[15]=m,this}identity(){return this.set(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1),this}clone(){return new Ft().fromArray(this.elements)}copy(e){const t=this.elements,n=e.elements;return t[0]=n[0],t[1]=n[1],t[2]=n[2],t[3]=n[3],t[4]=n[4],t[5]=n[5],t[6]=n[6],t[7]=n[7],t[8]=n[8],t[9]=n[9],t[10]=n[10],t[11]=n[11],t[12]=n[12],t[13]=n[13],t[14]=n[14],t[15]=n[15],this}copyPosition(e){const t=this.elements,n=e.elements;return t[12]=n[12],t[13]=n[13],t[14]=n[14],this}setFromMatrix3(e){const t=e.elements;return this.set(t[0],t[3],t[6],0,t[1],t[4],t[7],0,t[2],t[5],t[8],0,0,0,0,1),this}extractBasis(e,t,n){return this.determinant()===0?(e.set(1,0,0),t.set(0,1,0),n.set(0,0,1),this):(e.setFromMatrixColumn(this,0),t.setFromMatrixColumn(this,1),n.setFromMatrixColumn(this,2),this)}makeBasis(e,t,n){return this.set(e.x,t.x,n.x,0,e.y,t.y,n.y,0,e.z,t.z,n.z,0,0,0,0,1),this}extractRotation(e){if(e.determinant()===0)return this.identity();const t=this.elements,n=e.elements,s=1/ir.setFromMatrixColumn(e,0).length(),r=1/ir.setFromMatrixColumn(e,1).length(),a=1/ir.setFromMatrixColumn(e,2).length();return t[0]=n[0]*s,t[1]=n[1]*s,t[2]=n[2]*s,t[3]=0,t[4]=n[4]*r,t[5]=n[5]*r,t[6]=n[6]*r,t[7]=0,t[8]=n[8]*a,t[9]=n[9]*a,t[10]=n[10]*a,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromEuler(e){const t=this.elements,n=e.x,s=e.y,r=e.z,a=Math.cos(n),o=Math.sin(n),c=Math.cos(s),l=Math.sin(s),d=Math.cos(r),u=Math.sin(r);if(e.order==="XYZ"){const h=a*d,f=a*u,g=o*d,v=o*u;t[0]=c*d,t[4]=-c*u,t[8]=l,t[1]=f+g*l,t[5]=h-v*l,t[9]=-o*c,t[2]=v-h*l,t[6]=g+f*l,t[10]=a*c}else if(e.order==="YXZ"){const h=c*d,f=c*u,g=l*d,v=l*u;t[0]=h+v*o,t[4]=g*o-f,t[8]=a*l,t[1]=a*u,t[5]=a*d,t[9]=-o,t[2]=f*o-g,t[6]=v+h*o,t[10]=a*c}else if(e.order==="ZXY"){const h=c*d,f=c*u,g=l*d,v=l*u;t[0]=h-v*o,t[4]=-a*u,t[8]=g+f*o,t[1]=f+g*o,t[5]=a*d,t[9]=v-h*o,t[2]=-a*l,t[6]=o,t[10]=a*c}else if(e.order==="ZYX"){const h=a*d,f=a*u,g=o*d,v=o*u;t[0]=c*d,t[4]=g*l-f,t[8]=h*l+v,t[1]=c*u,t[5]=v*l+h,t[9]=f*l-g,t[2]=-l,t[6]=o*c,t[10]=a*c}else if(e.order==="YZX"){const h=a*c,f=a*l,g=o*c,v=o*l;t[0]=c*d,t[4]=v-h*u,t[8]=g*u+f,t[1]=u,t[5]=a*d,t[9]=-o*d,t[2]=-l*d,t[6]=f*u+g,t[10]=h-v*u}else if(e.order==="XZY"){const h=a*c,f=a*l,g=o*c,v=o*l;t[0]=c*d,t[4]=-u,t[8]=l*d,t[1]=h*u+v,t[5]=a*d,t[9]=f*u-g,t[2]=g*u-f,t[6]=o*d,t[10]=v*u+h}return t[3]=0,t[7]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromQuaternion(e){return this.compose(i_,e,s_)}lookAt(e,t,n){const s=this.elements;return _n.subVectors(e,t),_n.lengthSq()===0&&(_n.z=1),_n.normalize(),Ji.crossVectors(n,_n),Ji.lengthSq()===0&&(Math.abs(n.z)===1?_n.x+=1e-4:_n.z+=1e-4,_n.normalize(),Ji.crossVectors(n,_n)),Ji.normalize(),lo.crossVectors(_n,Ji),s[0]=Ji.x,s[4]=lo.x,s[8]=_n.x,s[1]=Ji.y,s[5]=lo.y,s[9]=_n.y,s[2]=Ji.z,s[6]=lo.z,s[10]=_n.z,this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){const n=e.elements,s=t.elements,r=this.elements,a=n[0],o=n[4],c=n[8],l=n[12],d=n[1],u=n[5],h=n[9],f=n[13],g=n[2],v=n[6],m=n[10],p=n[14],x=n[3],C=n[7],b=n[11],S=n[15],M=s[0],A=s[4],k=s[8],_=s[12],T=s[1],R=s[5],O=s[9],z=s[13],$=s[2],J=s[6],W=s[10],q=s[14],ne=s[3],be=s[7],ue=s[11],_e=s[15];return r[0]=a*M+o*T+c*$+l*ne,r[4]=a*A+o*R+c*J+l*be,r[8]=a*k+o*O+c*W+l*ue,r[12]=a*_+o*z+c*q+l*_e,r[1]=d*M+u*T+h*$+f*ne,r[5]=d*A+u*R+h*J+f*be,r[9]=d*k+u*O+h*W+f*ue,r[13]=d*_+u*z+h*q+f*_e,r[2]=g*M+v*T+m*$+p*ne,r[6]=g*A+v*R+m*J+p*be,r[10]=g*k+v*O+m*W+p*ue,r[14]=g*_+v*z+m*q+p*_e,r[3]=x*M+C*T+b*$+S*ne,r[7]=x*A+C*R+b*J+S*be,r[11]=x*k+C*O+b*W+S*ue,r[15]=x*_+C*z+b*q+S*_e,this}multiplyScalar(e){const t=this.elements;return t[0]*=e,t[4]*=e,t[8]*=e,t[12]*=e,t[1]*=e,t[5]*=e,t[9]*=e,t[13]*=e,t[2]*=e,t[6]*=e,t[10]*=e,t[14]*=e,t[3]*=e,t[7]*=e,t[11]*=e,t[15]*=e,this}determinant(){const e=this.elements,t=e[0],n=e[4],s=e[8],r=e[12],a=e[1],o=e[5],c=e[9],l=e[13],d=e[2],u=e[6],h=e[10],f=e[14],g=e[3],v=e[7],m=e[11],p=e[15],x=c*f-l*h,C=o*f-l*u,b=o*h-c*u,S=a*f-l*d,M=a*h-c*d,A=a*u-o*d;return t*(v*x-m*C+p*b)-n*(g*x-m*S+p*M)+s*(g*C-v*S+p*A)-r*(g*b-v*M+m*A)}transpose(){const e=this.elements;let t;return t=e[1],e[1]=e[4],e[4]=t,t=e[2],e[2]=e[8],e[8]=t,t=e[6],e[6]=e[9],e[9]=t,t=e[3],e[3]=e[12],e[12]=t,t=e[7],e[7]=e[13],e[13]=t,t=e[11],e[11]=e[14],e[14]=t,this}setPosition(e,t,n){const s=this.elements;return e.isVector3?(s[12]=e.x,s[13]=e.y,s[14]=e.z):(s[12]=e,s[13]=t,s[14]=n),this}invert(){const e=this.elements,t=e[0],n=e[1],s=e[2],r=e[3],a=e[4],o=e[5],c=e[6],l=e[7],d=e[8],u=e[9],h=e[10],f=e[11],g=e[12],v=e[13],m=e[14],p=e[15],x=u*m*l-v*h*l+v*c*f-o*m*f-u*c*p+o*h*p,C=g*h*l-d*m*l-g*c*f+a*m*f+d*c*p-a*h*p,b=d*v*l-g*u*l+g*o*f-a*v*f-d*o*p+a*u*p,S=g*u*c-d*v*c-g*o*h+a*v*h+d*o*m-a*u*m,M=t*x+n*C+s*b+r*S;if(M===0)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);const A=1/M;return e[0]=x*A,e[1]=(v*h*r-u*m*r-v*s*f+n*m*f+u*s*p-n*h*p)*A,e[2]=(o*m*r-v*c*r+v*s*l-n*m*l-o*s*p+n*c*p)*A,e[3]=(u*c*r-o*h*r-u*s*l+n*h*l+o*s*f-n*c*f)*A,e[4]=C*A,e[5]=(d*m*r-g*h*r+g*s*f-t*m*f-d*s*p+t*h*p)*A,e[6]=(g*c*r-a*m*r-g*s*l+t*m*l+a*s*p-t*c*p)*A,e[7]=(a*h*r-d*c*r+d*s*l-t*h*l-a*s*f+t*c*f)*A,e[8]=b*A,e[9]=(g*u*r-d*v*r-g*n*f+t*v*f+d*n*p-t*u*p)*A,e[10]=(a*v*r-g*o*r+g*n*l-t*v*l-a*n*p+t*o*p)*A,e[11]=(d*o*r-a*u*r-d*n*l+t*u*l+a*n*f-t*o*f)*A,e[12]=S*A,e[13]=(d*v*s-g*u*s+g*n*h-t*v*h-d*n*m+t*u*m)*A,e[14]=(g*o*s-a*v*s-g*n*c+t*v*c+a*n*m-t*o*m)*A,e[15]=(a*u*s-d*o*s+d*n*c-t*u*c-a*n*h+t*o*h)*A,this}scale(e){const t=this.elements,n=e.x,s=e.y,r=e.z;return t[0]*=n,t[4]*=s,t[8]*=r,t[1]*=n,t[5]*=s,t[9]*=r,t[2]*=n,t[6]*=s,t[10]*=r,t[3]*=n,t[7]*=s,t[11]*=r,this}getMaxScaleOnAxis(){const e=this.elements,t=e[0]*e[0]+e[1]*e[1]+e[2]*e[2],n=e[4]*e[4]+e[5]*e[5]+e[6]*e[6],s=e[8]*e[8]+e[9]*e[9]+e[10]*e[10];return Math.sqrt(Math.max(t,n,s))}makeTranslation(e,t,n){return e.isVector3?this.set(1,0,0,e.x,0,1,0,e.y,0,0,1,e.z,0,0,0,1):this.set(1,0,0,e,0,1,0,t,0,0,1,n,0,0,0,1),this}makeRotationX(e){const t=Math.cos(e),n=Math.sin(e);return this.set(1,0,0,0,0,t,-n,0,0,n,t,0,0,0,0,1),this}makeRotationY(e){const t=Math.cos(e),n=Math.sin(e);return this.set(t,0,n,0,0,1,0,0,-n,0,t,0,0,0,0,1),this}makeRotationZ(e){const t=Math.cos(e),n=Math.sin(e);return this.set(t,-n,0,0,n,t,0,0,0,0,1,0,0,0,0,1),this}makeRotationAxis(e,t){const n=Math.cos(t),s=Math.sin(t),r=1-n,a=e.x,o=e.y,c=e.z,l=r*a,d=r*o;return this.set(l*a+n,l*o-s*c,l*c+s*o,0,l*o+s*c,d*o+n,d*c-s*a,0,l*c-s*o,d*c+s*a,r*c*c+n,0,0,0,0,1),this}makeScale(e,t,n){return this.set(e,0,0,0,0,t,0,0,0,0,n,0,0,0,0,1),this}makeShear(e,t,n,s,r,a){return this.set(1,n,r,0,e,1,a,0,t,s,1,0,0,0,0,1),this}compose(e,t,n){const s=this.elements,r=t._x,a=t._y,o=t._z,c=t._w,l=r+r,d=a+a,u=o+o,h=r*l,f=r*d,g=r*u,v=a*d,m=a*u,p=o*u,x=c*l,C=c*d,b=c*u,S=n.x,M=n.y,A=n.z;return s[0]=(1-(v+p))*S,s[1]=(f+b)*S,s[2]=(g-C)*S,s[3]=0,s[4]=(f-b)*M,s[5]=(1-(h+p))*M,s[6]=(m+x)*M,s[7]=0,s[8]=(g+C)*A,s[9]=(m-x)*A,s[10]=(1-(h+v))*A,s[11]=0,s[12]=e.x,s[13]=e.y,s[14]=e.z,s[15]=1,this}decompose(e,t,n){const s=this.elements;if(e.x=s[12],e.y=s[13],e.z=s[14],this.determinant()===0)return n.set(1,1,1),t.identity(),this;let r=ir.set(s[0],s[1],s[2]).length();const a=ir.set(s[4],s[5],s[6]).length(),o=ir.set(s[8],s[9],s[10]).length();this.determinant()<0&&(r=-r),Vn.copy(this);const l=1/r,d=1/a,u=1/o;return Vn.elements[0]*=l,Vn.elements[1]*=l,Vn.elements[2]*=l,Vn.elements[4]*=d,Vn.elements[5]*=d,Vn.elements[6]*=d,Vn.elements[8]*=u,Vn.elements[9]*=u,Vn.elements[10]*=u,t.setFromRotationMatrix(Vn),n.x=r,n.y=a,n.z=o,this}makePerspective(e,t,n,s,r,a,o=si,c=!1){const l=this.elements,d=2*r/(t-e),u=2*r/(n-s),h=(t+e)/(t-e),f=(n+s)/(n-s);let g,v;if(c)g=r/(a-r),v=a*r/(a-r);else if(o===si)g=-(a+r)/(a-r),v=-2*a*r/(a-r);else if(o===no)g=-a/(a-r),v=-a*r/(a-r);else throw new Error("THREE.Matrix4.makePerspective(): Invalid coordinate system: "+o);return l[0]=d,l[4]=0,l[8]=h,l[12]=0,l[1]=0,l[5]=u,l[9]=f,l[13]=0,l[2]=0,l[6]=0,l[10]=g,l[14]=v,l[3]=0,l[7]=0,l[11]=-1,l[15]=0,this}makeOrthographic(e,t,n,s,r,a,o=si,c=!1){const l=this.elements,d=2/(t-e),u=2/(n-s),h=-(t+e)/(t-e),f=-(n+s)/(n-s);let g,v;if(c)g=1/(a-r),v=a/(a-r);else if(o===si)g=-2/(a-r),v=-(a+r)/(a-r);else if(o===no)g=-1/(a-r),v=-r/(a-r);else throw new Error("THREE.Matrix4.makeOrthographic(): Invalid coordinate system: "+o);return l[0]=d,l[4]=0,l[8]=0,l[12]=h,l[1]=0,l[5]=u,l[9]=0,l[13]=f,l[2]=0,l[6]=0,l[10]=g,l[14]=v,l[3]=0,l[7]=0,l[11]=0,l[15]=1,this}equals(e){const t=this.elements,n=e.elements;for(let s=0;s<16;s++)if(t[s]!==n[s])return!1;return!0}fromArray(e,t=0){for(let n=0;n<16;n++)this.elements[n]=e[n+t];return this}toArray(e=[],t=0){const n=this.elements;return e[t]=n[0],e[t+1]=n[1],e[t+2]=n[2],e[t+3]=n[3],e[t+4]=n[4],e[t+5]=n[5],e[t+6]=n[6],e[t+7]=n[7],e[t+8]=n[8],e[t+9]=n[9],e[t+10]=n[10],e[t+11]=n[11],e[t+12]=n[12],e[t+13]=n[13],e[t+14]=n[14],e[t+15]=n[15],e}}const ir=new B,Vn=new Ft,i_=new B(0,0,0),s_=new B(1,1,1),Ji=new B,lo=new B,_n=new B,Fp=new Ft,Bp=new Yr;class Ai{constructor(e=0,t=0,n=0,s=Ai.DEFAULT_ORDER){this.isEuler=!0,this._x=e,this._y=t,this._z=n,this._order=s}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get order(){return this._order}set order(e){this._order=e,this._onChangeCallback()}set(e,t,n,s=this._order){return this._x=e,this._y=t,this._z=n,this._order=s,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._order)}copy(e){return this._x=e._x,this._y=e._y,this._z=e._z,this._order=e._order,this._onChangeCallback(),this}setFromRotationMatrix(e,t=this._order,n=!0){const s=e.elements,r=s[0],a=s[4],o=s[8],c=s[1],l=s[5],d=s[9],u=s[2],h=s[6],f=s[10];switch(t){case"XYZ":this._y=Math.asin(et(o,-1,1)),Math.abs(o)<.9999999?(this._x=Math.atan2(-d,f),this._z=Math.atan2(-a,r)):(this._x=Math.atan2(h,l),this._z=0);break;case"YXZ":this._x=Math.asin(-et(d,-1,1)),Math.abs(d)<.9999999?(this._y=Math.atan2(o,f),this._z=Math.atan2(c,l)):(this._y=Math.atan2(-u,r),this._z=0);break;case"ZXY":this._x=Math.asin(et(h,-1,1)),Math.abs(h)<.9999999?(this._y=Math.atan2(-u,f),this._z=Math.atan2(-a,l)):(this._y=0,this._z=Math.atan2(c,r));break;case"ZYX":this._y=Math.asin(-et(u,-1,1)),Math.abs(u)<.9999999?(this._x=Math.atan2(h,f),this._z=Math.atan2(c,r)):(this._x=0,this._z=Math.atan2(-a,l));break;case"YZX":this._z=Math.asin(et(c,-1,1)),Math.abs(c)<.9999999?(this._x=Math.atan2(-d,l),this._y=Math.atan2(-u,r)):(this._x=0,this._y=Math.atan2(o,f));break;case"XZY":this._z=Math.asin(-et(a,-1,1)),Math.abs(a)<.9999999?(this._x=Math.atan2(h,l),this._y=Math.atan2(o,r)):(this._x=Math.atan2(-d,f),this._y=0);break;default:Oe("Euler: .setFromRotationMatrix() encountered an unknown order: "+t)}return this._order=t,n===!0&&this._onChangeCallback(),this}setFromQuaternion(e,t,n){return Fp.makeRotationFromQuaternion(e),this.setFromRotationMatrix(Fp,t,n)}setFromVector3(e,t=this._order){return this.set(e.x,e.y,e.z,t)}reorder(e){return Bp.setFromEuler(this),this.setFromQuaternion(Bp,e)}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._order===this._order}fromArray(e){return this._x=e[0],this._y=e[1],this._z=e[2],e[3]!==void 0&&(this._order=e[3]),this._onChangeCallback(),this}toArray(e=[],t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._order,e}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._order}}Ai.DEFAULT_ORDER="XYZ";class zp{constructor(){this.mask=1}set(e){this.mask=(1<<e|0)>>>0}enable(e){this.mask|=1<<e|0}enableAll(){this.mask=-1}toggle(e){this.mask^=1<<e|0}disable(e){this.mask&=~(1<<e|0)}disableAll(){this.mask=0}test(e){return(this.mask&e.mask)!==0}isEnabled(e){return(this.mask&(1<<e|0))!==0}}let r_=0;const Vp=new B,sr=new Yr,Ri=new Ft,uo=new B,Qr=new B,a_=new B,o_=new Yr,Gp=new B(1,0,0),Hp=new B(0,1,0),Wp=new B(0,0,1),qp={type:"added"},c_={type:"removed"},rr={type:"childadded",child:null},wd={type:"childremoved",child:null};class Sn extends Js{constructor(){super(),this.isObject3D=!0,Object.defineProperty(this,"id",{value:r_++}),this.uuid=jr(),this.name="",this.type="Object3D",this.parent=null,this.children=[],this.up=Sn.DEFAULT_UP.clone();const e=new B,t=new Ai,n=new Yr,s=new B(1,1,1);function r(){n.setFromEuler(t,!1)}function a(){t.setFromQuaternion(n,void 0,!1)}t._onChange(r),n._onChange(a),Object.defineProperties(this,{position:{configurable:!0,enumerable:!0,value:e},rotation:{configurable:!0,enumerable:!0,value:t},quaternion:{configurable:!0,enumerable:!0,value:n},scale:{configurable:!0,enumerable:!0,value:s},modelViewMatrix:{value:new Ft},normalMatrix:{value:new Ve}}),this.matrix=new Ft,this.matrixWorld=new Ft,this.matrixAutoUpdate=Sn.DEFAULT_MATRIX_AUTO_UPDATE,this.matrixWorldAutoUpdate=Sn.DEFAULT_MATRIX_WORLD_AUTO_UPDATE,this.matrixWorldNeedsUpdate=!1,this.layers=new zp,this.visible=!0,this.castShadow=!1,this.receiveShadow=!1,this.frustumCulled=!0,this.renderOrder=0,this.animations=[],this.customDepthMaterial=void 0,this.customDistanceMaterial=void 0,this.userData={}}onBeforeShadow(){}onAfterShadow(){}onBeforeRender(){}onAfterRender(){}applyMatrix4(e){this.matrixAutoUpdate&&this.updateMatrix(),this.matrix.premultiply(e),this.matrix.decompose(this.position,this.quaternion,this.scale)}applyQuaternion(e){return this.quaternion.premultiply(e),this}setRotationFromAxisAngle(e,t){this.quaternion.setFromAxisAngle(e,t)}setRotationFromEuler(e){this.quaternion.setFromEuler(e,!0)}setRotationFromMatrix(e){this.quaternion.setFromRotationMatrix(e)}setRotationFromQuaternion(e){this.quaternion.copy(e)}rotateOnAxis(e,t){return sr.setFromAxisAngle(e,t),this.quaternion.multiply(sr),this}rotateOnWorldAxis(e,t){return sr.setFromAxisAngle(e,t),this.quaternion.premultiply(sr),this}rotateX(e){return this.rotateOnAxis(Gp,e)}rotateY(e){return this.rotateOnAxis(Hp,e)}rotateZ(e){return this.rotateOnAxis(Wp,e)}translateOnAxis(e,t){return Vp.copy(e).applyQuaternion(this.quaternion),this.position.add(Vp.multiplyScalar(t)),this}translateX(e){return this.translateOnAxis(Gp,e)}translateY(e){return this.translateOnAxis(Hp,e)}translateZ(e){return this.translateOnAxis(Wp,e)}localToWorld(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(this.matrixWorld)}worldToLocal(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(Ri.copy(this.matrixWorld).invert())}lookAt(e,t,n){e.isVector3?uo.copy(e):uo.set(e,t,n);const s=this.parent;this.updateWorldMatrix(!0,!1),Qr.setFromMatrixPosition(this.matrixWorld),this.isCamera||this.isLight?Ri.lookAt(Qr,uo,this.up):Ri.lookAt(uo,Qr,this.up),this.quaternion.setFromRotationMatrix(Ri),s&&(Ri.extractRotation(s.matrixWorld),sr.setFromRotationMatrix(Ri),this.quaternion.premultiply(sr.invert()))}add(e){if(arguments.length>1){for(let t=0;t<arguments.length;t++)this.add(arguments[t]);return this}return e===this?(rt("Object3D.add: object can't be added as a child of itself.",e),this):(e&&e.isObject3D?(e.removeFromParent(),e.parent=this,this.children.push(e),e.dispatchEvent(qp),rr.child=e,this.dispatchEvent(rr),rr.child=null):rt("Object3D.add: object not an instance of THREE.Object3D.",e),this)}remove(e){if(arguments.length>1){for(let n=0;n<arguments.length;n++)this.remove(arguments[n]);return this}const t=this.children.indexOf(e);return t!==-1&&(e.parent=null,this.children.splice(t,1),e.dispatchEvent(c_),wd.child=e,this.dispatchEvent(wd),wd.child=null),this}removeFromParent(){const e=this.parent;return e!==null&&e.remove(this),this}clear(){return this.remove(...this.children)}attach(e){return this.updateWorldMatrix(!0,!1),Ri.copy(this.matrixWorld).invert(),e.parent!==null&&(e.parent.updateWorldMatrix(!0,!1),Ri.multiply(e.parent.matrixWorld)),e.applyMatrix4(Ri),e.removeFromParent(),e.parent=this,this.children.push(e),e.updateWorldMatrix(!1,!0),e.dispatchEvent(qp),rr.child=e,this.dispatchEvent(rr),rr.child=null,this}getObjectById(e){return this.getObjectByProperty("id",e)}getObjectByName(e){return this.getObjectByProperty("name",e)}getObjectByProperty(e,t){if(this[e]===t)return this;for(let n=0,s=this.children.length;n<s;n++){const a=this.children[n].getObjectByProperty(e,t);if(a!==void 0)return a}}getObjectsByProperty(e,t,n=[]){this[e]===t&&n.push(this);const s=this.children;for(let r=0,a=s.length;r<a;r++)s[r].getObjectsByProperty(e,t,n);return n}getWorldPosition(e){return this.updateWorldMatrix(!0,!1),e.setFromMatrixPosition(this.matrixWorld)}getWorldQuaternion(e){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(Qr,e,a_),e}getWorldScale(e){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(Qr,o_,e),e}getWorldDirection(e){this.updateWorldMatrix(!0,!1);const t=this.matrixWorld.elements;return e.set(t[8],t[9],t[10]).normalize()}raycast(){}traverse(e){e(this);const t=this.children;for(let n=0,s=t.length;n<s;n++)t[n].traverse(e)}traverseVisible(e){if(this.visible===!1)return;e(this);const t=this.children;for(let n=0,s=t.length;n<s;n++)t[n].traverseVisible(e)}traverseAncestors(e){const t=this.parent;t!==null&&(e(t),t.traverseAncestors(e))}updateMatrix(){this.matrix.compose(this.position,this.quaternion,this.scale),this.matrixWorldNeedsUpdate=!0}updateMatrixWorld(e){this.matrixAutoUpdate&&this.updateMatrix(),(this.matrixWorldNeedsUpdate||e)&&(this.matrixWorldAutoUpdate===!0&&(this.parent===null?this.matrixWorld.copy(this.matrix):this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix)),this.matrixWorldNeedsUpdate=!1,e=!0);const t=this.children;for(let n=0,s=t.length;n<s;n++)t[n].updateMatrixWorld(e)}updateWorldMatrix(e,t){const n=this.parent;if(e===!0&&n!==null&&n.updateWorldMatrix(!0,!1),this.matrixAutoUpdate&&this.updateMatrix(),this.matrixWorldAutoUpdate===!0&&(this.parent===null?this.matrixWorld.copy(this.matrix):this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix)),t===!0){const s=this.children;for(let r=0,a=s.length;r<a;r++)s[r].updateWorldMatrix(!1,!0)}}toJSON(e){const t=e===void 0||typeof e=="string",n={};t&&(e={geometries:{},materials:{},textures:{},images:{},shapes:{},skeletons:{},animations:{},nodes:{}},n.metadata={version:4.7,type:"Object",generator:"Object3D.toJSON"});const s={};s.uuid=this.uuid,s.type=this.type,this.name!==""&&(s.name=this.name),this.castShadow===!0&&(s.castShadow=!0),this.receiveShadow===!0&&(s.receiveShadow=!0),this.visible===!1&&(s.visible=!1),this.frustumCulled===!1&&(s.frustumCulled=!1),this.renderOrder!==0&&(s.renderOrder=this.renderOrder),Object.keys(this.userData).length>0&&(s.userData=this.userData),s.layers=this.layers.mask,s.matrix=this.matrix.toArray(),s.up=this.up.toArray(),this.matrixAutoUpdate===!1&&(s.matrixAutoUpdate=!1),this.isInstancedMesh&&(s.type="InstancedMesh",s.count=this.count,s.instanceMatrix=this.instanceMatrix.toJSON(),this.instanceColor!==null&&(s.instanceColor=this.instanceColor.toJSON())),this.isBatchedMesh&&(s.type="BatchedMesh",s.perObjectFrustumCulled=this.perObjectFrustumCulled,s.sortObjects=this.sortObjects,s.drawRanges=this._drawRanges,s.reservedRanges=this._reservedRanges,s.geometryInfo=this._geometryInfo.map(o=>({...o,boundingBox:o.boundingBox?o.boundingBox.toJSON():void 0,boundingSphere:o.boundingSphere?o.boundingSphere.toJSON():void 0})),s.instanceInfo=this._instanceInfo.map(o=>({...o})),s.availableInstanceIds=this._availableInstanceIds.slice(),s.availableGeometryIds=this._availableGeometryIds.slice(),s.nextIndexStart=this._nextIndexStart,s.nextVertexStart=this._nextVertexStart,s.geometryCount=this._geometryCount,s.maxInstanceCount=this._maxInstanceCount,s.maxVertexCount=this._maxVertexCount,s.maxIndexCount=this._maxIndexCount,s.geometryInitialized=this._geometryInitialized,s.matricesTexture=this._matricesTexture.toJSON(e),s.indirectTexture=this._indirectTexture.toJSON(e),this._colorsTexture!==null&&(s.colorsTexture=this._colorsTexture.toJSON(e)),this.boundingSphere!==null&&(s.boundingSphere=this.boundingSphere.toJSON()),this.boundingBox!==null&&(s.boundingBox=this.boundingBox.toJSON()));function r(o,c){return o[c.uuid]===void 0&&(o[c.uuid]=c.toJSON(e)),c.uuid}if(this.isScene)this.background&&(this.background.isColor?s.background=this.background.toJSON():this.background.isTexture&&(s.background=this.background.toJSON(e).uuid)),this.environment&&this.environment.isTexture&&this.environment.isRenderTargetTexture!==!0&&(s.environment=this.environment.toJSON(e).uuid);else if(this.isMesh||this.isLine||this.isPoints){s.geometry=r(e.geometries,this.geometry);const o=this.geometry.parameters;if(o!==void 0&&o.shapes!==void 0){const c=o.shapes;if(Array.isArray(c))for(let l=0,d=c.length;l<d;l++){const u=c[l];r(e.shapes,u)}else r(e.shapes,c)}}if(this.isSkinnedMesh&&(s.bindMode=this.bindMode,s.bindMatrix=this.bindMatrix.toArray(),this.skeleton!==void 0&&(r(e.skeletons,this.skeleton),s.skeleton=this.skeleton.uuid)),this.material!==void 0)if(Array.isArray(this.material)){const o=[];for(let c=0,l=this.material.length;c<l;c++)o.push(r(e.materials,this.material[c]));s.material=o}else s.material=r(e.materials,this.material);if(this.children.length>0){s.children=[];for(let o=0;o<this.children.length;o++)s.children.push(this.children[o].toJSON(e).object)}if(this.animations.length>0){s.animations=[];for(let o=0;o<this.animations.length;o++){const c=this.animations[o];s.animations.push(r(e.animations,c))}}if(t){const o=a(e.geometries),c=a(e.materials),l=a(e.textures),d=a(e.images),u=a(e.shapes),h=a(e.skeletons),f=a(e.animations),g=a(e.nodes);o.length>0&&(n.geometries=o),c.length>0&&(n.materials=c),l.length>0&&(n.textures=l),d.length>0&&(n.images=d),u.length>0&&(n.shapes=u),h.length>0&&(n.skeletons=h),f.length>0&&(n.animations=f),g.length>0&&(n.nodes=g)}return n.object=s,n;function a(o){const c=[];for(const l in o){const d=o[l];delete d.metadata,c.push(d)}return c}}clone(e){return new this.constructor().copy(this,e)}copy(e,t=!0){if(this.name=e.name,this.up.copy(e.up),this.position.copy(e.position),this.rotation.order=e.rotation.order,this.quaternion.copy(e.quaternion),this.scale.copy(e.scale),this.matrix.copy(e.matrix),this.matrixWorld.copy(e.matrixWorld),this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrixWorldAutoUpdate=e.matrixWorldAutoUpdate,this.matrixWorldNeedsUpdate=e.matrixWorldNeedsUpdate,this.layers.mask=e.layers.mask,this.visible=e.visible,this.castShadow=e.castShadow,this.receiveShadow=e.receiveShadow,this.frustumCulled=e.frustumCulled,this.renderOrder=e.renderOrder,this.animations=e.animations.slice(),this.userData=JSON.parse(JSON.stringify(e.userData)),t===!0)for(let n=0;n<e.children.length;n++){const s=e.children[n];this.add(s.clone())}return this}}Sn.DEFAULT_UP=new B(0,1,0),Sn.DEFAULT_MATRIX_AUTO_UPDATE=!0,Sn.DEFAULT_MATRIX_WORLD_AUTO_UPDATE=!0;const Gn=new B,Pi=new B,Ad=new B,ki=new B,ar=new B,or=new B,$p=new B,Rd=new B,Pd=new B,kd=new B,Id=new Ut,Dd=new Ut,Ld=new Ut;class Hn{constructor(e=new B,t=new B,n=new B){this.a=e,this.b=t,this.c=n}static getNormal(e,t,n,s){s.subVectors(n,t),Gn.subVectors(e,t),s.cross(Gn);const r=s.lengthSq();return r>0?s.multiplyScalar(1/Math.sqrt(r)):s.set(0,0,0)}static getBarycoord(e,t,n,s,r){Gn.subVectors(s,t),Pi.subVectors(n,t),Ad.subVectors(e,t);const a=Gn.dot(Gn),o=Gn.dot(Pi),c=Gn.dot(Ad),l=Pi.dot(Pi),d=Pi.dot(Ad),u=a*l-o*o;if(u===0)return r.set(0,0,0),null;const h=1/u,f=(l*c-o*d)*h,g=(a*d-o*c)*h;return r.set(1-f-g,g,f)}static containsPoint(e,t,n,s){return this.getBarycoord(e,t,n,s,ki)===null?!1:ki.x>=0&&ki.y>=0&&ki.x+ki.y<=1}static getInterpolation(e,t,n,s,r,a,o,c){return this.getBarycoord(e,t,n,s,ki)===null?(c.x=0,c.y=0,"z"in c&&(c.z=0),"w"in c&&(c.w=0),null):(c.setScalar(0),c.addScaledVector(r,ki.x),c.addScaledVector(a,ki.y),c.addScaledVector(o,ki.z),c)}static getInterpolatedAttribute(e,t,n,s,r,a){return Id.setScalar(0),Dd.setScalar(0),Ld.setScalar(0),Id.fromBufferAttribute(e,t),Dd.fromBufferAttribute(e,n),Ld.fromBufferAttribute(e,s),a.setScalar(0),a.addScaledVector(Id,r.x),a.addScaledVector(Dd,r.y),a.addScaledVector(Ld,r.z),a}static isFrontFacing(e,t,n,s){return Gn.subVectors(n,t),Pi.subVectors(e,t),Gn.cross(Pi).dot(s)<0}set(e,t,n){return this.a.copy(e),this.b.copy(t),this.c.copy(n),this}setFromPointsAndIndices(e,t,n,s){return this.a.copy(e[t]),this.b.copy(e[n]),this.c.copy(e[s]),this}setFromAttributeAndIndices(e,t,n,s){return this.a.fromBufferAttribute(e,t),this.b.fromBufferAttribute(e,n),this.c.fromBufferAttribute(e,s),this}clone(){return new this.constructor().copy(this)}copy(e){return this.a.copy(e.a),this.b.copy(e.b),this.c.copy(e.c),this}getArea(){return Gn.subVectors(this.c,this.b),Pi.subVectors(this.a,this.b),Gn.cross(Pi).length()*.5}getMidpoint(e){return e.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(e){return Hn.getNormal(this.a,this.b,this.c,e)}getPlane(e){return e.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(e,t){return Hn.getBarycoord(e,this.a,this.b,this.c,t)}getInterpolation(e,t,n,s,r){return Hn.getInterpolation(e,this.a,this.b,this.c,t,n,s,r)}containsPoint(e){return Hn.containsPoint(e,this.a,this.b,this.c)}isFrontFacing(e){return Hn.isFrontFacing(this.a,this.b,this.c,e)}intersectsBox(e){return e.intersectsTriangle(this)}closestPointToPoint(e,t){const n=this.a,s=this.b,r=this.c;let a,o;ar.subVectors(s,n),or.subVectors(r,n),Rd.subVectors(e,n);const c=ar.dot(Rd),l=or.dot(Rd);if(c<=0&&l<=0)return t.copy(n);Pd.subVectors(e,s);const d=ar.dot(Pd),u=or.dot(Pd);if(d>=0&&u<=d)return t.copy(s);const h=c*u-d*l;if(h<=0&&c>=0&&d<=0)return a=c/(c-d),t.copy(n).addScaledVector(ar,a);kd.subVectors(e,r);const f=ar.dot(kd),g=or.dot(kd);if(g>=0&&f<=g)return t.copy(r);const v=f*l-c*g;if(v<=0&&l>=0&&g<=0)return o=l/(l-g),t.copy(n).addScaledVector(or,o);const m=d*g-f*u;if(m<=0&&u-d>=0&&f-g>=0)return $p.subVectors(r,s),o=(u-d)/(u-d+(f-g)),t.copy(s).addScaledVector($p,o);const p=1/(m+v+h);return a=v*p,o=h*p,t.copy(n).addScaledVector(ar,a).addScaledVector(or,o)}equals(e){return e.a.equals(this.a)&&e.b.equals(this.b)&&e.c.equals(this.c)}}const jp={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074},Zi={h:0,s:0,l:0},ho={h:0,s:0,l:0};function Ud(i,e,t){return t<0&&(t+=1),t>1&&(t-=1),t<1/6?i+(e-i)*6*t:t<1/2?e:t<2/3?i+(e-i)*6*(2/3-t):i}class nt{constructor(e,t,n){return this.isColor=!0,this.r=1,this.g=1,this.b=1,this.set(e,t,n)}set(e,t,n){if(t===void 0&&n===void 0){const s=e;s&&s.isColor?this.copy(s):typeof s=="number"?this.setHex(s):typeof s=="string"&&this.setStyle(s)}else this.setRGB(e,t,n);return this}setScalar(e){return this.r=e,this.g=e,this.b=e,this}setHex(e,t=Mn){return e=Math.floor(e),this.r=(e>>16&255)/255,this.g=(e>>8&255)/255,this.b=(e&255)/255,it.colorSpaceToWorking(this,t),this}setRGB(e,t,n,s=it.workingColorSpace){return this.r=e,this.g=t,this.b=n,it.colorSpaceToWorking(this,s),this}setHSL(e,t,n,s=it.workingColorSpace){if(e=Xy(e,1),t=et(t,0,1),n=et(n,0,1),t===0)this.r=this.g=this.b=n;else{const r=n<=.5?n*(1+t):n+t-n*t,a=2*n-r;this.r=Ud(a,r,e+1/3),this.g=Ud(a,r,e),this.b=Ud(a,r,e-1/3)}return it.colorSpaceToWorking(this,s),this}setStyle(e,t=Mn){function n(r){r!==void 0&&parseFloat(r)<1&&Oe("Color: Alpha component of "+e+" will be ignored.")}let s;if(s=/^(\w+)\(([^\)]*)\)/.exec(e)){let r;const a=s[1],o=s[2];switch(a){case"rgb":case"rgba":if(r=/^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return n(r[4]),this.setRGB(Math.min(255,parseInt(r[1],10))/255,Math.min(255,parseInt(r[2],10))/255,Math.min(255,parseInt(r[3],10))/255,t);if(r=/^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return n(r[4]),this.setRGB(Math.min(100,parseInt(r[1],10))/100,Math.min(100,parseInt(r[2],10))/100,Math.min(100,parseInt(r[3],10))/100,t);break;case"hsl":case"hsla":if(r=/^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return n(r[4]),this.setHSL(parseFloat(r[1])/360,parseFloat(r[2])/100,parseFloat(r[3])/100,t);break;default:Oe("Color: Unknown color model "+e)}}else if(s=/^\#([A-Fa-f\d]+)$/.exec(e)){const r=s[1],a=r.length;if(a===3)return this.setRGB(parseInt(r.charAt(0),16)/15,parseInt(r.charAt(1),16)/15,parseInt(r.charAt(2),16)/15,t);if(a===6)return this.setHex(parseInt(r,16),t);Oe("Color: Invalid hex color "+e)}else if(e&&e.length>0)return this.setColorName(e,t);return this}setColorName(e,t=Mn){const n=jp[e.toLowerCase()];return n!==void 0?this.setHex(n,t):Oe("Color: Unknown color "+e),this}clone(){return new this.constructor(this.r,this.g,this.b)}copy(e){return this.r=e.r,this.g=e.g,this.b=e.b,this}copySRGBToLinear(e){return this.r=Ei(e.r),this.g=Ei(e.g),this.b=Ei(e.b),this}copyLinearToSRGB(e){return this.r=Zs(e.r),this.g=Zs(e.g),this.b=Zs(e.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(e=Mn){return it.workingToColorSpace(Qt.copy(this),e),Math.round(et(Qt.r*255,0,255))*65536+Math.round(et(Qt.g*255,0,255))*256+Math.round(et(Qt.b*255,0,255))}getHexString(e=Mn){return("000000"+this.getHex(e).toString(16)).slice(-6)}getHSL(e,t=it.workingColorSpace){it.workingToColorSpace(Qt.copy(this),t);const n=Qt.r,s=Qt.g,r=Qt.b,a=Math.max(n,s,r),o=Math.min(n,s,r);let c,l;const d=(o+a)/2;if(o===a)c=0,l=0;else{const u=a-o;switch(l=d<=.5?u/(a+o):u/(2-a-o),a){case n:c=(s-r)/u+(s<r?6:0);break;case s:c=(r-n)/u+2;break;case r:c=(n-s)/u+4;break}c/=6}return e.h=c,e.s=l,e.l=d,e}getRGB(e,t=it.workingColorSpace){return it.workingToColorSpace(Qt.copy(this),t),e.r=Qt.r,e.g=Qt.g,e.b=Qt.b,e}getStyle(e=Mn){it.workingToColorSpace(Qt.copy(this),e);const t=Qt.r,n=Qt.g,s=Qt.b;return e!==Mn?`color(${e} ${t.toFixed(3)} ${n.toFixed(3)} ${s.toFixed(3)})`:`rgb(${Math.round(t*255)},${Math.round(n*255)},${Math.round(s*255)})`}offsetHSL(e,t,n){return this.getHSL(Zi),this.setHSL(Zi.h+e,Zi.s+t,Zi.l+n)}add(e){return this.r+=e.r,this.g+=e.g,this.b+=e.b,this}addColors(e,t){return this.r=e.r+t.r,this.g=e.g+t.g,this.b=e.b+t.b,this}addScalar(e){return this.r+=e,this.g+=e,this.b+=e,this}sub(e){return this.r=Math.max(0,this.r-e.r),this.g=Math.max(0,this.g-e.g),this.b=Math.max(0,this.b-e.b),this}multiply(e){return this.r*=e.r,this.g*=e.g,this.b*=e.b,this}multiplyScalar(e){return this.r*=e,this.g*=e,this.b*=e,this}lerp(e,t){return this.r+=(e.r-this.r)*t,this.g+=(e.g-this.g)*t,this.b+=(e.b-this.b)*t,this}lerpColors(e,t,n){return this.r=e.r+(t.r-e.r)*n,this.g=e.g+(t.g-e.g)*n,this.b=e.b+(t.b-e.b)*n,this}lerpHSL(e,t){this.getHSL(Zi),e.getHSL(ho);const n=md(Zi.h,ho.h,t),s=md(Zi.s,ho.s,t),r=md(Zi.l,ho.l,t);return this.setHSL(n,s,r),this}setFromVector3(e){return this.r=e.x,this.g=e.y,this.b=e.z,this}applyMatrix3(e){const t=this.r,n=this.g,s=this.b,r=e.elements;return this.r=r[0]*t+r[3]*n+r[6]*s,this.g=r[1]*t+r[4]*n+r[7]*s,this.b=r[2]*t+r[5]*n+r[8]*s,this}equals(e){return e.r===this.r&&e.g===this.g&&e.b===this.b}fromArray(e,t=0){return this.r=e[t],this.g=e[t+1],this.b=e[t+2],this}toArray(e=[],t=0){return e[t]=this.r,e[t+1]=this.g,e[t+2]=this.b,e}fromBufferAttribute(e,t){return this.r=e.getX(t),this.g=e.getY(t),this.b=e.getZ(t),this}toJSON(){return this.getHex()}*[Symbol.iterator](){yield this.r,yield this.g,yield this.b}}const Qt=new nt;nt.NAMES=jp;let l_=0;class fo extends Js{constructor(){super(),this.isMaterial=!0,Object.defineProperty(this,"id",{value:l_++}),this.uuid=jr(),this.name="",this.type="Material",this.blending=qs,this.side=yi,this.vertexColors=!1,this.opacity=1,this.transparent=!1,this.alphaHash=!1,this.blendSrc=fl,this.blendDst=pl,this.blendEquation=us,this.blendSrcAlpha=null,this.blendDstAlpha=null,this.blendEquationAlpha=null,this.blendColor=new nt(0,0,0),this.blendAlpha=0,this.depthFunc=$s,this.depthTest=!0,this.depthWrite=!0,this.stencilWriteMask=255,this.stencilFunc=Ap,this.stencilRef=0,this.stencilFuncMask=255,this.stencilFail=Ks,this.stencilZFail=Ks,this.stencilZPass=Ks,this.stencilWrite=!1,this.clippingPlanes=null,this.clipIntersection=!1,this.clipShadows=!1,this.shadowSide=null,this.colorWrite=!0,this.precision=null,this.polygonOffset=!1,this.polygonOffsetFactor=0,this.polygonOffsetUnits=0,this.dithering=!1,this.alphaToCoverage=!1,this.premultipliedAlpha=!1,this.forceSinglePass=!1,this.allowOverride=!0,this.visible=!0,this.toneMapped=!0,this.userData={},this.version=0,this._alphaTest=0}get alphaTest(){return this._alphaTest}set alphaTest(e){this._alphaTest>0!=e>0&&this.version++,this._alphaTest=e}onBeforeRender(){}onBeforeCompile(){}customProgramCacheKey(){return this.onBeforeCompile.toString()}setValues(e){if(e!==void 0)for(const t in e){const n=e[t];if(n===void 0){Oe(`Material: parameter '${t}' has value of undefined.`);continue}const s=this[t];if(s===void 0){Oe(`Material: '${t}' is not a property of THREE.${this.type}.`);continue}s&&s.isColor?s.set(n):s&&s.isVector3&&n&&n.isVector3?s.copy(n):this[t]=n}}toJSON(e){const t=e===void 0||typeof e=="string";t&&(e={textures:{},images:{}});const n={metadata:{version:4.7,type:"Material",generator:"Material.toJSON"}};n.uuid=this.uuid,n.type=this.type,this.name!==""&&(n.name=this.name),this.color&&this.color.isColor&&(n.color=this.color.getHex()),this.roughness!==void 0&&(n.roughness=this.roughness),this.metalness!==void 0&&(n.metalness=this.metalness),this.sheen!==void 0&&(n.sheen=this.sheen),this.sheenColor&&this.sheenColor.isColor&&(n.sheenColor=this.sheenColor.getHex()),this.sheenRoughness!==void 0&&(n.sheenRoughness=this.sheenRoughness),this.emissive&&this.emissive.isColor&&(n.emissive=this.emissive.getHex()),this.emissiveIntensity!==void 0&&this.emissiveIntensity!==1&&(n.emissiveIntensity=this.emissiveIntensity),this.specular&&this.specular.isColor&&(n.specular=this.specular.getHex()),this.specularIntensity!==void 0&&(n.specularIntensity=this.specularIntensity),this.specularColor&&this.specularColor.isColor&&(n.specularColor=this.specularColor.getHex()),this.shininess!==void 0&&(n.shininess=this.shininess),this.clearcoat!==void 0&&(n.clearcoat=this.clearcoat),this.clearcoatRoughness!==void 0&&(n.clearcoatRoughness=this.clearcoatRoughness),this.clearcoatMap&&this.clearcoatMap.isTexture&&(n.clearcoatMap=this.clearcoatMap.toJSON(e).uuid),this.clearcoatRoughnessMap&&this.clearcoatRoughnessMap.isTexture&&(n.clearcoatRoughnessMap=this.clearcoatRoughnessMap.toJSON(e).uuid),this.clearcoatNormalMap&&this.clearcoatNormalMap.isTexture&&(n.clearcoatNormalMap=this.clearcoatNormalMap.toJSON(e).uuid,n.clearcoatNormalScale=this.clearcoatNormalScale.toArray()),this.sheenColorMap&&this.sheenColorMap.isTexture&&(n.sheenColorMap=this.sheenColorMap.toJSON(e).uuid),this.sheenRoughnessMap&&this.sheenRoughnessMap.isTexture&&(n.sheenRoughnessMap=this.sheenRoughnessMap.toJSON(e).uuid),this.dispersion!==void 0&&(n.dispersion=this.dispersion),this.iridescence!==void 0&&(n.iridescence=this.iridescence),this.iridescenceIOR!==void 0&&(n.iridescenceIOR=this.iridescenceIOR),this.iridescenceThicknessRange!==void 0&&(n.iridescenceThicknessRange=this.iridescenceThicknessRange),this.iridescenceMap&&this.iridescenceMap.isTexture&&(n.iridescenceMap=this.iridescenceMap.toJSON(e).uuid),this.iridescenceThicknessMap&&this.iridescenceThicknessMap.isTexture&&(n.iridescenceThicknessMap=this.iridescenceThicknessMap.toJSON(e).uuid),this.anisotropy!==void 0&&(n.anisotropy=this.anisotropy),this.anisotropyRotation!==void 0&&(n.anisotropyRotation=this.anisotropyRotation),this.anisotropyMap&&this.anisotropyMap.isTexture&&(n.anisotropyMap=this.anisotropyMap.toJSON(e).uuid),this.map&&this.map.isTexture&&(n.map=this.map.toJSON(e).uuid),this.matcap&&this.matcap.isTexture&&(n.matcap=this.matcap.toJSON(e).uuid),this.alphaMap&&this.alphaMap.isTexture&&(n.alphaMap=this.alphaMap.toJSON(e).uuid),this.lightMap&&this.lightMap.isTexture&&(n.lightMap=this.lightMap.toJSON(e).uuid,n.lightMapIntensity=this.lightMapIntensity),this.aoMap&&this.aoMap.isTexture&&(n.aoMap=this.aoMap.toJSON(e).uuid,n.aoMapIntensity=this.aoMapIntensity),this.bumpMap&&this.bumpMap.isTexture&&(n.bumpMap=this.bumpMap.toJSON(e).uuid,n.bumpScale=this.bumpScale),this.normalMap&&this.normalMap.isTexture&&(n.normalMap=this.normalMap.toJSON(e).uuid,n.normalMapType=this.normalMapType,n.normalScale=this.normalScale.toArray()),this.displacementMap&&this.displacementMap.isTexture&&(n.displacementMap=this.displacementMap.toJSON(e).uuid,n.displacementScale=this.displacementScale,n.displacementBias=this.displacementBias),this.roughnessMap&&this.roughnessMap.isTexture&&(n.roughnessMap=this.roughnessMap.toJSON(e).uuid),this.metalnessMap&&this.metalnessMap.isTexture&&(n.metalnessMap=this.metalnessMap.toJSON(e).uuid),this.emissiveMap&&this.emissiveMap.isTexture&&(n.emissiveMap=this.emissiveMap.toJSON(e).uuid),this.specularMap&&this.specularMap.isTexture&&(n.specularMap=this.specularMap.toJSON(e).uuid),this.specularIntensityMap&&this.specularIntensityMap.isTexture&&(n.specularIntensityMap=this.specularIntensityMap.toJSON(e).uuid),this.specularColorMap&&this.specularColorMap.isTexture&&(n.specularColorMap=this.specularColorMap.toJSON(e).uuid),this.envMap&&this.envMap.isTexture&&(n.envMap=this.envMap.toJSON(e).uuid,this.combine!==void 0&&(n.combine=this.combine)),this.envMapRotation!==void 0&&(n.envMapRotation=this.envMapRotation.toArray()),this.envMapIntensity!==void 0&&(n.envMapIntensity=this.envMapIntensity),this.reflectivity!==void 0&&(n.reflectivity=this.reflectivity),this.refractionRatio!==void 0&&(n.refractionRatio=this.refractionRatio),this.gradientMap&&this.gradientMap.isTexture&&(n.gradientMap=this.gradientMap.toJSON(e).uuid),this.transmission!==void 0&&(n.transmission=this.transmission),this.transmissionMap&&this.transmissionMap.isTexture&&(n.transmissionMap=this.transmissionMap.toJSON(e).uuid),this.thickness!==void 0&&(n.thickness=this.thickness),this.thicknessMap&&this.thicknessMap.isTexture&&(n.thicknessMap=this.thicknessMap.toJSON(e).uuid),this.attenuationDistance!==void 0&&this.attenuationDistance!==1/0&&(n.attenuationDistance=this.attenuationDistance),this.attenuationColor!==void 0&&(n.attenuationColor=this.attenuationColor.getHex()),this.size!==void 0&&(n.size=this.size),this.shadowSide!==null&&(n.shadowSide=this.shadowSide),this.sizeAttenuation!==void 0&&(n.sizeAttenuation=this.sizeAttenuation),this.blending!==qs&&(n.blending=this.blending),this.side!==yi&&(n.side=this.side),this.vertexColors===!0&&(n.vertexColors=!0),this.opacity<1&&(n.opacity=this.opacity),this.transparent===!0&&(n.transparent=!0),this.blendSrc!==fl&&(n.blendSrc=this.blendSrc),this.blendDst!==pl&&(n.blendDst=this.blendDst),this.blendEquation!==us&&(n.blendEquation=this.blendEquation),this.blendSrcAlpha!==null&&(n.blendSrcAlpha=this.blendSrcAlpha),this.blendDstAlpha!==null&&(n.blendDstAlpha=this.blendDstAlpha),this.blendEquationAlpha!==null&&(n.blendEquationAlpha=this.blendEquationAlpha),this.blendColor&&this.blendColor.isColor&&(n.blendColor=this.blendColor.getHex()),this.blendAlpha!==0&&(n.blendAlpha=this.blendAlpha),this.depthFunc!==$s&&(n.depthFunc=this.depthFunc),this.depthTest===!1&&(n.depthTest=this.depthTest),this.depthWrite===!1&&(n.depthWrite=this.depthWrite),this.colorWrite===!1&&(n.colorWrite=this.colorWrite),this.stencilWriteMask!==255&&(n.stencilWriteMask=this.stencilWriteMask),this.stencilFunc!==Ap&&(n.stencilFunc=this.stencilFunc),this.stencilRef!==0&&(n.stencilRef=this.stencilRef),this.stencilFuncMask!==255&&(n.stencilFuncMask=this.stencilFuncMask),this.stencilFail!==Ks&&(n.stencilFail=this.stencilFail),this.stencilZFail!==Ks&&(n.stencilZFail=this.stencilZFail),this.stencilZPass!==Ks&&(n.stencilZPass=this.stencilZPass),this.stencilWrite===!0&&(n.stencilWrite=this.stencilWrite),this.rotation!==void 0&&this.rotation!==0&&(n.rotation=this.rotation),this.polygonOffset===!0&&(n.polygonOffset=!0),this.polygonOffsetFactor!==0&&(n.polygonOffsetFactor=this.polygonOffsetFactor),this.polygonOffsetUnits!==0&&(n.polygonOffsetUnits=this.polygonOffsetUnits),this.linewidth!==void 0&&this.linewidth!==1&&(n.linewidth=this.linewidth),this.dashSize!==void 0&&(n.dashSize=this.dashSize),this.gapSize!==void 0&&(n.gapSize=this.gapSize),this.scale!==void 0&&(n.scale=this.scale),this.dithering===!0&&(n.dithering=!0),this.alphaTest>0&&(n.alphaTest=this.alphaTest),this.alphaHash===!0&&(n.alphaHash=!0),this.alphaToCoverage===!0&&(n.alphaToCoverage=!0),this.premultipliedAlpha===!0&&(n.premultipliedAlpha=!0),this.forceSinglePass===!0&&(n.forceSinglePass=!0),this.allowOverride===!1&&(n.allowOverride=!1),this.wireframe===!0&&(n.wireframe=!0),this.wireframeLinewidth>1&&(n.wireframeLinewidth=this.wireframeLinewidth),this.wireframeLinecap!=="round"&&(n.wireframeLinecap=this.wireframeLinecap),this.wireframeLinejoin!=="round"&&(n.wireframeLinejoin=this.wireframeLinejoin),this.flatShading===!0&&(n.flatShading=!0),this.visible===!1&&(n.visible=!1),this.toneMapped===!1&&(n.toneMapped=!1),this.fog===!1&&(n.fog=!1),Object.keys(this.userData).length>0&&(n.userData=this.userData);function s(r){const a=[];for(const o in r){const c=r[o];delete c.metadata,a.push(c)}return a}if(t){const r=s(e.textures),a=s(e.images);r.length>0&&(n.textures=r),a.length>0&&(n.images=a)}return n}clone(){return new this.constructor().copy(this)}copy(e){this.name=e.name,this.blending=e.blending,this.side=e.side,this.vertexColors=e.vertexColors,this.opacity=e.opacity,this.transparent=e.transparent,this.blendSrc=e.blendSrc,this.blendDst=e.blendDst,this.blendEquation=e.blendEquation,this.blendSrcAlpha=e.blendSrcAlpha,this.blendDstAlpha=e.blendDstAlpha,this.blendEquationAlpha=e.blendEquationAlpha,this.blendColor.copy(e.blendColor),this.blendAlpha=e.blendAlpha,this.depthFunc=e.depthFunc,this.depthTest=e.depthTest,this.depthWrite=e.depthWrite,this.stencilWriteMask=e.stencilWriteMask,this.stencilFunc=e.stencilFunc,this.stencilRef=e.stencilRef,this.stencilFuncMask=e.stencilFuncMask,this.stencilFail=e.stencilFail,this.stencilZFail=e.stencilZFail,this.stencilZPass=e.stencilZPass,this.stencilWrite=e.stencilWrite;const t=e.clippingPlanes;let n=null;if(t!==null){const s=t.length;n=new Array(s);for(let r=0;r!==s;++r)n[r]=t[r].clone()}return this.clippingPlanes=n,this.clipIntersection=e.clipIntersection,this.clipShadows=e.clipShadows,this.shadowSide=e.shadowSide,this.colorWrite=e.colorWrite,this.precision=e.precision,this.polygonOffset=e.polygonOffset,this.polygonOffsetFactor=e.polygonOffsetFactor,this.polygonOffsetUnits=e.polygonOffsetUnits,this.dithering=e.dithering,this.alphaTest=e.alphaTest,this.alphaHash=e.alphaHash,this.alphaToCoverage=e.alphaToCoverage,this.premultipliedAlpha=e.premultipliedAlpha,this.forceSinglePass=e.forceSinglePass,this.allowOverride=e.allowOverride,this.visible=e.visible,this.toneMapped=e.toneMapped,this.userData=JSON.parse(JSON.stringify(e.userData)),this}dispose(){this.dispatchEvent({type:"dispose"})}set needsUpdate(e){e===!0&&this.version++}}class Xp extends fo{constructor(e){super(),this.isMeshBasicMaterial=!0,this.type="MeshBasicMaterial",this.color=new nt(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new Ai,this.combine=hp,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.combine=e.combine,this.reflectivity=e.reflectivity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.fog=e.fog,this}}const Bt=new B,po=new lt;let d_=0;class ai{constructor(e,t,n=!1){if(Array.isArray(e))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");this.isBufferAttribute=!0,Object.defineProperty(this,"id",{value:d_++}),this.name="",this.array=e,this.itemSize=t,this.count=e!==void 0?e.length/t:0,this.normalized=n,this.usage=Rp,this.updateRanges=[],this.gpuType=ii,this.version=0}onUploadCallback(){}set needsUpdate(e){e===!0&&this.version++}setUsage(e){return this.usage=e,this}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}copy(e){return this.name=e.name,this.array=new e.array.constructor(e.array),this.itemSize=e.itemSize,this.count=e.count,this.normalized=e.normalized,this.usage=e.usage,this.gpuType=e.gpuType,this}copyAt(e,t,n){e*=this.itemSize,n*=t.itemSize;for(let s=0,r=this.itemSize;s<r;s++)this.array[e+s]=t.array[n+s];return this}copyArray(e){return this.array.set(e),this}applyMatrix3(e){if(this.itemSize===2)for(let t=0,n=this.count;t<n;t++)po.fromBufferAttribute(this,t),po.applyMatrix3(e),this.setXY(t,po.x,po.y);else if(this.itemSize===3)for(let t=0,n=this.count;t<n;t++)Bt.fromBufferAttribute(this,t),Bt.applyMatrix3(e),this.setXYZ(t,Bt.x,Bt.y,Bt.z);return this}applyMatrix4(e){for(let t=0,n=this.count;t<n;t++)Bt.fromBufferAttribute(this,t),Bt.applyMatrix4(e),this.setXYZ(t,Bt.x,Bt.y,Bt.z);return this}applyNormalMatrix(e){for(let t=0,n=this.count;t<n;t++)Bt.fromBufferAttribute(this,t),Bt.applyNormalMatrix(e),this.setXYZ(t,Bt.x,Bt.y,Bt.z);return this}transformDirection(e){for(let t=0,n=this.count;t<n;t++)Bt.fromBufferAttribute(this,t),Bt.transformDirection(e),this.setXYZ(t,Bt.x,Bt.y,Bt.z);return this}set(e,t=0){return this.array.set(e,t),this}getComponent(e,t){let n=this.array[e*this.itemSize+t];return this.normalized&&(n=Xr(n,this.array)),n}setComponent(e,t,n){return this.normalized&&(n=fn(n,this.array)),this.array[e*this.itemSize+t]=n,this}getX(e){let t=this.array[e*this.itemSize];return this.normalized&&(t=Xr(t,this.array)),t}setX(e,t){return this.normalized&&(t=fn(t,this.array)),this.array[e*this.itemSize]=t,this}getY(e){let t=this.array[e*this.itemSize+1];return this.normalized&&(t=Xr(t,this.array)),t}setY(e,t){return this.normalized&&(t=fn(t,this.array)),this.array[e*this.itemSize+1]=t,this}getZ(e){let t=this.array[e*this.itemSize+2];return this.normalized&&(t=Xr(t,this.array)),t}setZ(e,t){return this.normalized&&(t=fn(t,this.array)),this.array[e*this.itemSize+2]=t,this}getW(e){let t=this.array[e*this.itemSize+3];return this.normalized&&(t=Xr(t,this.array)),t}setW(e,t){return this.normalized&&(t=fn(t,this.array)),this.array[e*this.itemSize+3]=t,this}setXY(e,t,n){return e*=this.itemSize,this.normalized&&(t=fn(t,this.array),n=fn(n,this.array)),this.array[e+0]=t,this.array[e+1]=n,this}setXYZ(e,t,n,s){return e*=this.itemSize,this.normalized&&(t=fn(t,this.array),n=fn(n,this.array),s=fn(s,this.array)),this.array[e+0]=t,this.array[e+1]=n,this.array[e+2]=s,this}setXYZW(e,t,n,s,r){return e*=this.itemSize,this.normalized&&(t=fn(t,this.array),n=fn(n,this.array),s=fn(s,this.array),r=fn(r,this.array)),this.array[e+0]=t,this.array[e+1]=n,this.array[e+2]=s,this.array[e+3]=r,this}onUpload(e){return this.onUploadCallback=e,this}clone(){return new this.constructor(this.array,this.itemSize).copy(this)}toJSON(){const e={itemSize:this.itemSize,type:this.array.constructor.name,array:Array.from(this.array),normalized:this.normalized};return this.name!==""&&(e.name=this.name),this.usage!==Rp&&(e.usage=this.usage),e}}class Yp extends ai{constructor(e,t,n){super(new Uint16Array(e),t,n)}}class Kp extends ai{constructor(e,t,n){super(new Uint32Array(e),t,n)}}class nn extends ai{constructor(e,t,n){super(new Float32Array(e),t,n)}}let u_=0;const wn=new Ft,Nd=new Sn,cr=new B,xn=new Kr,ea=new Kr,jt=new B;class Wn extends Js{constructor(){super(),this.isBufferGeometry=!0,Object.defineProperty(this,"id",{value:u_++}),this.uuid=jr(),this.name="",this.type="BufferGeometry",this.index=null,this.indirect=null,this.indirectOffset=0,this.attributes={},this.morphAttributes={},this.morphTargetsRelative=!1,this.groups=[],this.boundingBox=null,this.boundingSphere=null,this.drawRange={start:0,count:1/0},this.userData={}}getIndex(){return this.index}setIndex(e){return Array.isArray(e)?this.index=new(kp(e)?Kp:Yp)(e,1):this.index=e,this}setIndirect(e,t=0){return this.indirect=e,this.indirectOffset=t,this}getIndirect(){return this.indirect}getAttribute(e){return this.attributes[e]}setAttribute(e,t){return this.attributes[e]=t,this}deleteAttribute(e){return delete this.attributes[e],this}hasAttribute(e){return this.attributes[e]!==void 0}addGroup(e,t,n=0){this.groups.push({start:e,count:t,materialIndex:n})}clearGroups(){this.groups=[]}setDrawRange(e,t){this.drawRange.start=e,this.drawRange.count=t}applyMatrix4(e){const t=this.attributes.position;t!==void 0&&(t.applyMatrix4(e),t.needsUpdate=!0);const n=this.attributes.normal;if(n!==void 0){const r=new Ve().getNormalMatrix(e);n.applyNormalMatrix(r),n.needsUpdate=!0}const s=this.attributes.tangent;return s!==void 0&&(s.transformDirection(e),s.needsUpdate=!0),this.boundingBox!==null&&this.computeBoundingBox(),this.boundingSphere!==null&&this.computeBoundingSphere(),this}applyQuaternion(e){return wn.makeRotationFromQuaternion(e),this.applyMatrix4(wn),this}rotateX(e){return wn.makeRotationX(e),this.applyMatrix4(wn),this}rotateY(e){return wn.makeRotationY(e),this.applyMatrix4(wn),this}rotateZ(e){return wn.makeRotationZ(e),this.applyMatrix4(wn),this}translate(e,t,n){return wn.makeTranslation(e,t,n),this.applyMatrix4(wn),this}scale(e,t,n){return wn.makeScale(e,t,n),this.applyMatrix4(wn),this}lookAt(e){return Nd.lookAt(e),Nd.updateMatrix(),this.applyMatrix4(Nd.matrix),this}center(){return this.computeBoundingBox(),this.boundingBox.getCenter(cr).negate(),this.translate(cr.x,cr.y,cr.z),this}setFromPoints(e){const t=this.getAttribute("position");if(t===void 0){const n=[];for(let s=0,r=e.length;s<r;s++){const a=e[s];n.push(a.x,a.y,a.z||0)}this.setAttribute("position",new nn(n,3))}else{const n=Math.min(e.length,t.count);for(let s=0;s<n;s++){const r=e[s];t.setXYZ(s,r.x,r.y,r.z||0)}e.length>t.count&&Oe("BufferGeometry: Buffer size too small for points data. Use .dispose() and create a new geometry."),t.needsUpdate=!0}return this}computeBoundingBox(){this.boundingBox===null&&(this.boundingBox=new Kr);const e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute){rt("BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.",this),this.boundingBox.set(new B(-1/0,-1/0,-1/0),new B(1/0,1/0,1/0));return}if(e!==void 0){if(this.boundingBox.setFromBufferAttribute(e),t)for(let n=0,s=t.length;n<s;n++){const r=t[n];xn.setFromBufferAttribute(r),this.morphTargetsRelative?(jt.addVectors(this.boundingBox.min,xn.min),this.boundingBox.expandByPoint(jt),jt.addVectors(this.boundingBox.max,xn.max),this.boundingBox.expandByPoint(jt)):(this.boundingBox.expandByPoint(xn.min),this.boundingBox.expandByPoint(xn.max))}}else this.boundingBox.makeEmpty();(isNaN(this.boundingBox.min.x)||isNaN(this.boundingBox.min.y)||isNaN(this.boundingBox.min.z))&&rt('BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.',this)}computeBoundingSphere(){this.boundingSphere===null&&(this.boundingSphere=new Td);const e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute){rt("BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.",this),this.boundingSphere.set(new B,1/0);return}if(e){const n=this.boundingSphere.center;if(xn.setFromBufferAttribute(e),t)for(let r=0,a=t.length;r<a;r++){const o=t[r];ea.setFromBufferAttribute(o),this.morphTargetsRelative?(jt.addVectors(xn.min,ea.min),xn.expandByPoint(jt),jt.addVectors(xn.max,ea.max),xn.expandByPoint(jt)):(xn.expandByPoint(ea.min),xn.expandByPoint(ea.max))}xn.getCenter(n);let s=0;for(let r=0,a=e.count;r<a;r++)jt.fromBufferAttribute(e,r),s=Math.max(s,n.distanceToSquared(jt));if(t)for(let r=0,a=t.length;r<a;r++){const o=t[r],c=this.morphTargetsRelative;for(let l=0,d=o.count;l<d;l++)jt.fromBufferAttribute(o,l),c&&(cr.fromBufferAttribute(e,l),jt.add(cr)),s=Math.max(s,n.distanceToSquared(jt))}this.boundingSphere.radius=Math.sqrt(s),isNaN(this.boundingSphere.radius)&&rt('BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.',this)}}computeTangents(){const e=this.index,t=this.attributes;if(e===null||t.position===void 0||t.normal===void 0||t.uv===void 0){rt("BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)");return}const n=t.position,s=t.normal,r=t.uv;this.hasAttribute("tangent")===!1&&this.setAttribute("tangent",new ai(new Float32Array(4*n.count),4));const a=this.getAttribute("tangent"),o=[],c=[];for(let k=0;k<n.count;k++)o[k]=new B,c[k]=new B;const l=new B,d=new B,u=new B,h=new lt,f=new lt,g=new lt,v=new B,m=new B;function p(k,_,T){l.fromBufferAttribute(n,k),d.fromBufferAttribute(n,_),u.fromBufferAttribute(n,T),h.fromBufferAttribute(r,k),f.fromBufferAttribute(r,_),g.fromBufferAttribute(r,T),d.sub(l),u.sub(l),f.sub(h),g.sub(h);const R=1/(f.x*g.y-g.x*f.y);isFinite(R)&&(v.copy(d).multiplyScalar(g.y).addScaledVector(u,-f.y).multiplyScalar(R),m.copy(u).multiplyScalar(f.x).addScaledVector(d,-g.x).multiplyScalar(R),o[k].add(v),o[_].add(v),o[T].add(v),c[k].add(m),c[_].add(m),c[T].add(m))}let x=this.groups;x.length===0&&(x=[{start:0,count:e.count}]);for(let k=0,_=x.length;k<_;++k){const T=x[k],R=T.start,O=T.count;for(let z=R,$=R+O;z<$;z+=3)p(e.getX(z+0),e.getX(z+1),e.getX(z+2))}const C=new B,b=new B,S=new B,M=new B;function A(k){S.fromBufferAttribute(s,k),M.copy(S);const _=o[k];C.copy(_),C.sub(S.multiplyScalar(S.dot(_))).normalize(),b.crossVectors(M,_);const R=b.dot(c[k])<0?-1:1;a.setXYZW(k,C.x,C.y,C.z,R)}for(let k=0,_=x.length;k<_;++k){const T=x[k],R=T.start,O=T.count;for(let z=R,$=R+O;z<$;z+=3)A(e.getX(z+0)),A(e.getX(z+1)),A(e.getX(z+2))}}computeVertexNormals(){const e=this.index,t=this.getAttribute("position");if(t!==void 0){let n=this.getAttribute("normal");if(n===void 0)n=new ai(new Float32Array(t.count*3),3),this.setAttribute("normal",n);else for(let h=0,f=n.count;h<f;h++)n.setXYZ(h,0,0,0);const s=new B,r=new B,a=new B,o=new B,c=new B,l=new B,d=new B,u=new B;if(e)for(let h=0,f=e.count;h<f;h+=3){const g=e.getX(h+0),v=e.getX(h+1),m=e.getX(h+2);s.fromBufferAttribute(t,g),r.fromBufferAttribute(t,v),a.fromBufferAttribute(t,m),d.subVectors(a,r),u.subVectors(s,r),d.cross(u),o.fromBufferAttribute(n,g),c.fromBufferAttribute(n,v),l.fromBufferAttribute(n,m),o.add(d),c.add(d),l.add(d),n.setXYZ(g,o.x,o.y,o.z),n.setXYZ(v,c.x,c.y,c.z),n.setXYZ(m,l.x,l.y,l.z)}else for(let h=0,f=t.count;h<f;h+=3)s.fromBufferAttribute(t,h+0),r.fromBufferAttribute(t,h+1),a.fromBufferAttribute(t,h+2),d.subVectors(a,r),u.subVectors(s,r),d.cross(u),n.setXYZ(h+0,d.x,d.y,d.z),n.setXYZ(h+1,d.x,d.y,d.z),n.setXYZ(h+2,d.x,d.y,d.z);this.normalizeNormals(),n.needsUpdate=!0}}normalizeNormals(){const e=this.attributes.normal;for(let t=0,n=e.count;t<n;t++)jt.fromBufferAttribute(e,t),jt.normalize(),e.setXYZ(t,jt.x,jt.y,jt.z)}toNonIndexed(){function e(o,c){const l=o.array,d=o.itemSize,u=o.normalized,h=new l.constructor(c.length*d);let f=0,g=0;for(let v=0,m=c.length;v<m;v++){o.isInterleavedBufferAttribute?f=c[v]*o.data.stride+o.offset:f=c[v]*d;for(let p=0;p<d;p++)h[g++]=l[f++]}return new ai(h,d,u)}if(this.index===null)return Oe("BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed."),this;const t=new Wn,n=this.index.array,s=this.attributes;for(const o in s){const c=s[o],l=e(c,n);t.setAttribute(o,l)}const r=this.morphAttributes;for(const o in r){const c=[],l=r[o];for(let d=0,u=l.length;d<u;d++){const h=l[d],f=e(h,n);c.push(f)}t.morphAttributes[o]=c}t.morphTargetsRelative=this.morphTargetsRelative;const a=this.groups;for(let o=0,c=a.length;o<c;o++){const l=a[o];t.addGroup(l.start,l.count,l.materialIndex)}return t}toJSON(){const e={metadata:{version:4.7,type:"BufferGeometry",generator:"BufferGeometry.toJSON"}};if(e.uuid=this.uuid,e.type=this.type,this.name!==""&&(e.name=this.name),Object.keys(this.userData).length>0&&(e.userData=this.userData),this.parameters!==void 0){const c=this.parameters;for(const l in c)c[l]!==void 0&&(e[l]=c[l]);return e}e.data={attributes:{}};const t=this.index;t!==null&&(e.data.index={type:t.array.constructor.name,array:Array.prototype.slice.call(t.array)});const n=this.attributes;for(const c in n){const l=n[c];e.data.attributes[c]=l.toJSON(e.data)}const s={};let r=!1;for(const c in this.morphAttributes){const l=this.morphAttributes[c],d=[];for(let u=0,h=l.length;u<h;u++){const f=l[u];d.push(f.toJSON(e.data))}d.length>0&&(s[c]=d,r=!0)}r&&(e.data.morphAttributes=s,e.data.morphTargetsRelative=this.morphTargetsRelative);const a=this.groups;a.length>0&&(e.data.groups=JSON.parse(JSON.stringify(a)));const o=this.boundingSphere;return o!==null&&(e.data.boundingSphere=o.toJSON()),e}clone(){return new this.constructor().copy(this)}copy(e){this.index=null,this.attributes={},this.morphAttributes={},this.groups=[],this.boundingBox=null,this.boundingSphere=null;const t={};this.name=e.name;const n=e.index;n!==null&&this.setIndex(n.clone());const s=e.attributes;for(const l in s){const d=s[l];this.setAttribute(l,d.clone(t))}const r=e.morphAttributes;for(const l in r){const d=[],u=r[l];for(let h=0,f=u.length;h<f;h++)d.push(u[h].clone(t));this.morphAttributes[l]=d}this.morphTargetsRelative=e.morphTargetsRelative;const a=e.groups;for(let l=0,d=a.length;l<d;l++){const u=a[l];this.addGroup(u.start,u.count,u.materialIndex)}const o=e.boundingBox;o!==null&&(this.boundingBox=o.clone());const c=e.boundingSphere;return c!==null&&(this.boundingSphere=c.clone()),this.drawRange.start=e.drawRange.start,this.drawRange.count=e.drawRange.count,this.userData=e.userData,this}dispose(){this.dispatchEvent({type:"dispose"})}}const Jp=new Ft,vs=new n_,mo=new Td,Zp=new B,go=new B,vo=new B,bo=new B,Od=new B,yo=new B,Qp=new B,_o=new B;class qn extends Sn{constructor(e=new Wn,t=new Xp){super(),this.isMesh=!0,this.type="Mesh",this.geometry=e,this.material=t,this.morphTargetDictionary=void 0,this.morphTargetInfluences=void 0,this.count=1,this.updateMorphTargets()}copy(e,t){return super.copy(e,t),e.morphTargetInfluences!==void 0&&(this.morphTargetInfluences=e.morphTargetInfluences.slice()),e.morphTargetDictionary!==void 0&&(this.morphTargetDictionary=Object.assign({},e.morphTargetDictionary)),this.material=Array.isArray(e.material)?e.material.slice():e.material,this.geometry=e.geometry,this}updateMorphTargets(){const t=this.geometry.morphAttributes,n=Object.keys(t);if(n.length>0){const s=t[n[0]];if(s!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let r=0,a=s.length;r<a;r++){const o=s[r].name||String(r);this.morphTargetInfluences.push(0),this.morphTargetDictionary[o]=r}}}}getVertexPosition(e,t){const n=this.geometry,s=n.attributes.position,r=n.morphAttributes.position,a=n.morphTargetsRelative;t.fromBufferAttribute(s,e);const o=this.morphTargetInfluences;if(r&&o){yo.set(0,0,0);for(let c=0,l=r.length;c<l;c++){const d=o[c],u=r[c];d!==0&&(Od.fromBufferAttribute(u,e),a?yo.addScaledVector(Od,d):yo.addScaledVector(Od.sub(t),d))}t.add(yo)}return t}raycast(e,t){const n=this.geometry,s=this.material,r=this.matrixWorld;s!==void 0&&(n.boundingSphere===null&&n.computeBoundingSphere(),mo.copy(n.boundingSphere),mo.applyMatrix4(r),vs.copy(e.ray).recast(e.near),!(mo.containsPoint(vs.origin)===!1&&(vs.intersectSphere(mo,Zp)===null||vs.origin.distanceToSquared(Zp)>(e.far-e.near)**2))&&(Jp.copy(r).invert(),vs.copy(e.ray).applyMatrix4(Jp),!(n.boundingBox!==null&&vs.intersectsBox(n.boundingBox)===!1)&&this._computeIntersections(e,t,vs)))}_computeIntersections(e,t,n){let s;const r=this.geometry,a=this.material,o=r.index,c=r.attributes.position,l=r.attributes.uv,d=r.attributes.uv1,u=r.attributes.normal,h=r.groups,f=r.drawRange;if(o!==null)if(Array.isArray(a))for(let g=0,v=h.length;g<v;g++){const m=h[g],p=a[m.materialIndex],x=Math.max(m.start,f.start),C=Math.min(o.count,Math.min(m.start+m.count,f.start+f.count));for(let b=x,S=C;b<S;b+=3){const M=o.getX(b),A=o.getX(b+1),k=o.getX(b+2);s=So(this,p,e,n,l,d,u,M,A,k),s&&(s.faceIndex=Math.floor(b/3),s.face.materialIndex=m.materialIndex,t.push(s))}}else{const g=Math.max(0,f.start),v=Math.min(o.count,f.start+f.count);for(let m=g,p=v;m<p;m+=3){const x=o.getX(m),C=o.getX(m+1),b=o.getX(m+2);s=So(this,a,e,n,l,d,u,x,C,b),s&&(s.faceIndex=Math.floor(m/3),t.push(s))}}else if(c!==void 0)if(Array.isArray(a))for(let g=0,v=h.length;g<v;g++){const m=h[g],p=a[m.materialIndex],x=Math.max(m.start,f.start),C=Math.min(c.count,Math.min(m.start+m.count,f.start+f.count));for(let b=x,S=C;b<S;b+=3){const M=b,A=b+1,k=b+2;s=So(this,p,e,n,l,d,u,M,A,k),s&&(s.faceIndex=Math.floor(b/3),s.face.materialIndex=m.materialIndex,t.push(s))}}else{const g=Math.max(0,f.start),v=Math.min(c.count,f.start+f.count);for(let m=g,p=v;m<p;m+=3){const x=m,C=m+1,b=m+2;s=So(this,a,e,n,l,d,u,x,C,b),s&&(s.faceIndex=Math.floor(m/3),t.push(s))}}}}function h_(i,e,t,n,s,r,a,o){let c;if(e.side===en?c=n.intersectTriangle(a,r,s,!0,o):c=n.intersectTriangle(s,r,a,e.side===yi,o),c===null)return null;_o.copy(o),_o.applyMatrix4(i.matrixWorld);const l=t.ray.origin.distanceTo(_o);return l<t.near||l>t.far?null:{distance:l,point:_o.clone(),object:i}}function So(i,e,t,n,s,r,a,o,c,l){i.getVertexPosition(o,go),i.getVertexPosition(c,vo),i.getVertexPosition(l,bo);const d=h_(i,e,t,n,go,vo,bo,Qp);if(d){const u=new B;Hn.getBarycoord(Qp,go,vo,bo,u),s&&(d.uv=Hn.getInterpolatedAttribute(s,o,c,l,u,new lt)),r&&(d.uv1=Hn.getInterpolatedAttribute(r,o,c,l,u,new lt)),a&&(d.normal=Hn.getInterpolatedAttribute(a,o,c,l,u,new B),d.normal.dot(n.direction)>0&&d.normal.multiplyScalar(-1));const h={a:o,b:c,c:l,normal:new B,materialIndex:0};Hn.getNormal(go,vo,bo,h.normal),d.face=h,d.barycoord=u}return d}class ta extends Wn{constructor(e=1,t=1,n=1,s=1,r=1,a=1){super(),this.type="BoxGeometry",this.parameters={width:e,height:t,depth:n,widthSegments:s,heightSegments:r,depthSegments:a};const o=this;s=Math.floor(s),r=Math.floor(r),a=Math.floor(a);const c=[],l=[],d=[],u=[];let h=0,f=0;g("z","y","x",-1,-1,n,t,e,a,r,0),g("z","y","x",1,-1,n,t,-e,a,r,1),g("x","z","y",1,1,e,n,t,s,a,2),g("x","z","y",1,-1,e,n,-t,s,a,3),g("x","y","z",1,-1,e,t,n,s,r,4),g("x","y","z",-1,-1,e,t,-n,s,r,5),this.setIndex(c),this.setAttribute("position",new nn(l,3)),this.setAttribute("normal",new nn(d,3)),this.setAttribute("uv",new nn(u,2));function g(v,m,p,x,C,b,S,M,A,k,_){const T=b/A,R=S/k,O=b/2,z=S/2,$=M/2,J=A+1,W=k+1;let q=0,ne=0;const be=new B;for(let ue=0;ue<W;ue++){const _e=ue*R-z;for(let ze=0;ze<J;ze++){const Be=ze*T-O;be[v]=Be*x,be[m]=_e*C,be[p]=$,l.push(be.x,be.y,be.z),be[v]=0,be[m]=0,be[p]=M>0?1:-1,d.push(be.x,be.y,be.z),u.push(ze/A),u.push(1-ue/k),q+=1}}for(let ue=0;ue<k;ue++)for(let _e=0;_e<A;_e++){const ze=h+_e+J*ue,Be=h+_e+J*(ue+1),wt=h+(_e+1)+J*(ue+1),vt=h+(_e+1)+J*ue;c.push(ze,Be,vt),c.push(Be,wt,vt),ne+=6}o.addGroup(f,ne,_),f+=ne,h+=q}}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new ta(e.width,e.height,e.depth,e.widthSegments,e.heightSegments,e.depthSegments)}}function lr(i){const e={};for(const t in i){e[t]={};for(const n in i[t]){const s=i[t][n];s&&(s.isColor||s.isMatrix3||s.isMatrix4||s.isVector2||s.isVector3||s.isVector4||s.isTexture||s.isQuaternion)?s.isRenderTargetTexture?(Oe("UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms()."),e[t][n]=null):e[t][n]=s.clone():Array.isArray(s)?e[t][n]=s.slice():e[t][n]=s}}return e}function sn(i){const e={};for(let t=0;t<i.length;t++){const n=lr(i[t]);for(const s in n)e[s]=n[s]}return e}function f_(i){const e=[];for(let t=0;t<i.length;t++)e.push(i[t].clone());return e}function em(i){const e=i.getRenderTarget();return e===null?i.outputColorSpace:e.isXRRenderTarget===!0?e.texture.colorSpace:it.workingColorSpace}const p_={clone:lr,merge:sn};var m_=`void main() {
|
|
89
89
|
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
|
|
90
90
|
}`,g_=`void main() {
|
|
91
91
|
gl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );
|
|
@@ -4099,7 +4099,7 @@ void main() {
|
|
|
4099
4099
|
|
|
4100
4100
|
}
|
|
4101
4101
|
|
|
4102
|
-
}`;class FC{constructor(){this.texture=null,this.mesh=null,this.depthNear=0,this.depthFar=0}init(e,t){if(this.texture===null){const n=new om(e.texture);(e.depthNear!==t.depthNear||e.depthFar!==t.depthFar)&&(this.depthNear=e.depthNear,this.depthFar=e.depthFar),this.texture=n}}getMesh(e){if(this.texture!==null&&this.mesh===null){const t=e.cameras[0].viewport,n=new An({vertexShader:NC,fragmentShader:OC,uniforms:{depthColor:{value:this.texture},depthWidth:{value:t.z},depthHeight:{value:t.w}}});this.mesh=new qn(new Co(20,20),n)}return this.mesh}reset(){this.texture=null,this.mesh=null}getDepthTexture(){return this.texture}}class BC extends Js{constructor(e,t){super();const n=this;let s=null,r=1,a=null,o="local-floor",c=1,l=null,d=null,u=null,h=null,f=null,g=null;const v=typeof XRWebGLBinding<"u",m=new FC,p={},x=t.getContextAttributes();let C=null,b=null;const S=[],M=[],A=new lt;let k=null;const _=new Rn;_.viewport=new Ut;const T=new Rn;T.viewport=new Ut;const R=[_,T],O=new A_;let z=null,$=null;this.cameraAutoUpdate=!0,this.enabled=!1,this.isPresenting=!1,this.getController=function(K){let se=S[K];return se===void 0&&(se=new Fd,S[K]=se),se.getTargetRaySpace()},this.getControllerGrip=function(K){let se=S[K];return se===void 0&&(se=new Fd,S[K]=se),se.getGripSpace()},this.getHand=function(K){let se=S[K];return se===void 0&&(se=new Fd,S[K]=se),se.getHandSpace()};function J(K){const se=M.indexOf(K.inputSource);if(se===-1)return;const Ce=S[se];Ce!==void 0&&(Ce.update(K.inputSource,K.frame,l||a),Ce.dispatchEvent({type:K.type,data:K.inputSource}))}function W(){s.removeEventListener("select",J),s.removeEventListener("selectstart",J),s.removeEventListener("selectend",J),s.removeEventListener("squeeze",J),s.removeEventListener("squeezestart",J),s.removeEventListener("squeezeend",J),s.removeEventListener("end",W),s.removeEventListener("inputsourceschange",q);for(let K=0;K<S.length;K++){const se=M[K];se!==null&&(M[K]=null,S[K].disconnect(se))}z=null,$=null,m.reset();for(const K in p)delete p[K];e.setRenderTarget(C),f=null,h=null,u=null,s=null,b=null,vt.stop(),n.isPresenting=!1,e.setPixelRatio(k),e.setSize(A.width,A.height,!1),n.dispatchEvent({type:"sessionend"})}this.setFramebufferScaleFactor=function(K){r=K,n.isPresenting===!0&&Oe("WebXRManager: Cannot change framebuffer scale while presenting.")},this.setReferenceSpaceType=function(K){o=K,n.isPresenting===!0&&Oe("WebXRManager: Cannot change reference space type while presenting.")},this.getReferenceSpace=function(){return l||a},this.setReferenceSpace=function(K){l=K},this.getBaseLayer=function(){return h!==null?h:f},this.getBinding=function(){return u===null&&v&&(u=new XRWebGLBinding(s,t)),u},this.getFrame=function(){return g},this.getSession=function(){return s},this.setSession=async function(K){if(s=K,s!==null){if(C=e.getRenderTarget(),s.addEventListener("select",J),s.addEventListener("selectstart",J),s.addEventListener("selectend",J),s.addEventListener("squeeze",J),s.addEventListener("squeezestart",J),s.addEventListener("squeezeend",J),s.addEventListener("end",W),s.addEventListener("inputsourceschange",q),x.xrCompatible!==!0&&await t.makeXRCompatible(),k=e.getPixelRatio(),e.getSize(A),v&&"createProjectionLayer"in XRWebGLBinding.prototype){let Ce=null,Ge=null,we=null;x.depth&&(we=x.stencil?t.DEPTH24_STENCIL8:t.DEPTH_COMPONENT24,Ce=x.stencil?ps:Ci,Ge=x.stencil?qr:ni);const at={colorFormat:t.RGBA8,depthFormat:we,scaleFactor:r};u=this.getBinding(),h=u.createProjectionLayer(at),s.updateRenderState({layers:[h]}),e.setPixelRatio(1),e.setSize(h.textureWidth,h.textureHeight,!1),b=new ri(h.textureWidth,h.textureHeight,{format:Bn,type:En,depthTexture:new na(h.textureWidth,h.textureHeight,Ge,void 0,void 0,void 0,void 0,void 0,void 0,Ce),stencilBuffer:x.stencil,colorSpace:e.outputColorSpace,samples:x.antialias?4:0,resolveDepthBuffer:h.ignoreDepthValues===!1,resolveStencilBuffer:h.ignoreDepthValues===!1})}else{const Ce={antialias:x.antialias,alpha:!0,depth:x.depth,stencil:x.stencil,framebufferScaleFactor:r};f=new XRWebGLLayer(s,t,Ce),s.updateRenderState({baseLayer:f}),e.setPixelRatio(1),e.setSize(f.framebufferWidth,f.framebufferHeight,!1),b=new ri(f.framebufferWidth,f.framebufferHeight,{format:Bn,type:En,colorSpace:e.outputColorSpace,stencilBuffer:x.stencil,resolveDepthBuffer:f.ignoreDepthValues===!1,resolveStencilBuffer:f.ignoreDepthValues===!1})}b.isXRRenderTarget=!0,this.setFoveation(c),l=null,a=await s.requestReferenceSpace(o),vt.setContext(s),vt.start(),n.isPresenting=!0,n.dispatchEvent({type:"sessionstart"})}},this.getEnvironmentBlendMode=function(){if(s!==null)return s.environmentBlendMode},this.getDepthTexture=function(){return m.getDepthTexture()};function q(K){for(let se=0;se<K.removed.length;se++){const Ce=K.removed[se],Ge=M.indexOf(Ce);Ge>=0&&(M[Ge]=null,S[Ge].disconnect(Ce))}for(let se=0;se<K.added.length;se++){const Ce=K.added[se];let Ge=M.indexOf(Ce);if(Ge===-1){for(let at=0;at<S.length;at++)if(at>=M.length){M.push(Ce),Ge=at;break}else if(M[at]===null){M[at]=Ce,Ge=at;break}if(Ge===-1)break}const we=S[Ge];we&&we.connect(Ce)}}const ne=new B,be=new B;function ue(K,se,Ce){ne.setFromMatrixPosition(se.matrixWorld),be.setFromMatrixPosition(Ce.matrixWorld);const Ge=ne.distanceTo(be),we=se.projectionMatrix.elements,at=Ce.projectionMatrix.elements,Xt=we[14]/(we[10]-1),st=we[14]/(we[10]+1),ht=(we[9]+1)/we[5],St=(we[9]-1)/we[5],qe=(we[8]-1)/we[0],zt=(at[8]+1)/at[0],I=Xt*qe,Vt=Xt*zt,dt=Ge/(-qe+zt),Tt=dt*-qe;if(se.matrixWorld.decompose(K.position,K.quaternion,K.scale),K.translateX(Tt),K.translateZ(dt),K.matrixWorld.compose(K.position,K.quaternion,K.scale),K.matrixWorldInverse.copy(K.matrixWorld).invert(),we[10]===-1)K.projectionMatrix.copy(se.projectionMatrix),K.projectionMatrixInverse.copy(se.projectionMatrixInverse);else{const Re=Xt+dt,w=st+dt,y=I-Tt,L=Vt+(Ge-Tt),X=ht*st/w*Re,te=St*st/w*Re;K.projectionMatrix.makePerspective(y,L,X,te,Re,w),K.projectionMatrixInverse.copy(K.projectionMatrix).invert()}}function _e(K,se){se===null?K.matrixWorld.copy(K.matrix):K.matrixWorld.multiplyMatrices(se.matrixWorld,K.matrix),K.matrixWorldInverse.copy(K.matrixWorld).invert()}this.updateCamera=function(K){if(s===null)return;let se=K.near,Ce=K.far;m.texture!==null&&(m.depthNear>0&&(se=m.depthNear),m.depthFar>0&&(Ce=m.depthFar)),O.near=T.near=_.near=se,O.far=T.far=_.far=Ce,(z!==O.near||$!==O.far)&&(s.updateRenderState({depthNear:O.near,depthFar:O.far}),z=O.near,$=O.far),O.layers.mask=K.layers.mask|6,_.layers.mask=O.layers.mask&3,T.layers.mask=O.layers.mask&5;const Ge=K.parent,we=O.cameras;_e(O,Ge);for(let at=0;at<we.length;at++)_e(we[at],Ge);we.length===2?ue(O,_,T):O.projectionMatrix.copy(_.projectionMatrix),ze(K,O,Ge)};function ze(K,se,Ce){Ce===null?K.matrix.copy(se.matrixWorld):(K.matrix.copy(Ce.matrixWorld),K.matrix.invert(),K.matrix.multiply(se.matrixWorld)),K.matrix.decompose(K.position,K.quaternion,K.scale),K.updateMatrixWorld(!0),K.projectionMatrix.copy(se.projectionMatrix),K.projectionMatrixInverse.copy(se.projectionMatrixInverse),K.isPerspectiveCamera&&(K.fov=pd*2*Math.atan(1/K.projectionMatrix.elements[5]),K.zoom=1)}this.getCamera=function(){return O},this.getFoveation=function(){if(!(h===null&&f===null))return c},this.setFoveation=function(K){c=K,h!==null&&(h.fixedFoveation=K),f!==null&&f.fixedFoveation!==void 0&&(f.fixedFoveation=K)},this.hasDepthSensing=function(){return m.texture!==null},this.getDepthSensingMesh=function(){return m.getMesh(O)},this.getCameraTexture=function(K){return p[K]};let Be=null;function wt(K,se){if(d=se.getViewerPose(l||a),g=se,d!==null){const Ce=d.views;f!==null&&(e.setRenderTargetFramebuffer(b,f.framebuffer),e.setRenderTarget(b));let Ge=!1;Ce.length!==O.cameras.length&&(O.cameras.length=0,Ge=!0);for(let st=0;st<Ce.length;st++){const ht=Ce[st];let St=null;if(f!==null)St=f.getViewport(ht);else{const zt=u.getViewSubImage(h,ht);St=zt.viewport,st===0&&(e.setRenderTargetTextures(b,zt.colorTexture,zt.depthStencilTexture),e.setRenderTarget(b))}let qe=R[st];qe===void 0&&(qe=new Rn,qe.layers.enable(st),qe.viewport=new Ut,R[st]=qe),qe.matrix.fromArray(ht.transform.matrix),qe.matrix.decompose(qe.position,qe.quaternion,qe.scale),qe.projectionMatrix.fromArray(ht.projectionMatrix),qe.projectionMatrixInverse.copy(qe.projectionMatrix).invert(),qe.viewport.set(St.x,St.y,St.width,St.height),st===0&&(O.matrix.copy(qe.matrix),O.matrix.decompose(O.position,O.quaternion,O.scale)),Ge===!0&&O.cameras.push(qe)}const we=s.enabledFeatures;if(we&&we.includes("depth-sensing")&&s.depthUsage=="gpu-optimized"&&v){u=n.getBinding();const st=u.getDepthInformation(Ce[0]);st&&st.isValid&&st.texture&&m.init(st,s.renderState)}if(we&&we.includes("camera-access")&&v){e.state.unbindTexture(),u=n.getBinding();for(let st=0;st<Ce.length;st++){const ht=Ce[st].camera;if(ht){let St=p[ht];St||(St=new om,p[ht]=St);const qe=u.getCameraImage(ht);St.sourceTexture=qe}}}}for(let Ce=0;Ce<S.length;Ce++){const Ge=M[Ce],we=S[Ce];Ge!==null&&we!==void 0&&we.update(Ge,se,l||a)}Be&&Be(K,se),se.detectedPlanes&&n.dispatchEvent({type:"planesdetected",data:se}),g=null}const vt=new dm;vt.setAnimationLoop(wt),this.setAnimationLoop=function(K){Be=K},this.dispose=function(){}}}const xs=new Ai,zC=new Ft;function VC(i,e){function t(m,p){m.matrixAutoUpdate===!0&&m.updateMatrix(),p.value.copy(m.matrix)}function n(m,p){p.color.getRGB(m.fogColor.value,em(i)),p.isFog?(m.fogNear.value=p.near,m.fogFar.value=p.far):p.isFogExp2&&(m.fogDensity.value=p.density)}function s(m,p,x,C,b){p.isMeshBasicMaterial||p.isMeshLambertMaterial?r(m,p):p.isMeshToonMaterial?(r(m,p),u(m,p)):p.isMeshPhongMaterial?(r(m,p),d(m,p)):p.isMeshStandardMaterial?(r(m,p),h(m,p),p.isMeshPhysicalMaterial&&f(m,p,b)):p.isMeshMatcapMaterial?(r(m,p),g(m,p)):p.isMeshDepthMaterial?r(m,p):p.isMeshDistanceMaterial?(r(m,p),v(m,p)):p.isMeshNormalMaterial?r(m,p):p.isLineBasicMaterial?(a(m,p),p.isLineDashedMaterial&&o(m,p)):p.isPointsMaterial?c(m,p,x,C):p.isSpriteMaterial?l(m,p):p.isShadowMaterial?(m.color.value.copy(p.color),m.opacity.value=p.opacity):p.isShaderMaterial&&(p.uniformsNeedUpdate=!1)}function r(m,p){m.opacity.value=p.opacity,p.color&&m.diffuse.value.copy(p.color),p.emissive&&m.emissive.value.copy(p.emissive).multiplyScalar(p.emissiveIntensity),p.map&&(m.map.value=p.map,t(p.map,m.mapTransform)),p.alphaMap&&(m.alphaMap.value=p.alphaMap,t(p.alphaMap,m.alphaMapTransform)),p.bumpMap&&(m.bumpMap.value=p.bumpMap,t(p.bumpMap,m.bumpMapTransform),m.bumpScale.value=p.bumpScale,p.side===en&&(m.bumpScale.value*=-1)),p.normalMap&&(m.normalMap.value=p.normalMap,t(p.normalMap,m.normalMapTransform),m.normalScale.value.copy(p.normalScale),p.side===en&&m.normalScale.value.negate()),p.displacementMap&&(m.displacementMap.value=p.displacementMap,t(p.displacementMap,m.displacementMapTransform),m.displacementScale.value=p.displacementScale,m.displacementBias.value=p.displacementBias),p.emissiveMap&&(m.emissiveMap.value=p.emissiveMap,t(p.emissiveMap,m.emissiveMapTransform)),p.specularMap&&(m.specularMap.value=p.specularMap,t(p.specularMap,m.specularMapTransform)),p.alphaTest>0&&(m.alphaTest.value=p.alphaTest);const x=e.get(p),C=x.envMap,b=x.envMapRotation;C&&(m.envMap.value=C,xs.copy(b),xs.x*=-1,xs.y*=-1,xs.z*=-1,C.isCubeTexture&&C.isRenderTargetTexture===!1&&(xs.y*=-1,xs.z*=-1),m.envMapRotation.value.setFromMatrix4(zC.makeRotationFromEuler(xs)),m.flipEnvMap.value=C.isCubeTexture&&C.isRenderTargetTexture===!1?-1:1,m.reflectivity.value=p.reflectivity,m.ior.value=p.ior,m.refractionRatio.value=p.refractionRatio),p.lightMap&&(m.lightMap.value=p.lightMap,m.lightMapIntensity.value=p.lightMapIntensity,t(p.lightMap,m.lightMapTransform)),p.aoMap&&(m.aoMap.value=p.aoMap,m.aoMapIntensity.value=p.aoMapIntensity,t(p.aoMap,m.aoMapTransform))}function a(m,p){m.diffuse.value.copy(p.color),m.opacity.value=p.opacity,p.map&&(m.map.value=p.map,t(p.map,m.mapTransform))}function o(m,p){m.dashSize.value=p.dashSize,m.totalSize.value=p.dashSize+p.gapSize,m.scale.value=p.scale}function c(m,p,x,C){m.diffuse.value.copy(p.color),m.opacity.value=p.opacity,m.size.value=p.size*x,m.scale.value=C*.5,p.map&&(m.map.value=p.map,t(p.map,m.uvTransform)),p.alphaMap&&(m.alphaMap.value=p.alphaMap,t(p.alphaMap,m.alphaMapTransform)),p.alphaTest>0&&(m.alphaTest.value=p.alphaTest)}function l(m,p){m.diffuse.value.copy(p.color),m.opacity.value=p.opacity,m.rotation.value=p.rotation,p.map&&(m.map.value=p.map,t(p.map,m.mapTransform)),p.alphaMap&&(m.alphaMap.value=p.alphaMap,t(p.alphaMap,m.alphaMapTransform)),p.alphaTest>0&&(m.alphaTest.value=p.alphaTest)}function d(m,p){m.specular.value.copy(p.specular),m.shininess.value=Math.max(p.shininess,1e-4)}function u(m,p){p.gradientMap&&(m.gradientMap.value=p.gradientMap)}function h(m,p){m.metalness.value=p.metalness,p.metalnessMap&&(m.metalnessMap.value=p.metalnessMap,t(p.metalnessMap,m.metalnessMapTransform)),m.roughness.value=p.roughness,p.roughnessMap&&(m.roughnessMap.value=p.roughnessMap,t(p.roughnessMap,m.roughnessMapTransform)),p.envMap&&(m.envMapIntensity.value=p.envMapIntensity)}function f(m,p,x){m.ior.value=p.ior,p.sheen>0&&(m.sheenColor.value.copy(p.sheenColor).multiplyScalar(p.sheen),m.sheenRoughness.value=p.sheenRoughness,p.sheenColorMap&&(m.sheenColorMap.value=p.sheenColorMap,t(p.sheenColorMap,m.sheenColorMapTransform)),p.sheenRoughnessMap&&(m.sheenRoughnessMap.value=p.sheenRoughnessMap,t(p.sheenRoughnessMap,m.sheenRoughnessMapTransform))),p.clearcoat>0&&(m.clearcoat.value=p.clearcoat,m.clearcoatRoughness.value=p.clearcoatRoughness,p.clearcoatMap&&(m.clearcoatMap.value=p.clearcoatMap,t(p.clearcoatMap,m.clearcoatMapTransform)),p.clearcoatRoughnessMap&&(m.clearcoatRoughnessMap.value=p.clearcoatRoughnessMap,t(p.clearcoatRoughnessMap,m.clearcoatRoughnessMapTransform)),p.clearcoatNormalMap&&(m.clearcoatNormalMap.value=p.clearcoatNormalMap,t(p.clearcoatNormalMap,m.clearcoatNormalMapTransform),m.clearcoatNormalScale.value.copy(p.clearcoatNormalScale),p.side===en&&m.clearcoatNormalScale.value.negate())),p.dispersion>0&&(m.dispersion.value=p.dispersion),p.iridescence>0&&(m.iridescence.value=p.iridescence,m.iridescenceIOR.value=p.iridescenceIOR,m.iridescenceThicknessMinimum.value=p.iridescenceThicknessRange[0],m.iridescenceThicknessMaximum.value=p.iridescenceThicknessRange[1],p.iridescenceMap&&(m.iridescenceMap.value=p.iridescenceMap,t(p.iridescenceMap,m.iridescenceMapTransform)),p.iridescenceThicknessMap&&(m.iridescenceThicknessMap.value=p.iridescenceThicknessMap,t(p.iridescenceThicknessMap,m.iridescenceThicknessMapTransform))),p.transmission>0&&(m.transmission.value=p.transmission,m.transmissionSamplerMap.value=x.texture,m.transmissionSamplerSize.value.set(x.width,x.height),p.transmissionMap&&(m.transmissionMap.value=p.transmissionMap,t(p.transmissionMap,m.transmissionMapTransform)),m.thickness.value=p.thickness,p.thicknessMap&&(m.thicknessMap.value=p.thicknessMap,t(p.thicknessMap,m.thicknessMapTransform)),m.attenuationDistance.value=p.attenuationDistance,m.attenuationColor.value.copy(p.attenuationColor)),p.anisotropy>0&&(m.anisotropyVector.value.set(p.anisotropy*Math.cos(p.anisotropyRotation),p.anisotropy*Math.sin(p.anisotropyRotation)),p.anisotropyMap&&(m.anisotropyMap.value=p.anisotropyMap,t(p.anisotropyMap,m.anisotropyMapTransform))),m.specularIntensity.value=p.specularIntensity,m.specularColor.value.copy(p.specularColor),p.specularColorMap&&(m.specularColorMap.value=p.specularColorMap,t(p.specularColorMap,m.specularColorMapTransform)),p.specularIntensityMap&&(m.specularIntensityMap.value=p.specularIntensityMap,t(p.specularIntensityMap,m.specularIntensityMapTransform))}function g(m,p){p.matcap&&(m.matcap.value=p.matcap)}function v(m,p){const x=e.get(p).light;m.referencePosition.value.setFromMatrixPosition(x.matrixWorld),m.nearDistance.value=x.shadow.camera.near,m.farDistance.value=x.shadow.camera.far}return{refreshFogUniforms:n,refreshMaterialUniforms:s}}function GC(i,e,t,n){let s={},r={},a=[];const o=i.getParameter(i.MAX_UNIFORM_BUFFER_BINDINGS);function c(x,C){const b=C.program;n.uniformBlockBinding(x,b)}function l(x,C){let b=s[x.id];b===void 0&&(g(x),b=d(x),s[x.id]=b,x.addEventListener("dispose",m));const S=C.program;n.updateUBOMapping(x,S);const M=e.render.frame;r[x.id]!==M&&(h(x),r[x.id]=M)}function d(x){const C=u();x.__bindingPointIndex=C;const b=i.createBuffer(),S=x.__size,M=x.usage;return i.bindBuffer(i.UNIFORM_BUFFER,b),i.bufferData(i.UNIFORM_BUFFER,S,M),i.bindBuffer(i.UNIFORM_BUFFER,null),i.bindBufferBase(i.UNIFORM_BUFFER,C,b),b}function u(){for(let x=0;x<o;x++)if(a.indexOf(x)===-1)return a.push(x),x;return rt("WebGLRenderer: Maximum number of simultaneously usable uniforms groups reached."),0}function h(x){const C=s[x.id],b=x.uniforms,S=x.__cache;i.bindBuffer(i.UNIFORM_BUFFER,C);for(let M=0,A=b.length;M<A;M++){const k=Array.isArray(b[M])?b[M]:[b[M]];for(let _=0,T=k.length;_<T;_++){const R=k[_];if(f(R,M,_,S)===!0){const O=R.__offset,z=Array.isArray(R.value)?R.value:[R.value];let $=0;for(let J=0;J<z.length;J++){const W=z[J],q=v(W);typeof W=="number"||typeof W=="boolean"?(R.__data[0]=W,i.bufferSubData(i.UNIFORM_BUFFER,O+$,R.__data)):W.isMatrix3?(R.__data[0]=W.elements[0],R.__data[1]=W.elements[1],R.__data[2]=W.elements[2],R.__data[3]=0,R.__data[4]=W.elements[3],R.__data[5]=W.elements[4],R.__data[6]=W.elements[5],R.__data[7]=0,R.__data[8]=W.elements[6],R.__data[9]=W.elements[7],R.__data[10]=W.elements[8],R.__data[11]=0):(W.toArray(R.__data,$),$+=q.storage/Float32Array.BYTES_PER_ELEMENT)}i.bufferSubData(i.UNIFORM_BUFFER,O,R.__data)}}}i.bindBuffer(i.UNIFORM_BUFFER,null)}function f(x,C,b,S){const M=x.value,A=C+"_"+b;if(S[A]===void 0)return typeof M=="number"||typeof M=="boolean"?S[A]=M:S[A]=M.clone(),!0;{const k=S[A];if(typeof M=="number"||typeof M=="boolean"){if(k!==M)return S[A]=M,!0}else if(k.equals(M)===!1)return k.copy(M),!0}return!1}function g(x){const C=x.uniforms;let b=0;const S=16;for(let A=0,k=C.length;A<k;A++){const _=Array.isArray(C[A])?C[A]:[C[A]];for(let T=0,R=_.length;T<R;T++){const O=_[T],z=Array.isArray(O.value)?O.value:[O.value];for(let $=0,J=z.length;$<J;$++){const W=z[$],q=v(W),ne=b%S,be=ne%q.boundary,ue=ne+be;b+=be,ue!==0&&S-ue<q.storage&&(b+=S-ue),O.__data=new Float32Array(q.storage/Float32Array.BYTES_PER_ELEMENT),O.__offset=b,b+=q.storage}}}const M=b%S;return M>0&&(b+=S-M),x.__size=b,x.__cache={},this}function v(x){const C={boundary:0,storage:0};return typeof x=="number"||typeof x=="boolean"?(C.boundary=4,C.storage=4):x.isVector2?(C.boundary=8,C.storage=8):x.isVector3||x.isColor?(C.boundary=16,C.storage=12):x.isVector4?(C.boundary=16,C.storage=16):x.isMatrix3?(C.boundary=48,C.storage=48):x.isMatrix4?(C.boundary=64,C.storage=64):x.isTexture?Oe("WebGLRenderer: Texture samplers can not be part of an uniforms group."):Oe("WebGLRenderer: Unsupported uniform value type.",x),C}function m(x){const C=x.target;C.removeEventListener("dispose",m);const b=a.indexOf(C.__bindingPointIndex);a.splice(b,1),i.deleteBuffer(s[C.id]),delete s[C.id],delete r[C.id]}function p(){for(const x in s)i.deleteBuffer(s[x]);a=[],s={},r={}}return{bind:c,update:l,dispose:p}}const HC=new Uint16Array([12469,15057,12620,14925,13266,14620,13807,14376,14323,13990,14545,13625,14713,13328,14840,12882,14931,12528,14996,12233,15039,11829,15066,11525,15080,11295,15085,10976,15082,10705,15073,10495,13880,14564,13898,14542,13977,14430,14158,14124,14393,13732,14556,13410,14702,12996,14814,12596,14891,12291,14937,11834,14957,11489,14958,11194,14943,10803,14921,10506,14893,10278,14858,9960,14484,14039,14487,14025,14499,13941,14524,13740,14574,13468,14654,13106,14743,12678,14818,12344,14867,11893,14889,11509,14893,11180,14881,10751,14852,10428,14812,10128,14765,9754,14712,9466,14764,13480,14764,13475,14766,13440,14766,13347,14769,13070,14786,12713,14816,12387,14844,11957,14860,11549,14868,11215,14855,10751,14825,10403,14782,10044,14729,9651,14666,9352,14599,9029,14967,12835,14966,12831,14963,12804,14954,12723,14936,12564,14917,12347,14900,11958,14886,11569,14878,11247,14859,10765,14828,10401,14784,10011,14727,9600,14660,9289,14586,8893,14508,8533,15111,12234,15110,12234,15104,12216,15092,12156,15067,12010,15028,11776,14981,11500,14942,11205,14902,10752,14861,10393,14812,9991,14752,9570,14682,9252,14603,8808,14519,8445,14431,8145,15209,11449,15208,11451,15202,11451,15190,11438,15163,11384,15117,11274,15055,10979,14994,10648,14932,10343,14871,9936,14803,9532,14729,9218,14645,8742,14556,8381,14461,8020,14365,7603,15273,10603,15272,10607,15267,10619,15256,10631,15231,10614,15182,10535,15118,10389,15042,10167,14963,9787,14883,9447,14800,9115,14710,8665,14615,8318,14514,7911,14411,7507,14279,7198,15314,9675,15313,9683,15309,9712,15298,9759,15277,9797,15229,9773,15166,9668,15084,9487,14995,9274,14898,8910,14800,8539,14697,8234,14590,7790,14479,7409,14367,7067,14178,6621,15337,8619,15337,8631,15333,8677,15325,8769,15305,8871,15264,8940,15202,8909,15119,8775,15022,8565,14916,8328,14804,8009,14688,7614,14569,7287,14448,6888,14321,6483,14088,6171,15350,7402,15350,7419,15347,7480,15340,7613,15322,7804,15287,7973,15229,8057,15148,8012,15046,7846,14933,7611,14810,7357,14682,7069,14552,6656,14421,6316,14251,5948,14007,5528,15356,5942,15356,5977,15353,6119,15348,6294,15332,6551,15302,6824,15249,7044,15171,7122,15070,7050,14949,6861,14818,6611,14679,6349,14538,6067,14398,5651,14189,5311,13935,4958,15359,4123,15359,4153,15356,4296,15353,4646,15338,5160,15311,5508,15263,5829,15188,6042,15088,6094,14966,6001,14826,5796,14678,5543,14527,5287,14377,4985,14133,4586,13869,4257,15360,1563,15360,1642,15358,2076,15354,2636,15341,3350,15317,4019,15273,4429,15203,4732,15105,4911,14981,4932,14836,4818,14679,4621,14517,4386,14359,4156,14083,3795,13808,3437,15360,122,15360,137,15358,285,15355,636,15344,1274,15322,2177,15281,2765,15215,3223,15120,3451,14995,3569,14846,3567,14681,3466,14511,3305,14344,3121,14037,2800,13753,2467,15360,0,15360,1,15359,21,15355,89,15346,253,15325,479,15287,796,15225,1148,15133,1492,15008,1749,14856,1882,14685,1886,14506,1783,14324,1608,13996,1398,13702,1183]);let ci=null;function WC(){return ci===null&&(ci=new __(HC,16,16,Xs,Ti),ci.name="DFG_LUT",ci.minFilter=Jt,ci.magFilter=Jt,ci.wrapS=xi,ci.wrapT=xi,ci.generateMipmaps=!1,ci.needsUpdate=!0),ci}class qC{constructor(e={}){const{canvas:t=$y(),context:n=null,depth:s=!0,stencil:r=!1,alpha:a=!1,antialias:o=!1,premultipliedAlpha:c=!0,preserveDrawingBuffer:l=!1,powerPreference:d="default",failIfMajorPerformanceCaveat:u=!1,reversedDepthBuffer:h=!1,outputBufferType:f=En}=e;this.isWebGLRenderer=!0;let g;if(n!==null){if(typeof WebGLRenderingContext<"u"&&n instanceof WebGLRenderingContext)throw new Error("THREE.WebGLRenderer: WebGL 1 is not supported since r163.");g=n.getContextAttributes().alpha}else g=a;const v=f,m=new Set([Il,kl,Pl]),p=new Set([En,ni,Wr,qr,Al,Rl]),x=new Uint32Array(4),C=new Int32Array(4);let b=null,S=null;const M=[],A=[];let k=null;this.domElement=t,this.debug={checkShaderErrors:!0,onShaderError:null},this.autoClear=!0,this.autoClearColor=!0,this.autoClearDepth=!0,this.autoClearStencil=!0,this.sortObjects=!0,this.clippingPlanes=[],this.localClippingEnabled=!1,this.toneMapping=ti,this.toneMappingExposure=1,this.transmissionResolutionScale=1;const _=this;let T=!1;this._outputColorSpace=Mn;let R=0,O=0,z=null,$=-1,J=null;const W=new Ut,q=new Ut;let ne=null;const be=new nt(0);let ue=0,_e=t.width,ze=t.height,Be=1,wt=null,vt=null;const K=new Ut(0,0,_e,ze),se=new Ut(0,0,_e,ze);let Ce=!1;const Ge=new am;let we=!1,at=!1;const Xt=new Ft,st=new B,ht=new Ut,St={background:null,fog:null,environment:null,overrideMaterial:null,isScene:!0};let qe=!1;function zt(){return z===null?Be:1}let I=n;function Vt(E,U){return t.getContext(E,U)}try{const E={alpha:!0,depth:s,stencil:r,antialias:o,premultipliedAlpha:c,preserveDrawingBuffer:l,powerPreference:d,failIfMajorPerformanceCaveat:u};if("setAttribute"in t&&t.setAttribute("data-engine",`three.js r${ul}`),t.addEventListener("webglcontextlost",Fe,!1),t.addEventListener("webglcontextrestored",Ct,!1),t.addEventListener("webglcontextcreationerror",ft,!1),I===null){const U="webgl2";if(I=Vt(U,E),I===null)throw Vt(U)?new Error("Error creating WebGL context with your selected attributes."):new Error("Error creating WebGL context.")}}catch(E){throw rt("WebGLRenderer: "+E.message),E}let dt,Tt,Re,w,y,L,X,te,j,ke,fe,Ae,Ne,ae,me,Me,Pe,pe,$e,D,Se,ce,xe,re;function ee(){dt=new Wx(I),dt.init(),ce=new UC(I,dt),Tt=new Ux(I,dt,e,ce),Re=new DC(I,dt),Tt.reversedDepthBuffer&&h&&Re.buffers.depth.setReversed(!0),w=new jx(I),y=new bC,L=new LC(I,dt,Re,y,Tt,ce,w),X=new Ox(_),te=new Hx(_),j=new k_(I),xe=new Dx(I,j),ke=new qx(I,j,w,xe),fe=new Yx(I,ke,j,w),$e=new Xx(I,Tt,L),Me=new Nx(y),Ae=new vC(_,X,te,dt,Tt,xe,Me),Ne=new VC(_,y),ae=new _C,me=new MC(dt),pe=new Ix(_,X,te,Re,fe,g,c),Pe=new kC(_,fe,Tt),re=new GC(I,w,Tt,Re),D=new Lx(I,dt,w),Se=new $x(I,dt,w),w.programs=Ae.programs,_.capabilities=Tt,_.extensions=dt,_.properties=y,_.renderLists=ae,_.shadowMap=Pe,_.state=Re,_.info=w}ee(),v!==En&&(k=new Jx(v,t.width,t.height,s,r));const he=new BC(_,I);this.xr=he,this.getContext=function(){return I},this.getContextAttributes=function(){return I.getContextAttributes()},this.forceContextLoss=function(){const E=dt.get("WEBGL_lose_context");E&&E.loseContext()},this.forceContextRestore=function(){const E=dt.get("WEBGL_lose_context");E&&E.restoreContext()},this.getPixelRatio=function(){return Be},this.setPixelRatio=function(E){E!==void 0&&(Be=E,this.setSize(_e,ze,!1))},this.getSize=function(E){return E.set(_e,ze)},this.setSize=function(E,U,H=!0){if(he.isPresenting){Oe("WebGLRenderer: Can't change size while VR device is presenting.");return}_e=E,ze=U,t.width=Math.floor(E*Be),t.height=Math.floor(U*Be),H===!0&&(t.style.width=E+"px",t.style.height=U+"px"),k!==null&&k.setSize(t.width,t.height),this.setViewport(0,0,E,U)},this.getDrawingBufferSize=function(E){return E.set(_e*Be,ze*Be).floor()},this.setDrawingBufferSize=function(E,U,H){_e=E,ze=U,Be=H,t.width=Math.floor(E*H),t.height=Math.floor(U*H),this.setViewport(0,0,E,U)},this.setEffects=function(E){if(v===En){console.error("THREE.WebGLRenderer: setEffects() requires outputBufferType set to HalfFloatType or FloatType.");return}if(E){for(let U=0;U<E.length;U++)if(E[U].isOutputPass===!0){console.warn("THREE.WebGLRenderer: OutputPass is not needed in setEffects(). Tone mapping and color space conversion are applied automatically.");break}}k.setEffects(E||[])},this.getCurrentViewport=function(E){return E.copy(W)},this.getViewport=function(E){return E.copy(K)},this.setViewport=function(E,U,H,V){E.isVector4?K.set(E.x,E.y,E.z,E.w):K.set(E,U,H,V),Re.viewport(W.copy(K).multiplyScalar(Be).round())},this.getScissor=function(E){return E.copy(se)},this.setScissor=function(E,U,H,V){E.isVector4?se.set(E.x,E.y,E.z,E.w):se.set(E,U,H,V),Re.scissor(q.copy(se).multiplyScalar(Be).round())},this.getScissorTest=function(){return Ce},this.setScissorTest=function(E){Re.setScissorTest(Ce=E)},this.setOpaqueSort=function(E){wt=E},this.setTransparentSort=function(E){vt=E},this.getClearColor=function(E){return E.copy(pe.getClearColor())},this.setClearColor=function(){pe.setClearColor(...arguments)},this.getClearAlpha=function(){return pe.getClearAlpha()},this.setClearAlpha=function(){pe.setClearAlpha(...arguments)},this.clear=function(E=!0,U=!0,H=!0){let V=0;if(E){let F=!1;if(z!==null){const ge=z.texture.format;F=m.has(ge)}if(F){const ge=z.texture.type,Te=p.has(ge),ye=pe.getClearColor(),Ee=pe.getClearAlpha(),Ie=ye.r,Ue=ye.g,De=ye.b;Te?(x[0]=Ie,x[1]=Ue,x[2]=De,x[3]=Ee,I.clearBufferuiv(I.COLOR,0,x)):(C[0]=Ie,C[1]=Ue,C[2]=De,C[3]=Ee,I.clearBufferiv(I.COLOR,0,C))}else V|=I.COLOR_BUFFER_BIT}U&&(V|=I.DEPTH_BUFFER_BIT),H&&(V|=I.STENCIL_BUFFER_BIT,this.state.buffers.stencil.setMask(4294967295)),I.clear(V)},this.clearColor=function(){this.clear(!0,!1,!1)},this.clearDepth=function(){this.clear(!1,!0,!1)},this.clearStencil=function(){this.clear(!1,!1,!0)},this.dispose=function(){t.removeEventListener("webglcontextlost",Fe,!1),t.removeEventListener("webglcontextrestored",Ct,!1),t.removeEventListener("webglcontextcreationerror",ft,!1),pe.dispose(),ae.dispose(),me.dispose(),y.dispose(),X.dispose(),te.dispose(),fe.dispose(),xe.dispose(),re.dispose(),Ae.dispose(),he.dispose(),he.removeEventListener("sessionstart",Vm),he.removeEventListener("sessionend",Gm),Es.stop()};function Fe(E){E.preventDefault(),Dp("WebGLRenderer: Context Lost."),T=!0}function Ct(){Dp("WebGLRenderer: Context Restored."),T=!1;const E=w.autoReset,U=Pe.enabled,H=Pe.autoUpdate,V=Pe.needsUpdate,F=Pe.type;ee(),w.autoReset=E,Pe.enabled=U,Pe.autoUpdate=H,Pe.needsUpdate=V,Pe.type=F}function ft(E){rt("WebGLRenderer: A WebGL context could not be created. Reason: ",E.statusMessage)}function li(E){const U=E.target;U.removeEventListener("dispose",li),Ii(U)}function Ii(E){vE(E),y.remove(E)}function vE(E){const U=y.get(E).programs;U!==void 0&&(U.forEach(function(H){Ae.releaseProgram(H)}),E.isShaderMaterial&&Ae.releaseShaderCache(E))}this.renderBufferDirect=function(E,U,H,V,F,ge){U===null&&(U=St);const Te=F.isMesh&&F.matrixWorld.determinant()<0,ye=yE(E,U,H,V,F);Re.setMaterial(V,Te);let Ee=H.index,Ie=1;if(V.wireframe===!0){if(Ee=ke.getWireframeAttribute(H),Ee===void 0)return;Ie=2}const Ue=H.drawRange,De=H.attributes.position;let je=Ue.start*Ie,bt=(Ue.start+Ue.count)*Ie;ge!==null&&(je=Math.max(je,ge.start*Ie),bt=Math.min(bt,(ge.start+ge.count)*Ie)),Ee!==null?(je=Math.max(je,0),bt=Math.min(bt,Ee.count)):De!=null&&(je=Math.max(je,0),bt=Math.min(bt,De.count));const It=bt-je;if(It<0||It===1/0)return;xe.setup(F,V,ye,H,Ee);let Dt,xt=D;if(Ee!==null&&(Dt=j.get(Ee),xt=Se,xt.setIndex(Dt)),F.isMesh)V.wireframe===!0?(Re.setLineWidth(V.wireframeLinewidth*zt()),xt.setMode(I.LINES)):xt.setMode(I.TRIANGLES);else if(F.isLine){let Le=V.linewidth;Le===void 0&&(Le=1),Re.setLineWidth(Le*zt()),F.isLineSegments?xt.setMode(I.LINES):F.isLineLoop?xt.setMode(I.LINE_LOOP):xt.setMode(I.LINE_STRIP)}else F.isPoints?xt.setMode(I.POINTS):F.isSprite&&xt.setMode(I.TRIANGLES);if(F.isBatchedMesh)if(F._multiDrawInstances!==null)$r("WebGLRenderer: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection."),xt.renderMultiDrawInstances(F._multiDrawStarts,F._multiDrawCounts,F._multiDrawCount,F._multiDrawInstances);else if(dt.get("WEBGL_multi_draw"))xt.renderMultiDraw(F._multiDrawStarts,F._multiDrawCounts,F._multiDrawCount);else{const Le=F._multiDrawStarts,pt=F._multiDrawCounts,ot=F._multiDrawCount,Tn=Ee?j.get(Ee).bytesPerElement:1,gr=y.get(V).currentProgram.getUniforms();for(let Cn=0;Cn<ot;Cn++)gr.setValue(I,"_gl_DrawID",Cn),xt.render(Le[Cn]/Tn,pt[Cn])}else if(F.isInstancedMesh)xt.renderInstances(je,It,F.count);else if(H.isInstancedBufferGeometry){const Le=H._maxInstanceCount!==void 0?H._maxInstanceCount:1/0,pt=Math.min(H.instanceCount,Le);xt.renderInstances(je,It,pt)}else xt.render(je,It)};function zm(E,U,H){E.transparent===!0&&E.side===_i&&E.forceSinglePass===!1?(E.side=en,E.needsUpdate=!0,Fo(E,U,H),E.side=yi,E.needsUpdate=!0,Fo(E,U,H),E.side=_i):Fo(E,U,H)}this.compile=function(E,U,H=null){H===null&&(H=E),S=me.get(H),S.init(U),A.push(S),H.traverseVisible(function(F){F.isLight&&F.layers.test(U.layers)&&(S.pushLight(F),F.castShadow&&S.pushShadow(F))}),E!==H&&E.traverseVisible(function(F){F.isLight&&F.layers.test(U.layers)&&(S.pushLight(F),F.castShadow&&S.pushShadow(F))}),S.setupLights();const V=new Set;return E.traverse(function(F){if(!(F.isMesh||F.isPoints||F.isLine||F.isSprite))return;const ge=F.material;if(ge)if(Array.isArray(ge))for(let Te=0;Te<ge.length;Te++){const ye=ge[Te];zm(ye,H,F),V.add(ye)}else zm(ge,H,F),V.add(ge)}),S=A.pop(),V},this.compileAsync=function(E,U,H=null){const V=this.compile(E,U,H);return new Promise(F=>{function ge(){if(V.forEach(function(Te){y.get(Te).currentProgram.isReady()&&V.delete(Te)}),V.size===0){F(E);return}setTimeout(ge,10)}dt.get("KHR_parallel_shader_compile")!==null?ge():setTimeout(ge,10)})};let Qd=null;function bE(E){Qd&&Qd(E)}function Vm(){Es.stop()}function Gm(){Es.start()}const Es=new dm;Es.setAnimationLoop(bE),typeof self<"u"&&Es.setContext(self),this.setAnimationLoop=function(E){Qd=E,he.setAnimationLoop(E),E===null?Es.stop():Es.start()},he.addEventListener("sessionstart",Vm),he.addEventListener("sessionend",Gm),this.render=function(E,U){if(U!==void 0&&U.isCamera!==!0){rt("WebGLRenderer.render: camera is not an instance of THREE.Camera.");return}if(T===!0)return;const H=he.enabled===!0&&he.isPresenting===!0,V=k!==null&&(z===null||H)&&k.begin(_,z);if(E.matrixWorldAutoUpdate===!0&&E.updateMatrixWorld(),U.parent===null&&U.matrixWorldAutoUpdate===!0&&U.updateMatrixWorld(),he.enabled===!0&&he.isPresenting===!0&&(k===null||k.isCompositing()===!1)&&(he.cameraAutoUpdate===!0&&he.updateCamera(U),U=he.getCamera()),E.isScene===!0&&E.onBeforeRender(_,E,U,z),S=me.get(E,A.length),S.init(U),A.push(S),Xt.multiplyMatrices(U.projectionMatrix,U.matrixWorldInverse),Ge.setFromProjectionMatrix(Xt,si,U.reversedDepth),at=this.localClippingEnabled,we=Me.init(this.clippingPlanes,at),b=ae.get(E,M.length),b.init(),M.push(b),he.enabled===!0&&he.isPresenting===!0){const Te=_.xr.getDepthSensingMesh();Te!==null&&eu(Te,U,-1/0,_.sortObjects)}eu(E,U,0,_.sortObjects),b.finish(),_.sortObjects===!0&&b.sort(wt,vt),qe=he.enabled===!1||he.isPresenting===!1||he.hasDepthSensing()===!1,qe&&pe.addToRenderList(b,E),this.info.render.frame++,we===!0&&Me.beginShadows();const F=S.state.shadowsArray;if(Pe.render(F,E,U),we===!0&&Me.endShadows(),this.info.autoReset===!0&&this.info.reset(),(V&&k.hasRenderPass())===!1){const Te=b.opaque,ye=b.transmissive;if(S.setupLights(),U.isArrayCamera){const Ee=U.cameras;if(ye.length>0)for(let Ie=0,Ue=Ee.length;Ie<Ue;Ie++){const De=Ee[Ie];Wm(Te,ye,E,De)}qe&&pe.render(E);for(let Ie=0,Ue=Ee.length;Ie<Ue;Ie++){const De=Ee[Ie];Hm(b,E,De,De.viewport)}}else ye.length>0&&Wm(Te,ye,E,U),qe&&pe.render(E),Hm(b,E,U)}z!==null&&O===0&&(L.updateMultisampleRenderTarget(z),L.updateRenderTargetMipmap(z)),V&&k.end(_),E.isScene===!0&&E.onAfterRender(_,E,U),xe.resetDefaultState(),$=-1,J=null,A.pop(),A.length>0?(S=A[A.length-1],we===!0&&Me.setGlobalState(_.clippingPlanes,S.state.camera)):S=null,M.pop(),M.length>0?b=M[M.length-1]:b=null};function eu(E,U,H,V){if(E.visible===!1)return;if(E.layers.test(U.layers)){if(E.isGroup)H=E.renderOrder;else if(E.isLOD)E.autoUpdate===!0&&E.update(U);else if(E.isLight)S.pushLight(E),E.castShadow&&S.pushShadow(E);else if(E.isSprite){if(!E.frustumCulled||Ge.intersectsSprite(E)){V&&ht.setFromMatrixPosition(E.matrixWorld).applyMatrix4(Xt);const Te=fe.update(E),ye=E.material;ye.visible&&b.push(E,Te,ye,H,ht.z,null)}}else if((E.isMesh||E.isLine||E.isPoints)&&(!E.frustumCulled||Ge.intersectsObject(E))){const Te=fe.update(E),ye=E.material;if(V&&(E.boundingSphere!==void 0?(E.boundingSphere===null&&E.computeBoundingSphere(),ht.copy(E.boundingSphere.center)):(Te.boundingSphere===null&&Te.computeBoundingSphere(),ht.copy(Te.boundingSphere.center)),ht.applyMatrix4(E.matrixWorld).applyMatrix4(Xt)),Array.isArray(ye)){const Ee=Te.groups;for(let Ie=0,Ue=Ee.length;Ie<Ue;Ie++){const De=Ee[Ie],je=ye[De.materialIndex];je&&je.visible&&b.push(E,Te,je,H,ht.z,De)}}else ye.visible&&b.push(E,Te,ye,H,ht.z,null)}}const ge=E.children;for(let Te=0,ye=ge.length;Te<ye;Te++)eu(ge[Te],U,H,V)}function Hm(E,U,H,V){const{opaque:F,transmissive:ge,transparent:Te}=E;S.setupLightsView(H),we===!0&&Me.setGlobalState(_.clippingPlanes,H),V&&Re.viewport(W.copy(V)),F.length>0&&Oo(F,U,H),ge.length>0&&Oo(ge,U,H),Te.length>0&&Oo(Te,U,H),Re.buffers.depth.setTest(!0),Re.buffers.depth.setMask(!0),Re.buffers.color.setMask(!0),Re.setPolygonOffset(!1)}function Wm(E,U,H,V){if((H.isScene===!0?H.overrideMaterial:null)!==null)return;if(S.state.transmissionRenderTarget[V.id]===void 0){const je=dt.has("EXT_color_buffer_half_float")||dt.has("EXT_color_buffer_float");S.state.transmissionRenderTarget[V.id]=new ri(1,1,{generateMipmaps:!0,type:je?Ti:En,minFilter:fs,samples:Tt.samples,stencilBuffer:r,resolveDepthBuffer:!1,resolveStencilBuffer:!1,colorSpace:it.workingColorSpace})}const ge=S.state.transmissionRenderTarget[V.id],Te=V.viewport||W;ge.setSize(Te.z*_.transmissionResolutionScale,Te.w*_.transmissionResolutionScale);const ye=_.getRenderTarget(),Ee=_.getActiveCubeFace(),Ie=_.getActiveMipmapLevel();_.setRenderTarget(ge),_.getClearColor(be),ue=_.getClearAlpha(),ue<1&&_.setClearColor(16777215,.5),_.clear(),qe&&pe.render(H);const Ue=_.toneMapping;_.toneMapping=ti;const De=V.viewport;if(V.viewport!==void 0&&(V.viewport=void 0),S.setupLightsView(V),we===!0&&Me.setGlobalState(_.clippingPlanes,V),Oo(E,H,V),L.updateMultisampleRenderTarget(ge),L.updateRenderTargetMipmap(ge),dt.has("WEBGL_multisampled_render_to_texture")===!1){let je=!1;for(let bt=0,It=U.length;bt<It;bt++){const Dt=U[bt],{object:xt,geometry:Le,material:pt,group:ot}=Dt;if(pt.side===_i&&xt.layers.test(V.layers)){const Tn=pt.side;pt.side=en,pt.needsUpdate=!0,qm(xt,H,V,Le,pt,ot),pt.side=Tn,pt.needsUpdate=!0,je=!0}}je===!0&&(L.updateMultisampleRenderTarget(ge),L.updateRenderTargetMipmap(ge))}_.setRenderTarget(ye,Ee,Ie),_.setClearColor(be,ue),De!==void 0&&(V.viewport=De),_.toneMapping=Ue}function Oo(E,U,H){const V=U.isScene===!0?U.overrideMaterial:null;for(let F=0,ge=E.length;F<ge;F++){const Te=E[F],{object:ye,geometry:Ee,group:Ie}=Te;let Ue=Te.material;Ue.allowOverride===!0&&V!==null&&(Ue=V),ye.layers.test(H.layers)&&qm(ye,U,H,Ee,Ue,Ie)}}function qm(E,U,H,V,F,ge){E.onBeforeRender(_,U,H,V,F,ge),E.modelViewMatrix.multiplyMatrices(H.matrixWorldInverse,E.matrixWorld),E.normalMatrix.getNormalMatrix(E.modelViewMatrix),F.onBeforeRender(_,U,H,V,E,ge),F.transparent===!0&&F.side===_i&&F.forceSinglePass===!1?(F.side=en,F.needsUpdate=!0,_.renderBufferDirect(H,U,V,F,E,ge),F.side=yi,F.needsUpdate=!0,_.renderBufferDirect(H,U,V,F,E,ge),F.side=_i):_.renderBufferDirect(H,U,V,F,E,ge),E.onAfterRender(_,U,H,V,F,ge)}function Fo(E,U,H){U.isScene!==!0&&(U=St);const V=y.get(E),F=S.state.lights,ge=S.state.shadowsArray,Te=F.state.version,ye=Ae.getParameters(E,F.state,ge,U,H),Ee=Ae.getProgramCacheKey(ye);let Ie=V.programs;V.environment=E.isMeshStandardMaterial?U.environment:null,V.fog=U.fog,V.envMap=(E.isMeshStandardMaterial?te:X).get(E.envMap||V.environment),V.envMapRotation=V.environment!==null&&E.envMap===null?U.environmentRotation:E.envMapRotation,Ie===void 0&&(E.addEventListener("dispose",li),Ie=new Map,V.programs=Ie);let Ue=Ie.get(Ee);if(Ue!==void 0){if(V.currentProgram===Ue&&V.lightsStateVersion===Te)return jm(E,ye),Ue}else ye.uniforms=Ae.getUniforms(E),E.onBeforeCompile(ye,_),Ue=Ae.acquireProgram(ye,Ee),Ie.set(Ee,Ue),V.uniforms=ye.uniforms;const De=V.uniforms;return(!E.isShaderMaterial&&!E.isRawShaderMaterial||E.clipping===!0)&&(De.clippingPlanes=Me.uniform),jm(E,ye),V.needsLights=SE(E),V.lightsStateVersion=Te,V.needsLights&&(De.ambientLightColor.value=F.state.ambient,De.lightProbe.value=F.state.probe,De.directionalLights.value=F.state.directional,De.directionalLightShadows.value=F.state.directionalShadow,De.spotLights.value=F.state.spot,De.spotLightShadows.value=F.state.spotShadow,De.rectAreaLights.value=F.state.rectArea,De.ltc_1.value=F.state.rectAreaLTC1,De.ltc_2.value=F.state.rectAreaLTC2,De.pointLights.value=F.state.point,De.pointLightShadows.value=F.state.pointShadow,De.hemisphereLights.value=F.state.hemi,De.directionalShadowMap.value=F.state.directionalShadowMap,De.directionalShadowMatrix.value=F.state.directionalShadowMatrix,De.spotShadowMap.value=F.state.spotShadowMap,De.spotLightMatrix.value=F.state.spotLightMatrix,De.spotLightMap.value=F.state.spotLightMap,De.pointShadowMap.value=F.state.pointShadowMap,De.pointShadowMatrix.value=F.state.pointShadowMatrix),V.currentProgram=Ue,V.uniformsList=null,Ue}function $m(E){if(E.uniformsList===null){const U=E.currentProgram.getUniforms();E.uniformsList=Ao.seqWithValue(U.seq,E.uniforms)}return E.uniformsList}function jm(E,U){const H=y.get(E);H.outputColorSpace=U.outputColorSpace,H.batching=U.batching,H.batchingColor=U.batchingColor,H.instancing=U.instancing,H.instancingColor=U.instancingColor,H.instancingMorph=U.instancingMorph,H.skinning=U.skinning,H.morphTargets=U.morphTargets,H.morphNormals=U.morphNormals,H.morphColors=U.morphColors,H.morphTargetsCount=U.morphTargetsCount,H.numClippingPlanes=U.numClippingPlanes,H.numIntersection=U.numClipIntersection,H.vertexAlphas=U.vertexAlphas,H.vertexTangents=U.vertexTangents,H.toneMapping=U.toneMapping}function yE(E,U,H,V,F){U.isScene!==!0&&(U=St),L.resetTextureUnits();const ge=U.fog,Te=V.isMeshStandardMaterial?U.environment:null,ye=z===null?_.outputColorSpace:z.isXRRenderTarget===!0?z.texture.colorSpace:Ys,Ee=(V.isMeshStandardMaterial?te:X).get(V.envMap||Te),Ie=V.vertexColors===!0&&!!H.attributes.color&&H.attributes.color.itemSize===4,Ue=!!H.attributes.tangent&&(!!V.normalMap||V.anisotropy>0),De=!!H.morphAttributes.position,je=!!H.morphAttributes.normal,bt=!!H.morphAttributes.color;let It=ti;V.toneMapped&&(z===null||z.isXRRenderTarget===!0)&&(It=_.toneMapping);const Dt=H.morphAttributes.position||H.morphAttributes.normal||H.morphAttributes.color,xt=Dt!==void 0?Dt.length:0,Le=y.get(V),pt=S.state.lights;if(we===!0&&(at===!0||E!==J)){const rn=E===J&&V.id===$;Me.setState(V,E,rn)}let ot=!1;V.version===Le.__version?(Le.needsLights&&Le.lightsStateVersion!==pt.state.version||Le.outputColorSpace!==ye||F.isBatchedMesh&&Le.batching===!1||!F.isBatchedMesh&&Le.batching===!0||F.isBatchedMesh&&Le.batchingColor===!0&&F.colorTexture===null||F.isBatchedMesh&&Le.batchingColor===!1&&F.colorTexture!==null||F.isInstancedMesh&&Le.instancing===!1||!F.isInstancedMesh&&Le.instancing===!0||F.isSkinnedMesh&&Le.skinning===!1||!F.isSkinnedMesh&&Le.skinning===!0||F.isInstancedMesh&&Le.instancingColor===!0&&F.instanceColor===null||F.isInstancedMesh&&Le.instancingColor===!1&&F.instanceColor!==null||F.isInstancedMesh&&Le.instancingMorph===!0&&F.morphTexture===null||F.isInstancedMesh&&Le.instancingMorph===!1&&F.morphTexture!==null||Le.envMap!==Ee||V.fog===!0&&Le.fog!==ge||Le.numClippingPlanes!==void 0&&(Le.numClippingPlanes!==Me.numPlanes||Le.numIntersection!==Me.numIntersection)||Le.vertexAlphas!==Ie||Le.vertexTangents!==Ue||Le.morphTargets!==De||Le.morphNormals!==je||Le.morphColors!==bt||Le.toneMapping!==It||Le.morphTargetsCount!==xt)&&(ot=!0):(ot=!0,Le.__version=V.version);let Tn=Le.currentProgram;ot===!0&&(Tn=Fo(V,U,F));let gr=!1,Cn=!1,ua=!1;const Et=Tn.getUniforms(),mn=Le.uniforms;if(Re.useProgram(Tn.program)&&(gr=!0,Cn=!0,ua=!0),V.id!==$&&($=V.id,Cn=!0),gr||J!==E){Re.buffers.depth.getReversed()&&E.reversedDepth!==!0&&(E._reversedDepth=!0,E.updateProjectionMatrix()),Et.setValue(I,"projectionMatrix",E.projectionMatrix),Et.setValue(I,"viewMatrix",E.matrixWorldInverse);const gn=Et.map.cameraPosition;gn!==void 0&&gn.setValue(I,st.setFromMatrixPosition(E.matrixWorld)),Tt.logarithmicDepthBuffer&&Et.setValue(I,"logDepthBufFC",2/(Math.log(E.far+1)/Math.LN2)),(V.isMeshPhongMaterial||V.isMeshToonMaterial||V.isMeshLambertMaterial||V.isMeshBasicMaterial||V.isMeshStandardMaterial||V.isShaderMaterial)&&Et.setValue(I,"isOrthographic",E.isOrthographicCamera===!0),J!==E&&(J=E,Cn=!0,ua=!0)}if(Le.needsLights&&(pt.state.directionalShadowMap.length>0&&Et.setValue(I,"directionalShadowMap",pt.state.directionalShadowMap,L),pt.state.spotShadowMap.length>0&&Et.setValue(I,"spotShadowMap",pt.state.spotShadowMap,L),pt.state.pointShadowMap.length>0&&Et.setValue(I,"pointShadowMap",pt.state.pointShadowMap,L)),F.isSkinnedMesh){Et.setOptional(I,F,"bindMatrix"),Et.setOptional(I,F,"bindMatrixInverse");const rn=F.skeleton;rn&&(rn.boneTexture===null&&rn.computeBoneTexture(),Et.setValue(I,"boneTexture",rn.boneTexture,L))}F.isBatchedMesh&&(Et.setOptional(I,F,"batchingTexture"),Et.setValue(I,"batchingTexture",F._matricesTexture,L),Et.setOptional(I,F,"batchingIdTexture"),Et.setValue(I,"batchingIdTexture",F._indirectTexture,L),Et.setOptional(I,F,"batchingColorTexture"),F._colorsTexture!==null&&Et.setValue(I,"batchingColorTexture",F._colorsTexture,L));const Pn=H.morphAttributes;if((Pn.position!==void 0||Pn.normal!==void 0||Pn.color!==void 0)&&$e.update(F,H,Tn),(Cn||Le.receiveShadow!==F.receiveShadow)&&(Le.receiveShadow=F.receiveShadow,Et.setValue(I,"receiveShadow",F.receiveShadow)),V.isMeshGouraudMaterial&&V.envMap!==null&&(mn.envMap.value=Ee,mn.flipEnvMap.value=Ee.isCubeTexture&&Ee.isRenderTargetTexture===!1?-1:1),V.isMeshStandardMaterial&&V.envMap===null&&U.environment!==null&&(mn.envMapIntensity.value=U.environmentIntensity),mn.dfgLUT!==void 0&&(mn.dfgLUT.value=WC()),Cn&&(Et.setValue(I,"toneMappingExposure",_.toneMappingExposure),Le.needsLights&&_E(mn,ua),ge&&V.fog===!0&&Ne.refreshFogUniforms(mn,ge),Ne.refreshMaterialUniforms(mn,V,Be,ze,S.state.transmissionRenderTarget[E.id]),Ao.upload(I,$m(Le),mn,L)),V.isShaderMaterial&&V.uniformsNeedUpdate===!0&&(Ao.upload(I,$m(Le),mn,L),V.uniformsNeedUpdate=!1),V.isSpriteMaterial&&Et.setValue(I,"center",F.center),Et.setValue(I,"modelViewMatrix",F.modelViewMatrix),Et.setValue(I,"normalMatrix",F.normalMatrix),Et.setValue(I,"modelMatrix",F.matrixWorld),V.isShaderMaterial||V.isRawShaderMaterial){const rn=V.uniformsGroups;for(let gn=0,tu=rn.length;gn<tu;gn++){const Ms=rn[gn];re.update(Ms,Tn),re.bind(Ms,Tn)}}return Tn}function _E(E,U){E.ambientLightColor.needsUpdate=U,E.lightProbe.needsUpdate=U,E.directionalLights.needsUpdate=U,E.directionalLightShadows.needsUpdate=U,E.pointLights.needsUpdate=U,E.pointLightShadows.needsUpdate=U,E.spotLights.needsUpdate=U,E.spotLightShadows.needsUpdate=U,E.rectAreaLights.needsUpdate=U,E.hemisphereLights.needsUpdate=U}function SE(E){return E.isMeshLambertMaterial||E.isMeshToonMaterial||E.isMeshPhongMaterial||E.isMeshStandardMaterial||E.isShadowMaterial||E.isShaderMaterial&&E.lights===!0}this.getActiveCubeFace=function(){return R},this.getActiveMipmapLevel=function(){return O},this.getRenderTarget=function(){return z},this.setRenderTargetTextures=function(E,U,H){const V=y.get(E);V.__autoAllocateDepthBuffer=E.resolveDepthBuffer===!1,V.__autoAllocateDepthBuffer===!1&&(V.__useRenderToTexture=!1),y.get(E.texture).__webglTexture=U,y.get(E.depthTexture).__webglTexture=V.__autoAllocateDepthBuffer?void 0:H,V.__hasExternalTextures=!0},this.setRenderTargetFramebuffer=function(E,U){const H=y.get(E);H.__webglFramebuffer=U,H.__useDefaultFramebuffer=U===void 0};const xE=I.createFramebuffer();this.setRenderTarget=function(E,U=0,H=0){z=E,R=U,O=H;let V=null,F=!1,ge=!1;if(E){const ye=y.get(E);if(ye.__useDefaultFramebuffer!==void 0){Re.bindFramebuffer(I.FRAMEBUFFER,ye.__webglFramebuffer),W.copy(E.viewport),q.copy(E.scissor),ne=E.scissorTest,Re.viewport(W),Re.scissor(q),Re.setScissorTest(ne),$=-1;return}else if(ye.__webglFramebuffer===void 0)L.setupRenderTarget(E);else if(ye.__hasExternalTextures)L.rebindTextures(E,y.get(E.texture).__webglTexture,y.get(E.depthTexture).__webglTexture);else if(E.depthBuffer){const Ue=E.depthTexture;if(ye.__boundDepthTexture!==Ue){if(Ue!==null&&y.has(Ue)&&(E.width!==Ue.image.width||E.height!==Ue.image.height))throw new Error("WebGLRenderTarget: Attached DepthTexture is initialized to the incorrect size.");L.setupDepthRenderbuffer(E)}}const Ee=E.texture;(Ee.isData3DTexture||Ee.isDataArrayTexture||Ee.isCompressedArrayTexture)&&(ge=!0);const Ie=y.get(E).__webglFramebuffer;E.isWebGLCubeRenderTarget?(Array.isArray(Ie[U])?V=Ie[U][H]:V=Ie[U],F=!0):E.samples>0&&L.useMultisampledRTT(E)===!1?V=y.get(E).__webglMultisampledFramebuffer:Array.isArray(Ie)?V=Ie[H]:V=Ie,W.copy(E.viewport),q.copy(E.scissor),ne=E.scissorTest}else W.copy(K).multiplyScalar(Be).floor(),q.copy(se).multiplyScalar(Be).floor(),ne=Ce;if(H!==0&&(V=xE),Re.bindFramebuffer(I.FRAMEBUFFER,V)&&Re.drawBuffers(E,V),Re.viewport(W),Re.scissor(q),Re.setScissorTest(ne),F){const ye=y.get(E.texture);I.framebufferTexture2D(I.FRAMEBUFFER,I.COLOR_ATTACHMENT0,I.TEXTURE_CUBE_MAP_POSITIVE_X+U,ye.__webglTexture,H)}else if(ge){const ye=U;for(let Ee=0;Ee<E.textures.length;Ee++){const Ie=y.get(E.textures[Ee]);I.framebufferTextureLayer(I.FRAMEBUFFER,I.COLOR_ATTACHMENT0+Ee,Ie.__webglTexture,H,ye)}}else if(E!==null&&H!==0){const ye=y.get(E.texture);I.framebufferTexture2D(I.FRAMEBUFFER,I.COLOR_ATTACHMENT0,I.TEXTURE_2D,ye.__webglTexture,H)}$=-1},this.readRenderTargetPixels=function(E,U,H,V,F,ge,Te,ye=0){if(!(E&&E.isWebGLRenderTarget)){rt("WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");return}let Ee=y.get(E).__webglFramebuffer;if(E.isWebGLCubeRenderTarget&&Te!==void 0&&(Ee=Ee[Te]),Ee){Re.bindFramebuffer(I.FRAMEBUFFER,Ee);try{const Ie=E.textures[ye],Ue=Ie.format,De=Ie.type;if(!Tt.textureFormatReadable(Ue)){rt("WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.");return}if(!Tt.textureTypeReadable(De)){rt("WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.");return}U>=0&&U<=E.width-V&&H>=0&&H<=E.height-F&&(E.textures.length>1&&I.readBuffer(I.COLOR_ATTACHMENT0+ye),I.readPixels(U,H,V,F,ce.convert(Ue),ce.convert(De),ge))}finally{const Ie=z!==null?y.get(z).__webglFramebuffer:null;Re.bindFramebuffer(I.FRAMEBUFFER,Ie)}}},this.readRenderTargetPixelsAsync=async function(E,U,H,V,F,ge,Te,ye=0){if(!(E&&E.isWebGLRenderTarget))throw new Error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");let Ee=y.get(E).__webglFramebuffer;if(E.isWebGLCubeRenderTarget&&Te!==void 0&&(Ee=Ee[Te]),Ee)if(U>=0&&U<=E.width-V&&H>=0&&H<=E.height-F){Re.bindFramebuffer(I.FRAMEBUFFER,Ee);const Ie=E.textures[ye],Ue=Ie.format,De=Ie.type;if(!Tt.textureFormatReadable(Ue))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.");if(!Tt.textureTypeReadable(De))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.");const je=I.createBuffer();I.bindBuffer(I.PIXEL_PACK_BUFFER,je),I.bufferData(I.PIXEL_PACK_BUFFER,ge.byteLength,I.STREAM_READ),E.textures.length>1&&I.readBuffer(I.COLOR_ATTACHMENT0+ye),I.readPixels(U,H,V,F,ce.convert(Ue),ce.convert(De),0);const bt=z!==null?y.get(z).__webglFramebuffer:null;Re.bindFramebuffer(I.FRAMEBUFFER,bt);const It=I.fenceSync(I.SYNC_GPU_COMMANDS_COMPLETE,0);return I.flush(),await jy(I,It,4),I.bindBuffer(I.PIXEL_PACK_BUFFER,je),I.getBufferSubData(I.PIXEL_PACK_BUFFER,0,ge),I.deleteBuffer(je),I.deleteSync(It),ge}else throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range.")},this.copyFramebufferToTexture=function(E,U=null,H=0){const V=Math.pow(2,-H),F=Math.floor(E.image.width*V),ge=Math.floor(E.image.height*V),Te=U!==null?U.x:0,ye=U!==null?U.y:0;L.setTexture2D(E,0),I.copyTexSubImage2D(I.TEXTURE_2D,H,0,0,Te,ye,F,ge),Re.unbindTexture()};const TE=I.createFramebuffer(),CE=I.createFramebuffer();this.copyTextureToTexture=function(E,U,H=null,V=null,F=0,ge=null){ge===null&&(F!==0?($r("WebGLRenderer: copyTextureToTexture function signature has changed to support src and dst mipmap levels."),ge=F,F=0):ge=0);let Te,ye,Ee,Ie,Ue,De,je,bt,It;const Dt=E.isCompressedTexture?E.mipmaps[ge]:E.image;if(H!==null)Te=H.max.x-H.min.x,ye=H.max.y-H.min.y,Ee=H.isBox3?H.max.z-H.min.z:1,Ie=H.min.x,Ue=H.min.y,De=H.isBox3?H.min.z:0;else{const Pn=Math.pow(2,-F);Te=Math.floor(Dt.width*Pn),ye=Math.floor(Dt.height*Pn),E.isDataArrayTexture?Ee=Dt.depth:E.isData3DTexture?Ee=Math.floor(Dt.depth*Pn):Ee=1,Ie=0,Ue=0,De=0}V!==null?(je=V.x,bt=V.y,It=V.z):(je=0,bt=0,It=0);const xt=ce.convert(U.format),Le=ce.convert(U.type);let pt;U.isData3DTexture?(L.setTexture3D(U,0),pt=I.TEXTURE_3D):U.isDataArrayTexture||U.isCompressedArrayTexture?(L.setTexture2DArray(U,0),pt=I.TEXTURE_2D_ARRAY):(L.setTexture2D(U,0),pt=I.TEXTURE_2D),I.pixelStorei(I.UNPACK_FLIP_Y_WEBGL,U.flipY),I.pixelStorei(I.UNPACK_PREMULTIPLY_ALPHA_WEBGL,U.premultiplyAlpha),I.pixelStorei(I.UNPACK_ALIGNMENT,U.unpackAlignment);const ot=I.getParameter(I.UNPACK_ROW_LENGTH),Tn=I.getParameter(I.UNPACK_IMAGE_HEIGHT),gr=I.getParameter(I.UNPACK_SKIP_PIXELS),Cn=I.getParameter(I.UNPACK_SKIP_ROWS),ua=I.getParameter(I.UNPACK_SKIP_IMAGES);I.pixelStorei(I.UNPACK_ROW_LENGTH,Dt.width),I.pixelStorei(I.UNPACK_IMAGE_HEIGHT,Dt.height),I.pixelStorei(I.UNPACK_SKIP_PIXELS,Ie),I.pixelStorei(I.UNPACK_SKIP_ROWS,Ue),I.pixelStorei(I.UNPACK_SKIP_IMAGES,De);const Et=E.isDataArrayTexture||E.isData3DTexture,mn=U.isDataArrayTexture||U.isData3DTexture;if(E.isDepthTexture){const Pn=y.get(E),rn=y.get(U),gn=y.get(Pn.__renderTarget),tu=y.get(rn.__renderTarget);Re.bindFramebuffer(I.READ_FRAMEBUFFER,gn.__webglFramebuffer),Re.bindFramebuffer(I.DRAW_FRAMEBUFFER,tu.__webglFramebuffer);for(let Ms=0;Ms<Ee;Ms++)Et&&(I.framebufferTextureLayer(I.READ_FRAMEBUFFER,I.COLOR_ATTACHMENT0,y.get(E).__webglTexture,F,De+Ms),I.framebufferTextureLayer(I.DRAW_FRAMEBUFFER,I.COLOR_ATTACHMENT0,y.get(U).__webglTexture,ge,It+Ms)),I.blitFramebuffer(Ie,Ue,Te,ye,je,bt,Te,ye,I.DEPTH_BUFFER_BIT,I.NEAREST);Re.bindFramebuffer(I.READ_FRAMEBUFFER,null),Re.bindFramebuffer(I.DRAW_FRAMEBUFFER,null)}else if(F!==0||E.isRenderTargetTexture||y.has(E)){const Pn=y.get(E),rn=y.get(U);Re.bindFramebuffer(I.READ_FRAMEBUFFER,TE),Re.bindFramebuffer(I.DRAW_FRAMEBUFFER,CE);for(let gn=0;gn<Ee;gn++)Et?I.framebufferTextureLayer(I.READ_FRAMEBUFFER,I.COLOR_ATTACHMENT0,Pn.__webglTexture,F,De+gn):I.framebufferTexture2D(I.READ_FRAMEBUFFER,I.COLOR_ATTACHMENT0,I.TEXTURE_2D,Pn.__webglTexture,F),mn?I.framebufferTextureLayer(I.DRAW_FRAMEBUFFER,I.COLOR_ATTACHMENT0,rn.__webglTexture,ge,It+gn):I.framebufferTexture2D(I.DRAW_FRAMEBUFFER,I.COLOR_ATTACHMENT0,I.TEXTURE_2D,rn.__webglTexture,ge),F!==0?I.blitFramebuffer(Ie,Ue,Te,ye,je,bt,Te,ye,I.COLOR_BUFFER_BIT,I.NEAREST):mn?I.copyTexSubImage3D(pt,ge,je,bt,It+gn,Ie,Ue,Te,ye):I.copyTexSubImage2D(pt,ge,je,bt,Ie,Ue,Te,ye);Re.bindFramebuffer(I.READ_FRAMEBUFFER,null),Re.bindFramebuffer(I.DRAW_FRAMEBUFFER,null)}else mn?E.isDataTexture||E.isData3DTexture?I.texSubImage3D(pt,ge,je,bt,It,Te,ye,Ee,xt,Le,Dt.data):U.isCompressedArrayTexture?I.compressedTexSubImage3D(pt,ge,je,bt,It,Te,ye,Ee,xt,Dt.data):I.texSubImage3D(pt,ge,je,bt,It,Te,ye,Ee,xt,Le,Dt):E.isDataTexture?I.texSubImage2D(I.TEXTURE_2D,ge,je,bt,Te,ye,xt,Le,Dt.data):E.isCompressedTexture?I.compressedTexSubImage2D(I.TEXTURE_2D,ge,je,bt,Dt.width,Dt.height,xt,Dt.data):I.texSubImage2D(I.TEXTURE_2D,ge,je,bt,Te,ye,xt,Le,Dt);I.pixelStorei(I.UNPACK_ROW_LENGTH,ot),I.pixelStorei(I.UNPACK_IMAGE_HEIGHT,Tn),I.pixelStorei(I.UNPACK_SKIP_PIXELS,gr),I.pixelStorei(I.UNPACK_SKIP_ROWS,Cn),I.pixelStorei(I.UNPACK_SKIP_IMAGES,ua),ge===0&&U.generateMipmaps&&I.generateMipmap(pt),Re.unbindTexture()},this.initRenderTarget=function(E){y.get(E).__webglFramebuffer===void 0&&L.setupRenderTarget(E)},this.initTexture=function(E){E.isCubeTexture?L.setTextureCube(E,0):E.isData3DTexture?L.setTexture3D(E,0):E.isDataArrayTexture||E.isCompressedArrayTexture?L.setTexture2DArray(E,0):L.setTexture2D(E,0),Re.unbindTexture()},this.resetState=function(){R=0,O=0,z=null,Re.reset(),xe.reset()},typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}get coordinateSystem(){return si}get outputColorSpace(){return this._outputColorSpace}set outputColorSpace(e){this._outputColorSpace=e;const t=this.getContext();t.drawingBufferColorSpace=it._getDrawingBufferColorSpace(e),t.unpackColorSpace=it._getUnpackColorSpace()}}const $C=`
|
|
4102
|
+
}`;class FC{constructor(){this.texture=null,this.mesh=null,this.depthNear=0,this.depthFar=0}init(e,t){if(this.texture===null){const n=new om(e.texture);(e.depthNear!==t.depthNear||e.depthFar!==t.depthFar)&&(this.depthNear=e.depthNear,this.depthFar=e.depthFar),this.texture=n}}getMesh(e){if(this.texture!==null&&this.mesh===null){const t=e.cameras[0].viewport,n=new An({vertexShader:NC,fragmentShader:OC,uniforms:{depthColor:{value:this.texture},depthWidth:{value:t.z},depthHeight:{value:t.w}}});this.mesh=new qn(new Co(20,20),n)}return this.mesh}reset(){this.texture=null,this.mesh=null}getDepthTexture(){return this.texture}}class BC extends Js{constructor(e,t){super();const n=this;let s=null,r=1,a=null,o="local-floor",c=1,l=null,d=null,u=null,h=null,f=null,g=null;const v=typeof XRWebGLBinding<"u",m=new FC,p={},x=t.getContextAttributes();let C=null,b=null;const S=[],M=[],A=new lt;let k=null;const _=new Rn;_.viewport=new Ut;const T=new Rn;T.viewport=new Ut;const R=[_,T],O=new A_;let z=null,$=null;this.cameraAutoUpdate=!0,this.enabled=!1,this.isPresenting=!1,this.getController=function(K){let se=S[K];return se===void 0&&(se=new Fd,S[K]=se),se.getTargetRaySpace()},this.getControllerGrip=function(K){let se=S[K];return se===void 0&&(se=new Fd,S[K]=se),se.getGripSpace()},this.getHand=function(K){let se=S[K];return se===void 0&&(se=new Fd,S[K]=se),se.getHandSpace()};function J(K){const se=M.indexOf(K.inputSource);if(se===-1)return;const Ce=S[se];Ce!==void 0&&(Ce.update(K.inputSource,K.frame,l||a),Ce.dispatchEvent({type:K.type,data:K.inputSource}))}function W(){s.removeEventListener("select",J),s.removeEventListener("selectstart",J),s.removeEventListener("selectend",J),s.removeEventListener("squeeze",J),s.removeEventListener("squeezestart",J),s.removeEventListener("squeezeend",J),s.removeEventListener("end",W),s.removeEventListener("inputsourceschange",q);for(let K=0;K<S.length;K++){const se=M[K];se!==null&&(M[K]=null,S[K].disconnect(se))}z=null,$=null,m.reset();for(const K in p)delete p[K];e.setRenderTarget(C),f=null,h=null,u=null,s=null,b=null,vt.stop(),n.isPresenting=!1,e.setPixelRatio(k),e.setSize(A.width,A.height,!1),n.dispatchEvent({type:"sessionend"})}this.setFramebufferScaleFactor=function(K){r=K,n.isPresenting===!0&&Oe("WebXRManager: Cannot change framebuffer scale while presenting.")},this.setReferenceSpaceType=function(K){o=K,n.isPresenting===!0&&Oe("WebXRManager: Cannot change reference space type while presenting.")},this.getReferenceSpace=function(){return l||a},this.setReferenceSpace=function(K){l=K},this.getBaseLayer=function(){return h!==null?h:f},this.getBinding=function(){return u===null&&v&&(u=new XRWebGLBinding(s,t)),u},this.getFrame=function(){return g},this.getSession=function(){return s},this.setSession=async function(K){if(s=K,s!==null){if(C=e.getRenderTarget(),s.addEventListener("select",J),s.addEventListener("selectstart",J),s.addEventListener("selectend",J),s.addEventListener("squeeze",J),s.addEventListener("squeezestart",J),s.addEventListener("squeezeend",J),s.addEventListener("end",W),s.addEventListener("inputsourceschange",q),x.xrCompatible!==!0&&await t.makeXRCompatible(),k=e.getPixelRatio(),e.getSize(A),v&&"createProjectionLayer"in XRWebGLBinding.prototype){let Ce=null,Ge=null,we=null;x.depth&&(we=x.stencil?t.DEPTH24_STENCIL8:t.DEPTH_COMPONENT24,Ce=x.stencil?ps:Ci,Ge=x.stencil?qr:ni);const at={colorFormat:t.RGBA8,depthFormat:we,scaleFactor:r};u=this.getBinding(),h=u.createProjectionLayer(at),s.updateRenderState({layers:[h]}),e.setPixelRatio(1),e.setSize(h.textureWidth,h.textureHeight,!1),b=new ri(h.textureWidth,h.textureHeight,{format:Bn,type:En,depthTexture:new na(h.textureWidth,h.textureHeight,Ge,void 0,void 0,void 0,void 0,void 0,void 0,Ce),stencilBuffer:x.stencil,colorSpace:e.outputColorSpace,samples:x.antialias?4:0,resolveDepthBuffer:h.ignoreDepthValues===!1,resolveStencilBuffer:h.ignoreDepthValues===!1})}else{const Ce={antialias:x.antialias,alpha:!0,depth:x.depth,stencil:x.stencil,framebufferScaleFactor:r};f=new XRWebGLLayer(s,t,Ce),s.updateRenderState({baseLayer:f}),e.setPixelRatio(1),e.setSize(f.framebufferWidth,f.framebufferHeight,!1),b=new ri(f.framebufferWidth,f.framebufferHeight,{format:Bn,type:En,colorSpace:e.outputColorSpace,stencilBuffer:x.stencil,resolveDepthBuffer:f.ignoreDepthValues===!1,resolveStencilBuffer:f.ignoreDepthValues===!1})}b.isXRRenderTarget=!0,this.setFoveation(c),l=null,a=await s.requestReferenceSpace(o),vt.setContext(s),vt.start(),n.isPresenting=!0,n.dispatchEvent({type:"sessionstart"})}},this.getEnvironmentBlendMode=function(){if(s!==null)return s.environmentBlendMode},this.getDepthTexture=function(){return m.getDepthTexture()};function q(K){for(let se=0;se<K.removed.length;se++){const Ce=K.removed[se],Ge=M.indexOf(Ce);Ge>=0&&(M[Ge]=null,S[Ge].disconnect(Ce))}for(let se=0;se<K.added.length;se++){const Ce=K.added[se];let Ge=M.indexOf(Ce);if(Ge===-1){for(let at=0;at<S.length;at++)if(at>=M.length){M.push(Ce),Ge=at;break}else if(M[at]===null){M[at]=Ce,Ge=at;break}if(Ge===-1)break}const we=S[Ge];we&&we.connect(Ce)}}const ne=new B,be=new B;function ue(K,se,Ce){ne.setFromMatrixPosition(se.matrixWorld),be.setFromMatrixPosition(Ce.matrixWorld);const Ge=ne.distanceTo(be),we=se.projectionMatrix.elements,at=Ce.projectionMatrix.elements,Xt=we[14]/(we[10]-1),st=we[14]/(we[10]+1),ht=(we[9]+1)/we[5],St=(we[9]-1)/we[5],qe=(we[8]-1)/we[0],zt=(at[8]+1)/at[0],I=Xt*qe,Vt=Xt*zt,dt=Ge/(-qe+zt),Tt=dt*-qe;if(se.matrixWorld.decompose(K.position,K.quaternion,K.scale),K.translateX(Tt),K.translateZ(dt),K.matrixWorld.compose(K.position,K.quaternion,K.scale),K.matrixWorldInverse.copy(K.matrixWorld).invert(),we[10]===-1)K.projectionMatrix.copy(se.projectionMatrix),K.projectionMatrixInverse.copy(se.projectionMatrixInverse);else{const Re=Xt+dt,w=st+dt,y=I-Tt,L=Vt+(Ge-Tt),X=ht*st/w*Re,te=St*st/w*Re;K.projectionMatrix.makePerspective(y,L,X,te,Re,w),K.projectionMatrixInverse.copy(K.projectionMatrix).invert()}}function _e(K,se){se===null?K.matrixWorld.copy(K.matrix):K.matrixWorld.multiplyMatrices(se.matrixWorld,K.matrix),K.matrixWorldInverse.copy(K.matrixWorld).invert()}this.updateCamera=function(K){if(s===null)return;let se=K.near,Ce=K.far;m.texture!==null&&(m.depthNear>0&&(se=m.depthNear),m.depthFar>0&&(Ce=m.depthFar)),O.near=T.near=_.near=se,O.far=T.far=_.far=Ce,(z!==O.near||$!==O.far)&&(s.updateRenderState({depthNear:O.near,depthFar:O.far}),z=O.near,$=O.far),O.layers.mask=K.layers.mask|6,_.layers.mask=O.layers.mask&3,T.layers.mask=O.layers.mask&5;const Ge=K.parent,we=O.cameras;_e(O,Ge);for(let at=0;at<we.length;at++)_e(we[at],Ge);we.length===2?ue(O,_,T):O.projectionMatrix.copy(_.projectionMatrix),ze(K,O,Ge)};function ze(K,se,Ce){Ce===null?K.matrix.copy(se.matrixWorld):(K.matrix.copy(Ce.matrixWorld),K.matrix.invert(),K.matrix.multiply(se.matrixWorld)),K.matrix.decompose(K.position,K.quaternion,K.scale),K.updateMatrixWorld(!0),K.projectionMatrix.copy(se.projectionMatrix),K.projectionMatrixInverse.copy(se.projectionMatrixInverse),K.isPerspectiveCamera&&(K.fov=pd*2*Math.atan(1/K.projectionMatrix.elements[5]),K.zoom=1)}this.getCamera=function(){return O},this.getFoveation=function(){if(!(h===null&&f===null))return c},this.setFoveation=function(K){c=K,h!==null&&(h.fixedFoveation=K),f!==null&&f.fixedFoveation!==void 0&&(f.fixedFoveation=K)},this.hasDepthSensing=function(){return m.texture!==null},this.getDepthSensingMesh=function(){return m.getMesh(O)},this.getCameraTexture=function(K){return p[K]};let Be=null;function wt(K,se){if(d=se.getViewerPose(l||a),g=se,d!==null){const Ce=d.views;f!==null&&(e.setRenderTargetFramebuffer(b,f.framebuffer),e.setRenderTarget(b));let Ge=!1;Ce.length!==O.cameras.length&&(O.cameras.length=0,Ge=!0);for(let st=0;st<Ce.length;st++){const ht=Ce[st];let St=null;if(f!==null)St=f.getViewport(ht);else{const zt=u.getViewSubImage(h,ht);St=zt.viewport,st===0&&(e.setRenderTargetTextures(b,zt.colorTexture,zt.depthStencilTexture),e.setRenderTarget(b))}let qe=R[st];qe===void 0&&(qe=new Rn,qe.layers.enable(st),qe.viewport=new Ut,R[st]=qe),qe.matrix.fromArray(ht.transform.matrix),qe.matrix.decompose(qe.position,qe.quaternion,qe.scale),qe.projectionMatrix.fromArray(ht.projectionMatrix),qe.projectionMatrixInverse.copy(qe.projectionMatrix).invert(),qe.viewport.set(St.x,St.y,St.width,St.height),st===0&&(O.matrix.copy(qe.matrix),O.matrix.decompose(O.position,O.quaternion,O.scale)),Ge===!0&&O.cameras.push(qe)}const we=s.enabledFeatures;if(we&&we.includes("depth-sensing")&&s.depthUsage=="gpu-optimized"&&v){u=n.getBinding();const st=u.getDepthInformation(Ce[0]);st&&st.isValid&&st.texture&&m.init(st,s.renderState)}if(we&&we.includes("camera-access")&&v){e.state.unbindTexture(),u=n.getBinding();for(let st=0;st<Ce.length;st++){const ht=Ce[st].camera;if(ht){let St=p[ht];St||(St=new om,p[ht]=St);const qe=u.getCameraImage(ht);St.sourceTexture=qe}}}}for(let Ce=0;Ce<S.length;Ce++){const Ge=M[Ce],we=S[Ce];Ge!==null&&we!==void 0&&we.update(Ge,se,l||a)}Be&&Be(K,se),se.detectedPlanes&&n.dispatchEvent({type:"planesdetected",data:se}),g=null}const vt=new dm;vt.setAnimationLoop(wt),this.setAnimationLoop=function(K){Be=K},this.dispose=function(){}}}const xs=new Ai,zC=new Ft;function VC(i,e){function t(m,p){m.matrixAutoUpdate===!0&&m.updateMatrix(),p.value.copy(m.matrix)}function n(m,p){p.color.getRGB(m.fogColor.value,em(i)),p.isFog?(m.fogNear.value=p.near,m.fogFar.value=p.far):p.isFogExp2&&(m.fogDensity.value=p.density)}function s(m,p,x,C,b){p.isMeshBasicMaterial||p.isMeshLambertMaterial?r(m,p):p.isMeshToonMaterial?(r(m,p),u(m,p)):p.isMeshPhongMaterial?(r(m,p),d(m,p)):p.isMeshStandardMaterial?(r(m,p),h(m,p),p.isMeshPhysicalMaterial&&f(m,p,b)):p.isMeshMatcapMaterial?(r(m,p),g(m,p)):p.isMeshDepthMaterial?r(m,p):p.isMeshDistanceMaterial?(r(m,p),v(m,p)):p.isMeshNormalMaterial?r(m,p):p.isLineBasicMaterial?(a(m,p),p.isLineDashedMaterial&&o(m,p)):p.isPointsMaterial?c(m,p,x,C):p.isSpriteMaterial?l(m,p):p.isShadowMaterial?(m.color.value.copy(p.color),m.opacity.value=p.opacity):p.isShaderMaterial&&(p.uniformsNeedUpdate=!1)}function r(m,p){m.opacity.value=p.opacity,p.color&&m.diffuse.value.copy(p.color),p.emissive&&m.emissive.value.copy(p.emissive).multiplyScalar(p.emissiveIntensity),p.map&&(m.map.value=p.map,t(p.map,m.mapTransform)),p.alphaMap&&(m.alphaMap.value=p.alphaMap,t(p.alphaMap,m.alphaMapTransform)),p.bumpMap&&(m.bumpMap.value=p.bumpMap,t(p.bumpMap,m.bumpMapTransform),m.bumpScale.value=p.bumpScale,p.side===en&&(m.bumpScale.value*=-1)),p.normalMap&&(m.normalMap.value=p.normalMap,t(p.normalMap,m.normalMapTransform),m.normalScale.value.copy(p.normalScale),p.side===en&&m.normalScale.value.negate()),p.displacementMap&&(m.displacementMap.value=p.displacementMap,t(p.displacementMap,m.displacementMapTransform),m.displacementScale.value=p.displacementScale,m.displacementBias.value=p.displacementBias),p.emissiveMap&&(m.emissiveMap.value=p.emissiveMap,t(p.emissiveMap,m.emissiveMapTransform)),p.specularMap&&(m.specularMap.value=p.specularMap,t(p.specularMap,m.specularMapTransform)),p.alphaTest>0&&(m.alphaTest.value=p.alphaTest);const x=e.get(p),C=x.envMap,b=x.envMapRotation;C&&(m.envMap.value=C,xs.copy(b),xs.x*=-1,xs.y*=-1,xs.z*=-1,C.isCubeTexture&&C.isRenderTargetTexture===!1&&(xs.y*=-1,xs.z*=-1),m.envMapRotation.value.setFromMatrix4(zC.makeRotationFromEuler(xs)),m.flipEnvMap.value=C.isCubeTexture&&C.isRenderTargetTexture===!1?-1:1,m.reflectivity.value=p.reflectivity,m.ior.value=p.ior,m.refractionRatio.value=p.refractionRatio),p.lightMap&&(m.lightMap.value=p.lightMap,m.lightMapIntensity.value=p.lightMapIntensity,t(p.lightMap,m.lightMapTransform)),p.aoMap&&(m.aoMap.value=p.aoMap,m.aoMapIntensity.value=p.aoMapIntensity,t(p.aoMap,m.aoMapTransform))}function a(m,p){m.diffuse.value.copy(p.color),m.opacity.value=p.opacity,p.map&&(m.map.value=p.map,t(p.map,m.mapTransform))}function o(m,p){m.dashSize.value=p.dashSize,m.totalSize.value=p.dashSize+p.gapSize,m.scale.value=p.scale}function c(m,p,x,C){m.diffuse.value.copy(p.color),m.opacity.value=p.opacity,m.size.value=p.size*x,m.scale.value=C*.5,p.map&&(m.map.value=p.map,t(p.map,m.uvTransform)),p.alphaMap&&(m.alphaMap.value=p.alphaMap,t(p.alphaMap,m.alphaMapTransform)),p.alphaTest>0&&(m.alphaTest.value=p.alphaTest)}function l(m,p){m.diffuse.value.copy(p.color),m.opacity.value=p.opacity,m.rotation.value=p.rotation,p.map&&(m.map.value=p.map,t(p.map,m.mapTransform)),p.alphaMap&&(m.alphaMap.value=p.alphaMap,t(p.alphaMap,m.alphaMapTransform)),p.alphaTest>0&&(m.alphaTest.value=p.alphaTest)}function d(m,p){m.specular.value.copy(p.specular),m.shininess.value=Math.max(p.shininess,1e-4)}function u(m,p){p.gradientMap&&(m.gradientMap.value=p.gradientMap)}function h(m,p){m.metalness.value=p.metalness,p.metalnessMap&&(m.metalnessMap.value=p.metalnessMap,t(p.metalnessMap,m.metalnessMapTransform)),m.roughness.value=p.roughness,p.roughnessMap&&(m.roughnessMap.value=p.roughnessMap,t(p.roughnessMap,m.roughnessMapTransform)),p.envMap&&(m.envMapIntensity.value=p.envMapIntensity)}function f(m,p,x){m.ior.value=p.ior,p.sheen>0&&(m.sheenColor.value.copy(p.sheenColor).multiplyScalar(p.sheen),m.sheenRoughness.value=p.sheenRoughness,p.sheenColorMap&&(m.sheenColorMap.value=p.sheenColorMap,t(p.sheenColorMap,m.sheenColorMapTransform)),p.sheenRoughnessMap&&(m.sheenRoughnessMap.value=p.sheenRoughnessMap,t(p.sheenRoughnessMap,m.sheenRoughnessMapTransform))),p.clearcoat>0&&(m.clearcoat.value=p.clearcoat,m.clearcoatRoughness.value=p.clearcoatRoughness,p.clearcoatMap&&(m.clearcoatMap.value=p.clearcoatMap,t(p.clearcoatMap,m.clearcoatMapTransform)),p.clearcoatRoughnessMap&&(m.clearcoatRoughnessMap.value=p.clearcoatRoughnessMap,t(p.clearcoatRoughnessMap,m.clearcoatRoughnessMapTransform)),p.clearcoatNormalMap&&(m.clearcoatNormalMap.value=p.clearcoatNormalMap,t(p.clearcoatNormalMap,m.clearcoatNormalMapTransform),m.clearcoatNormalScale.value.copy(p.clearcoatNormalScale),p.side===en&&m.clearcoatNormalScale.value.negate())),p.dispersion>0&&(m.dispersion.value=p.dispersion),p.iridescence>0&&(m.iridescence.value=p.iridescence,m.iridescenceIOR.value=p.iridescenceIOR,m.iridescenceThicknessMinimum.value=p.iridescenceThicknessRange[0],m.iridescenceThicknessMaximum.value=p.iridescenceThicknessRange[1],p.iridescenceMap&&(m.iridescenceMap.value=p.iridescenceMap,t(p.iridescenceMap,m.iridescenceMapTransform)),p.iridescenceThicknessMap&&(m.iridescenceThicknessMap.value=p.iridescenceThicknessMap,t(p.iridescenceThicknessMap,m.iridescenceThicknessMapTransform))),p.transmission>0&&(m.transmission.value=p.transmission,m.transmissionSamplerMap.value=x.texture,m.transmissionSamplerSize.value.set(x.width,x.height),p.transmissionMap&&(m.transmissionMap.value=p.transmissionMap,t(p.transmissionMap,m.transmissionMapTransform)),m.thickness.value=p.thickness,p.thicknessMap&&(m.thicknessMap.value=p.thicknessMap,t(p.thicknessMap,m.thicknessMapTransform)),m.attenuationDistance.value=p.attenuationDistance,m.attenuationColor.value.copy(p.attenuationColor)),p.anisotropy>0&&(m.anisotropyVector.value.set(p.anisotropy*Math.cos(p.anisotropyRotation),p.anisotropy*Math.sin(p.anisotropyRotation)),p.anisotropyMap&&(m.anisotropyMap.value=p.anisotropyMap,t(p.anisotropyMap,m.anisotropyMapTransform))),m.specularIntensity.value=p.specularIntensity,m.specularColor.value.copy(p.specularColor),p.specularColorMap&&(m.specularColorMap.value=p.specularColorMap,t(p.specularColorMap,m.specularColorMapTransform)),p.specularIntensityMap&&(m.specularIntensityMap.value=p.specularIntensityMap,t(p.specularIntensityMap,m.specularIntensityMapTransform))}function g(m,p){p.matcap&&(m.matcap.value=p.matcap)}function v(m,p){const x=e.get(p).light;m.referencePosition.value.setFromMatrixPosition(x.matrixWorld),m.nearDistance.value=x.shadow.camera.near,m.farDistance.value=x.shadow.camera.far}return{refreshFogUniforms:n,refreshMaterialUniforms:s}}function GC(i,e,t,n){let s={},r={},a=[];const o=i.getParameter(i.MAX_UNIFORM_BUFFER_BINDINGS);function c(x,C){const b=C.program;n.uniformBlockBinding(x,b)}function l(x,C){let b=s[x.id];b===void 0&&(g(x),b=d(x),s[x.id]=b,x.addEventListener("dispose",m));const S=C.program;n.updateUBOMapping(x,S);const M=e.render.frame;r[x.id]!==M&&(h(x),r[x.id]=M)}function d(x){const C=u();x.__bindingPointIndex=C;const b=i.createBuffer(),S=x.__size,M=x.usage;return i.bindBuffer(i.UNIFORM_BUFFER,b),i.bufferData(i.UNIFORM_BUFFER,S,M),i.bindBuffer(i.UNIFORM_BUFFER,null),i.bindBufferBase(i.UNIFORM_BUFFER,C,b),b}function u(){for(let x=0;x<o;x++)if(a.indexOf(x)===-1)return a.push(x),x;return rt("WebGLRenderer: Maximum number of simultaneously usable uniforms groups reached."),0}function h(x){const C=s[x.id],b=x.uniforms,S=x.__cache;i.bindBuffer(i.UNIFORM_BUFFER,C);for(let M=0,A=b.length;M<A;M++){const k=Array.isArray(b[M])?b[M]:[b[M]];for(let _=0,T=k.length;_<T;_++){const R=k[_];if(f(R,M,_,S)===!0){const O=R.__offset,z=Array.isArray(R.value)?R.value:[R.value];let $=0;for(let J=0;J<z.length;J++){const W=z[J],q=v(W);typeof W=="number"||typeof W=="boolean"?(R.__data[0]=W,i.bufferSubData(i.UNIFORM_BUFFER,O+$,R.__data)):W.isMatrix3?(R.__data[0]=W.elements[0],R.__data[1]=W.elements[1],R.__data[2]=W.elements[2],R.__data[3]=0,R.__data[4]=W.elements[3],R.__data[5]=W.elements[4],R.__data[6]=W.elements[5],R.__data[7]=0,R.__data[8]=W.elements[6],R.__data[9]=W.elements[7],R.__data[10]=W.elements[8],R.__data[11]=0):(W.toArray(R.__data,$),$+=q.storage/Float32Array.BYTES_PER_ELEMENT)}i.bufferSubData(i.UNIFORM_BUFFER,O,R.__data)}}}i.bindBuffer(i.UNIFORM_BUFFER,null)}function f(x,C,b,S){const M=x.value,A=C+"_"+b;if(S[A]===void 0)return typeof M=="number"||typeof M=="boolean"?S[A]=M:S[A]=M.clone(),!0;{const k=S[A];if(typeof M=="number"||typeof M=="boolean"){if(k!==M)return S[A]=M,!0}else if(k.equals(M)===!1)return k.copy(M),!0}return!1}function g(x){const C=x.uniforms;let b=0;const S=16;for(let A=0,k=C.length;A<k;A++){const _=Array.isArray(C[A])?C[A]:[C[A]];for(let T=0,R=_.length;T<R;T++){const O=_[T],z=Array.isArray(O.value)?O.value:[O.value];for(let $=0,J=z.length;$<J;$++){const W=z[$],q=v(W),ne=b%S,be=ne%q.boundary,ue=ne+be;b+=be,ue!==0&&S-ue<q.storage&&(b+=S-ue),O.__data=new Float32Array(q.storage/Float32Array.BYTES_PER_ELEMENT),O.__offset=b,b+=q.storage}}}const M=b%S;return M>0&&(b+=S-M),x.__size=b,x.__cache={},this}function v(x){const C={boundary:0,storage:0};return typeof x=="number"||typeof x=="boolean"?(C.boundary=4,C.storage=4):x.isVector2?(C.boundary=8,C.storage=8):x.isVector3||x.isColor?(C.boundary=16,C.storage=12):x.isVector4?(C.boundary=16,C.storage=16):x.isMatrix3?(C.boundary=48,C.storage=48):x.isMatrix4?(C.boundary=64,C.storage=64):x.isTexture?Oe("WebGLRenderer: Texture samplers can not be part of an uniforms group."):Oe("WebGLRenderer: Unsupported uniform value type.",x),C}function m(x){const C=x.target;C.removeEventListener("dispose",m);const b=a.indexOf(C.__bindingPointIndex);a.splice(b,1),i.deleteBuffer(s[C.id]),delete s[C.id],delete r[C.id]}function p(){for(const x in s)i.deleteBuffer(s[x]);a=[],s={},r={}}return{bind:c,update:l,dispose:p}}const HC=new Uint16Array([12469,15057,12620,14925,13266,14620,13807,14376,14323,13990,14545,13625,14713,13328,14840,12882,14931,12528,14996,12233,15039,11829,15066,11525,15080,11295,15085,10976,15082,10705,15073,10495,13880,14564,13898,14542,13977,14430,14158,14124,14393,13732,14556,13410,14702,12996,14814,12596,14891,12291,14937,11834,14957,11489,14958,11194,14943,10803,14921,10506,14893,10278,14858,9960,14484,14039,14487,14025,14499,13941,14524,13740,14574,13468,14654,13106,14743,12678,14818,12344,14867,11893,14889,11509,14893,11180,14881,10751,14852,10428,14812,10128,14765,9754,14712,9466,14764,13480,14764,13475,14766,13440,14766,13347,14769,13070,14786,12713,14816,12387,14844,11957,14860,11549,14868,11215,14855,10751,14825,10403,14782,10044,14729,9651,14666,9352,14599,9029,14967,12835,14966,12831,14963,12804,14954,12723,14936,12564,14917,12347,14900,11958,14886,11569,14878,11247,14859,10765,14828,10401,14784,10011,14727,9600,14660,9289,14586,8893,14508,8533,15111,12234,15110,12234,15104,12216,15092,12156,15067,12010,15028,11776,14981,11500,14942,11205,14902,10752,14861,10393,14812,9991,14752,9570,14682,9252,14603,8808,14519,8445,14431,8145,15209,11449,15208,11451,15202,11451,15190,11438,15163,11384,15117,11274,15055,10979,14994,10648,14932,10343,14871,9936,14803,9532,14729,9218,14645,8742,14556,8381,14461,8020,14365,7603,15273,10603,15272,10607,15267,10619,15256,10631,15231,10614,15182,10535,15118,10389,15042,10167,14963,9787,14883,9447,14800,9115,14710,8665,14615,8318,14514,7911,14411,7507,14279,7198,15314,9675,15313,9683,15309,9712,15298,9759,15277,9797,15229,9773,15166,9668,15084,9487,14995,9274,14898,8910,14800,8539,14697,8234,14590,7790,14479,7409,14367,7067,14178,6621,15337,8619,15337,8631,15333,8677,15325,8769,15305,8871,15264,8940,15202,8909,15119,8775,15022,8565,14916,8328,14804,8009,14688,7614,14569,7287,14448,6888,14321,6483,14088,6171,15350,7402,15350,7419,15347,7480,15340,7613,15322,7804,15287,7973,15229,8057,15148,8012,15046,7846,14933,7611,14810,7357,14682,7069,14552,6656,14421,6316,14251,5948,14007,5528,15356,5942,15356,5977,15353,6119,15348,6294,15332,6551,15302,6824,15249,7044,15171,7122,15070,7050,14949,6861,14818,6611,14679,6349,14538,6067,14398,5651,14189,5311,13935,4958,15359,4123,15359,4153,15356,4296,15353,4646,15338,5160,15311,5508,15263,5829,15188,6042,15088,6094,14966,6001,14826,5796,14678,5543,14527,5287,14377,4985,14133,4586,13869,4257,15360,1563,15360,1642,15358,2076,15354,2636,15341,3350,15317,4019,15273,4429,15203,4732,15105,4911,14981,4932,14836,4818,14679,4621,14517,4386,14359,4156,14083,3795,13808,3437,15360,122,15360,137,15358,285,15355,636,15344,1274,15322,2177,15281,2765,15215,3223,15120,3451,14995,3569,14846,3567,14681,3466,14511,3305,14344,3121,14037,2800,13753,2467,15360,0,15360,1,15359,21,15355,89,15346,253,15325,479,15287,796,15225,1148,15133,1492,15008,1749,14856,1882,14685,1886,14506,1783,14324,1608,13996,1398,13702,1183]);let ci=null;function WC(){return ci===null&&(ci=new __(HC,16,16,Xs,Ti),ci.name="DFG_LUT",ci.minFilter=Jt,ci.magFilter=Jt,ci.wrapS=xi,ci.wrapT=xi,ci.generateMipmaps=!1,ci.needsUpdate=!0),ci}class qC{constructor(e={}){const{canvas:t=$y(),context:n=null,depth:s=!0,stencil:r=!1,alpha:a=!1,antialias:o=!1,premultipliedAlpha:c=!0,preserveDrawingBuffer:l=!1,powerPreference:d="default",failIfMajorPerformanceCaveat:u=!1,reversedDepthBuffer:h=!1,outputBufferType:f=En}=e;this.isWebGLRenderer=!0;let g;if(n!==null){if(typeof WebGLRenderingContext<"u"&&n instanceof WebGLRenderingContext)throw new Error("THREE.WebGLRenderer: WebGL 1 is not supported since r163.");g=n.getContextAttributes().alpha}else g=a;const v=f,m=new Set([Il,kl,Pl]),p=new Set([En,ni,Wr,qr,Al,Rl]),x=new Uint32Array(4),C=new Int32Array(4);let b=null,S=null;const M=[],A=[];let k=null;this.domElement=t,this.debug={checkShaderErrors:!0,onShaderError:null},this.autoClear=!0,this.autoClearColor=!0,this.autoClearDepth=!0,this.autoClearStencil=!0,this.sortObjects=!0,this.clippingPlanes=[],this.localClippingEnabled=!1,this.toneMapping=ti,this.toneMappingExposure=1,this.transmissionResolutionScale=1;const _=this;let T=!1;this._outputColorSpace=Mn;let R=0,O=0,z=null,$=-1,J=null;const W=new Ut,q=new Ut;let ne=null;const be=new nt(0);let ue=0,_e=t.width,ze=t.height,Be=1,wt=null,vt=null;const K=new Ut(0,0,_e,ze),se=new Ut(0,0,_e,ze);let Ce=!1;const Ge=new am;let we=!1,at=!1;const Xt=new Ft,st=new B,ht=new Ut,St={background:null,fog:null,environment:null,overrideMaterial:null,isScene:!0};let qe=!1;function zt(){return z===null?Be:1}let I=n;function Vt(E,U){return t.getContext(E,U)}try{const E={alpha:!0,depth:s,stencil:r,antialias:o,premultipliedAlpha:c,preserveDrawingBuffer:l,powerPreference:d,failIfMajorPerformanceCaveat:u};if("setAttribute"in t&&t.setAttribute("data-engine",`three.js r${ul}`),t.addEventListener("webglcontextlost",Fe,!1),t.addEventListener("webglcontextrestored",Ct,!1),t.addEventListener("webglcontextcreationerror",ft,!1),I===null){const U="webgl2";if(I=Vt(U,E),I===null)throw Vt(U)?new Error("Error creating WebGL context with your selected attributes."):new Error("Error creating WebGL context.")}}catch(E){throw rt("WebGLRenderer: "+E.message),E}let dt,Tt,Re,w,y,L,X,te,j,ke,fe,Ae,Ne,ae,me,Me,Pe,pe,$e,D,Se,ce,xe,re;function ee(){dt=new Wx(I),dt.init(),ce=new UC(I,dt),Tt=new Ux(I,dt,e,ce),Re=new DC(I,dt),Tt.reversedDepthBuffer&&h&&Re.buffers.depth.setReversed(!0),w=new jx(I),y=new bC,L=new LC(I,dt,Re,y,Tt,ce,w),X=new Ox(_),te=new Hx(_),j=new k_(I),xe=new Dx(I,j),ke=new qx(I,j,w,xe),fe=new Yx(I,ke,j,w),$e=new Xx(I,Tt,L),Me=new Nx(y),Ae=new vC(_,X,te,dt,Tt,xe,Me),Ne=new VC(_,y),ae=new _C,me=new MC(dt),pe=new Ix(_,X,te,Re,fe,g,c),Pe=new kC(_,fe,Tt),re=new GC(I,w,Tt,Re),D=new Lx(I,dt,w),Se=new $x(I,dt,w),w.programs=Ae.programs,_.capabilities=Tt,_.extensions=dt,_.properties=y,_.renderLists=ae,_.shadowMap=Pe,_.state=Re,_.info=w}ee(),v!==En&&(k=new Jx(v,t.width,t.height,s,r));const he=new BC(_,I);this.xr=he,this.getContext=function(){return I},this.getContextAttributes=function(){return I.getContextAttributes()},this.forceContextLoss=function(){const E=dt.get("WEBGL_lose_context");E&&E.loseContext()},this.forceContextRestore=function(){const E=dt.get("WEBGL_lose_context");E&&E.restoreContext()},this.getPixelRatio=function(){return Be},this.setPixelRatio=function(E){E!==void 0&&(Be=E,this.setSize(_e,ze,!1))},this.getSize=function(E){return E.set(_e,ze)},this.setSize=function(E,U,H=!0){if(he.isPresenting){Oe("WebGLRenderer: Can't change size while VR device is presenting.");return}_e=E,ze=U,t.width=Math.floor(E*Be),t.height=Math.floor(U*Be),H===!0&&(t.style.width=E+"px",t.style.height=U+"px"),k!==null&&k.setSize(t.width,t.height),this.setViewport(0,0,E,U)},this.getDrawingBufferSize=function(E){return E.set(_e*Be,ze*Be).floor()},this.setDrawingBufferSize=function(E,U,H){_e=E,ze=U,Be=H,t.width=Math.floor(E*H),t.height=Math.floor(U*H),this.setViewport(0,0,E,U)},this.setEffects=function(E){if(v===En){console.error("THREE.WebGLRenderer: setEffects() requires outputBufferType set to HalfFloatType or FloatType.");return}if(E){for(let U=0;U<E.length;U++)if(E[U].isOutputPass===!0){console.warn("THREE.WebGLRenderer: OutputPass is not needed in setEffects(). Tone mapping and color space conversion are applied automatically.");break}}k.setEffects(E||[])},this.getCurrentViewport=function(E){return E.copy(W)},this.getViewport=function(E){return E.copy(K)},this.setViewport=function(E,U,H,V){E.isVector4?K.set(E.x,E.y,E.z,E.w):K.set(E,U,H,V),Re.viewport(W.copy(K).multiplyScalar(Be).round())},this.getScissor=function(E){return E.copy(se)},this.setScissor=function(E,U,H,V){E.isVector4?se.set(E.x,E.y,E.z,E.w):se.set(E,U,H,V),Re.scissor(q.copy(se).multiplyScalar(Be).round())},this.getScissorTest=function(){return Ce},this.setScissorTest=function(E){Re.setScissorTest(Ce=E)},this.setOpaqueSort=function(E){wt=E},this.setTransparentSort=function(E){vt=E},this.getClearColor=function(E){return E.copy(pe.getClearColor())},this.setClearColor=function(){pe.setClearColor(...arguments)},this.getClearAlpha=function(){return pe.getClearAlpha()},this.setClearAlpha=function(){pe.setClearAlpha(...arguments)},this.clear=function(E=!0,U=!0,H=!0){let V=0;if(E){let F=!1;if(z!==null){const ge=z.texture.format;F=m.has(ge)}if(F){const ge=z.texture.type,Te=p.has(ge),ye=pe.getClearColor(),Ee=pe.getClearAlpha(),Ie=ye.r,Ue=ye.g,De=ye.b;Te?(x[0]=Ie,x[1]=Ue,x[2]=De,x[3]=Ee,I.clearBufferuiv(I.COLOR,0,x)):(C[0]=Ie,C[1]=Ue,C[2]=De,C[3]=Ee,I.clearBufferiv(I.COLOR,0,C))}else V|=I.COLOR_BUFFER_BIT}U&&(V|=I.DEPTH_BUFFER_BIT),H&&(V|=I.STENCIL_BUFFER_BIT,this.state.buffers.stencil.setMask(4294967295)),I.clear(V)},this.clearColor=function(){this.clear(!0,!1,!1)},this.clearDepth=function(){this.clear(!1,!0,!1)},this.clearStencil=function(){this.clear(!1,!1,!0)},this.dispose=function(){t.removeEventListener("webglcontextlost",Fe,!1),t.removeEventListener("webglcontextrestored",Ct,!1),t.removeEventListener("webglcontextcreationerror",ft,!1),pe.dispose(),ae.dispose(),me.dispose(),y.dispose(),X.dispose(),te.dispose(),fe.dispose(),xe.dispose(),re.dispose(),Ae.dispose(),he.dispose(),he.removeEventListener("sessionstart",Vm),he.removeEventListener("sessionend",Gm),Es.stop()};function Fe(E){E.preventDefault(),Dp("WebGLRenderer: Context Lost."),T=!0}function Ct(){Dp("WebGLRenderer: Context Restored."),T=!1;const E=w.autoReset,U=Pe.enabled,H=Pe.autoUpdate,V=Pe.needsUpdate,F=Pe.type;ee(),w.autoReset=E,Pe.enabled=U,Pe.autoUpdate=H,Pe.needsUpdate=V,Pe.type=F}function ft(E){rt("WebGLRenderer: A WebGL context could not be created. Reason: ",E.statusMessage)}function li(E){const U=E.target;U.removeEventListener("dispose",li),Ii(U)}function Ii(E){vE(E),y.remove(E)}function vE(E){const U=y.get(E).programs;U!==void 0&&(U.forEach(function(H){Ae.releaseProgram(H)}),E.isShaderMaterial&&Ae.releaseShaderCache(E))}this.renderBufferDirect=function(E,U,H,V,F,ge){U===null&&(U=St);const Te=F.isMesh&&F.matrixWorld.determinant()<0,ye=yE(E,U,H,V,F);Re.setMaterial(V,Te);let Ee=H.index,Ie=1;if(V.wireframe===!0){if(Ee=ke.getWireframeAttribute(H),Ee===void 0)return;Ie=2}const Ue=H.drawRange,De=H.attributes.position;let je=Ue.start*Ie,bt=(Ue.start+Ue.count)*Ie;ge!==null&&(je=Math.max(je,ge.start*Ie),bt=Math.min(bt,(ge.start+ge.count)*Ie)),Ee!==null?(je=Math.max(je,0),bt=Math.min(bt,Ee.count)):De!=null&&(je=Math.max(je,0),bt=Math.min(bt,De.count));const It=bt-je;if(It<0||It===1/0)return;xe.setup(F,V,ye,H,Ee);let Dt,xt=D;if(Ee!==null&&(Dt=j.get(Ee),xt=Se,xt.setIndex(Dt)),F.isMesh)V.wireframe===!0?(Re.setLineWidth(V.wireframeLinewidth*zt()),xt.setMode(I.LINES)):xt.setMode(I.TRIANGLES);else if(F.isLine){let Le=V.linewidth;Le===void 0&&(Le=1),Re.setLineWidth(Le*zt()),F.isLineSegments?xt.setMode(I.LINES):F.isLineLoop?xt.setMode(I.LINE_LOOP):xt.setMode(I.LINE_STRIP)}else F.isPoints?xt.setMode(I.POINTS):F.isSprite&&xt.setMode(I.TRIANGLES);if(F.isBatchedMesh)if(F._multiDrawInstances!==null)$r("WebGLRenderer: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection."),xt.renderMultiDrawInstances(F._multiDrawStarts,F._multiDrawCounts,F._multiDrawCount,F._multiDrawInstances);else if(dt.get("WEBGL_multi_draw"))xt.renderMultiDraw(F._multiDrawStarts,F._multiDrawCounts,F._multiDrawCount);else{const Le=F._multiDrawStarts,pt=F._multiDrawCounts,ot=F._multiDrawCount,Tn=Ee?j.get(Ee).bytesPerElement:1,gr=y.get(V).currentProgram.getUniforms();for(let Cn=0;Cn<ot;Cn++)gr.setValue(I,"_gl_DrawID",Cn),xt.render(Le[Cn]/Tn,pt[Cn])}else if(F.isInstancedMesh)xt.renderInstances(je,It,F.count);else if(H.isInstancedBufferGeometry){const Le=H._maxInstanceCount!==void 0?H._maxInstanceCount:1/0,pt=Math.min(H.instanceCount,Le);xt.renderInstances(je,It,pt)}else xt.render(je,It)};function zm(E,U,H){E.transparent===!0&&E.side===_i&&E.forceSinglePass===!1?(E.side=en,E.needsUpdate=!0,Fo(E,U,H),E.side=yi,E.needsUpdate=!0,Fo(E,U,H),E.side=_i):Fo(E,U,H)}this.compile=function(E,U,H=null){H===null&&(H=E),S=me.get(H),S.init(U),A.push(S),H.traverseVisible(function(F){F.isLight&&F.layers.test(U.layers)&&(S.pushLight(F),F.castShadow&&S.pushShadow(F))}),E!==H&&E.traverseVisible(function(F){F.isLight&&F.layers.test(U.layers)&&(S.pushLight(F),F.castShadow&&S.pushShadow(F))}),S.setupLights();const V=new Set;return E.traverse(function(F){if(!(F.isMesh||F.isPoints||F.isLine||F.isSprite))return;const ge=F.material;if(ge)if(Array.isArray(ge))for(let Te=0;Te<ge.length;Te++){const ye=ge[Te];zm(ye,H,F),V.add(ye)}else zm(ge,H,F),V.add(ge)}),S=A.pop(),V},this.compileAsync=function(E,U,H=null){const V=this.compile(E,U,H);return new Promise(F=>{function ge(){if(V.forEach(function(Te){y.get(Te).currentProgram.isReady()&&V.delete(Te)}),V.size===0){F(E);return}setTimeout(ge,10)}dt.get("KHR_parallel_shader_compile")!==null?ge():setTimeout(ge,10)})};let Qd=null;function bE(E){Qd&&Qd(E)}function Vm(){Es.stop()}function Gm(){Es.start()}const Es=new dm;Es.setAnimationLoop(bE),typeof self<"u"&&Es.setContext(self),this.setAnimationLoop=function(E){Qd=E,he.setAnimationLoop(E),E===null?Es.stop():Es.start()},he.addEventListener("sessionstart",Vm),he.addEventListener("sessionend",Gm),this.render=function(E,U){if(U!==void 0&&U.isCamera!==!0){rt("WebGLRenderer.render: camera is not an instance of THREE.Camera.");return}if(T===!0)return;const H=he.enabled===!0&&he.isPresenting===!0,V=k!==null&&(z===null||H)&&k.begin(_,z);if(E.matrixWorldAutoUpdate===!0&&E.updateMatrixWorld(),U.parent===null&&U.matrixWorldAutoUpdate===!0&&U.updateMatrixWorld(),he.enabled===!0&&he.isPresenting===!0&&(k===null||k.isCompositing()===!1)&&(he.cameraAutoUpdate===!0&&he.updateCamera(U),U=he.getCamera()),E.isScene===!0&&E.onBeforeRender(_,E,U,z),S=me.get(E,A.length),S.init(U),A.push(S),Xt.multiplyMatrices(U.projectionMatrix,U.matrixWorldInverse),Ge.setFromProjectionMatrix(Xt,si,U.reversedDepth),at=this.localClippingEnabled,we=Me.init(this.clippingPlanes,at),b=ae.get(E,M.length),b.init(),M.push(b),he.enabled===!0&&he.isPresenting===!0){const Te=_.xr.getDepthSensingMesh();Te!==null&&eu(Te,U,-1/0,_.sortObjects)}eu(E,U,0,_.sortObjects),b.finish(),_.sortObjects===!0&&b.sort(wt,vt),qe=he.enabled===!1||he.isPresenting===!1||he.hasDepthSensing()===!1,qe&&pe.addToRenderList(b,E),this.info.render.frame++,we===!0&&Me.beginShadows();const F=S.state.shadowsArray;if(Pe.render(F,E,U),we===!0&&Me.endShadows(),this.info.autoReset===!0&&this.info.reset(),(V&&k.hasRenderPass())===!1){const Te=b.opaque,ye=b.transmissive;if(S.setupLights(),U.isArrayCamera){const Ee=U.cameras;if(ye.length>0)for(let Ie=0,Ue=Ee.length;Ie<Ue;Ie++){const De=Ee[Ie];Wm(Te,ye,E,De)}qe&&pe.render(E);for(let Ie=0,Ue=Ee.length;Ie<Ue;Ie++){const De=Ee[Ie];Hm(b,E,De,De.viewport)}}else ye.length>0&&Wm(Te,ye,E,U),qe&&pe.render(E),Hm(b,E,U)}z!==null&&O===0&&(L.updateMultisampleRenderTarget(z),L.updateRenderTargetMipmap(z)),V&&k.end(_),E.isScene===!0&&E.onAfterRender(_,E,U),xe.resetDefaultState(),$=-1,J=null,A.pop(),A.length>0?(S=A[A.length-1],we===!0&&Me.setGlobalState(_.clippingPlanes,S.state.camera)):S=null,M.pop(),M.length>0?b=M[M.length-1]:b=null};function eu(E,U,H,V){if(E.visible===!1)return;if(E.layers.test(U.layers)){if(E.isGroup)H=E.renderOrder;else if(E.isLOD)E.autoUpdate===!0&&E.update(U);else if(E.isLight)S.pushLight(E),E.castShadow&&S.pushShadow(E);else if(E.isSprite){if(!E.frustumCulled||Ge.intersectsSprite(E)){V&&ht.setFromMatrixPosition(E.matrixWorld).applyMatrix4(Xt);const Te=fe.update(E),ye=E.material;ye.visible&&b.push(E,Te,ye,H,ht.z,null)}}else if((E.isMesh||E.isLine||E.isPoints)&&(!E.frustumCulled||Ge.intersectsObject(E))){const Te=fe.update(E),ye=E.material;if(V&&(E.boundingSphere!==void 0?(E.boundingSphere===null&&E.computeBoundingSphere(),ht.copy(E.boundingSphere.center)):(Te.boundingSphere===null&&Te.computeBoundingSphere(),ht.copy(Te.boundingSphere.center)),ht.applyMatrix4(E.matrixWorld).applyMatrix4(Xt)),Array.isArray(ye)){const Ee=Te.groups;for(let Ie=0,Ue=Ee.length;Ie<Ue;Ie++){const De=Ee[Ie],je=ye[De.materialIndex];je&&je.visible&&b.push(E,Te,je,H,ht.z,De)}}else ye.visible&&b.push(E,Te,ye,H,ht.z,null)}}const ge=E.children;for(let Te=0,ye=ge.length;Te<ye;Te++)eu(ge[Te],U,H,V)}function Hm(E,U,H,V){const{opaque:F,transmissive:ge,transparent:Te}=E;S.setupLightsView(H),we===!0&&Me.setGlobalState(_.clippingPlanes,H),V&&Re.viewport(W.copy(V)),F.length>0&&Oo(F,U,H),ge.length>0&&Oo(ge,U,H),Te.length>0&&Oo(Te,U,H),Re.buffers.depth.setTest(!0),Re.buffers.depth.setMask(!0),Re.buffers.color.setMask(!0),Re.setPolygonOffset(!1)}function Wm(E,U,H,V){if((H.isScene===!0?H.overrideMaterial:null)!==null)return;if(S.state.transmissionRenderTarget[V.id]===void 0){const je=dt.has("EXT_color_buffer_half_float")||dt.has("EXT_color_buffer_float");S.state.transmissionRenderTarget[V.id]=new ri(1,1,{generateMipmaps:!0,type:je?Ti:En,minFilter:fs,samples:Tt.samples,stencilBuffer:r,resolveDepthBuffer:!1,resolveStencilBuffer:!1,colorSpace:it.workingColorSpace})}const ge=S.state.transmissionRenderTarget[V.id],Te=V.viewport||W;ge.setSize(Te.z*_.transmissionResolutionScale,Te.w*_.transmissionResolutionScale);const ye=_.getRenderTarget(),Ee=_.getActiveCubeFace(),Ie=_.getActiveMipmapLevel();_.setRenderTarget(ge),_.getClearColor(be),ue=_.getClearAlpha(),ue<1&&_.setClearColor(16777215,.5),_.clear(),qe&&pe.render(H);const Ue=_.toneMapping;_.toneMapping=ti;const De=V.viewport;if(V.viewport!==void 0&&(V.viewport=void 0),S.setupLightsView(V),we===!0&&Me.setGlobalState(_.clippingPlanes,V),Oo(E,H,V),L.updateMultisampleRenderTarget(ge),L.updateRenderTargetMipmap(ge),dt.has("WEBGL_multisampled_render_to_texture")===!1){let je=!1;for(let bt=0,It=U.length;bt<It;bt++){const Dt=U[bt],{object:xt,geometry:Le,material:pt,group:ot}=Dt;if(pt.side===_i&&xt.layers.test(V.layers)){const Tn=pt.side;pt.side=en,pt.needsUpdate=!0,qm(xt,H,V,Le,pt,ot),pt.side=Tn,pt.needsUpdate=!0,je=!0}}je===!0&&(L.updateMultisampleRenderTarget(ge),L.updateRenderTargetMipmap(ge))}_.setRenderTarget(ye,Ee,Ie),_.setClearColor(be,ue),De!==void 0&&(V.viewport=De),_.toneMapping=Ue}function Oo(E,U,H){const V=U.isScene===!0?U.overrideMaterial:null;for(let F=0,ge=E.length;F<ge;F++){const Te=E[F],{object:ye,geometry:Ee,group:Ie}=Te;let Ue=Te.material;Ue.allowOverride===!0&&V!==null&&(Ue=V),ye.layers.test(H.layers)&&qm(ye,U,H,Ee,Ue,Ie)}}function qm(E,U,H,V,F,ge){E.onBeforeRender(_,U,H,V,F,ge),E.modelViewMatrix.multiplyMatrices(H.matrixWorldInverse,E.matrixWorld),E.normalMatrix.getNormalMatrix(E.modelViewMatrix),F.onBeforeRender(_,U,H,V,E,ge),F.transparent===!0&&F.side===_i&&F.forceSinglePass===!1?(F.side=en,F.needsUpdate=!0,_.renderBufferDirect(H,U,V,F,E,ge),F.side=yi,F.needsUpdate=!0,_.renderBufferDirect(H,U,V,F,E,ge),F.side=_i):_.renderBufferDirect(H,U,V,F,E,ge),E.onAfterRender(_,U,H,V,F,ge)}function Fo(E,U,H){U.isScene!==!0&&(U=St);const V=y.get(E),F=S.state.lights,ge=S.state.shadowsArray,Te=F.state.version,ye=Ae.getParameters(E,F.state,ge,U,H),Ee=Ae.getProgramCacheKey(ye);let Ie=V.programs;V.environment=E.isMeshStandardMaterial?U.environment:null,V.fog=U.fog,V.envMap=(E.isMeshStandardMaterial?te:X).get(E.envMap||V.environment),V.envMapRotation=V.environment!==null&&E.envMap===null?U.environmentRotation:E.envMapRotation,Ie===void 0&&(E.addEventListener("dispose",li),Ie=new Map,V.programs=Ie);let Ue=Ie.get(Ee);if(Ue!==void 0){if(V.currentProgram===Ue&&V.lightsStateVersion===Te)return jm(E,ye),Ue}else ye.uniforms=Ae.getUniforms(E),E.onBeforeCompile(ye,_),Ue=Ae.acquireProgram(ye,Ee),Ie.set(Ee,Ue),V.uniforms=ye.uniforms;const De=V.uniforms;return(!E.isShaderMaterial&&!E.isRawShaderMaterial||E.clipping===!0)&&(De.clippingPlanes=Me.uniform),jm(E,ye),V.needsLights=SE(E),V.lightsStateVersion=Te,V.needsLights&&(De.ambientLightColor.value=F.state.ambient,De.lightProbe.value=F.state.probe,De.directionalLights.value=F.state.directional,De.directionalLightShadows.value=F.state.directionalShadow,De.spotLights.value=F.state.spot,De.spotLightShadows.value=F.state.spotShadow,De.rectAreaLights.value=F.state.rectArea,De.ltc_1.value=F.state.rectAreaLTC1,De.ltc_2.value=F.state.rectAreaLTC2,De.pointLights.value=F.state.point,De.pointLightShadows.value=F.state.pointShadow,De.hemisphereLights.value=F.state.hemi,De.directionalShadowMap.value=F.state.directionalShadowMap,De.directionalShadowMatrix.value=F.state.directionalShadowMatrix,De.spotShadowMap.value=F.state.spotShadowMap,De.spotLightMatrix.value=F.state.spotLightMatrix,De.spotLightMap.value=F.state.spotLightMap,De.pointShadowMap.value=F.state.pointShadowMap,De.pointShadowMatrix.value=F.state.pointShadowMatrix),V.currentProgram=Ue,V.uniformsList=null,Ue}function $m(E){if(E.uniformsList===null){const U=E.currentProgram.getUniforms();E.uniformsList=Ao.seqWithValue(U.seq,E.uniforms)}return E.uniformsList}function jm(E,U){const H=y.get(E);H.outputColorSpace=U.outputColorSpace,H.batching=U.batching,H.batchingColor=U.batchingColor,H.instancing=U.instancing,H.instancingColor=U.instancingColor,H.instancingMorph=U.instancingMorph,H.skinning=U.skinning,H.morphTargets=U.morphTargets,H.morphNormals=U.morphNormals,H.morphColors=U.morphColors,H.morphTargetsCount=U.morphTargetsCount,H.numClippingPlanes=U.numClippingPlanes,H.numIntersection=U.numClipIntersection,H.vertexAlphas=U.vertexAlphas,H.vertexTangents=U.vertexTangents,H.toneMapping=U.toneMapping}function yE(E,U,H,V,F){U.isScene!==!0&&(U=St),L.resetTextureUnits();const ge=U.fog,Te=V.isMeshStandardMaterial?U.environment:null,ye=z===null?_.outputColorSpace:z.isXRRenderTarget===!0?z.texture.colorSpace:Ys,Ee=(V.isMeshStandardMaterial?te:X).get(V.envMap||Te),Ie=V.vertexColors===!0&&!!H.attributes.color&&H.attributes.color.itemSize===4,Ue=!!H.attributes.tangent&&(!!V.normalMap||V.anisotropy>0),De=!!H.morphAttributes.position,je=!!H.morphAttributes.normal,bt=!!H.morphAttributes.color;let It=ti;V.toneMapped&&(z===null||z.isXRRenderTarget===!0)&&(It=_.toneMapping);const Dt=H.morphAttributes.position||H.morphAttributes.normal||H.morphAttributes.color,xt=Dt!==void 0?Dt.length:0,Le=y.get(V),pt=S.state.lights;if(we===!0&&(at===!0||E!==J)){const on=E===J&&V.id===$;Me.setState(V,E,on)}let ot=!1;V.version===Le.__version?(Le.needsLights&&Le.lightsStateVersion!==pt.state.version||Le.outputColorSpace!==ye||F.isBatchedMesh&&Le.batching===!1||!F.isBatchedMesh&&Le.batching===!0||F.isBatchedMesh&&Le.batchingColor===!0&&F.colorTexture===null||F.isBatchedMesh&&Le.batchingColor===!1&&F.colorTexture!==null||F.isInstancedMesh&&Le.instancing===!1||!F.isInstancedMesh&&Le.instancing===!0||F.isSkinnedMesh&&Le.skinning===!1||!F.isSkinnedMesh&&Le.skinning===!0||F.isInstancedMesh&&Le.instancingColor===!0&&F.instanceColor===null||F.isInstancedMesh&&Le.instancingColor===!1&&F.instanceColor!==null||F.isInstancedMesh&&Le.instancingMorph===!0&&F.morphTexture===null||F.isInstancedMesh&&Le.instancingMorph===!1&&F.morphTexture!==null||Le.envMap!==Ee||V.fog===!0&&Le.fog!==ge||Le.numClippingPlanes!==void 0&&(Le.numClippingPlanes!==Me.numPlanes||Le.numIntersection!==Me.numIntersection)||Le.vertexAlphas!==Ie||Le.vertexTangents!==Ue||Le.morphTargets!==De||Le.morphNormals!==je||Le.morphColors!==bt||Le.toneMapping!==It||Le.morphTargetsCount!==xt)&&(ot=!0):(ot=!0,Le.__version=V.version);let Tn=Le.currentProgram;ot===!0&&(Tn=Fo(V,U,F));let gr=!1,Cn=!1,ua=!1;const Et=Tn.getUniforms(),mn=Le.uniforms;if(Re.useProgram(Tn.program)&&(gr=!0,Cn=!0,ua=!0),V.id!==$&&($=V.id,Cn=!0),gr||J!==E){Re.buffers.depth.getReversed()&&E.reversedDepth!==!0&&(E._reversedDepth=!0,E.updateProjectionMatrix()),Et.setValue(I,"projectionMatrix",E.projectionMatrix),Et.setValue(I,"viewMatrix",E.matrixWorldInverse);const gn=Et.map.cameraPosition;gn!==void 0&&gn.setValue(I,st.setFromMatrixPosition(E.matrixWorld)),Tt.logarithmicDepthBuffer&&Et.setValue(I,"logDepthBufFC",2/(Math.log(E.far+1)/Math.LN2)),(V.isMeshPhongMaterial||V.isMeshToonMaterial||V.isMeshLambertMaterial||V.isMeshBasicMaterial||V.isMeshStandardMaterial||V.isShaderMaterial)&&Et.setValue(I,"isOrthographic",E.isOrthographicCamera===!0),J!==E&&(J=E,Cn=!0,ua=!0)}if(Le.needsLights&&(pt.state.directionalShadowMap.length>0&&Et.setValue(I,"directionalShadowMap",pt.state.directionalShadowMap,L),pt.state.spotShadowMap.length>0&&Et.setValue(I,"spotShadowMap",pt.state.spotShadowMap,L),pt.state.pointShadowMap.length>0&&Et.setValue(I,"pointShadowMap",pt.state.pointShadowMap,L)),F.isSkinnedMesh){Et.setOptional(I,F,"bindMatrix"),Et.setOptional(I,F,"bindMatrixInverse");const on=F.skeleton;on&&(on.boneTexture===null&&on.computeBoneTexture(),Et.setValue(I,"boneTexture",on.boneTexture,L))}F.isBatchedMesh&&(Et.setOptional(I,F,"batchingTexture"),Et.setValue(I,"batchingTexture",F._matricesTexture,L),Et.setOptional(I,F,"batchingIdTexture"),Et.setValue(I,"batchingIdTexture",F._indirectTexture,L),Et.setOptional(I,F,"batchingColorTexture"),F._colorsTexture!==null&&Et.setValue(I,"batchingColorTexture",F._colorsTexture,L));const Pn=H.morphAttributes;if((Pn.position!==void 0||Pn.normal!==void 0||Pn.color!==void 0)&&$e.update(F,H,Tn),(Cn||Le.receiveShadow!==F.receiveShadow)&&(Le.receiveShadow=F.receiveShadow,Et.setValue(I,"receiveShadow",F.receiveShadow)),V.isMeshGouraudMaterial&&V.envMap!==null&&(mn.envMap.value=Ee,mn.flipEnvMap.value=Ee.isCubeTexture&&Ee.isRenderTargetTexture===!1?-1:1),V.isMeshStandardMaterial&&V.envMap===null&&U.environment!==null&&(mn.envMapIntensity.value=U.environmentIntensity),mn.dfgLUT!==void 0&&(mn.dfgLUT.value=WC()),Cn&&(Et.setValue(I,"toneMappingExposure",_.toneMappingExposure),Le.needsLights&&_E(mn,ua),ge&&V.fog===!0&&Ne.refreshFogUniforms(mn,ge),Ne.refreshMaterialUniforms(mn,V,Be,ze,S.state.transmissionRenderTarget[E.id]),Ao.upload(I,$m(Le),mn,L)),V.isShaderMaterial&&V.uniformsNeedUpdate===!0&&(Ao.upload(I,$m(Le),mn,L),V.uniformsNeedUpdate=!1),V.isSpriteMaterial&&Et.setValue(I,"center",F.center),Et.setValue(I,"modelViewMatrix",F.modelViewMatrix),Et.setValue(I,"normalMatrix",F.normalMatrix),Et.setValue(I,"modelMatrix",F.matrixWorld),V.isShaderMaterial||V.isRawShaderMaterial){const on=V.uniformsGroups;for(let gn=0,tu=on.length;gn<tu;gn++){const Ms=on[gn];re.update(Ms,Tn),re.bind(Ms,Tn)}}return Tn}function _E(E,U){E.ambientLightColor.needsUpdate=U,E.lightProbe.needsUpdate=U,E.directionalLights.needsUpdate=U,E.directionalLightShadows.needsUpdate=U,E.pointLights.needsUpdate=U,E.pointLightShadows.needsUpdate=U,E.spotLights.needsUpdate=U,E.spotLightShadows.needsUpdate=U,E.rectAreaLights.needsUpdate=U,E.hemisphereLights.needsUpdate=U}function SE(E){return E.isMeshLambertMaterial||E.isMeshToonMaterial||E.isMeshPhongMaterial||E.isMeshStandardMaterial||E.isShadowMaterial||E.isShaderMaterial&&E.lights===!0}this.getActiveCubeFace=function(){return R},this.getActiveMipmapLevel=function(){return O},this.getRenderTarget=function(){return z},this.setRenderTargetTextures=function(E,U,H){const V=y.get(E);V.__autoAllocateDepthBuffer=E.resolveDepthBuffer===!1,V.__autoAllocateDepthBuffer===!1&&(V.__useRenderToTexture=!1),y.get(E.texture).__webglTexture=U,y.get(E.depthTexture).__webglTexture=V.__autoAllocateDepthBuffer?void 0:H,V.__hasExternalTextures=!0},this.setRenderTargetFramebuffer=function(E,U){const H=y.get(E);H.__webglFramebuffer=U,H.__useDefaultFramebuffer=U===void 0};const xE=I.createFramebuffer();this.setRenderTarget=function(E,U=0,H=0){z=E,R=U,O=H;let V=null,F=!1,ge=!1;if(E){const ye=y.get(E);if(ye.__useDefaultFramebuffer!==void 0){Re.bindFramebuffer(I.FRAMEBUFFER,ye.__webglFramebuffer),W.copy(E.viewport),q.copy(E.scissor),ne=E.scissorTest,Re.viewport(W),Re.scissor(q),Re.setScissorTest(ne),$=-1;return}else if(ye.__webglFramebuffer===void 0)L.setupRenderTarget(E);else if(ye.__hasExternalTextures)L.rebindTextures(E,y.get(E.texture).__webglTexture,y.get(E.depthTexture).__webglTexture);else if(E.depthBuffer){const Ue=E.depthTexture;if(ye.__boundDepthTexture!==Ue){if(Ue!==null&&y.has(Ue)&&(E.width!==Ue.image.width||E.height!==Ue.image.height))throw new Error("WebGLRenderTarget: Attached DepthTexture is initialized to the incorrect size.");L.setupDepthRenderbuffer(E)}}const Ee=E.texture;(Ee.isData3DTexture||Ee.isDataArrayTexture||Ee.isCompressedArrayTexture)&&(ge=!0);const Ie=y.get(E).__webglFramebuffer;E.isWebGLCubeRenderTarget?(Array.isArray(Ie[U])?V=Ie[U][H]:V=Ie[U],F=!0):E.samples>0&&L.useMultisampledRTT(E)===!1?V=y.get(E).__webglMultisampledFramebuffer:Array.isArray(Ie)?V=Ie[H]:V=Ie,W.copy(E.viewport),q.copy(E.scissor),ne=E.scissorTest}else W.copy(K).multiplyScalar(Be).floor(),q.copy(se).multiplyScalar(Be).floor(),ne=Ce;if(H!==0&&(V=xE),Re.bindFramebuffer(I.FRAMEBUFFER,V)&&Re.drawBuffers(E,V),Re.viewport(W),Re.scissor(q),Re.setScissorTest(ne),F){const ye=y.get(E.texture);I.framebufferTexture2D(I.FRAMEBUFFER,I.COLOR_ATTACHMENT0,I.TEXTURE_CUBE_MAP_POSITIVE_X+U,ye.__webglTexture,H)}else if(ge){const ye=U;for(let Ee=0;Ee<E.textures.length;Ee++){const Ie=y.get(E.textures[Ee]);I.framebufferTextureLayer(I.FRAMEBUFFER,I.COLOR_ATTACHMENT0+Ee,Ie.__webglTexture,H,ye)}}else if(E!==null&&H!==0){const ye=y.get(E.texture);I.framebufferTexture2D(I.FRAMEBUFFER,I.COLOR_ATTACHMENT0,I.TEXTURE_2D,ye.__webglTexture,H)}$=-1},this.readRenderTargetPixels=function(E,U,H,V,F,ge,Te,ye=0){if(!(E&&E.isWebGLRenderTarget)){rt("WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");return}let Ee=y.get(E).__webglFramebuffer;if(E.isWebGLCubeRenderTarget&&Te!==void 0&&(Ee=Ee[Te]),Ee){Re.bindFramebuffer(I.FRAMEBUFFER,Ee);try{const Ie=E.textures[ye],Ue=Ie.format,De=Ie.type;if(!Tt.textureFormatReadable(Ue)){rt("WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.");return}if(!Tt.textureTypeReadable(De)){rt("WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.");return}U>=0&&U<=E.width-V&&H>=0&&H<=E.height-F&&(E.textures.length>1&&I.readBuffer(I.COLOR_ATTACHMENT0+ye),I.readPixels(U,H,V,F,ce.convert(Ue),ce.convert(De),ge))}finally{const Ie=z!==null?y.get(z).__webglFramebuffer:null;Re.bindFramebuffer(I.FRAMEBUFFER,Ie)}}},this.readRenderTargetPixelsAsync=async function(E,U,H,V,F,ge,Te,ye=0){if(!(E&&E.isWebGLRenderTarget))throw new Error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");let Ee=y.get(E).__webglFramebuffer;if(E.isWebGLCubeRenderTarget&&Te!==void 0&&(Ee=Ee[Te]),Ee)if(U>=0&&U<=E.width-V&&H>=0&&H<=E.height-F){Re.bindFramebuffer(I.FRAMEBUFFER,Ee);const Ie=E.textures[ye],Ue=Ie.format,De=Ie.type;if(!Tt.textureFormatReadable(Ue))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.");if(!Tt.textureTypeReadable(De))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.");const je=I.createBuffer();I.bindBuffer(I.PIXEL_PACK_BUFFER,je),I.bufferData(I.PIXEL_PACK_BUFFER,ge.byteLength,I.STREAM_READ),E.textures.length>1&&I.readBuffer(I.COLOR_ATTACHMENT0+ye),I.readPixels(U,H,V,F,ce.convert(Ue),ce.convert(De),0);const bt=z!==null?y.get(z).__webglFramebuffer:null;Re.bindFramebuffer(I.FRAMEBUFFER,bt);const It=I.fenceSync(I.SYNC_GPU_COMMANDS_COMPLETE,0);return I.flush(),await jy(I,It,4),I.bindBuffer(I.PIXEL_PACK_BUFFER,je),I.getBufferSubData(I.PIXEL_PACK_BUFFER,0,ge),I.deleteBuffer(je),I.deleteSync(It),ge}else throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range.")},this.copyFramebufferToTexture=function(E,U=null,H=0){const V=Math.pow(2,-H),F=Math.floor(E.image.width*V),ge=Math.floor(E.image.height*V),Te=U!==null?U.x:0,ye=U!==null?U.y:0;L.setTexture2D(E,0),I.copyTexSubImage2D(I.TEXTURE_2D,H,0,0,Te,ye,F,ge),Re.unbindTexture()};const TE=I.createFramebuffer(),CE=I.createFramebuffer();this.copyTextureToTexture=function(E,U,H=null,V=null,F=0,ge=null){ge===null&&(F!==0?($r("WebGLRenderer: copyTextureToTexture function signature has changed to support src and dst mipmap levels."),ge=F,F=0):ge=0);let Te,ye,Ee,Ie,Ue,De,je,bt,It;const Dt=E.isCompressedTexture?E.mipmaps[ge]:E.image;if(H!==null)Te=H.max.x-H.min.x,ye=H.max.y-H.min.y,Ee=H.isBox3?H.max.z-H.min.z:1,Ie=H.min.x,Ue=H.min.y,De=H.isBox3?H.min.z:0;else{const Pn=Math.pow(2,-F);Te=Math.floor(Dt.width*Pn),ye=Math.floor(Dt.height*Pn),E.isDataArrayTexture?Ee=Dt.depth:E.isData3DTexture?Ee=Math.floor(Dt.depth*Pn):Ee=1,Ie=0,Ue=0,De=0}V!==null?(je=V.x,bt=V.y,It=V.z):(je=0,bt=0,It=0);const xt=ce.convert(U.format),Le=ce.convert(U.type);let pt;U.isData3DTexture?(L.setTexture3D(U,0),pt=I.TEXTURE_3D):U.isDataArrayTexture||U.isCompressedArrayTexture?(L.setTexture2DArray(U,0),pt=I.TEXTURE_2D_ARRAY):(L.setTexture2D(U,0),pt=I.TEXTURE_2D),I.pixelStorei(I.UNPACK_FLIP_Y_WEBGL,U.flipY),I.pixelStorei(I.UNPACK_PREMULTIPLY_ALPHA_WEBGL,U.premultiplyAlpha),I.pixelStorei(I.UNPACK_ALIGNMENT,U.unpackAlignment);const ot=I.getParameter(I.UNPACK_ROW_LENGTH),Tn=I.getParameter(I.UNPACK_IMAGE_HEIGHT),gr=I.getParameter(I.UNPACK_SKIP_PIXELS),Cn=I.getParameter(I.UNPACK_SKIP_ROWS),ua=I.getParameter(I.UNPACK_SKIP_IMAGES);I.pixelStorei(I.UNPACK_ROW_LENGTH,Dt.width),I.pixelStorei(I.UNPACK_IMAGE_HEIGHT,Dt.height),I.pixelStorei(I.UNPACK_SKIP_PIXELS,Ie),I.pixelStorei(I.UNPACK_SKIP_ROWS,Ue),I.pixelStorei(I.UNPACK_SKIP_IMAGES,De);const Et=E.isDataArrayTexture||E.isData3DTexture,mn=U.isDataArrayTexture||U.isData3DTexture;if(E.isDepthTexture){const Pn=y.get(E),on=y.get(U),gn=y.get(Pn.__renderTarget),tu=y.get(on.__renderTarget);Re.bindFramebuffer(I.READ_FRAMEBUFFER,gn.__webglFramebuffer),Re.bindFramebuffer(I.DRAW_FRAMEBUFFER,tu.__webglFramebuffer);for(let Ms=0;Ms<Ee;Ms++)Et&&(I.framebufferTextureLayer(I.READ_FRAMEBUFFER,I.COLOR_ATTACHMENT0,y.get(E).__webglTexture,F,De+Ms),I.framebufferTextureLayer(I.DRAW_FRAMEBUFFER,I.COLOR_ATTACHMENT0,y.get(U).__webglTexture,ge,It+Ms)),I.blitFramebuffer(Ie,Ue,Te,ye,je,bt,Te,ye,I.DEPTH_BUFFER_BIT,I.NEAREST);Re.bindFramebuffer(I.READ_FRAMEBUFFER,null),Re.bindFramebuffer(I.DRAW_FRAMEBUFFER,null)}else if(F!==0||E.isRenderTargetTexture||y.has(E)){const Pn=y.get(E),on=y.get(U);Re.bindFramebuffer(I.READ_FRAMEBUFFER,TE),Re.bindFramebuffer(I.DRAW_FRAMEBUFFER,CE);for(let gn=0;gn<Ee;gn++)Et?I.framebufferTextureLayer(I.READ_FRAMEBUFFER,I.COLOR_ATTACHMENT0,Pn.__webglTexture,F,De+gn):I.framebufferTexture2D(I.READ_FRAMEBUFFER,I.COLOR_ATTACHMENT0,I.TEXTURE_2D,Pn.__webglTexture,F),mn?I.framebufferTextureLayer(I.DRAW_FRAMEBUFFER,I.COLOR_ATTACHMENT0,on.__webglTexture,ge,It+gn):I.framebufferTexture2D(I.DRAW_FRAMEBUFFER,I.COLOR_ATTACHMENT0,I.TEXTURE_2D,on.__webglTexture,ge),F!==0?I.blitFramebuffer(Ie,Ue,Te,ye,je,bt,Te,ye,I.COLOR_BUFFER_BIT,I.NEAREST):mn?I.copyTexSubImage3D(pt,ge,je,bt,It+gn,Ie,Ue,Te,ye):I.copyTexSubImage2D(pt,ge,je,bt,Ie,Ue,Te,ye);Re.bindFramebuffer(I.READ_FRAMEBUFFER,null),Re.bindFramebuffer(I.DRAW_FRAMEBUFFER,null)}else mn?E.isDataTexture||E.isData3DTexture?I.texSubImage3D(pt,ge,je,bt,It,Te,ye,Ee,xt,Le,Dt.data):U.isCompressedArrayTexture?I.compressedTexSubImage3D(pt,ge,je,bt,It,Te,ye,Ee,xt,Dt.data):I.texSubImage3D(pt,ge,je,bt,It,Te,ye,Ee,xt,Le,Dt):E.isDataTexture?I.texSubImage2D(I.TEXTURE_2D,ge,je,bt,Te,ye,xt,Le,Dt.data):E.isCompressedTexture?I.compressedTexSubImage2D(I.TEXTURE_2D,ge,je,bt,Dt.width,Dt.height,xt,Dt.data):I.texSubImage2D(I.TEXTURE_2D,ge,je,bt,Te,ye,xt,Le,Dt);I.pixelStorei(I.UNPACK_ROW_LENGTH,ot),I.pixelStorei(I.UNPACK_IMAGE_HEIGHT,Tn),I.pixelStorei(I.UNPACK_SKIP_PIXELS,gr),I.pixelStorei(I.UNPACK_SKIP_ROWS,Cn),I.pixelStorei(I.UNPACK_SKIP_IMAGES,ua),ge===0&&U.generateMipmaps&&I.generateMipmap(pt),Re.unbindTexture()},this.initRenderTarget=function(E){y.get(E).__webglFramebuffer===void 0&&L.setupRenderTarget(E)},this.initTexture=function(E){E.isCubeTexture?L.setTextureCube(E,0):E.isData3DTexture?L.setTexture3D(E,0):E.isDataArrayTexture||E.isCompressedArrayTexture?L.setTexture2DArray(E,0):L.setTexture2D(E,0),Re.unbindTexture()},this.resetState=function(){R=0,O=0,z=null,Re.reset(),xe.reset()},typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}get coordinateSystem(){return si}get outputColorSpace(){return this._outputColorSpace}set outputColorSpace(e){this._outputColorSpace=e;const t=this.getContext();t.drawingBufferColorSpace=it._getDrawingBufferColorSpace(e),t.unpackColorSpace=it._getUnpackColorSpace()}}const $C=`
|
|
4103
4103
|
uniform float uTime;
|
|
4104
4104
|
uniform float uAudioBass;
|
|
4105
4105
|
uniform float uAudioMid;
|
|
@@ -4482,7 +4482,7 @@ void main() {
|
|
|
4482
4482
|
// Softer alpha for more diffuse appearance
|
|
4483
4483
|
gl_FragColor = vec4(glowColor, glow * 0.4);
|
|
4484
4484
|
}
|
|
4485
|
-
`,Ts={primary:"#6366f1",secondary:"#8b5cf6",accent:"#06b6d4",glow:"#818cf8",atmosphere:"#c4b5fd",depth:"#312e81",highlight:"#e0e7ff"},KC={size:1,segments:128,colors:Ts,morphStrength:1,noiseScale:1.5,noiseSpeed:.3,glowIntensity:.8,idleGlowMultiplier:.4,fresnelPower:2.5,rotationSpeed:.1,audioReactivity:3,audioSmoothing:.9,idleMorphMultiplier:.25,colorContrast:1.5};class Po{constructor(e,t={}){this.orb=null,this.glowMesh=null,this.orbMaterial=null,this.glowMaterial=null,this.animationId=null,this.isActive=!1,this.targetRotation={x:0,y:0},this.currentRotation={x:0,y:0},this.audioValues={bass:0,mid:0,treble:0,level:0},this.resizeObserver=null,this.resizeTimeoutId=null,this.isContextLost=!1,this.animate=()=>{if(this.isContextLost)return;this.animationId=requestAnimationFrame(this.animate);const u=this.clock.getElapsedTime();if(this.clock.getDelta(),this.orbMaterial){this.orbMaterial.uniforms.uTime.value=u,this.orbMaterial.uniforms.uAudioBass.value=this.audioValues.bass,this.orbMaterial.uniforms.uAudioMid.value=this.audioValues.mid,this.orbMaterial.uniforms.uAudioTreble.value=this.audioValues.treble,this.orbMaterial.uniforms.uAudioLevel.value=this.audioValues.level;const h=this.isActive?this.config.morphStrength*1.5:this.config.morphStrength*this.config.idleMorphMultiplier,f=this.orbMaterial.uniforms.uMorphStrength.value;this.orbMaterial.uniforms.uMorphStrength.value+=(h-f)*.05}if(this.glowMaterial){this.glowMaterial.uniforms.uTime.value=u,this.glowMaterial.uniforms.uAudioLevel.value=this.audioValues.level;const h=this.isActive?this.config.glowIntensity*1.5:this.config.glowIntensity*this.config.idleGlowMultiplier,f=this.glowMaterial.uniforms.uGlowIntensity.value;this.glowMaterial.uniforms.uGlowIntensity.value+=(h-f)*.05}this.currentRotation.x+=(this.targetRotation.x-this.currentRotation.x)*.05,this.currentRotation.y+=(this.targetRotation.y-this.currentRotation.y)*.05,this.orb&&(this.orb.rotation.x=this.currentRotation.x+u*this.config.rotationSpeed*.3,this.orb.rotation.y=this.currentRotation.y+u*this.config.rotationSpeed),this.glowMesh&&(this.glowMesh.rotation.x=this.currentRotation.x+u*this.config.rotationSpeed*.3,this.glowMesh.rotation.y=this.currentRotation.y+u*this.config.rotationSpeed),this.renderer.render(this.scene,this.camera)},this.handleResize=()=>{this.resizeTimeoutId!==null&&clearTimeout(this.resizeTimeoutId),this.resizeTimeoutId=setTimeout(()=>{this.resizeTimeoutId=null;const u=this.container.clientWidth,h=this.container.clientHeight;if(u===0||h===0)return;const f=u*this.canvasPadding,g=h*this.canvasPadding;this.camera.aspect=f/g,this.camera.updateProjectionMatrix(),this.renderer.setSize(f,g)},100)},this.handleMouseMove=u=>{const h=this.container.getBoundingClientRect(),f=(u.clientX-h.left)/h.width*2-1,g=-((u.clientY-h.top)/h.height)*2+1;this.targetRotation.x=g*.3,this.targetRotation.y=f*.3},this.handleMouseLeave=()=>{this.targetRotation.x=0,this.targetRotation.y=0},this.container=e,this.config={...KC,...t},this.clock=new R_;const n=/iPhone|iPad|iPod/i.test(navigator.userAgent),s=/Android/i.test(navigator.userAgent);this.canvasPadding=n?1.5:s?2:3,this.boundHandleContextLost=this.handleContextLost.bind(this),this.boundHandleContextRestored=this.handleContextRestored.bind(this),this.scene=new y_;const r=e.clientWidth*this.canvasPadding,a=e.clientHeight*this.canvasPadding,o=r/a;this.camera=new Rn(45,o,.1,100);const c=3,l=9;this.camera.position.z=l*(this.canvasPadding/c),this.renderer=new qC({antialias:!0,alpha:!0,powerPreference:"high-performance"}),this.renderer.setPixelRatio(Math.min(window.devicePixelRatio,2)),this.renderer.setSize(r,a),this.renderer.setClearColor(0,0);const d=this.renderer.domElement;d.style.position="absolute",d.style.left="50%",d.style.top="50%",d.style.transform="translate(-50%, -50%)",d.style.pointerEvents="none",e.appendChild(d),d.addEventListener("webglcontextlost",this.boundHandleContextLost),d.addEventListener("webglcontextrestored",this.boundHandleContextRestored),this.createOrb(),window.addEventListener("resize",this.handleResize),this.resizeObserver=new ResizeObserver(this.handleResize),this.resizeObserver.observe(e),e.addEventListener("mousemove",this.handleMouseMove),e.addEventListener("mouseleave",this.handleMouseLeave)}handleContextLost(e){e.preventDefault(),this.isContextLost=!0,this.stop()}handleContextRestored(e){this.isContextLost=!1,this.recreateAfterContextLoss(),this.start()}recreateAfterContextLoss(){this.orb&&(this.orb.geometry.dispose(),this.scene.remove(this.orb),this.orb=null),this.glowMesh&&(this.glowMesh.geometry.dispose(),this.scene.remove(this.glowMesh),this.glowMesh=null),this.orbMaterial&&(this.orbMaterial.dispose(),this.orbMaterial=null),this.glowMaterial&&(this.glowMaterial.dispose(),this.glowMaterial=null),this.createOrb()}createOrb(){const e={...Ts,...this.config.colors},t=new Vd(this.config.size,this.config.segments/4);this.orbMaterial=new An({vertexShader:$C,fragmentShader:jC,uniforms:{uTime:{value:0},uAudioBass:{value:0},uAudioMid:{value:0},uAudioTreble:{value:0},uAudioLevel:{value:0},uMorphStrength:{value:this.config.morphStrength},uNoiseScale:{value:this.config.noiseScale},uNoiseSpeed:{value:this.config.noiseSpeed},uAudioReactivity:{value:this.config.audioReactivity},uColorPrimary:{value:new nt(e.primary)},uColorSecondary:{value:new nt(e.secondary)},uColorAccent:{value:new nt(e.accent)},uColorDepth:{value:new nt(e.depth||Ts.depth)},uColorHighlight:{value:new nt(e.highlight||Ts.highlight)},uFresnelPower:{value:this.config.fresnelPower},uGlowIntensity:{value:this.config.glowIntensity},uColorContrast:{value:this.config.colorContrast}},transparent:!0,side:yi}),this.orb=new qn(t,this.orbMaterial),this.scene.add(this.orb);const n=new Gd(this.config.size,64,64);this.glowMaterial=new An({vertexShader:XC,fragmentShader:YC,uniforms:{uTime:{value:0},uAudioLevel:{value:0},uGlowColor:{value:new nt(e.glow)},uGlowIntensity:{value:this.config.glowIntensity*.6},uPulseSpeed:{value:2}},transparent:!0,side:en,blending:hl,depthWrite:!1}),this.glowMesh=new qn(n,this.glowMaterial),this.scene.add(this.glowMesh)}updateAudio(e){const t=this.config.audioSmoothing;this.audioValues.bass+=(e.bass-this.audioValues.bass)*t,this.audioValues.mid+=(e.mid-this.audioValues.mid)*t,this.audioValues.treble+=(e.treble-this.audioValues.treble)*t,this.audioValues.level+=(e.level-this.audioValues.level)*t}setSimulatedAudio(e,t,n,s){const r=this.config.audioSmoothing;this.audioValues.bass+=(e-this.audioValues.bass)*r,this.audioValues.mid+=(t-this.audioValues.mid)*r,this.audioValues.treble+=(n-this.audioValues.treble)*r,this.audioValues.level+=(s-this.audioValues.level)*r}setActive(e){this.isActive=e}setColors(e){const t={...Ts,...this.config.colors,...e};this.orbMaterial&&(this.orbMaterial.uniforms.uColorPrimary.value.set(t.primary),this.orbMaterial.uniforms.uColorSecondary.value.set(t.secondary),this.orbMaterial.uniforms.uColorAccent.value.set(t.accent),this.orbMaterial.uniforms.uColorDepth.value.set(t.depth||Ts.depth),this.orbMaterial.uniforms.uColorHighlight.value.set(t.highlight||Ts.highlight)),this.glowMaterial&&this.glowMaterial.uniforms.uGlowColor.value.set(t.glow)}setGlowSettings(e,t){this.config.glowIntensity=e,this.config.idleGlowMultiplier=t}start(){this.animationId===null&&(this.clock.start(),this.animate())}stop(){this.animationId!==null&&(cancelAnimationFrame(this.animationId),this.animationId=null)}getCanvas(){return this.renderer.domElement}destroy(){this.stop(),this.resizeTimeoutId!==null&&(clearTimeout(this.resizeTimeoutId),this.resizeTimeoutId=null),window.removeEventListener("resize",this.handleResize),this.resizeObserver&&(this.resizeObserver.disconnect(),this.resizeObserver=null),this.container.removeEventListener("mousemove",this.handleMouseMove),this.container.removeEventListener("mouseleave",this.handleMouseLeave);const e=this.renderer.domElement;e.removeEventListener("webglcontextlost",this.boundHandleContextLost),e.removeEventListener("webglcontextrestored",this.boundHandleContextRestored),this.orb&&(this.orb.geometry.dispose(),this.scene.remove(this.orb),this.orb=null),this.glowMesh&&(this.glowMesh.geometry.dispose(),this.scene.remove(this.glowMesh),this.glowMesh=null),this.orbMaterial&&(this.orbMaterial.dispose(),this.orbMaterial=null),this.glowMaterial&&(this.glowMaterial.dispose(),this.glowMaterial=null),this.renderer.dispose(),e.parentNode&&e.parentNode.removeChild(e)}}class ko{constructor(e={}){this.audioContext=null,this.analyser=null,this.source=null,this.localSource=null,this.mixer=null,this.frequencyData=new Uint8Array(0),this.waveformData=new Float32Array(0),this.hasAcquiredContext=!1,this.smoothedBass=0,this.smoothedMid=0,this.smoothedTreble=0,this.smoothedLevel=0,this.smoothingFactor=.3,this.options={fftSize:e.fftSize??2048,smoothingTimeConstant:e.smoothingTimeConstant??.8,minDecibels:e.minDecibels??-90,maxDecibels:e.maxDecibels??-10}}async ensureAudioContext(){if(!this.audioContext)this.audioContext=await ei.acquire(),this.audioContext&&(this.hasAcquiredContext=!0);else if(!await ei.ensureResumed())return null;return this.audioContext}async connectStream(e){const t=await this.ensureAudioContext();if(!t){console.warn("[AudioAnalyzer] Could not acquire AudioContext");return}if(this.source)try{this.source.disconnect()}catch{}this.source=t.createMediaStreamSource(e),this.setupMixerAndAnalyser(),this.mixer&&this.source.connect(this.mixer)}async connectLocalStream(e){const t=await this.ensureAudioContext();if(!t){console.warn("[AudioAnalyzer] Could not acquire AudioContext");return}if(this.localSource)try{this.localSource.disconnect()}catch{}this.localSource=t.createMediaStreamSource(e),this.setupMixerAndAnalyser(),this.mixer&&this.localSource.connect(this.mixer)}setupMixerAndAnalyser(){this.audioContext&&(this.mixer||(this.mixer=this.audioContext.createGain(),this.mixer.gain.value=1),this.analyser||(this.analyser=this.audioContext.createAnalyser()),this.analyser.fftSize=this.options.fftSize,this.analyser.smoothingTimeConstant=this.options.smoothingTimeConstant,this.analyser.minDecibels=this.options.minDecibels,this.analyser.maxDecibels=this.options.maxDecibels,this.mixer.disconnect(),this.mixer.connect(this.analyser),this.frequencyData=new Uint8Array(this.analyser.frequencyBinCount),this.waveformData=new Float32Array(this.analyser.fftSize))}async connectAudioElement(e){const t=await this.ensureAudioContext();if(!t){console.warn("[AudioAnalyzer] Could not acquire AudioContext");return}if(this.source)try{this.source.disconnect()}catch{}const n=t.createMediaElementSource(e);this.analyser||(this.analyser=t.createAnalyser()),this.analyser.fftSize=this.options.fftSize,this.analyser.smoothingTimeConstant=this.options.smoothingTimeConstant,this.analyser.minDecibels=this.options.minDecibels,this.analyser.maxDecibels=this.options.maxDecibels,n.connect(this.analyser),this.analyser.connect(t.destination),this.frequencyData=new Uint8Array(this.analyser.frequencyBinCount),this.waveformData=new Float32Array(this.analyser.fftSize)}getAudioData(){if(!this.analyser)return{bass:0,mid:0,treble:0,level:0,waveform:new Float32Array(0),frequency:new Uint8Array(0)};this.analyser.getByteFrequencyData(this.frequencyData),this.analyser.getFloatTimeDomainData(this.waveformData);const{bass:e,mid:t,treble:n}=this.calculateFrequencyBands(),s=this.calculateOverallLevel();return this.smoothedBass+=(e-this.smoothedBass)*this.smoothingFactor,this.smoothedMid+=(t-this.smoothedMid)*this.smoothingFactor,this.smoothedTreble+=(n-this.smoothedTreble)*this.smoothingFactor,this.smoothedLevel+=(s-this.smoothedLevel)*this.smoothingFactor,{bass:this.smoothedBass,mid:this.smoothedMid,treble:this.smoothedTreble,level:this.smoothedLevel,waveform:this.waveformData,frequency:this.frequencyData}}calculateFrequencyBands(){if(!this.audioContext||this.frequencyData.length===0)return{bass:0,mid:0,treble:0};const e=this.audioContext.sampleRate,t=this.frequencyData.length,n=e/(t*2),s=Math.floor(250/n),r=Math.floor(2e3/n);let a=0,o=0,c=0;for(let h=0;h<t;h++){const f=this.frequencyData[h]/255;h<s?a+=f:h<r?o+=f:c+=f}const l=s>0?a/s:0,d=r-s>0?o/(r-s):0,u=t-r>0?c/(t-r):0;return{bass:Math.pow(l,.8),mid:Math.pow(d,.9),treble:Math.pow(u,1.1)}}calculateOverallLevel(){if(this.frequencyData.length===0)return 0;let e=0;for(let n=0;n<this.frequencyData.length;n++)e+=this.frequencyData[n];const t=e/this.frequencyData.length/255;return Math.pow(t,.8)}getPeakLevel(){if(this.frequencyData.length===0)return 0;let e=0;for(let t=0;t<this.frequencyData.length;t++)this.frequencyData[t]>e&&(e=this.frequencyData[t]);return e/255}isActive(){return this.audioContext!==null&&this.audioContext.state==="running"}disconnect(){if(this.source){try{this.source.disconnect()}catch{}this.source=null}if(this.localSource){try{this.localSource.disconnect()}catch{}this.localSource=null}if(this.mixer){try{this.mixer.disconnect()}catch{}this.mixer=null}if(this.analyser){try{this.analyser.disconnect()}catch{}this.analyser=null}this.hasAcquiredContext&&(ei.release(),this.hasAcquiredContext=!1),this.audioContext=null,this.smoothedBass=0,this.smoothedMid=0,this.smoothedTreble=0,this.smoothedLevel=0}getAudioContext(){return this.audioContext}getAnalyser(){return this.analyser}}class aa{constructor(e={}){this.hasAcquired=!1,this.config={enabled:!0,volume:.3,preset:"1",...e}}async ensureContext(){if(!this.config.enabled||this.config.preset==="none")return null;const e=await ei.acquire();return e&&(this.hasAcquired=!0),e}async prewarm(){await this.ensureContext()}async playDrop(e){const t=await this.ensureContext();if(!t)return;const n=t.currentTime,s=this.config.volume,r=e?900:700,a=e?500:400,o=t.createOscillator(),c=t.createGain();o.type="sine",o.frequency.setValueAtTime(r,n),o.frequency.exponentialRampToValueAtTime(a,n+.15),c.gain.setValueAtTime(0,n),c.gain.linearRampToValueAtTime(s*.3,n+.015),c.gain.linearRampToValueAtTime(s*.2,n+.1),c.gain.exponentialRampToValueAtTime(.001,n+.35),o.connect(c).connect(t.destination),o.start(n),o.stop(n+.4)}async playGlassTap(e){const t=await this.ensureContext();if(!t)return;const n=t.currentTime,s=this.config.volume,r=e?2200:1760,a=t.createOscillator(),o=t.createGain();a.type="sine",a.frequency.setValueAtTime(r,n),o.gain.setValueAtTime(0,n),o.gain.linearRampToValueAtTime(s*.25,n+.002),o.gain.exponentialRampToValueAtTime(s*.1,n+.08),o.gain.exponentialRampToValueAtTime(.001,n+.3),a.connect(o).connect(t.destination),a.start(n),a.stop(n+.35);const c=t.createOscillator(),l=t.createGain();c.type="sine",c.frequency.setValueAtTime(r*2.5,n),l.gain.setValueAtTime(0,n),l.gain.linearRampToValueAtTime(s*.08,n+.001),l.gain.exponentialRampToValueAtTime(.001,n+.12),c.connect(l).connect(t.destination),c.start(n),c.stop(n+.15)}async playWhoosh(e){const t=await this.ensureContext();if(!t)return;const n=t.currentTime,s=this.config.volume,r=t.sampleRate*.5,a=t.createBuffer(1,r,t.sampleRate),o=a.getChannelData(0);for(let f=0;f<r;f++)o[f]=Math.random()*2-1;const c=t.createBufferSource();c.buffer=a;const l=t.createBiquadFilter();l.type="bandpass",l.Q.setValueAtTime(2,n);const d=t.createGain();e?(l.frequency.setValueAtTime(300,n),l.frequency.exponentialRampToValueAtTime(2e3,n+.15),l.frequency.exponentialRampToValueAtTime(800,n+.35),d.gain.setValueAtTime(0,n),d.gain.linearRampToValueAtTime(s*.3,n+.05),d.gain.linearRampToValueAtTime(s*.4,n+.15),d.gain.exponentialRampToValueAtTime(.001,n+.4)):(l.frequency.setValueAtTime(1500,n),l.frequency.exponentialRampToValueAtTime(200,n+.3),d.gain.setValueAtTime(0,n),d.gain.linearRampToValueAtTime(s*.35,n+.05),d.gain.exponentialRampToValueAtTime(.001,n+.35));const u=t.createOscillator(),h=t.createGain();u.type="sine",e?(u.frequency.setValueAtTime(300,n),u.frequency.linearRampToValueAtTime(500,n+.2)):(u.frequency.setValueAtTime(400,n),u.frequency.linearRampToValueAtTime(200,n+.25)),h.gain.setValueAtTime(0,n),h.gain.linearRampToValueAtTime(s*.15,n+.05),h.gain.exponentialRampToValueAtTime(.001,n+.35),c.connect(l).connect(d).connect(t.destination),u.connect(h).connect(t.destination),c.start(n),c.stop(n+.5),u.start(n),u.stop(n+.4)}async playGentleNote(e){const t=await this.ensureContext();if(!t)return;const n=t.currentTime,s=this.config.volume,r=e?659.25:523.25,a=t.createOscillator(),o=t.createGain();a.type="sine",a.frequency.setValueAtTime(r,n),o.gain.setValueAtTime(0,n),o.gain.linearRampToValueAtTime(s*.3,n+.02),o.gain.linearRampToValueAtTime(s*.25,n+.1),o.gain.exponentialRampToValueAtTime(s*.08,n+.3),o.gain.exponentialRampToValueAtTime(.001,n+.5),a.connect(o).connect(t.destination),a.start(n),a.stop(n+.55);const c=t.createOscillator(),l=t.createGain();c.type="sine",c.frequency.setValueAtTime(r*2,n),l.gain.setValueAtTime(0,n),l.gain.linearRampToValueAtTime(s*.06,n+.02),l.gain.exponentialRampToValueAtTime(.001,n+.2),c.connect(l).connect(t.destination),c.start(n),c.stop(n+.25)}async playCallStartSound(){if(!(!this.config.enabled||this.config.preset==="none"))switch(this.config.preset){case"1":await this.playDrop(!0);break;case"2":await this.playGlassTap(!0);break;case"3":await this.playWhoosh(!0);break;case"4":await this.playGentleNote(!0);break}}async playCallEndSound(){if(!(!this.config.enabled||this.config.preset==="none"))switch(this.config.preset){case"1":await this.playDrop(!1);break;case"2":await this.playGlassTap(!1);break;case"3":await this.playWhoosh(!1);break;case"4":await this.playGentleNote(!1);break}}setConfig(e){this.config={...this.config,...e}}setEnabled(e){this.config.enabled=e}setVolume(e){this.config.volume=Math.max(0,Math.min(1,e))}setPreset(e){this.config.preset=e}getConfig(){return{...this.config}}isEnabled(){return this.config.enabled&&this.config.preset!=="none"}destroy(){this.hasAcquired&&(ei.release(),this.hasAcquired=!1)}}const hn={default:{primary:"#6366f1",secondary:"#8b5cf6",accent:"#06b6d4",glow:"#818cf8",atmosphere:"#c4b5fd",depth:"#312e81",highlight:"#e0e7ff"},emerald:{primary:"#10b981",secondary:"#34d399",accent:"#6ee7b7",glow:"#34d399",atmosphere:"#a7f3d0",depth:"#064e3b",highlight:"#d1fae5"},rose:{primary:"#f43f5e",secondary:"#fb7185",accent:"#fda4af",glow:"#fb7185",atmosphere:"#fecdd3",depth:"#881337",highlight:"#ffe4e6"},amber:{primary:"#f59e0b",secondary:"#fbbf24",accent:"#fcd34d",glow:"#fbbf24",atmosphere:"#fde68a",depth:"#78350f",highlight:"#fef3c7"},cyan:{primary:"#06b6d4",secondary:"#22d3ee",accent:"#67e8f9",glow:"#22d3ee",atmosphere:"#a5f3fc",depth:"#164e63",highlight:"#cffafe"},purple:{primary:"#9333ea",secondary:"#a855f7",accent:"#c084fc",glow:"#a855f7",atmosphere:"#d8b4fe",depth:"#581c87",highlight:"#f3e8ff"},blue:{primary:"#2563eb",secondary:"#3b82f6",accent:"#60a5fa",glow:"#3b82f6",atmosphere:"#93c5fd",depth:"#1e3a8a",highlight:"#dbeafe"},white:{primary:"#d1d5db",secondary:"#e5e7eb",accent:"#f3f4f6",glow:"#e5e7eb",atmosphere:"#f9fafb",depth:"#4b5563",highlight:"#ffffff"},black:{primary:"#18182b",secondary:"#242440",accent:"#35355a",glow:"#242440",atmosphere:"#4a4a70",depth:"#08080f",highlight:"#7070a0"},tangerine:{primary:"#ff2d00",secondary:"#ff4500",accent:"#ff6600",glow:"#ff4500",atmosphere:"#ff8533",depth:"#cc1100",highlight:"#ff9955"},ember:{primary:"#ff0000",secondary:"#ff0010",accent:"#ff0018",glow:"#ff0008",atmosphere:"#ff1020",depth:"#aa0008",highlight:"#ff2030"}},fn={indigo:{primary:"#3730a3",secondary:"#4338ca",accent:"#4f46e5",glow:"#3730a3",atmosphere:"#4338ca",depth:"#1e1b4b",highlight:"#a5b4fc"},violet:{primary:"#5b21b6",secondary:"#6d28d9",accent:"#7c3aed",glow:"#5b21b6",atmosphere:"#6d28d9",depth:"#2e1065",highlight:"#c4b5fd"},teal:{primary:"#0f766e",secondary:"#0d9488",accent:"#14b8a6",glow:"#0f766e",atmosphere:"#0d9488",depth:"#042f2e",highlight:"#5eead4"},orange:{primary:"#c2410c",secondary:"#ea580c",accent:"#f97316",glow:"#c2410c",atmosphere:"#ea580c",depth:"#431407",highlight:"#fed7aa"},blue:{primary:"#1d4ed8",secondary:"#2563eb",accent:"#3b82f6",glow:"#1d4ed8",atmosphere:"#2563eb",depth:"#1e3a8a",highlight:"#93c5fd"},pink:{primary:"#be185d",secondary:"#db2777",accent:"#ec4899",glow:"#be185d",atmosphere:"#db2777",depth:"#500724",highlight:"#f9a8d4"},silver:{primary:"#6b7280",secondary:"#9ca3af",accent:"#d1d5db",glow:"#e5e7eb",atmosphere:"#f3f4f6",depth:"#374151",highlight:"#f9fafb"},charcoal:{primary:"#0f0f1a",secondary:"#1a1a2e",accent:"#2a2a45",glow:"#0f0f1a",atmosphere:"#1a1a2e",depth:"#050509",highlight:"#50507a"},tangerine:{primary:"#d4960a",secondary:"#e6a000",accent:"#fdb813",glow:"#d4960a",atmosphere:"#e6a000",depth:"#a06800",highlight:"#ffe082"},ember:{primary:"#b80000",secondary:"#d50000",accent:"#ff1744",glow:"#d50000",atmosphere:"#ff5252",depth:"#8b0000",highlight:"#ff8a80"}};function JC(i,e="dark"){const t=e==="dark"?hn:fn;return t[i]||t[Object.keys(t)[0]]}function ZC(i="dark"){return Object.keys(i==="dark"?hn:fn)}const pr={default:{dark:{colors:hn.default,glowIntensity:1.2,idleGlowMultiplier:.6},light:{colors:fn.indigo,glowIntensity:1.8,idleGlowMultiplier:1.2}},emerald:{dark:{colors:hn.emerald,glowIntensity:1.2,idleGlowMultiplier:.6},light:{colors:fn.teal,glowIntensity:1.8,idleGlowMultiplier:1.2}},rose:{dark:{colors:hn.rose,glowIntensity:1.2,idleGlowMultiplier:.6},light:{colors:fn.pink,glowIntensity:1.8,idleGlowMultiplier:1.2}},amber:{dark:{colors:hn.amber,glowIntensity:1.2,idleGlowMultiplier:.6},light:{colors:fn.orange,glowIntensity:1.8,idleGlowMultiplier:1.2}},cyan:{dark:{colors:hn.cyan,glowIntensity:1.2,idleGlowMultiplier:.6},light:{colors:fn.blue,glowIntensity:1.8,idleGlowMultiplier:1.2}},purple:{dark:{colors:hn.purple,glowIntensity:1.2,idleGlowMultiplier:.6},light:{colors:fn.violet,glowIntensity:1.8,idleGlowMultiplier:1.2}},blue:{dark:{colors:hn.blue,glowIntensity:1.2,idleGlowMultiplier:.6},light:{colors:fn.blue,glowIntensity:1.8,idleGlowMultiplier:1.2}},white:{dark:{colors:hn.white,glowIntensity:1.2,idleGlowMultiplier:.6},light:{colors:fn.silver,glowIntensity:1.8,idleGlowMultiplier:1.2}},black:{dark:{colors:hn.black,glowIntensity:1.2,idleGlowMultiplier:.6},light:{colors:fn.charcoal,glowIntensity:1.8,idleGlowMultiplier:1.2}},tangerine:{dark:{colors:hn.tangerine,glowIntensity:1.2,idleGlowMultiplier:.6},light:{colors:fn.tangerine,glowIntensity:1.8,idleGlowMultiplier:1.2}},ember:{dark:{colors:hn.ember,glowIntensity:1.2,idleGlowMultiplier:.6},light:{colors:fn.ember,glowIntensity:1.8,idleGlowMultiplier:1.2}}},QC=Object.fromEntries(Object.entries(pr).map(([i,e])=>[i,e.dark])),eE=Object.fromEntries(Object.entries(pr).map(([i,e])=>[i,e.light]));function mr(i){return(pr[i]||pr.default).dark}function tE(){return Object.keys(pr)}function nE(i,e){const t=mr(e);i.orbColors=t.colors,i.glowIntensity=t.glowIntensity,i.idleGlowMultiplier=t.idleGlowMultiplier}const Fm="privacy_accepted",Jd="user_identity";function Io(){try{return localStorage.getItem(Fm)==="true"}catch{return!1}}function Do(){try{localStorage.setItem(Fm,"true")}catch{}}function Lo(){try{let i=localStorage.getItem(Jd);return i||(i=crypto.randomUUID(),localStorage.setItem(Jd,i)),i}catch{return crypto.randomUUID()}}function Uo(){try{return localStorage.getItem(Jd)}catch{return null}}function iE(){if(typeof window>"u")return"https://api.hanc.ai";const i=window.location.hostname;return i.endsWith(".hanc.me")||i==="hanc.me"||i==="localhost"?"https://api.hanc.me":"https://api.hanc.ai"}const oa=iE(),Zd={terms_enabled:!1,terms_content:"",terms_url:"https://hanc.ai/terms",privacy_url:"https://hanc.ai/privacy",theme:"default",allow_all_domains:!0,allowed_domains:[]},No=new Map,sE=1e3;async function ca(i,e=oa){if(!i)return console.warn("[hanc-widget] No agentId provided, using default config"),Zd;const t=No.get(i);if(t&&Date.now()-t.timestamp<sE)return t.config;try{const n=await fetch(`${e}/v1/site/widget-config/${i}`,{method:"GET",headers:{"Content-Type":"application/json"}});if(!n.ok){if(n.status===404)return console.warn(`[hanc-widget] Agent ${i} not found, using default config`),Zd;throw new Error(`HTTP ${n.status}: ${n.statusText}`)}const s=await n.json();return No.set(i,{config:s,timestamp:Date.now()}),s}catch(n){return console.error("[hanc-widget] Failed to fetch widget config:",n),Zd}}const rE=["hanc.ai","hanc.me","localhost"];function la(i){const e=window.location.hostname;return rE.some(n=>e===n||e.endsWith(`.${n}`))||i.allow_all_domains||!i.allowed_domains||i.allowed_domains.length===0?!0:i.allowed_domains.some(n=>e===n||e.endsWith(`.${n}`))}function aE(i){i?No.delete(i):No.clear()}var oE=Object.defineProperty,cE=Object.getOwnPropertyDescriptor,da=(i,e,t,n)=>{for(var s=n>1?void 0:n?cE(e,t):e,r=i.length-1,a;r>=0;r--)(a=i[r])&&(s=(n?a(e,t,s):a(s))||s);return n&&s&&oE(e,t,s),s};let Cs=class extends di{constructor(){super(...arguments),this.privacyUrl="https://hanc.ai/privacy",this.termsUrl="https://hanc.ai/terms",this.termsContent="",this.modalTitle="Before we start",this.modalContainer=null}connectedCallback(){super.connectedCallback(),this.createModal()}disconnectedCallback(){super.disconnectedCallback(),this.removeModal()}createModal(){this.modalContainer=document.createElement("div"),this.modalContainer.innerHTML=this.getModalHTML(),document.body.appendChild(this.modalContainer);const i=this.modalContainer.querySelector(".hanc-privacy-overlay"),e=this.modalContainer.querySelector(".hanc-btn-accept"),t=this.modalContainer.querySelector(".hanc-btn-decline");i==null||i.addEventListener("click",n=>{n.target===i&&this.handleDecline()}),e==null||e.addEventListener("click",()=>this.handleAccept()),t==null||t.addEventListener("click",()=>this.handleDecline())}removeModal(){this.modalContainer&&(this.modalContainer.remove(),this.modalContainer=null)}renderMarkdown(i){if(!i)return"";let t=(n=>n.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"))(i);return t=t.replace(/^#### (.+)$/gm,"<h4>$1</h4>"),t=t.replace(/^### (.+)$/gm,"<h3>$1</h3>"),t=t.replace(/^## (.+)$/gm,"<h2>$1</h2>"),t=t.replace(/^# (.+)$/gm,"<h1>$1</h1>"),t=t.replace(/\*\*(.+?)\*\*/g,"<strong>$1</strong>"),t=t.replace(/__(.+?)__/g,"<strong>$1</strong>"),t=t.replace(/\*(.+?)\*/g,"<em>$1</em>"),t=t.replace(/_(.+?)_/g,"<em>$1</em>"),t=t.replace(/\[([^\]]+)\]\((https?:\/\/[^)]+)\)/g,'<a href="$2" target="_blank" rel="noopener noreferrer">$1</a>'),t=t.replace(/^\- (.+)$/gm,"<li>$1</li>"),t=t.replace(/(<li>.*<\/li>\n?)+/g,"<ul>$&</ul>"),t=t.replace(/\n\n/g,"</p><p>"),t="<p>"+t+"</p>",t=t.replace(/<p><\/p>/g,""),t=t.replace(/<p>(<h[1-4]>)/g,"$1"),t=t.replace(/(<\/h[1-4]>)<\/p>/g,"$1"),t=t.replace(/<p>(<ul>)/g,"$1"),t=t.replace(/(<\/ul>)<\/p>/g,"$1"),t=t.replace(/\n/g,"<br>"),t}getModalHTML(){const i=this.termsContent&&this.termsContent.trim().length>0,e=i?this.renderMarkdown(this.termsContent):"By starting this call, you agree to our Terms of Service and Privacy Policy.";return`
|
|
4485
|
+
`,Ts={primary:"#6366f1",secondary:"#8b5cf6",accent:"#06b6d4",glow:"#818cf8",atmosphere:"#c4b5fd",depth:"#312e81",highlight:"#e0e7ff"},KC={size:1,segments:128,colors:Ts,morphStrength:1,noiseScale:1.5,noiseSpeed:.3,glowIntensity:.8,idleGlowMultiplier:.4,fresnelPower:2.5,rotationSpeed:.1,audioReactivity:3,audioSmoothing:.9,idleMorphMultiplier:.25,colorContrast:1.5};class Po{constructor(e,t={}){this.orb=null,this.glowMesh=null,this.orbMaterial=null,this.glowMaterial=null,this.animationId=null,this.isActive=!1,this.targetRotation={x:0,y:0},this.currentRotation={x:0,y:0},this.audioValues={bass:0,mid:0,treble:0,level:0},this.resizeObserver=null,this.resizeTimeoutId=null,this.isContextLost=!1,this.animate=()=>{if(this.isContextLost)return;this.animationId=requestAnimationFrame(this.animate);const u=this.clock.getElapsedTime();if(this.clock.getDelta(),this.orbMaterial){this.orbMaterial.uniforms.uTime.value=u,this.orbMaterial.uniforms.uAudioBass.value=this.audioValues.bass,this.orbMaterial.uniforms.uAudioMid.value=this.audioValues.mid,this.orbMaterial.uniforms.uAudioTreble.value=this.audioValues.treble,this.orbMaterial.uniforms.uAudioLevel.value=this.audioValues.level;const h=this.isActive?this.config.morphStrength*1.5:this.config.morphStrength*this.config.idleMorphMultiplier,f=this.orbMaterial.uniforms.uMorphStrength.value;this.orbMaterial.uniforms.uMorphStrength.value+=(h-f)*.05}if(this.glowMaterial){this.glowMaterial.uniforms.uTime.value=u,this.glowMaterial.uniforms.uAudioLevel.value=this.audioValues.level;const h=this.isActive?this.config.glowIntensity*1.5:this.config.glowIntensity*this.config.idleGlowMultiplier,f=this.glowMaterial.uniforms.uGlowIntensity.value;this.glowMaterial.uniforms.uGlowIntensity.value+=(h-f)*.05}this.currentRotation.x+=(this.targetRotation.x-this.currentRotation.x)*.05,this.currentRotation.y+=(this.targetRotation.y-this.currentRotation.y)*.05,this.orb&&(this.orb.rotation.x=this.currentRotation.x+u*this.config.rotationSpeed*.3,this.orb.rotation.y=this.currentRotation.y+u*this.config.rotationSpeed),this.glowMesh&&(this.glowMesh.rotation.x=this.currentRotation.x+u*this.config.rotationSpeed*.3,this.glowMesh.rotation.y=this.currentRotation.y+u*this.config.rotationSpeed),this.renderer.render(this.scene,this.camera)},this.handleResize=()=>{this.resizeTimeoutId!==null&&clearTimeout(this.resizeTimeoutId),this.resizeTimeoutId=setTimeout(()=>{this.resizeTimeoutId=null;const u=this.container.clientWidth,h=this.container.clientHeight;if(u===0||h===0)return;const f=u*this.canvasPadding,g=h*this.canvasPadding;this.camera.aspect=f/g,this.camera.updateProjectionMatrix(),this.renderer.setSize(f,g)},100)},this.handleMouseMove=u=>{const h=this.container.getBoundingClientRect(),f=(u.clientX-h.left)/h.width*2-1,g=-((u.clientY-h.top)/h.height)*2+1;this.targetRotation.x=g*.3,this.targetRotation.y=f*.3},this.handleMouseLeave=()=>{this.targetRotation.x=0,this.targetRotation.y=0},this.container=e,this.config={...KC,...t},this.clock=new R_;const n=/iPhone|iPad|iPod/i.test(navigator.userAgent),s=/Android/i.test(navigator.userAgent);this.canvasPadding=n?1.5:s?2:3,this.boundHandleContextLost=this.handleContextLost.bind(this),this.boundHandleContextRestored=this.handleContextRestored.bind(this),this.scene=new y_;const r=e.clientWidth*this.canvasPadding,a=e.clientHeight*this.canvasPadding,o=r/a;this.camera=new Rn(45,o,.1,100);const c=3,l=9;this.camera.position.z=l*(this.canvasPadding/c),this.renderer=new qC({antialias:!0,alpha:!0,powerPreference:"high-performance"}),this.renderer.setPixelRatio(Math.min(window.devicePixelRatio,2)),this.renderer.setSize(r,a),this.renderer.setClearColor(0,0);const d=this.renderer.domElement;d.style.position="absolute",d.style.left="50%",d.style.top="50%",d.style.transform="translate(-50%, -50%)",d.style.pointerEvents="none",e.appendChild(d),d.addEventListener("webglcontextlost",this.boundHandleContextLost),d.addEventListener("webglcontextrestored",this.boundHandleContextRestored),this.createOrb(),window.addEventListener("resize",this.handleResize),this.resizeObserver=new ResizeObserver(this.handleResize),this.resizeObserver.observe(e),e.addEventListener("mousemove",this.handleMouseMove),e.addEventListener("mouseleave",this.handleMouseLeave)}handleContextLost(e){e.preventDefault(),this.isContextLost=!0,this.stop()}handleContextRestored(e){this.isContextLost=!1,this.recreateAfterContextLoss(),this.start()}recreateAfterContextLoss(){this.orb&&(this.orb.geometry.dispose(),this.scene.remove(this.orb),this.orb=null),this.glowMesh&&(this.glowMesh.geometry.dispose(),this.scene.remove(this.glowMesh),this.glowMesh=null),this.orbMaterial&&(this.orbMaterial.dispose(),this.orbMaterial=null),this.glowMaterial&&(this.glowMaterial.dispose(),this.glowMaterial=null),this.createOrb()}createOrb(){const e={...Ts,...this.config.colors},t=new Vd(this.config.size,this.config.segments/4);this.orbMaterial=new An({vertexShader:$C,fragmentShader:jC,uniforms:{uTime:{value:0},uAudioBass:{value:0},uAudioMid:{value:0},uAudioTreble:{value:0},uAudioLevel:{value:0},uMorphStrength:{value:this.config.morphStrength},uNoiseScale:{value:this.config.noiseScale},uNoiseSpeed:{value:this.config.noiseSpeed},uAudioReactivity:{value:this.config.audioReactivity},uColorPrimary:{value:new nt(e.primary)},uColorSecondary:{value:new nt(e.secondary)},uColorAccent:{value:new nt(e.accent)},uColorDepth:{value:new nt(e.depth||Ts.depth)},uColorHighlight:{value:new nt(e.highlight||Ts.highlight)},uFresnelPower:{value:this.config.fresnelPower},uGlowIntensity:{value:this.config.glowIntensity},uColorContrast:{value:this.config.colorContrast}},transparent:!0,side:yi}),this.orb=new qn(t,this.orbMaterial),this.scene.add(this.orb);const n=new Gd(this.config.size,64,64);this.glowMaterial=new An({vertexShader:XC,fragmentShader:YC,uniforms:{uTime:{value:0},uAudioLevel:{value:0},uGlowColor:{value:new nt(e.glow)},uGlowIntensity:{value:this.config.glowIntensity*.6},uPulseSpeed:{value:2}},transparent:!0,side:en,blending:hl,depthWrite:!1}),this.glowMesh=new qn(n,this.glowMaterial),this.scene.add(this.glowMesh)}updateAudio(e){const t=this.config.audioSmoothing;this.audioValues.bass+=(e.bass-this.audioValues.bass)*t,this.audioValues.mid+=(e.mid-this.audioValues.mid)*t,this.audioValues.treble+=(e.treble-this.audioValues.treble)*t,this.audioValues.level+=(e.level-this.audioValues.level)*t}setSimulatedAudio(e,t,n,s){const r=this.config.audioSmoothing;this.audioValues.bass+=(e-this.audioValues.bass)*r,this.audioValues.mid+=(t-this.audioValues.mid)*r,this.audioValues.treble+=(n-this.audioValues.treble)*r,this.audioValues.level+=(s-this.audioValues.level)*r}setActive(e){this.isActive=e}setColors(e){const t={...Ts,...this.config.colors,...e};this.orbMaterial&&(this.orbMaterial.uniforms.uColorPrimary.value.set(t.primary),this.orbMaterial.uniforms.uColorSecondary.value.set(t.secondary),this.orbMaterial.uniforms.uColorAccent.value.set(t.accent),this.orbMaterial.uniforms.uColorDepth.value.set(t.depth||Ts.depth),this.orbMaterial.uniforms.uColorHighlight.value.set(t.highlight||Ts.highlight)),this.glowMaterial&&this.glowMaterial.uniforms.uGlowColor.value.set(t.glow)}setGlowSettings(e,t){this.config.glowIntensity=e,this.config.idleGlowMultiplier=t}start(){this.animationId===null&&(this.clock.start(),this.animate())}stop(){this.animationId!==null&&(cancelAnimationFrame(this.animationId),this.animationId=null)}getCanvas(){return this.renderer.domElement}destroy(){this.stop(),this.resizeTimeoutId!==null&&(clearTimeout(this.resizeTimeoutId),this.resizeTimeoutId=null),window.removeEventListener("resize",this.handleResize),this.resizeObserver&&(this.resizeObserver.disconnect(),this.resizeObserver=null),this.container.removeEventListener("mousemove",this.handleMouseMove),this.container.removeEventListener("mouseleave",this.handleMouseLeave);const e=this.renderer.domElement;e.removeEventListener("webglcontextlost",this.boundHandleContextLost),e.removeEventListener("webglcontextrestored",this.boundHandleContextRestored),this.orb&&(this.orb.geometry.dispose(),this.scene.remove(this.orb),this.orb=null),this.glowMesh&&(this.glowMesh.geometry.dispose(),this.scene.remove(this.glowMesh),this.glowMesh=null),this.orbMaterial&&(this.orbMaterial.dispose(),this.orbMaterial=null),this.glowMaterial&&(this.glowMaterial.dispose(),this.glowMaterial=null),this.renderer.dispose(),e.parentNode&&e.parentNode.removeChild(e)}}class ko{constructor(e={}){this.audioContext=null,this.analyser=null,this.source=null,this.localSource=null,this.mixer=null,this.frequencyData=new Uint8Array(0),this.waveformData=new Float32Array(0),this.hasAcquiredContext=!1,this.smoothedBass=0,this.smoothedMid=0,this.smoothedTreble=0,this.smoothedLevel=0,this.smoothingFactor=.3,this.options={fftSize:e.fftSize??2048,smoothingTimeConstant:e.smoothingTimeConstant??.8,minDecibels:e.minDecibels??-90,maxDecibels:e.maxDecibels??-10}}async ensureAudioContext(){if(!this.audioContext)this.audioContext=await ei.acquire(),this.audioContext&&(this.hasAcquiredContext=!0);else if(!await ei.ensureResumed())return null;return this.audioContext}async connectStream(e){const t=await this.ensureAudioContext();if(!t){console.warn("[AudioAnalyzer] Could not acquire AudioContext");return}if(this.source)try{this.source.disconnect()}catch{}this.source=t.createMediaStreamSource(e),this.setupMixerAndAnalyser(),this.mixer&&this.source.connect(this.mixer)}async connectLocalStream(e){const t=await this.ensureAudioContext();if(!t){console.warn("[AudioAnalyzer] Could not acquire AudioContext");return}if(this.localSource)try{this.localSource.disconnect()}catch{}this.localSource=t.createMediaStreamSource(e),this.setupMixerAndAnalyser(),this.mixer&&this.localSource.connect(this.mixer)}setupMixerAndAnalyser(){this.audioContext&&(this.mixer||(this.mixer=this.audioContext.createGain(),this.mixer.gain.value=1),this.analyser||(this.analyser=this.audioContext.createAnalyser()),this.analyser.fftSize=this.options.fftSize,this.analyser.smoothingTimeConstant=this.options.smoothingTimeConstant,this.analyser.minDecibels=this.options.minDecibels,this.analyser.maxDecibels=this.options.maxDecibels,this.mixer.disconnect(),this.mixer.connect(this.analyser),this.frequencyData=new Uint8Array(this.analyser.frequencyBinCount),this.waveformData=new Float32Array(this.analyser.fftSize))}async connectAudioElement(e){const t=await this.ensureAudioContext();if(!t){console.warn("[AudioAnalyzer] Could not acquire AudioContext");return}if(this.source)try{this.source.disconnect()}catch{}const n=t.createMediaElementSource(e);this.analyser||(this.analyser=t.createAnalyser()),this.analyser.fftSize=this.options.fftSize,this.analyser.smoothingTimeConstant=this.options.smoothingTimeConstant,this.analyser.minDecibels=this.options.minDecibels,this.analyser.maxDecibels=this.options.maxDecibels,n.connect(this.analyser),this.analyser.connect(t.destination),this.frequencyData=new Uint8Array(this.analyser.frequencyBinCount),this.waveformData=new Float32Array(this.analyser.fftSize)}getAudioData(){if(!this.analyser)return{bass:0,mid:0,treble:0,level:0,waveform:new Float32Array(0),frequency:new Uint8Array(0)};this.analyser.getByteFrequencyData(this.frequencyData),this.analyser.getFloatTimeDomainData(this.waveformData);const{bass:e,mid:t,treble:n}=this.calculateFrequencyBands(),s=this.calculateOverallLevel();return this.smoothedBass+=(e-this.smoothedBass)*this.smoothingFactor,this.smoothedMid+=(t-this.smoothedMid)*this.smoothingFactor,this.smoothedTreble+=(n-this.smoothedTreble)*this.smoothingFactor,this.smoothedLevel+=(s-this.smoothedLevel)*this.smoothingFactor,{bass:this.smoothedBass,mid:this.smoothedMid,treble:this.smoothedTreble,level:this.smoothedLevel,waveform:this.waveformData,frequency:this.frequencyData}}calculateFrequencyBands(){if(!this.audioContext||this.frequencyData.length===0)return{bass:0,mid:0,treble:0};const e=this.audioContext.sampleRate,t=this.frequencyData.length,n=e/(t*2),s=Math.floor(250/n),r=Math.floor(2e3/n);let a=0,o=0,c=0;for(let h=0;h<t;h++){const f=this.frequencyData[h]/255;h<s?a+=f:h<r?o+=f:c+=f}const l=s>0?a/s:0,d=r-s>0?o/(r-s):0,u=t-r>0?c/(t-r):0;return{bass:Math.pow(l,.8),mid:Math.pow(d,.9),treble:Math.pow(u,1.1)}}calculateOverallLevel(){if(this.frequencyData.length===0)return 0;let e=0;for(let n=0;n<this.frequencyData.length;n++)e+=this.frequencyData[n];const t=e/this.frequencyData.length/255;return Math.pow(t,.8)}getPeakLevel(){if(this.frequencyData.length===0)return 0;let e=0;for(let t=0;t<this.frequencyData.length;t++)this.frequencyData[t]>e&&(e=this.frequencyData[t]);return e/255}isActive(){return this.audioContext!==null&&this.audioContext.state==="running"}disconnect(){if(this.source){try{this.source.disconnect()}catch{}this.source=null}if(this.localSource){try{this.localSource.disconnect()}catch{}this.localSource=null}if(this.mixer){try{this.mixer.disconnect()}catch{}this.mixer=null}if(this.analyser){try{this.analyser.disconnect()}catch{}this.analyser=null}this.hasAcquiredContext&&(ei.release(),this.hasAcquiredContext=!1),this.audioContext=null,this.smoothedBass=0,this.smoothedMid=0,this.smoothedTreble=0,this.smoothedLevel=0}getAudioContext(){return this.audioContext}getAnalyser(){return this.analyser}}class aa{constructor(e={}){this.hasAcquired=!1,this.config={enabled:!0,volume:.3,preset:"1",...e}}async ensureContext(){if(!this.config.enabled||this.config.preset==="none")return null;const e=await ei.acquire();return e&&(this.hasAcquired=!0),e}async prewarm(){await this.ensureContext()}async playDrop(e){const t=await this.ensureContext();if(!t)return;const n=t.currentTime,s=this.config.volume,r=e?900:700,a=e?500:400,o=t.createOscillator(),c=t.createGain();o.type="sine",o.frequency.setValueAtTime(r,n),o.frequency.exponentialRampToValueAtTime(a,n+.15),c.gain.setValueAtTime(0,n),c.gain.linearRampToValueAtTime(s*.3,n+.015),c.gain.linearRampToValueAtTime(s*.2,n+.1),c.gain.exponentialRampToValueAtTime(.001,n+.35),o.connect(c).connect(t.destination),o.start(n),o.stop(n+.4)}async playGlassTap(e){const t=await this.ensureContext();if(!t)return;const n=t.currentTime,s=this.config.volume,r=e?2200:1760,a=t.createOscillator(),o=t.createGain();a.type="sine",a.frequency.setValueAtTime(r,n),o.gain.setValueAtTime(0,n),o.gain.linearRampToValueAtTime(s*.25,n+.002),o.gain.exponentialRampToValueAtTime(s*.1,n+.08),o.gain.exponentialRampToValueAtTime(.001,n+.3),a.connect(o).connect(t.destination),a.start(n),a.stop(n+.35);const c=t.createOscillator(),l=t.createGain();c.type="sine",c.frequency.setValueAtTime(r*2.5,n),l.gain.setValueAtTime(0,n),l.gain.linearRampToValueAtTime(s*.08,n+.001),l.gain.exponentialRampToValueAtTime(.001,n+.12),c.connect(l).connect(t.destination),c.start(n),c.stop(n+.15)}async playWhoosh(e){const t=await this.ensureContext();if(!t)return;const n=t.currentTime,s=this.config.volume,r=t.sampleRate*.5,a=t.createBuffer(1,r,t.sampleRate),o=a.getChannelData(0);for(let f=0;f<r;f++)o[f]=Math.random()*2-1;const c=t.createBufferSource();c.buffer=a;const l=t.createBiquadFilter();l.type="bandpass",l.Q.setValueAtTime(2,n);const d=t.createGain();e?(l.frequency.setValueAtTime(300,n),l.frequency.exponentialRampToValueAtTime(2e3,n+.15),l.frequency.exponentialRampToValueAtTime(800,n+.35),d.gain.setValueAtTime(0,n),d.gain.linearRampToValueAtTime(s*.3,n+.05),d.gain.linearRampToValueAtTime(s*.4,n+.15),d.gain.exponentialRampToValueAtTime(.001,n+.4)):(l.frequency.setValueAtTime(1500,n),l.frequency.exponentialRampToValueAtTime(200,n+.3),d.gain.setValueAtTime(0,n),d.gain.linearRampToValueAtTime(s*.35,n+.05),d.gain.exponentialRampToValueAtTime(.001,n+.35));const u=t.createOscillator(),h=t.createGain();u.type="sine",e?(u.frequency.setValueAtTime(300,n),u.frequency.linearRampToValueAtTime(500,n+.2)):(u.frequency.setValueAtTime(400,n),u.frequency.linearRampToValueAtTime(200,n+.25)),h.gain.setValueAtTime(0,n),h.gain.linearRampToValueAtTime(s*.15,n+.05),h.gain.exponentialRampToValueAtTime(.001,n+.35),c.connect(l).connect(d).connect(t.destination),u.connect(h).connect(t.destination),c.start(n),c.stop(n+.5),u.start(n),u.stop(n+.4)}async playGentleNote(e){const t=await this.ensureContext();if(!t)return;const n=t.currentTime,s=this.config.volume,r=e?659.25:523.25,a=t.createOscillator(),o=t.createGain();a.type="sine",a.frequency.setValueAtTime(r,n),o.gain.setValueAtTime(0,n),o.gain.linearRampToValueAtTime(s*.3,n+.02),o.gain.linearRampToValueAtTime(s*.25,n+.1),o.gain.exponentialRampToValueAtTime(s*.08,n+.3),o.gain.exponentialRampToValueAtTime(.001,n+.5),a.connect(o).connect(t.destination),a.start(n),a.stop(n+.55);const c=t.createOscillator(),l=t.createGain();c.type="sine",c.frequency.setValueAtTime(r*2,n),l.gain.setValueAtTime(0,n),l.gain.linearRampToValueAtTime(s*.06,n+.02),l.gain.exponentialRampToValueAtTime(.001,n+.2),c.connect(l).connect(t.destination),c.start(n),c.stop(n+.25)}async playCallStartSound(){if(!(!this.config.enabled||this.config.preset==="none"))switch(this.config.preset){case"1":await this.playDrop(!0);break;case"2":await this.playGlassTap(!0);break;case"3":await this.playWhoosh(!0);break;case"4":await this.playGentleNote(!0);break}}async playCallEndSound(){if(!(!this.config.enabled||this.config.preset==="none"))switch(this.config.preset){case"1":await this.playDrop(!1);break;case"2":await this.playGlassTap(!1);break;case"3":await this.playWhoosh(!1);break;case"4":await this.playGentleNote(!1);break}}setConfig(e){this.config={...this.config,...e}}setEnabled(e){this.config.enabled=e}setVolume(e){this.config.volume=Math.max(0,Math.min(1,e))}setPreset(e){this.config.preset=e}getConfig(){return{...this.config}}isEnabled(){return this.config.enabled&&this.config.preset!=="none"}destroy(){this.hasAcquired&&(ei.release(),this.hasAcquired=!1)}}const rn={default:{primary:"#6366f1",secondary:"#8b5cf6",accent:"#06b6d4",glow:"#818cf8",atmosphere:"#c4b5fd",depth:"#312e81",highlight:"#e0e7ff"},emerald:{primary:"#10b981",secondary:"#34d399",accent:"#6ee7b7",glow:"#34d399",atmosphere:"#a7f3d0",depth:"#064e3b",highlight:"#d1fae5"},rose:{primary:"#f43f5e",secondary:"#fb7185",accent:"#fda4af",glow:"#fb7185",atmosphere:"#fecdd3",depth:"#881337",highlight:"#ffe4e6"},amber:{primary:"#f59e0b",secondary:"#fbbf24",accent:"#fcd34d",glow:"#fbbf24",atmosphere:"#fde68a",depth:"#78350f",highlight:"#fef3c7"},cyan:{primary:"#06b6d4",secondary:"#22d3ee",accent:"#67e8f9",glow:"#22d3ee",atmosphere:"#a5f3fc",depth:"#164e63",highlight:"#cffafe"},purple:{primary:"#9333ea",secondary:"#a855f7",accent:"#c084fc",glow:"#a855f7",atmosphere:"#d8b4fe",depth:"#581c87",highlight:"#f3e8ff"},blue:{primary:"#2563eb",secondary:"#3b82f6",accent:"#60a5fa",glow:"#3b82f6",atmosphere:"#93c5fd",depth:"#1e3a8a",highlight:"#dbeafe"},white:{primary:"#d1d5db",secondary:"#e5e7eb",accent:"#f3f4f6",glow:"#e5e7eb",atmosphere:"#f9fafb",depth:"#4b5563",highlight:"#ffffff"},black:{primary:"#18182b",secondary:"#242440",accent:"#35355a",glow:"#242440",atmosphere:"#4a4a70",depth:"#08080f",highlight:"#7070a0"},tangerine:{primary:"#ff2d00",secondary:"#ff4500",accent:"#ff6600",glow:"#ff4500",atmosphere:"#ff8533",depth:"#cc1100",highlight:"#ff9955"},ember:{primary:"#ff0000",secondary:"#ff0010",accent:"#ff0018",glow:"#ff0008",atmosphere:"#ff1020",depth:"#aa0008",highlight:"#ff2030"},"tangerine-neon":{primary:"#F97316",secondary:"#EF4444",accent:"#EC4899",glow:"#F97316",atmosphere:"#FB923C",depth:"#C2410C",highlight:"#FDBA74"}},an={indigo:{primary:"#3730a3",secondary:"#4338ca",accent:"#4f46e5",glow:"#3730a3",atmosphere:"#4338ca",depth:"#1e1b4b",highlight:"#a5b4fc"},violet:{primary:"#5b21b6",secondary:"#6d28d9",accent:"#7c3aed",glow:"#5b21b6",atmosphere:"#6d28d9",depth:"#2e1065",highlight:"#c4b5fd"},teal:{primary:"#0f766e",secondary:"#0d9488",accent:"#14b8a6",glow:"#0f766e",atmosphere:"#0d9488",depth:"#042f2e",highlight:"#5eead4"},orange:{primary:"#c2410c",secondary:"#ea580c",accent:"#f97316",glow:"#c2410c",atmosphere:"#ea580c",depth:"#431407",highlight:"#fed7aa"},blue:{primary:"#1d4ed8",secondary:"#2563eb",accent:"#3b82f6",glow:"#1d4ed8",atmosphere:"#2563eb",depth:"#1e3a8a",highlight:"#93c5fd"},pink:{primary:"#be185d",secondary:"#db2777",accent:"#ec4899",glow:"#be185d",atmosphere:"#db2777",depth:"#500724",highlight:"#f9a8d4"},silver:{primary:"#6b7280",secondary:"#9ca3af",accent:"#d1d5db",glow:"#e5e7eb",atmosphere:"#f3f4f6",depth:"#374151",highlight:"#f9fafb"},charcoal:{primary:"#0f0f1a",secondary:"#1a1a2e",accent:"#2a2a45",glow:"#0f0f1a",atmosphere:"#1a1a2e",depth:"#050509",highlight:"#50507a"},tangerine:{primary:"#d4960a",secondary:"#e6a000",accent:"#fdb813",glow:"#d4960a",atmosphere:"#e6a000",depth:"#a06800",highlight:"#ffe082"},ember:{primary:"#b80000",secondary:"#d50000",accent:"#ff1744",glow:"#d50000",atmosphere:"#ff5252",depth:"#8b0000",highlight:"#ff8a80"},"tangerine-neon":{primary:"#EA580C",secondary:"#F97316",accent:"#FB923C",glow:"#EA580C",atmosphere:"#F97316",depth:"#9A3412",highlight:"#FDBA74"}};function JC(i,e="dark"){const t=e==="dark"?rn:an;return t[i]||t[Object.keys(t)[0]]}function ZC(i="dark"){return Object.keys(i==="dark"?rn:an)}const pr={default:{dark:{colors:rn.default,glowIntensity:1.2,idleGlowMultiplier:.6},light:{colors:an.indigo,glowIntensity:1.8,idleGlowMultiplier:1.2}},emerald:{dark:{colors:rn.emerald,glowIntensity:1.2,idleGlowMultiplier:.6},light:{colors:an.teal,glowIntensity:1.8,idleGlowMultiplier:1.2}},rose:{dark:{colors:rn.rose,glowIntensity:1.2,idleGlowMultiplier:.6},light:{colors:an.pink,glowIntensity:1.8,idleGlowMultiplier:1.2}},amber:{dark:{colors:rn.amber,glowIntensity:1.2,idleGlowMultiplier:.6},light:{colors:an.orange,glowIntensity:1.8,idleGlowMultiplier:1.2}},cyan:{dark:{colors:rn.cyan,glowIntensity:1.2,idleGlowMultiplier:.6},light:{colors:an.blue,glowIntensity:1.8,idleGlowMultiplier:1.2}},purple:{dark:{colors:rn.purple,glowIntensity:1.2,idleGlowMultiplier:.6},light:{colors:an.violet,glowIntensity:1.8,idleGlowMultiplier:1.2}},blue:{dark:{colors:rn.blue,glowIntensity:1.2,idleGlowMultiplier:.6},light:{colors:an.blue,glowIntensity:1.8,idleGlowMultiplier:1.2}},white:{dark:{colors:rn.white,glowIntensity:1.2,idleGlowMultiplier:.6},light:{colors:an.silver,glowIntensity:1.8,idleGlowMultiplier:1.2}},black:{dark:{colors:rn.black,glowIntensity:1.2,idleGlowMultiplier:.6},light:{colors:an.charcoal,glowIntensity:1.8,idleGlowMultiplier:1.2}},tangerine:{dark:{colors:rn.tangerine,glowIntensity:1.2,idleGlowMultiplier:.6},light:{colors:an.tangerine,glowIntensity:1.8,idleGlowMultiplier:1.2}},ember:{dark:{colors:rn.ember,glowIntensity:1.2,idleGlowMultiplier:.6},light:{colors:an.ember,glowIntensity:1.8,idleGlowMultiplier:1.2}},"tangerine-neon":{dark:{colors:rn["tangerine-neon"],glowIntensity:1.4,idleGlowMultiplier:.7},light:{colors:an["tangerine-neon"],glowIntensity:2,idleGlowMultiplier:1.3}}},QC=Object.fromEntries(Object.entries(pr).map(([i,e])=>[i,e.dark])),eE=Object.fromEntries(Object.entries(pr).map(([i,e])=>[i,e.light]));function mr(i){return(pr[i]||pr.default).dark}function tE(){return Object.keys(pr)}function nE(i,e){const t=mr(e);i.orbColors=t.colors,i.glowIntensity=t.glowIntensity,i.idleGlowMultiplier=t.idleGlowMultiplier}const Fm="privacy_accepted",Jd="user_identity";function Io(){try{return localStorage.getItem(Fm)==="true"}catch{return!1}}function Do(){try{localStorage.setItem(Fm,"true")}catch{}}function Lo(){try{let i=localStorage.getItem(Jd);return i||(i=crypto.randomUUID(),localStorage.setItem(Jd,i)),i}catch{return crypto.randomUUID()}}function Uo(){try{return localStorage.getItem(Jd)}catch{return null}}function iE(){if(typeof window>"u")return"https://api.hanc.ai";const i=window.location.hostname;return i.endsWith(".hanc.me")||i==="hanc.me"||i==="localhost"?"https://api.hanc.me":"https://api.hanc.ai"}const oa=iE(),Zd={terms_enabled:!1,terms_content:"",terms_url:"https://hanc.ai/terms",privacy_url:"https://hanc.ai/privacy",theme:"default",allow_all_domains:!0,allowed_domains:[]},No=new Map,sE=1e3;async function ca(i,e=oa){if(!i)return console.warn("[hanc-widget] No agentId provided, using default config"),Zd;const t=No.get(i);if(t&&Date.now()-t.timestamp<sE)return t.config;try{const n=await fetch(`${e}/v1/site/widget-config/${i}`,{method:"GET",headers:{"Content-Type":"application/json"}});if(!n.ok){if(n.status===404)return console.warn(`[hanc-widget] Agent ${i} not found, using default config`),Zd;throw new Error(`HTTP ${n.status}: ${n.statusText}`)}const s=await n.json();return No.set(i,{config:s,timestamp:Date.now()}),s}catch(n){return console.error("[hanc-widget] Failed to fetch widget config:",n),Zd}}const rE=["hanc.ai","hanc.me","localhost"];function la(i){const e=window.location.hostname;return rE.some(n=>e===n||e.endsWith(`.${n}`))||i.allow_all_domains||!i.allowed_domains||i.allowed_domains.length===0?!0:i.allowed_domains.some(n=>e===n||e.endsWith(`.${n}`))}function aE(i){i?No.delete(i):No.clear()}var oE=Object.defineProperty,cE=Object.getOwnPropertyDescriptor,da=(i,e,t,n)=>{for(var s=n>1?void 0:n?cE(e,t):e,r=i.length-1,a;r>=0;r--)(a=i[r])&&(s=(n?a(e,t,s):a(s))||s);return n&&s&&oE(e,t,s),s};let Cs=class extends di{constructor(){super(...arguments),this.privacyUrl="https://hanc.ai/privacy",this.termsUrl="https://hanc.ai/terms",this.termsContent="",this.modalTitle="Before we start",this.modalContainer=null}connectedCallback(){super.connectedCallback(),this.createModal()}disconnectedCallback(){super.disconnectedCallback(),this.removeModal()}createModal(){this.modalContainer=document.createElement("div"),this.modalContainer.innerHTML=this.getModalHTML(),document.body.appendChild(this.modalContainer);const i=this.modalContainer.querySelector(".hanc-privacy-overlay"),e=this.modalContainer.querySelector(".hanc-btn-accept"),t=this.modalContainer.querySelector(".hanc-btn-decline");i==null||i.addEventListener("click",n=>{n.target===i&&this.handleDecline()}),e==null||e.addEventListener("click",()=>this.handleAccept()),t==null||t.addEventListener("click",()=>this.handleDecline())}removeModal(){this.modalContainer&&(this.modalContainer.remove(),this.modalContainer=null)}renderMarkdown(i){if(!i)return"";let t=(n=>n.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"))(i);return t=t.replace(/^#### (.+)$/gm,"<h4>$1</h4>"),t=t.replace(/^### (.+)$/gm,"<h3>$1</h3>"),t=t.replace(/^## (.+)$/gm,"<h2>$1</h2>"),t=t.replace(/^# (.+)$/gm,"<h1>$1</h1>"),t=t.replace(/\*\*(.+?)\*\*/g,"<strong>$1</strong>"),t=t.replace(/__(.+?)__/g,"<strong>$1</strong>"),t=t.replace(/\*(.+?)\*/g,"<em>$1</em>"),t=t.replace(/_(.+?)_/g,"<em>$1</em>"),t=t.replace(/\[([^\]]+)\]\((https?:\/\/[^)]+)\)/g,'<a href="$2" target="_blank" rel="noopener noreferrer">$1</a>'),t=t.replace(/^\- (.+)$/gm,"<li>$1</li>"),t=t.replace(/(<li>.*<\/li>\n?)+/g,"<ul>$&</ul>"),t=t.replace(/\n\n/g,"</p><p>"),t="<p>"+t+"</p>",t=t.replace(/<p><\/p>/g,""),t=t.replace(/<p>(<h[1-4]>)/g,"$1"),t=t.replace(/(<\/h[1-4]>)<\/p>/g,"$1"),t=t.replace(/<p>(<ul>)/g,"$1"),t=t.replace(/(<\/ul>)<\/p>/g,"$1"),t=t.replace(/\n/g,"<br>"),t}getModalHTML(){const i=this.termsContent&&this.termsContent.trim().length>0,e=i?this.renderMarkdown(this.termsContent):"By starting this call, you agree to our Terms of Service and Privacy Policy.";return`
|
|
4486
4486
|
<style>
|
|
4487
4487
|
.hanc-privacy-overlay {
|
|
4488
4488
|
position: fixed;
|
|
@@ -5753,4 +5753,4 @@ void main() {
|
|
|
5753
5753
|
:host {
|
|
5754
5754
|
display: block;
|
|
5755
5755
|
}
|
|
5756
|
-
`,Ye([Y({type:String,attribute:"agent-id"})],N.PillFloatingCall.prototype,"agentId",2),Ye([Y({type:String,attribute:"voice-service-url"})],N.PillFloatingCall.prototype,"voiceServiceUrl",2),Ye([mt()],N.PillFloatingCall.prototype,"callStatus",2),Ye([mt()],N.PillFloatingCall.prototype,"microphoneEnabled",2),Ye([mt()],N.PillFloatingCall.prototype,"microphoneInitialized",2),Ye([mt()],N.PillFloatingCall.prototype,"showPrivacyModal",2),Ye([mt()],N.PillFloatingCall.prototype,"widgetConfig",2),Ye([mt()],N.PillFloatingCall.prototype,"configLoading",2),Ye([mt()],N.PillFloatingCall.prototype,"domainBlocked",2),Ye([Y({type:String,attribute:"privacy-url"})],N.PillFloatingCall.prototype,"privacyUrl",2),Ye([Y({type:String,attribute:"terms-url"})],N.PillFloatingCall.prototype,"termsUrl",2),Ye([Y({type:Boolean,attribute:"terms-enabled"})],N.PillFloatingCall.prototype,"termsEnabled",2),Ye([Y({type:String,attribute:"terms-content"})],N.PillFloatingCall.prototype,"termsContent",2),Ye([Y({type:Boolean,attribute:"skip-fetch"})],N.PillFloatingCall.prototype,"skipFetch",2),Ye([Y({type:String,attribute:"api-base-url"})],N.PillFloatingCall.prototype,"apiBaseUrl",2),Ye([Y({type:String,attribute:"button-start-text"})],N.PillFloatingCall.prototype,"buttonStartText",2),Ye([Y({type:String,attribute:"button-connecting-text"})],N.PillFloatingCall.prototype,"buttonConnectingText",2),Ye([Y({type:String,attribute:"button-end-text"})],N.PillFloatingCall.prototype,"buttonEndText",2),Ye([Y({type:String,attribute:"position"})],N.PillFloatingCall.prototype,"position",2),Ye([Y({type:Number,attribute:"orb-size"})],N.PillFloatingCall.prototype,"orbSize",2),Ye([Y({type:String,attribute:"theme"})],N.PillFloatingCall.prototype,"theme",2),Ye([Y({type:Object,attribute:"orb-colors"})],N.PillFloatingCall.prototype,"orbColors",2),Ye([Y({type:Number,attribute:"glow-intensity"})],N.PillFloatingCall.prototype,"glowIntensity",2),Ye([Y({type:Number,attribute:"idle-glow-multiplier"})],N.PillFloatingCall.prototype,"idleGlowMultiplier",2),Ye([Y({type:Number,attribute:"morph-strength"})],N.PillFloatingCall.prototype,"morphStrength",2),Ye([Y({type:Number,attribute:"noise-scale"})],N.PillFloatingCall.prototype,"noiseScale",2),Ye([Y({type:Number,attribute:"noise-speed"})],N.PillFloatingCall.prototype,"noiseSpeed",2),Ye([Y({type:Number,attribute:"fresnel-power"})],N.PillFloatingCall.prototype,"fresnelPower",2),Ye([Y({type:Number,attribute:"rotation-speed"})],N.PillFloatingCall.prototype,"rotationSpeed",2),Ye([Y({type:Number,attribute:"audio-reactivity"})],N.PillFloatingCall.prototype,"audioReactivity",2),Ye([Y({type:Number,attribute:"audio-smoothing"})],N.PillFloatingCall.prototype,"audioSmoothing",2),Ye([Y({type:Number,attribute:"idle-morph-multiplier"})],N.PillFloatingCall.prototype,"idleMorphMultiplier",2),Ye([Y({type:Number,attribute:"color-contrast"})],N.PillFloatingCall.prototype,"colorContrast",2),Ye([Y({type:Boolean,attribute:"sound-enabled"})],N.PillFloatingCall.prototype,"soundEnabled",2),Ye([Y({type:Number,attribute:"sound-volume"})],N.PillFloatingCall.prototype,"soundVolume",2),Ye([Y({type:String,attribute:"sound-preset"})],N.PillFloatingCall.prototype,"soundPreset",2),N.PillFloatingCall=Ye([Er("hanc-ai-pill-floating-call")],N.PillFloatingCall),N.SoundManager=aa,N.applyTheme=nE,N.clearConfigCache=aE,N.darkPresets=
|
|
5756
|
+
`,Ye([Y({type:String,attribute:"agent-id"})],N.PillFloatingCall.prototype,"agentId",2),Ye([Y({type:String,attribute:"voice-service-url"})],N.PillFloatingCall.prototype,"voiceServiceUrl",2),Ye([mt()],N.PillFloatingCall.prototype,"callStatus",2),Ye([mt()],N.PillFloatingCall.prototype,"microphoneEnabled",2),Ye([mt()],N.PillFloatingCall.prototype,"microphoneInitialized",2),Ye([mt()],N.PillFloatingCall.prototype,"showPrivacyModal",2),Ye([mt()],N.PillFloatingCall.prototype,"widgetConfig",2),Ye([mt()],N.PillFloatingCall.prototype,"configLoading",2),Ye([mt()],N.PillFloatingCall.prototype,"domainBlocked",2),Ye([Y({type:String,attribute:"privacy-url"})],N.PillFloatingCall.prototype,"privacyUrl",2),Ye([Y({type:String,attribute:"terms-url"})],N.PillFloatingCall.prototype,"termsUrl",2),Ye([Y({type:Boolean,attribute:"terms-enabled"})],N.PillFloatingCall.prototype,"termsEnabled",2),Ye([Y({type:String,attribute:"terms-content"})],N.PillFloatingCall.prototype,"termsContent",2),Ye([Y({type:Boolean,attribute:"skip-fetch"})],N.PillFloatingCall.prototype,"skipFetch",2),Ye([Y({type:String,attribute:"api-base-url"})],N.PillFloatingCall.prototype,"apiBaseUrl",2),Ye([Y({type:String,attribute:"button-start-text"})],N.PillFloatingCall.prototype,"buttonStartText",2),Ye([Y({type:String,attribute:"button-connecting-text"})],N.PillFloatingCall.prototype,"buttonConnectingText",2),Ye([Y({type:String,attribute:"button-end-text"})],N.PillFloatingCall.prototype,"buttonEndText",2),Ye([Y({type:String,attribute:"position"})],N.PillFloatingCall.prototype,"position",2),Ye([Y({type:Number,attribute:"orb-size"})],N.PillFloatingCall.prototype,"orbSize",2),Ye([Y({type:String,attribute:"theme"})],N.PillFloatingCall.prototype,"theme",2),Ye([Y({type:Object,attribute:"orb-colors"})],N.PillFloatingCall.prototype,"orbColors",2),Ye([Y({type:Number,attribute:"glow-intensity"})],N.PillFloatingCall.prototype,"glowIntensity",2),Ye([Y({type:Number,attribute:"idle-glow-multiplier"})],N.PillFloatingCall.prototype,"idleGlowMultiplier",2),Ye([Y({type:Number,attribute:"morph-strength"})],N.PillFloatingCall.prototype,"morphStrength",2),Ye([Y({type:Number,attribute:"noise-scale"})],N.PillFloatingCall.prototype,"noiseScale",2),Ye([Y({type:Number,attribute:"noise-speed"})],N.PillFloatingCall.prototype,"noiseSpeed",2),Ye([Y({type:Number,attribute:"fresnel-power"})],N.PillFloatingCall.prototype,"fresnelPower",2),Ye([Y({type:Number,attribute:"rotation-speed"})],N.PillFloatingCall.prototype,"rotationSpeed",2),Ye([Y({type:Number,attribute:"audio-reactivity"})],N.PillFloatingCall.prototype,"audioReactivity",2),Ye([Y({type:Number,attribute:"audio-smoothing"})],N.PillFloatingCall.prototype,"audioSmoothing",2),Ye([Y({type:Number,attribute:"idle-morph-multiplier"})],N.PillFloatingCall.prototype,"idleMorphMultiplier",2),Ye([Y({type:Number,attribute:"color-contrast"})],N.PillFloatingCall.prototype,"colorContrast",2),Ye([Y({type:Boolean,attribute:"sound-enabled"})],N.PillFloatingCall.prototype,"soundEnabled",2),Ye([Y({type:Number,attribute:"sound-volume"})],N.PillFloatingCall.prototype,"soundVolume",2),Ye([Y({type:String,attribute:"sound-preset"})],N.PillFloatingCall.prototype,"soundPreset",2),N.PillFloatingCall=Ye([Er("hanc-ai-pill-floating-call")],N.PillFloatingCall),N.SoundManager=aa,N.applyTheme=nE,N.clearConfigCache=aE,N.darkPresets=rn,N.darkThemes=QC,N.fetchWidgetConfig=ca,N.getColorPreset=JC,N.getPresetNames=ZC,N.getTheme=mr,N.getThemeNames=tE,N.isDomainAllowed=la,N.lightPresets=an,N.lightThemes=eE,N.themes=pr,Object.defineProperty(N,Symbol.toStringTag,{value:"Module"})});
|