hanc-webrtc-widgets 2.2.13 → 2.3.0

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.
@@ -28,7 +28,7 @@
28
28
  * @license
29
29
  * Copyright 2017 Google LLC
30
30
  * SPDX-License-Identifier: BSD-3-Clause
31
- */function ai(i){return Se({...i,state:!0,attribute:!1})}/**
31
+ */function yn(i){return Se({...i,state:!0,attribute:!1})}/**
32
32
  * @license
33
33
  * Copyright 2020 Google LLC
34
34
  * SPDX-License-Identifier: BSD-3-Clause
@@ -45,7 +45,7 @@
45
45
  * Copyright 2020 Google LLC
46
46
  * SPDX-License-Identifier: BSD-3-Clause
47
47
  */const ko=()=>new hg;let hg=class{};const Io=new WeakMap,Do=ag(class extends ug{render(i){return Dt}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)),Dt}rt(i){if(this.isConnected||(i=void 0),typeof this.Y=="function"){const e=this.ht??globalThis;let t=Io.get(e);t===void 0&&(t=new WeakMap,Io.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=Io.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 fg(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 pg=Object.defineProperty,mg=(i,e,t)=>e in i?pg(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,au=(i,e,t)=>mg(i,typeof e!="symbol"?e+"":e,t);class sn{constructor(){au(this,"_locking"),au(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 Mt(i,e){if(!i)throw new Error(e)}const gg=34028234663852886e22,vg=-34028234663852886e22,bg=4294967295,_g=2147483647,yg=-2147483648;function aa(i){if(typeof i!="number")throw new Error("invalid int 32: "+typeof i);if(!Number.isInteger(i)||i>_g||i<yg)throw new Error("invalid int 32: "+i)}function Lo(i){if(typeof i!="number")throw new Error("invalid uint 32: "+typeof i);if(!Number.isInteger(i)||i>bg||i<0)throw new Error("invalid uint 32: "+i)}function ou(i){if(typeof i!="number")throw new Error("invalid float 32: "+typeof i);if(Number.isFinite(i)&&(i>gg||i<vg))throw new Error("invalid float 32: "+i)}const cu=Symbol("@bufbuild/protobuf/enum-type");function Sg(i){const e=i[cu];return Mt(e,"missing enum type on enum object"),e}function lu(i,e,t,n){i[cu]=du(e,t.map(s=>({no:s.no,name:s.name,localName:i[s.no]})))}function du(i,e,t){const n=Object.create(null),s=Object.create(null),r=[];for(const a of e){const o=uu(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 xg(i,e,t){const n={};for(const s of e){const r=uu(s);n[r.localName]=r.no,n[r.no]=r.localName}return lu(n,i,e),n}function uu(i){return"localName"in i?i:Object.assign(Object.assign({},i),{localName:i.name})}class No{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 Tg(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 No),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 Cg(){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 Uo(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 oa=4294967296;function hu(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>=oa&&(s=s+(n/oa|0),n=n%oa)}return r(-24,-18),r(-18,-12),r(-12,-6),r(-6),e?pu(n,s):Oo(n,s)}function Eg(i,e){let t=Oo(i,e);const n=t.hi&2147483648;n&&(t=pu(t.lo,t.hi));const s=fu(t.lo,t.hi);return n?"-"+s:s}function fu(i,e){if({lo:i,hi:e}=Mg(i,e),e<=2097151)return String(oa*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()+mu(a)+mu(r)}function Mg(i,e){return{lo:i>>>0,hi:e>>>0}}function Oo(i,e){return{lo:i|0,hi:e|0}}function pu(i,e){return e=~e,i?i=~i+1:e+=1,Oo(i,e)}const mu=i=>{const e=String(i);return"0000000".slice(e.length)+e};function gu(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 wg(){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 Ag(){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=>Mt(/^-?[0-9]+$/.test(s),"int64 invalid: ".concat(s)),n=s=>Mt(/^[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),hu(s)},uEnc(s){return typeof s!="string"&&(s=s.toString()),n(s),hu(s)},dec(s,r){return Eg(s,r)},uDec(s,r){return fu(s,r)}}}const Et=Ag();var J;(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"})(J||(J={}));var Ii;(function(i){i[i.BIGINT=0]="BIGINT",i[i.STRING=1]="STRING"})(Ii||(Ii={}));function Di(i,e,t){if(e===t)return!0;if(i==J.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 J.UINT64:case J.FIXED64:case J.INT64:case J.SFIXED64:case J.SINT64:return e==t}return!1}function ws(i,e){switch(i){case J.BOOL:return!1;case J.UINT64:case J.FIXED64:case J.INT64:case J.SFIXED64:case J.SINT64:return e==0?Et.zero:"0";case J.DOUBLE:case J.FLOAT:return 0;case J.BYTES:return new Uint8Array(0);case J.STRING:return"";default:return 0}}function vu(i,e){switch(i){case J.BOOL:return e===!1;case J.STRING:return e==="";case J.BYTES:return e instanceof Uint8Array&&!e.byteLength;default:return e==0}}var kt;(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"})(kt||(kt={}));class Rg{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(Lo(e);e>127;)this.buf.push(e&127|128),e=e>>>7;return this.buf.push(e),this}int32(e){return aa(e),gu(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){ou(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){Lo(e);let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!0),this.raw(t)}sfixed32(e){aa(e);let t=new Uint8Array(4);return new DataView(t.buffer).setInt32(0,e,!0),this.raw(t)}sint32(e){return aa(e),e=(e<<1^e>>31)>>>0,gu(e,this.buf),this}sfixed64(e){let t=new Uint8Array(8),n=new DataView(t.buffer),s=Et.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=Et.uEnc(e);return n.setInt32(0,s.lo,!0),n.setInt32(4,s.hi,!0),this.raw(t)}int64(e){let t=Et.enc(e);return Uo(t.lo,t.hi,this.buf),this}sint64(e){let t=Et.enc(e),n=t.hi>>31,s=t.lo<<1^n,r=(t.hi<<1|t.lo>>>31)^n;return Uo(s,r,this.buf),this}uint64(e){let t=Et.uEnc(e);return Uo(t.lo,t.hi,this.buf),this}}class Pg{constructor(e,t){this.varint64=Cg,this.uint32=wg,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 kt.Varint:for(;this.buf[this.pos++]&128;);break;case kt.Bit64:this.pos+=4;case kt.Bit32:this.pos+=4;break;case kt.LengthDelimited:let s=this.uint32();this.pos+=s;break;case kt.StartGroup:for(;;){const[r,a]=this.tag();if(a===kt.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 Et.dec(...this.varint64())}uint64(){return Et.uDec(...this.varint64())}sint64(){let[e,t]=this.varint64(),n=-(e&1);return e=(e>>>1|(t&1)<<31)^n,t=t>>>1^n,Et.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 Et.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return Et.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 kg(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 bu(i){const e=i.field.localName,t=Object.create(null);return t[e]=Ig(i),[t,()=>t[e]]}function Ig(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 ws(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 Dg(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 oi="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),ca=[];for(let i=0;i<oi.length;i++)ca[oi[i].charCodeAt(0)]=i;ca[45]=oi.indexOf("+"),ca[95]=oi.indexOf("/");const _u={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=ca[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+=oi[n>>2],s=(n&3)<<4,t=1;break;case 1:e+=oi[s|n>>4],s=(n&15)<<2,t=2;break;case 2:e+=oi[s|n>>6],e+=oi[n&63],t=0;break}return t&&(e+=oi[s],e+="=",t==1&&(e+="=")),e}};function Lg(i,e,t){Su(e,i);const n=e.runtime.bin.makeReadOptions(t),s=Dg(i.getType().runtime.bin.listUnknownFields(i),e.field),[r,a]=bu(e);for(const o of s)e.runtime.bin.readField(r,n.readerFactory(o.data),e.field,o.wireType,n);return a()}function Ng(i,e,t,n){Su(e,i);const s=e.runtime.bin.makeReadOptions(n),r=e.runtime.bin.makeWriteOptions(n);if(yu(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 yu(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 Su(i,e){Mt(i.extendee.typeName==e.getType().typeName,"extension ".concat(i.typeName," can only be applied to message ").concat(i.extendee.typeName))}function xu(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:!vu(i.T,e[t]);case"message":return e[t]!==void 0;case"map":return Object.keys(e[t]).length>0}}function Tu(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?ws(i.T,i.L):void 0;break;case"message":e[t]=void 0;break}}function ci(i,e){if(i===null||typeof i!="object"||!Object.getOwnPropertyNames(No.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 Cu(i,e){return ci(e)||!i.fieldWrapper?e:i.fieldWrapper.wrapField(e)}J.DOUBLE,J.FLOAT,J.INT64,J.UINT64,J.INT32,J.UINT32,J.BOOL,J.STRING,J.BYTES;const Eu={ignoreUnknownFields:!1},Mu={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0};function Ug(i){return i?Object.assign(Object.assign({},Eu),i):Eu}function Og(i){return i?Object.assign(Object.assign({},Mu),i):Mu}const la=Symbol(),da=Symbol();function Fg(){return{makeReadOptions:Ug,makeWriteOptions:Og,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(zn(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)}wu(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]=bu(d);wu(u,o,d.field,t,d),Ng(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(!xu(s,i)){if(s.req)throw"required field not set";if(!e.emitDefaultValues||!Vg(s))continue}const a=s.oneof?i[s.oneof.localName].value:i[s.localName],o=Au(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&&yu(i,o)){const c=Lg(i,o,e),l=Au(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 Sr(i,e,t??Ii.BIGINT,!0)},writeScalar(i,e,t){if(e!==void 0&&(t||vu(i,e)))return ua(i,e)},debug:zn}}function zn(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 wu(i,e,t,n,s){let r=t.localName;if(t.repeated){if(Mt(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(zn(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(zn(o)));switch(t.kind){case"message":a.push(t.T.fromJson(o,n));break;case"enum":const c=Fo(t.T,o,n.ignoreUnknownFields,!0);c!==da&&a.push(c);break;case"scalar":try{a.push(Sr(t.T,o,t.L,!0))}catch(l){let d="cannot decode field ".concat(s.typeName,".").concat(t.name," from JSON: ").concat(zn(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(zn(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=Bg(t.K,o)}catch(d){let u="cannot decode map key for field ".concat(s.typeName,".").concat(t.name," from JSON: ").concat(zn(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=Fo(t.V.T,c,n.ignoreUnknownFields,!0);d!==da&&(a[l]=d);break;case"scalar":try{a[l]=Sr(t.V.T,c,Ii.BIGINT,!0)}catch(u){let h="cannot decode map value for field ".concat(s.typeName,".").concat(t.name," from JSON: ").concat(zn(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];ci(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=Fo(t.T,e,n.ignoreUnknownFields,!1);switch(c){case la:Tu(t,i);break;case da:break;default:i[r]=c;break}break;case"scalar":try{const l=Sr(t.T,e,t.L,!1);switch(l){case la:Tu(t,i);break;default:i[r]=l;break}}catch(l){let d="cannot decode field ".concat(s.typeName,".").concat(t.name," from JSON: ").concat(zn(e));throw l instanceof Error&&l.message.length>0&&(d+=": ".concat(l.message)),new Error(d)}break}}function Bg(i,e){if(i===J.BOOL)switch(e){case"true":e=!0;break;case"false":e=!1;break}return Sr(i,e,Ii.BIGINT,!0).toString()}function Sr(i,e,t,n){if(e===null)return n?ws(i,t):la;switch(i){case J.DOUBLE:case J.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==J.FLOAT&&ou(s),s;case J.INT32:case J.FIXED32:case J.SFIXED32:case J.SINT32:case J.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==J.UINT32||i==J.FIXED32?Lo(r):aa(r),r;case J.INT64:case J.SFIXED64:case J.SINT64:if(typeof e!="number"&&typeof e!="string")break;const a=Et.parse(e);return t?a.toString():a;case J.FIXED64:case J.UINT64:if(typeof e!="number"&&typeof e!="string")break;const o=Et.uParse(e);return t?o.toString():o;case J.BOOL:if(typeof e!="boolean")break;return e;case J.STRING:if(typeof e!="string")break;try{encodeURIComponent(e)}catch{throw new Error("invalid UTF8")}return e;case J.BYTES:if(e==="")return new Uint8Array(0);if(typeof e!="string")break;return _u.dec(e)}throw new Error}function Fo(i,e,t,n){if(e===null)return i.typeName=="google.protobuf.NullValue"?0:n?i.values[0].no:la;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 da;break}throw new Error("cannot decode enum ".concat(i.typeName," from JSON: ").concat(zn(e)))}function Vg(i){return i.repeated||i.kind=="map"?!0:!(i.oneof||i.kind=="message"||i.opt||i.req)}function Au(i,e,t){if(i.kind=="map"){Mt(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()]=ua(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()]=Bo(r,o,t.enumAsInteger);break}return t.emitDefaultValues||s.length>0?n:void 0}if(i.repeated){Mt(Array.isArray(e));const n=[];switch(i.kind){case"scalar":for(let s=0;s<e.length;s++)n.push(ua(i.T,e[s]));break;case"enum":for(let s=0;s<e.length;s++)n.push(Bo(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 ua(i.T,e);case"enum":return Bo(i.T,e,t.enumAsInteger);case"message":return Cu(i.T,e).toJson(t)}}function Bo(i,e,t){var n;if(Mt(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 ua(i,e){switch(i){case J.INT32:case J.SFIXED32:case J.SINT32:case J.FIXED32:case J.UINT32:return Mt(typeof e=="number"),e;case J.FLOAT:case J.DOUBLE:return Mt(typeof e=="number"),Number.isNaN(e)?"NaN":e===Number.POSITIVE_INFINITY?"Infinity":e===Number.NEGATIVE_INFINITY?"-Infinity":e;case J.STRING:return Mt(typeof e=="string"),e;case J.BOOL:return Mt(typeof e=="boolean"),e;case J.UINT64:case J.FIXED64:case J.INT64:case J.SFIXED64:case J.SINT64:return Mt(typeof e=="bigint"||typeof e=="string"||typeof e=="number"),e.toString();case J.BYTES:return Mt(e instanceof Uint8Array),_u.enc(e)}}const As=Symbol("@bufbuild/protobuf/unknown-fields"),Ru={readUnknownFields:!0,readerFactory:i=>new Pg(i)},Pu={writeUnknownFields:!0,writerFactory:()=>new Rg};function zg(i){return i?Object.assign(Object.assign({},Ru),i):Ru}function Gg(i){return i?Object.assign(Object.assign({},Pu),i):Pu}function Hg(){return{makeReadOptions:zg,makeWriteOptions:Gg,listUnknownFields(i){var e;return(e=i[As])!==null&&e!==void 0?e:[]},discardUnknownFields(i){delete i[As]},writeUnknownFields(i,e){const n=i[As];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[As])||(s[As]=[]),s[As].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==kt.EndGroup));){const l=r.fields.find(o);if(!l){const d=e.skip(c,o);n.readUnknownFields&&this.onUnknownField(i,o,c,d);continue}ku(i,e,l,c,n)}if(s&&(c!=kt.EndGroup||o!==t))throw new Error("invalid end group tag")},readField:ku,writeMessage(i,e,t){const n=i.getType();for(const s of n.fields.byNumber()){if(!xu(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];Iu(s,r,e,t)}return t.writeUnknownFields&&this.writeUnknownFields(i,e),e},writeField(i,e,t,n){e!==void 0&&Iu(i,e,t,n)}}}function ku(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"?J.INT32:t.T;let c=fa;if(t.kind=="scalar"&&t.L>0&&(c=qg),r){let h=i[a];if(n==kt.LengthDelimited&&o!=J.STRING&&o!=J.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(ha(e,new l,s,t)):ci(i[a])?ha(e,i[a],s,t):(i[a]=ha(e,new l,s,t),l.fieldWrapper&&!t.oneof&&!t.repeated&&(i[a]=l.fieldWrapper.unwrapField(i[a])));break;case"map":let[d,u]=Wg(t,e,s);i[a][d]=u;break}}function ha(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 Wg(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=fa(e,i.K);break;case 2:switch(i.V.kind){case"scalar":a=fa(e,i.V.T);break;case"enum":a=e.int32();break;case"message":a=ha(e,new i.V.T,t,void 0);break}break}}if(r===void 0&&(r=ws(i.K,Ii.BIGINT)),typeof r!="string"&&typeof r!="number"&&(r=r.toString()),a===void 0)switch(i.V.kind){case"scalar":a=ws(i.V.T,Ii.BIGINT);break;case"enum":a=i.V.T.values[0].no;break;case"message":a=new i.V.T;break}return[r,a]}function qg(i,e){const t=fa(i,e);return typeof t=="bigint"?t.toString():t}function fa(i,e){switch(e){case J.STRING:return i.string();case J.BOOL:return i.bool();case J.DOUBLE:return i.double();case J.FLOAT:return i.float();case J.INT32:return i.int32();case J.INT64:return i.int64();case J.UINT64:return i.uint64();case J.FIXED64:return i.fixed64();case J.BYTES:return i.bytes();case J.FIXED32:return i.fixed32();case J.SFIXED32:return i.sfixed32();case J.SFIXED64:return i.sfixed64();case J.SINT64:return i.sint64();case J.UINT32:return i.uint32();case J.SINT32:return i.sint32()}}function Iu(i,e,t,n){Mt(e!==void 0);const s=i.repeated;switch(i.kind){case"scalar":case"enum":let r=i.kind=="enum"?J.INT32:i.T;if(s)if(Mt(Array.isArray(e)),i.packed)$g(t,r,i.no,e);else for(const a of e)xr(t,r,i.no,a);else xr(t,r,i.no,e);break;case"message":if(s){Mt(Array.isArray(e));for(const a of e)Du(t,n,i,a)}else Du(t,n,i,e);break;case"map":Mt(typeof e=="object"&&e!=null);for(const[a,o]of Object.entries(e))jg(t,n,i,a,o);break}}function jg(i,e,t,n,s){i.tag(t.no,kt.LengthDelimited),i.fork();let r=n;switch(t.K){case J.INT32:case J.FIXED32:case J.UINT32:case J.SFIXED32:case J.SINT32:r=Number.parseInt(n);break;case J.BOOL:Mt(n=="true"||n=="false"),r=n=="true";break}switch(xr(i,t.K,1,r),t.V.kind){case"scalar":xr(i,t.V.T,2,s);break;case"enum":xr(i,J.INT32,2,s);break;case"message":Mt(s!==void 0),i.tag(2,kt.LengthDelimited).bytes(s.toBinary(e));break}i.join()}function Du(i,e,t,n){const s=Cu(t.T,n);t.delimited?i.tag(t.no,kt.StartGroup).raw(s.toBinary(e)).tag(t.no,kt.EndGroup):i.tag(t.no,kt.LengthDelimited).bytes(s.toBinary(e))}function xr(i,e,t,n){Mt(n!==void 0);let[s,r]=Lu(e);i.tag(t,s)[r](n)}function $g(i,e,t,n){if(!n.length)return;i.tag(t,kt.LengthDelimited).fork();let[,s]=Lu(e);for(let r=0;r<n.length;r++)i[s](n[r]);i.join()}function Lu(i){let e=kt.Varint;switch(i){case J.BYTES:case J.STRING:e=kt.LengthDelimited;break;case J.DOUBLE:case J.FIXED64:case J.SFIXED64:e=kt.Bit64;break;case J.FIXED32:case J.SFIXED32:case J.FLOAT:e=kt.Bit32;break}const t=J[i].toLowerCase();return[e,t]}function Xg(){return{setEnumType:lu,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"&&!ci(l,c.T)?l=new c.T(l):c&&c.kind==="scalar"&&c.T===J.BYTES&&(l=Tr(l)),r[s]={case:o,value:l};break;case"scalar":case"enum":let d=a[s];n.T===J.BYTES&&(d=n.repeated?d.map(Tr):Tr(d)),r[s]=d;break;case"map":switch(n.V.kind){case"scalar":case"enum":if(n.V.T===J.BYTES)for(const[f,g]of Object.entries(a[s]))r[s][f]=Tr(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=>ci(h,u)?h:new u(h));else{const h=a[s];u.fieldWrapper?u.typeName==="google.protobuf.BytesValue"?r[s]=Tr(h):r[s]=h:r[s]=ci(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)=>Di(n.T,a,r[o]));case"enum":return s.every((a,o)=>Di(J.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&&!ci(a)&&(a=n.T.fieldWrapper.wrapField(a)),o!==void 0&&!ci(o)&&(o=n.T.fieldWrapper.wrapField(o))),n.T.equals(a,o);case"enum":return Di(J.INT32,s,r);case"scalar":return Di(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 Di(J.INT32,s.value,r.value);case"scalar":return Di(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=>Di(J.INT32,s[h],r[h]));case"scalar":const u=n.V.T;return l.every(h=>Di(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(pa);else if(s.kind=="map"){a=n[s.localName];for(const[o,c]of Object.entries(r))a[o]=pa(c)}else s.kind=="oneof"?a=s.findField(r.case)?{case:r.case,value:pa(r.value)}:{case:void 0}:a=pa(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 pa(i){if(i===void 0)return i;if(ci(i))return i.clone();if(i instanceof Uint8Array){const e=new Uint8Array(i.byteLength);return e.set(i),e}return i}function Tr(i){return i instanceof Uint8Array?i:new Uint8Array(i)}function Kg(i,e,t){return{syntax:i,json:Fg(),bin:Hg(),util:Object.assign(Object.assign({},Xg()),{newFieldList:e,initFields:t}),makeMessageType(n,s,r){return Tg(this,n,s,r)},makeEnum:xg,makeEnumType:du,getEnumType:Sg,makeExtension(n,s,r){return kg(this,n,s,r)}}}class Yg{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 Nu(i,e){const t=Uu(i);return e?t:nv(tv(t))}function Jg(i){return Nu(i,!1)}const Zg=Uu;function Uu(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 Qg=new Set(["constructor","toString","toJSON","valueOf"]),ev=new Set(["getType","clone","equals","fromBinary","fromJson","fromJsonString","toBinary","toJson","toJsonString","toObject"]),Ou=i=>"".concat(i,"$"),tv=i=>ev.has(i)?Ou(i):i,nv=i=>Qg.has(i)?Ou(i):i;class iv{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=Jg(e)}addField(e){Mt(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 sv(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=Nu(d.name,d.oneof!==void 0),u.jsonName=(t=d.jsonName)!==null&&t!==void 0?t:Zg(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:Ii.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!=J.BYTES&&d.T!=J.STRING),d.oneof!==void 0){const h=typeof d.oneof=="string"?d.oneof:d.oneof.name;(!l||l.name!=h)&&(l=new iv(h)),u.oneof=l,l.addField(u)}c.push(u)}return c}const z=Kg("proto3",i=>new Yg(i,e=>sv(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]=ws(e.T,e.L);break}}});class rn extends No{constructor(e){super(),this.seconds=Et.zero,this.nanos=0,z.util.initPartial(e,this)}fromJson(e,t){if(typeof e!="string")throw new Error("cannot decode google.protobuf.Timestamp from JSON: ".concat(z.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=Et.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 rn.fromDate(new Date)}static fromDate(e){const t=e.getTime();return new rn({seconds:Et.parse(Math.floor(t/1e3)),nanos:t%1e3*1e6})}static fromBinary(e,t){return new rn().fromBinary(e,t)}static fromJson(e,t){return new rn().fromJson(e,t)}static fromJsonString(e,t){return new rn().fromJsonString(e,t)}static equals(e,t){return z.util.equals(rn,e,t)}}rn.runtime=z,rn.typeName="google.protobuf.Timestamp",rn.fields=z.util.newFieldList(()=>[{no:1,name:"seconds",kind:"scalar",T:3},{no:2,name:"nanos",kind:"scalar",T:5}]);const rv=z.makeMessageType("livekit.MetricsBatch",()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:rn},{no:3,name:"str_data",kind:"scalar",T:9,repeated:!0},{no:4,name:"time_series",kind:"message",T:av,repeated:!0},{no:5,name:"events",kind:"message",T:cv,repeated:!0}]),av=z.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:ov,repeated:!0},{no:5,name:"rid",kind:"scalar",T:13}]),ov=z.makeMessageType("livekit.MetricSample",()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:rn},{no:3,name:"value",kind:"scalar",T:2}]),cv=z.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:rn},{no:7,name:"normalized_end_timestamp",kind:"message",T:rn,opt:!0},{no:8,name:"metadata",kind:"scalar",T:9},{no:9,name:"rid",kind:"scalar",T:13}]),Fu=z.makeEnum("livekit.BackupCodecPolicy",[{no:0,name:"PREFER_REGRESSION"},{no:1,name:"SIMULCAST"},{no:2,name:"REGRESSION"}]),Mn=z.makeEnum("livekit.TrackType",[{no:0,name:"AUDIO"},{no:1,name:"VIDEO"},{no:2,name:"DATA"}]),Lt=z.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"}]),Vo=z.makeEnum("livekit.VideoQuality",[{no:0,name:"LOW"},{no:1,name:"MEDIUM"},{no:2,name:"HIGH"},{no:3,name:"OFF"}]),Cr=z.makeEnum("livekit.ConnectionQuality",[{no:0,name:"POOR"},{no:1,name:"GOOD"},{no:2,name:"EXCELLENT"},{no:3,name:"LOST"}]),Er=z.makeEnum("livekit.ClientConfigSetting",[{no:0,name:"UNSET"},{no:1,name:"DISABLED"},{no:2,name:"ENABLED"}]),wn=z.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"}]),Rs=z.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"}]),lv=z.makeEnum("livekit.SubscriptionError",[{no:0,name:"SE_UNKNOWN"},{no:1,name:"SE_CODEC_UNSUPPORTED"},{no:2,name:"SE_TRACK_NOTFOUND"}]),Ht=z.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"}]),ma=z.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:ga,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:Zu}]),ga=z.makeMessageType("livekit.Codec",()=>[{no:1,name:"mime",kind:"scalar",T:9},{no:2,name:"fmtp_line",kind:"scalar",T:9}]),dv=z.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:z.getEnumType(Lt),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}]),ns=z.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:z.getEnumType(Ps)},{no:4,name:"tracks",kind:"message",T:ks,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:dv},{no:12,name:"region",kind:"scalar",T:9},{no:13,name:"is_publisher",kind:"scalar",T:8},{no:14,name:"kind",kind:"enum",T:z.getEnumType(Mr)},{no:15,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:16,name:"disconnect_reason",kind:"enum",T:z.getEnumType(wn)},{no:18,name:"kind_details",kind:"enum",T:z.getEnumType(uv),repeated:!0}]),Ps=z.makeEnum("livekit.ParticipantInfo.State",[{no:0,name:"JOINING"},{no:1,name:"JOINED"},{no:2,name:"ACTIVE"},{no:3,name:"DISCONNECTED"}]),Mr=z.makeEnum("livekit.ParticipantInfo.Kind",[{no:0,name:"STANDARD"},{no:1,name:"INGRESS"},{no:2,name:"EGRESS"},{no:3,name:"SIP"},{no:4,name:"AGENT"}]),uv=z.makeEnum("livekit.ParticipantInfo.KindDetail",[{no:0,name:"CLOUD_AGENT"},{no:1,name:"FORWARDED"}]),hn=z.makeEnum("livekit.Encryption.Type",[{no:0,name:"NONE"},{no:1,name:"GCM"},{no:2,name:"CUSTOM"}]),hv=z.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:is,repeated:!0}]),ks=z.makeMessageType("livekit.TrackInfo",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"type",kind:"enum",T:z.getEnumType(Mn)},{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:z.getEnumType(Lt)},{no:10,name:"layers",kind:"message",T:is,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:hv,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:z.getEnumType(hn)},{no:17,name:"stream",kind:"scalar",T:9},{no:18,name:"version",kind:"message",T:Zu},{no:19,name:"audio_features",kind:"enum",T:z.getEnumType(Ht),repeated:!0},{no:20,name:"backup_codec_policy",kind:"enum",T:z.getEnumType(Fu)}]),is=z.makeMessageType("livekit.VideoLayer",()=>[{no:1,name:"quality",kind:"enum",T:z.getEnumType(Vo)},{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}]),an=z.makeMessageType("livekit.DataPacket",()=>[{no:1,name:"kind",kind:"enum",T:z.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:Vu,oneof:"value"},{no:3,name:"speaker",kind:"message",T:fv,oneof:"value"},{no:6,name:"sip_dtmf",kind:"message",T:zu,oneof:"value"},{no:7,name:"transcription",kind:"message",T:pv,oneof:"value"},{no:8,name:"metrics",kind:"message",T:rv,oneof:"value"},{no:9,name:"chat_message",kind:"message",T:zo,oneof:"value"},{no:10,name:"rpc_request",kind:"message",T:Gu,oneof:"value"},{no:11,name:"rpc_ack",kind:"message",T:Hu,oneof:"value"},{no:12,name:"rpc_response",kind:"message",T:Wu,oneof:"value"},{no:13,name:"stream_header",kind:"message",T:Ho,oneof:"value"},{no:14,name:"stream_chunk",kind:"message",T:Wo,oneof:"value"},{no:15,name:"stream_trailer",kind:"message",T:qo,oneof:"value"},{no:16,name:"sequence",kind:"scalar",T:13},{no:17,name:"participant_sid",kind:"scalar",T:9}]),We=z.makeEnum("livekit.DataPacket.Kind",[{no:0,name:"RELIABLE"},{no:1,name:"LOSSY"}]),fv=z.makeMessageType("livekit.ActiveSpeakerUpdate",()=>[{no:1,name:"speakers",kind:"message",T:Bu,repeated:!0}]),Bu=z.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}]),Vu=z.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}]),zu=z.makeMessageType("livekit.SipDTMF",()=>[{no:3,name:"code",kind:"scalar",T:13},{no:4,name:"digit",kind:"scalar",T:9}]),pv=z.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=z.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}]),zo=z.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}]),Gu=z.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}]),Hu=z.makeMessageType("livekit.RpcAck",()=>[{no:1,name:"request_id",kind:"scalar",T:9}]),Wu=z.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:qu,oneof:"value"}]),qu=z.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}]),ju=z.makeMessageType("livekit.ParticipantTracks",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"track_sids",kind:"scalar",T:9,repeated:!0}]),$u=z.makeMessageType("livekit.ServerInfo",()=>[{no:1,name:"edition",kind:"enum",T:z.getEnumType(Xu)},{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}]),Xu=z.makeEnum("livekit.ServerInfo.Edition",[{no:0,name:"Standard"},{no:1,name:"Cloud"}]),gv=z.makeMessageType("livekit.ClientInfo",()=>[{no:1,name:"sdk",kind:"enum",T:z.getEnumType(Ku)},{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}]),Ku=z.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"}]),Yu=z.makeMessageType("livekit.ClientConfiguration",()=>[{no:1,name:"video",kind:"message",T:Ju},{no:2,name:"screen",kind:"message",T:Ju},{no:3,name:"resume_connection",kind:"enum",T:z.getEnumType(Er)},{no:4,name:"disabled_codecs",kind:"message",T:vv},{no:5,name:"force_relay",kind:"enum",T:z.getEnumType(Er)}]),Ju=z.makeMessageType("livekit.VideoConfiguration",()=>[{no:1,name:"hardware_encoder",kind:"enum",T:z.getEnumType(Er)}]),vv=z.makeMessageType("livekit.DisabledCodecs",()=>[{no:1,name:"codecs",kind:"message",T:ga,repeated:!0},{no:2,name:"publish",kind:"message",T:ga,repeated:!0}]),Zu=z.makeMessageType("livekit.TimedVersion",()=>[{no:1,name:"unix_micro",kind:"scalar",T:3},{no:2,name:"ticks",kind:"scalar",T:5}]),Go=z.makeEnum("livekit.DataStream.OperationType",[{no:0,name:"CREATE"},{no:1,name:"UPDATE"},{no:2,name:"DELETE"},{no:3,name:"REACTION"}]),Qu=z.makeMessageType("livekit.DataStream.TextHeader",()=>[{no:1,name:"operation_type",kind:"enum",T:z.getEnumType(Go)},{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"}),eh=z.makeMessageType("livekit.DataStream.ByteHeader",()=>[{no:1,name:"name",kind:"scalar",T:9}],{localName:"DataStream_ByteHeader"}),Ho=z.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:z.getEnumType(hn)},{no:8,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:9,name:"text_header",kind:"message",T:Qu,oneof:"content_header"},{no:10,name:"byte_header",kind:"message",T:eh,oneof:"content_header"}],{localName:"DataStream_Header"}),Wo=z.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"}),qo=z.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"}),An=z.makeEnum("livekit.SignalTarget",[{no:0,name:"PUBLISHER"},{no:1,name:"SUBSCRIBER"}]),jo=z.makeEnum("livekit.StreamState",[{no:0,name:"ACTIVE"},{no:1,name:"PAUSED"}]),bv=z.makeEnum("livekit.CandidateProtocol",[{no:0,name:"UDP"},{no:1,name:"TCP"},{no:2,name:"TLS"}]),_v=z.makeMessageType("livekit.SignalRequest",()=>[{no:1,name:"offer",kind:"message",T:ss,oneof:"message"},{no:2,name:"answer",kind:"message",T:ss,oneof:"message"},{no:3,name:"trickle",kind:"message",T:Ko,oneof:"message"},{no:4,name:"add_track",kind:"message",T:Xo,oneof:"message"},{no:5,name:"mute",kind:"message",T:Yo,oneof:"message"},{no:6,name:"subscription",kind:"message",T:va,oneof:"message"},{no:7,name:"track_setting",kind:"message",T:nh,oneof:"message"},{no:8,name:"leave",kind:"message",T:ba,oneof:"message"},{no:10,name:"update_layers",kind:"message",T:sh,oneof:"message"},{no:11,name:"subscription_permission",kind:"message",T:ch,oneof:"message"},{no:12,name:"sync_state",kind:"message",T:lh,oneof:"message"},{no:13,name:"simulate",kind:"message",T:Gn,oneof:"message"},{no:14,name:"ping",kind:"scalar",T:3,oneof:"message"},{no:15,name:"update_metadata",kind:"message",T:rh,oneof:"message"},{no:16,name:"ping_req",kind:"message",T:hh,oneof:"message"},{no:17,name:"update_audio_track",kind:"message",T:ih,oneof:"message"},{no:18,name:"update_video_track",kind:"message",T:Cv,oneof:"message"}]),th=z.makeMessageType("livekit.SignalResponse",()=>[{no:1,name:"join",kind:"message",T:yv,oneof:"message"},{no:2,name:"answer",kind:"message",T:ss,oneof:"message"},{no:3,name:"offer",kind:"message",T:ss,oneof:"message"},{no:4,name:"trickle",kind:"message",T:Ko,oneof:"message"},{no:5,name:"update",kind:"message",T:Tv,oneof:"message"},{no:6,name:"track_published",kind:"message",T:Jo,oneof:"message"},{no:8,name:"leave",kind:"message",T:ba,oneof:"message"},{no:9,name:"mute",kind:"message",T:Yo,oneof:"message"},{no:10,name:"speakers_changed",kind:"message",T:Ev,oneof:"message"},{no:11,name:"room_update",kind:"message",T:Mv,oneof:"message"},{no:12,name:"connection_quality",kind:"message",T:Av,oneof:"message"},{no:13,name:"stream_state_update",kind:"message",T:Pv,oneof:"message"},{no:14,name:"subscribed_quality_update",kind:"message",T:Iv,oneof:"message"},{no:15,name:"subscription_permission_update",kind:"message",T:Dv,oneof:"message"},{no:16,name:"refresh_token",kind:"scalar",T:9,oneof:"message"},{no:17,name:"track_unpublished",kind:"message",T:xv,oneof:"message"},{no:18,name:"pong",kind:"scalar",T:3,oneof:"message"},{no:19,name:"reconnect",kind:"message",T:Sv,oneof:"message"},{no:20,name:"pong_resp",kind:"message",T:Nv,oneof:"message"},{no:21,name:"subscription_response",kind:"message",T:Fv,oneof:"message"},{no:22,name:"request_response",kind:"message",T:Bv,oneof:"message"},{no:23,name:"track_subscribed",kind:"message",T:Vv,oneof:"message"},{no:24,name:"room_moved",kind:"message",T:Lv,oneof:"message"}]),$o=z.makeMessageType("livekit.SimulcastCodec",()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"cid",kind:"scalar",T:9}]),Xo=z.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:z.getEnumType(Mn)},{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:z.getEnumType(Lt)},{no:9,name:"layers",kind:"message",T:is,repeated:!0},{no:10,name:"simulcast_codecs",kind:"message",T:$o,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:z.getEnumType(hn)},{no:15,name:"stream",kind:"scalar",T:9},{no:16,name:"backup_codec_policy",kind:"enum",T:z.getEnumType(Fu)},{no:17,name:"audio_features",kind:"enum",T:z.getEnumType(Ht),repeated:!0}]),Ko=z.makeMessageType("livekit.TrickleRequest",()=>[{no:1,name:"candidateInit",kind:"scalar",T:9},{no:2,name:"target",kind:"enum",T:z.getEnumType(An)},{no:3,name:"final",kind:"scalar",T:8}]),Yo=z.makeMessageType("livekit.MuteTrackRequest",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"muted",kind:"scalar",T:8}]),yv=z.makeMessageType("livekit.JoinResponse",()=>[{no:1,name:"room",kind:"message",T:ma},{no:2,name:"participant",kind:"message",T:ns},{no:3,name:"other_participants",kind:"message",T:ns,repeated:!0},{no:4,name:"server_version",kind:"scalar",T:9},{no:5,name:"ice_servers",kind:"message",T:ah,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:Yu},{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:$u},{no:13,name:"sif_trailer",kind:"scalar",T:12},{no:14,name:"enabled_publish_codecs",kind:"message",T:ga,repeated:!0},{no:15,name:"fast_publish",kind:"scalar",T:8}]),Sv=z.makeMessageType("livekit.ReconnectResponse",()=>[{no:1,name:"ice_servers",kind:"message",T:ah,repeated:!0},{no:2,name:"client_configuration",kind:"message",T:Yu},{no:3,name:"server_info",kind:"message",T:$u},{no:4,name:"last_message_seq",kind:"scalar",T:13}]),Jo=z.makeMessageType("livekit.TrackPublishedResponse",()=>[{no:1,name:"cid",kind:"scalar",T:9},{no:2,name:"track",kind:"message",T:ks}]),xv=z.makeMessageType("livekit.TrackUnpublishedResponse",()=>[{no:1,name:"track_sid",kind:"scalar",T:9}]),ss=z.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}]),Tv=z.makeMessageType("livekit.ParticipantUpdate",()=>[{no:1,name:"participants",kind:"message",T:ns,repeated:!0}]),va=z.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:ju,repeated:!0}]),nh=z.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:z.getEnumType(Vo)},{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}]),ih=z.makeMessageType("livekit.UpdateLocalAudioTrack",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"features",kind:"enum",T:z.getEnumType(Ht),repeated:!0}]),Cv=z.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}]),ba=z.makeMessageType("livekit.LeaveRequest",()=>[{no:1,name:"can_reconnect",kind:"scalar",T:8},{no:2,name:"reason",kind:"enum",T:z.getEnumType(wn)},{no:3,name:"action",kind:"enum",T:z.getEnumType(Is)},{no:4,name:"regions",kind:"message",T:Uv}]),Is=z.makeEnum("livekit.LeaveRequest.Action",[{no:0,name:"DISCONNECT"},{no:1,name:"RESUME"},{no:2,name:"RECONNECT"}]),sh=z.makeMessageType("livekit.UpdateVideoLayers",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"layers",kind:"message",T:is,repeated:!0}]),rh=z.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}]),ah=z.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}]),Ev=z.makeMessageType("livekit.SpeakersChanged",()=>[{no:1,name:"speakers",kind:"message",T:Bu,repeated:!0}]),Mv=z.makeMessageType("livekit.RoomUpdate",()=>[{no:1,name:"room",kind:"message",T:ma}]),wv=z.makeMessageType("livekit.ConnectionQualityInfo",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"quality",kind:"enum",T:z.getEnumType(Cr)},{no:3,name:"score",kind:"scalar",T:2}]),Av=z.makeMessageType("livekit.ConnectionQualityUpdate",()=>[{no:1,name:"updates",kind:"message",T:wv,repeated:!0}]),Rv=z.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:z.getEnumType(jo)}]),Pv=z.makeMessageType("livekit.StreamStateUpdate",()=>[{no:1,name:"stream_states",kind:"message",T:Rv,repeated:!0}]),Zo=z.makeMessageType("livekit.SubscribedQuality",()=>[{no:1,name:"quality",kind:"enum",T:z.getEnumType(Vo)},{no:2,name:"enabled",kind:"scalar",T:8}]),kv=z.makeMessageType("livekit.SubscribedCodec",()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"qualities",kind:"message",T:Zo,repeated:!0}]),Iv=z.makeMessageType("livekit.SubscribedQualityUpdate",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribed_qualities",kind:"message",T:Zo,repeated:!0},{no:3,name:"subscribed_codecs",kind:"message",T:kv,repeated:!0}]),oh=z.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}]),ch=z.makeMessageType("livekit.SubscriptionPermission",()=>[{no:1,name:"all_participants",kind:"scalar",T:8},{no:2,name:"track_permissions",kind:"message",T:oh,repeated:!0}]),Dv=z.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}]),Lv=z.makeMessageType("livekit.RoomMovedResponse",()=>[{no:1,name:"room",kind:"message",T:ma},{no:2,name:"token",kind:"scalar",T:9},{no:3,name:"participant",kind:"message",T:ns},{no:4,name:"other_participants",kind:"message",T:ns,repeated:!0}]),lh=z.makeMessageType("livekit.SyncState",()=>[{no:1,name:"answer",kind:"message",T:ss},{no:2,name:"subscription",kind:"message",T:va},{no:3,name:"publish_tracks",kind:"message",T:Jo,repeated:!0},{no:4,name:"data_channels",kind:"message",T:uh,repeated:!0},{no:5,name:"offer",kind:"message",T:ss},{no:6,name:"track_sids_disabled",kind:"scalar",T:9,repeated:!0},{no:7,name:"datachannel_receive_states",kind:"message",T:dh,repeated:!0}]),dh=z.makeMessageType("livekit.DataChannelReceiveState",()=>[{no:1,name:"publisher_sid",kind:"scalar",T:9},{no:2,name:"last_seq",kind:"scalar",T:13}]),uh=z.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:z.getEnumType(An)}]),Gn=z.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:z.getEnumType(bv),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"}]),hh=z.makeMessageType("livekit.Ping",()=>[{no:1,name:"timestamp",kind:"scalar",T:3},{no:2,name:"rtt",kind:"scalar",T:3}]),Nv=z.makeMessageType("livekit.Pong",()=>[{no:1,name:"last_ping_timestamp",kind:"scalar",T:3},{no:2,name:"timestamp",kind:"scalar",T:3}]),Uv=z.makeMessageType("livekit.RegionSettings",()=>[{no:1,name:"regions",kind:"message",T:Ov,repeated:!0}]),Ov=z.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}]),Fv=z.makeMessageType("livekit.SubscriptionResponse",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"err",kind:"enum",T:z.getEnumType(lv)}]),Bv=z.makeMessageType("livekit.RequestResponse",()=>[{no:1,name:"request_id",kind:"scalar",T:13},{no:2,name:"reason",kind:"enum",T:z.getEnumType(Qo)},{no:3,name:"message",kind:"scalar",T:9}]),Qo=z.makeEnum("livekit.RequestResponse.Reason",[{no:0,name:"OK"},{no:1,name:"NOT_FOUND"},{no:2,name:"NOT_ALLOWED"},{no:3,name:"LIMIT_EXCEEDED"}]),Vv=z.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 _a={exports:{}},Gv=_a.exports,fh;function Hv(){return fh||(fh=1,function(i){(function(e,t){i.exports?i.exports=t():e.log=t()})(Gv,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 U=(s[R]||"silent").toUpperCase();if(!(typeof window===t||!S)){try{window.localStorage[S]=U;return}catch{}try{window.document.cookie=encodeURIComponent(S)+"="+U+";"}catch{}}}function A(){var R;if(!(typeof window===t||!S)){try{R=window.localStorage[S]}catch{}if(typeof R===t)try{var U=window.document.cookie,B=encodeURIComponent(S),q=U.indexOf(B+"=");q!==-1&&(R=/^([^;]+)/.exec(U.slice(q+B.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 y(R){var U=R;if(typeof U=="string"&&p.levels[U.toUpperCase()]!==void 0&&(U=p.levels[U.toUpperCase()]),typeof U=="number"&&U>=0&&U<=p.levels.SILENT)return U;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,U){return b=y(R),U!==!1&&M(b),d.call(p)},p.setDefaultLevel=function(R){C=y(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=y(a.getLevel())),d.call(p),a===p)for(var R in r)r[R].rebuild()},x=y(a?a.getLevel():"WARN");var T=A();T!=null&&(b=y(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})}(_a)),_a.exports}var ya=Hv(),ec;(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"})(ec||(ec={}));var Rn;(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"})(Rn||(Rn={}));let Ke=ya.getLogger("livekit");Object.values(Rn).map(i=>ya.getLogger(i)),Ke.setDefaultLevel(ec.info);function li(i){const e=ya.getLogger(i);return e.setDefaultLevel(Ke.getLevel()),e}const Wv=ya.getLogger("lk-e2ee"),wr=7e3,qv=[0,300,2*2*300,3*3*300,4*4*300,wr,wr,wr,wr,wr];class jv{constructor(e){this._retryDelays=e!==void 0?[...e]:qv}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 $v(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 ph(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 di(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 ph=="function"?ph(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 Sa={exports:{}},mh;function Xv(){if(mh)return Sa.exports;mh=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)}Sa.exports=r,Sa.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",y=this._events;if(y!==void 0)k=k&&y.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 U=y[S];if(U===void 0)return!1;if(typeof U=="function")e(U,this,M);else for(var B=U.length,q=g(U,B),A=0;A<B;++A)e(q[A],this,M);return!0};function l(b,S,M,A){var k,y,T;if(o(M),y=b._events,y===void 0?(y=b._events=Object.create(null),b._eventsCount=0):(y.newListener!==void 0&&(b.emit("newListener",S,M.listener?M.listener:M),y=b._events),T=y[S]),T===void 0)T=y[S]=M,++b._eventsCount;else if(typeof T=="function"?T=y[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,y,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(y=-1,T=A.length-1;T>=0;T--)if(A[T]===M||A[T].listener===M){R=A[T].listener,y=T;break}if(y<0)return this;y===0?A.shift():v(A,y),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 y=Object.keys(A),T;for(k=0;k<y.length;++k)T=y[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,y),A(T)}function y(){typeof b.removeListener=="function"&&b.removeListener("error",k),M([].slice.call(arguments))}C(b,S,y,{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(y){A.once&&b.removeEventListener(S,k),M(y)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof b)}return Sa.exports}var Hn=Xv();let gh=!0,vh=!0;function Ar(i,e,t){const n=i.match(e);return n&&n.length>=t&&parseFloat(n[t],10)}function rs(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 Kv(i){return typeof i!="boolean"?new Error("Argument type: "+typeof i+". Please use a boolean."):(gh=i,i?"adapter.js logging disabled":"adapter.js logging enabled")}function Yv(i){return typeof i!="boolean"?new Error("Argument type: "+typeof i+". Please use a boolean."):(vh=!i,"adapter.js deprecation warnings "+(i?"disabled":"enabled"))}function bh(){if(typeof window=="object"){if(gh)return;typeof console<"u"&&typeof console.log=="function"&&console.log.apply(console,arguments)}}function tc(i,e){vh&&console.warn(i+" is deprecated, please use "+e+" instead.")}function Jv(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(Ar(t.userAgent,/Firefox\/(\d+)\./,1));else if(t.webkitGetUserMedia||i.isSecureContext===!1&&i.webkitRTCPeerConnection)e.browser="chrome",e.version=parseInt(Ar(t.userAgent,/Chrom(e|ium)\/(\d+)\./,2));else if(i.RTCPeerConnection&&t.userAgent.match(/AppleWebKit\/(\d+)\./))e.browser="safari",e.version=parseInt(Ar(t.userAgent,/AppleWebKit\/(\d+)\./,1)),e.supportsUnifiedPlan=i.RTCRtpTransceiver&&"currentDirection"in i.RTCRtpTransceiver.prototype,e._safariVersion=Ar(t.userAgent,/Version\/(\d+(\.?\d+))/,1);else return e.browser="Not a supported browser.",e;return e}function _h(i){return Object.prototype.toString.call(i)==="[object Object]"}function yh(i){return _h(i)?Object.keys(i).reduce(function(e,t){const n=_h(i[t]),s=n?yh(i[t]):i[t],r=n&&!Object.keys(s).length;return s===void 0||r?e:Object.assign(e,{[t]:s})},{}):i}function nc(i,e,t){!e||t.has(e.id)||(t.set(e.id,e),Object.keys(e).forEach(n=>{n.endsWith("Id")?nc(i,i.get(e[n]),t):n.endsWith("Ids")&&e[n].forEach(s=>{nc(i,i.get(s),t)})}))}function Sh(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&&nc(i,o,s)})}),s}const xh=bh;function Th(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),xh("chrome: "+JSON.stringify(o)),c(o)})}o.video=n(o.video)}return xh("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 Ch(i){i.MediaStream=i.MediaStream||i.webkitMediaStream}function Eh(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 rs(i,"track",e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e))}function Mh(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 wh(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=>Sh(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}),rs(i,"track",n=>(n.receiver._pc=n.srcElement,n)),i.RTCRtpReceiver.prototype.getStats=function(){const s=this;return this._pc.getStats().then(r=>Sh(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 Ah(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 Rh(i,e){if(!i.RTCPeerConnection)return;if(i.RTCPeerConnection.prototype.addTrack&&e.version>=65)return Ah(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 ic(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 Ph(i,e){rs(i,"negotiationneeded",t=>{const n=t.target;if(!((e.version<72||n.getConfiguration&&n.getConfiguration().sdpSemantics==="plan-b")&&n.signalingState!=="stable"))return t})}var kh=Object.freeze({__proto__:null,fixNegotiationNeeded:Ph,shimAddTrackRemoveTrack:Rh,shimAddTrackRemoveTrackWithNative:Ah,shimGetSendersWithDtmf:Mh,shimGetUserMedia:Th,shimMediaStream:Ch,shimOnTrack:Eh,shimPeerConnection:ic,shimSenderReceiverGetStats:wh});function Ih(i,e){const t=i&&i.navigator,n=i&&i.MediaStreamTrack;if(t.getUserMedia=function(s,r,a){tc("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 Zv(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 Dh(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 sc(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 Lh(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 Nh(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}),rs(i,"track",t=>(t.receiver._pc=t.srcElement,t)),i.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function Uh(i){!i.RTCPeerConnection||"removeStream"in i.RTCPeerConnection.prototype||(i.RTCPeerConnection.prototype.removeStream=function(t){tc("removeStream","removeTrack"),this.getSenders().forEach(n=>{n.track&&t.getTracks().includes(n.track)&&this.removeTrack(n)})})}function Oh(i){i.DataChannel&&!i.RTCDataChannel&&(i.RTCDataChannel=i.DataChannel)}function Fh(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 Bh(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 Vh(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 zh(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 Gh=Object.freeze({__proto__:null,shimAddTransceiver:Fh,shimCreateAnswer:zh,shimCreateOffer:Vh,shimGetDisplayMedia:Zv,shimGetParameters:Bh,shimGetUserMedia:Ih,shimOnTrack:Dh,shimPeerConnection:sc,shimRTCDataChannel:Oh,shimReceiverGetStats:Nh,shimRemoveStream:Uh,shimSenderGetStats:Lh});function Hh(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 Wh(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 qh(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 jh(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($h(s))}!e.getUserMedia&&e.mediaDevices&&e.mediaDevices.getUserMedia&&(e.getUserMedia=(function(n,s,r){e.mediaDevices.getUserMedia(n).then(s,r)}).bind(e))}function $h(i){return i&&i.video!==void 0?Object.assign({},i,{video:yh(i.video)}):i}function Xh(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?(tc("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 Kh(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 Yh(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 Jh(i){typeof i!="object"||i.AudioContext||(i.AudioContext=i.webkitAudioContext)}var Zh=Object.freeze({__proto__:null,shimAudioContext:Jh,shimCallbacksAPI:qh,shimConstraints:$h,shimCreateOfferLegacy:Yh,shimGetUserMedia:jh,shimLocalStreamsAPI:Hh,shimRTCIceServerUrls:Xh,shimRemoteStreamsAPI:Wh,shimTrackEventTransceiver:Kh}),rc={exports:{}},Qh;function Qv(){return Qh||(Qh=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(`
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+=oi[n>>2],s=(n&3)<<4,t=1;break;case 1:e+=oi[s|n>>4],s=(n&15)<<2,t=2;break;case 2:e+=oi[s|n>>6],e+=oi[n&63],t=0;break}return t&&(e+=oi[s],e+="=",t==1&&(e+="=")),e}};function Lg(i,e,t){Su(e,i);const n=e.runtime.bin.makeReadOptions(t),s=Dg(i.getType().runtime.bin.listUnknownFields(i),e.field),[r,a]=bu(e);for(const o of s)e.runtime.bin.readField(r,n.readerFactory(o.data),e.field,o.wireType,n);return a()}function Ng(i,e,t,n){Su(e,i);const s=e.runtime.bin.makeReadOptions(n),r=e.runtime.bin.makeWriteOptions(n);if(yu(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 yu(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 Su(i,e){Mt(i.extendee.typeName==e.getType().typeName,"extension ".concat(i.typeName," can only be applied to message ").concat(i.extendee.typeName))}function xu(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:!vu(i.T,e[t]);case"message":return e[t]!==void 0;case"map":return Object.keys(e[t]).length>0}}function Tu(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?ws(i.T,i.L):void 0;break;case"message":e[t]=void 0;break}}function ci(i,e){if(i===null||typeof i!="object"||!Object.getOwnPropertyNames(No.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 Cu(i,e){return ci(e)||!i.fieldWrapper?e:i.fieldWrapper.wrapField(e)}J.DOUBLE,J.FLOAT,J.INT64,J.UINT64,J.INT32,J.UINT32,J.BOOL,J.STRING,J.BYTES;const Eu={ignoreUnknownFields:!1},Mu={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0};function Ug(i){return i?Object.assign(Object.assign({},Eu),i):Eu}function Og(i){return i?Object.assign(Object.assign({},Mu),i):Mu}const la=Symbol(),da=Symbol();function Fg(){return{makeReadOptions:Ug,makeWriteOptions:Og,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(Gn(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)}wu(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]=bu(d);wu(u,o,d.field,t,d),Ng(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(!xu(s,i)){if(s.req)throw"required field not set";if(!e.emitDefaultValues||!Vg(s))continue}const a=s.oneof?i[s.oneof.localName].value:i[s.localName],o=Au(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&&yu(i,o)){const c=Lg(i,o,e),l=Au(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 Sr(i,e,t??Ii.BIGINT,!0)},writeScalar(i,e,t){if(e!==void 0&&(t||vu(i,e)))return ua(i,e)},debug:Gn}}function Gn(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 wu(i,e,t,n,s){let r=t.localName;if(t.repeated){if(Mt(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(Gn(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(Gn(o)));switch(t.kind){case"message":a.push(t.T.fromJson(o,n));break;case"enum":const c=Fo(t.T,o,n.ignoreUnknownFields,!0);c!==da&&a.push(c);break;case"scalar":try{a.push(Sr(t.T,o,t.L,!0))}catch(l){let d="cannot decode field ".concat(s.typeName,".").concat(t.name," from JSON: ").concat(Gn(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(Gn(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=Bg(t.K,o)}catch(d){let u="cannot decode map key for field ".concat(s.typeName,".").concat(t.name," from JSON: ").concat(Gn(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=Fo(t.V.T,c,n.ignoreUnknownFields,!0);d!==da&&(a[l]=d);break;case"scalar":try{a[l]=Sr(t.V.T,c,Ii.BIGINT,!0)}catch(u){let h="cannot decode map value for field ".concat(s.typeName,".").concat(t.name," from JSON: ").concat(Gn(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];ci(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=Fo(t.T,e,n.ignoreUnknownFields,!1);switch(c){case la:Tu(t,i);break;case da:break;default:i[r]=c;break}break;case"scalar":try{const l=Sr(t.T,e,t.L,!1);switch(l){case la:Tu(t,i);break;default:i[r]=l;break}}catch(l){let d="cannot decode field ".concat(s.typeName,".").concat(t.name," from JSON: ").concat(Gn(e));throw l instanceof Error&&l.message.length>0&&(d+=": ".concat(l.message)),new Error(d)}break}}function Bg(i,e){if(i===J.BOOL)switch(e){case"true":e=!0;break;case"false":e=!1;break}return Sr(i,e,Ii.BIGINT,!0).toString()}function Sr(i,e,t,n){if(e===null)return n?ws(i,t):la;switch(i){case J.DOUBLE:case J.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==J.FLOAT&&ou(s),s;case J.INT32:case J.FIXED32:case J.SFIXED32:case J.SINT32:case J.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==J.UINT32||i==J.FIXED32?Lo(r):aa(r),r;case J.INT64:case J.SFIXED64:case J.SINT64:if(typeof e!="number"&&typeof e!="string")break;const a=Et.parse(e);return t?a.toString():a;case J.FIXED64:case J.UINT64:if(typeof e!="number"&&typeof e!="string")break;const o=Et.uParse(e);return t?o.toString():o;case J.BOOL:if(typeof e!="boolean")break;return e;case J.STRING:if(typeof e!="string")break;try{encodeURIComponent(e)}catch{throw new Error("invalid UTF8")}return e;case J.BYTES:if(e==="")return new Uint8Array(0);if(typeof e!="string")break;return _u.dec(e)}throw new Error}function Fo(i,e,t,n){if(e===null)return i.typeName=="google.protobuf.NullValue"?0:n?i.values[0].no:la;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 da;break}throw new Error("cannot decode enum ".concat(i.typeName," from JSON: ").concat(Gn(e)))}function Vg(i){return i.repeated||i.kind=="map"?!0:!(i.oneof||i.kind=="message"||i.opt||i.req)}function Au(i,e,t){if(i.kind=="map"){Mt(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()]=ua(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()]=Bo(r,o,t.enumAsInteger);break}return t.emitDefaultValues||s.length>0?n:void 0}if(i.repeated){Mt(Array.isArray(e));const n=[];switch(i.kind){case"scalar":for(let s=0;s<e.length;s++)n.push(ua(i.T,e[s]));break;case"enum":for(let s=0;s<e.length;s++)n.push(Bo(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 ua(i.T,e);case"enum":return Bo(i.T,e,t.enumAsInteger);case"message":return Cu(i.T,e).toJson(t)}}function Bo(i,e,t){var n;if(Mt(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 ua(i,e){switch(i){case J.INT32:case J.SFIXED32:case J.SINT32:case J.FIXED32:case J.UINT32:return Mt(typeof e=="number"),e;case J.FLOAT:case J.DOUBLE:return Mt(typeof e=="number"),Number.isNaN(e)?"NaN":e===Number.POSITIVE_INFINITY?"Infinity":e===Number.NEGATIVE_INFINITY?"-Infinity":e;case J.STRING:return Mt(typeof e=="string"),e;case J.BOOL:return Mt(typeof e=="boolean"),e;case J.UINT64:case J.FIXED64:case J.INT64:case J.SFIXED64:case J.SINT64:return Mt(typeof e=="bigint"||typeof e=="string"||typeof e=="number"),e.toString();case J.BYTES:return Mt(e instanceof Uint8Array),_u.enc(e)}}const As=Symbol("@bufbuild/protobuf/unknown-fields"),Ru={readUnknownFields:!0,readerFactory:i=>new Pg(i)},Pu={writeUnknownFields:!0,writerFactory:()=>new Rg};function zg(i){return i?Object.assign(Object.assign({},Ru),i):Ru}function Gg(i){return i?Object.assign(Object.assign({},Pu),i):Pu}function Hg(){return{makeReadOptions:zg,makeWriteOptions:Gg,listUnknownFields(i){var e;return(e=i[As])!==null&&e!==void 0?e:[]},discardUnknownFields(i){delete i[As]},writeUnknownFields(i,e){const n=i[As];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[As])||(s[As]=[]),s[As].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==kt.EndGroup));){const l=r.fields.find(o);if(!l){const d=e.skip(c,o);n.readUnknownFields&&this.onUnknownField(i,o,c,d);continue}ku(i,e,l,c,n)}if(s&&(c!=kt.EndGroup||o!==t))throw new Error("invalid end group tag")},readField:ku,writeMessage(i,e,t){const n=i.getType();for(const s of n.fields.byNumber()){if(!xu(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];Iu(s,r,e,t)}return t.writeUnknownFields&&this.writeUnknownFields(i,e),e},writeField(i,e,t,n){e!==void 0&&Iu(i,e,t,n)}}}function ku(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"?J.INT32:t.T;let c=fa;if(t.kind=="scalar"&&t.L>0&&(c=qg),r){let h=i[a];if(n==kt.LengthDelimited&&o!=J.STRING&&o!=J.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(ha(e,new l,s,t)):ci(i[a])?ha(e,i[a],s,t):(i[a]=ha(e,new l,s,t),l.fieldWrapper&&!t.oneof&&!t.repeated&&(i[a]=l.fieldWrapper.unwrapField(i[a])));break;case"map":let[d,u]=Wg(t,e,s);i[a][d]=u;break}}function ha(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 Wg(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=fa(e,i.K);break;case 2:switch(i.V.kind){case"scalar":a=fa(e,i.V.T);break;case"enum":a=e.int32();break;case"message":a=ha(e,new i.V.T,t,void 0);break}break}}if(r===void 0&&(r=ws(i.K,Ii.BIGINT)),typeof r!="string"&&typeof r!="number"&&(r=r.toString()),a===void 0)switch(i.V.kind){case"scalar":a=ws(i.V.T,Ii.BIGINT);break;case"enum":a=i.V.T.values[0].no;break;case"message":a=new i.V.T;break}return[r,a]}function qg(i,e){const t=fa(i,e);return typeof t=="bigint"?t.toString():t}function fa(i,e){switch(e){case J.STRING:return i.string();case J.BOOL:return i.bool();case J.DOUBLE:return i.double();case J.FLOAT:return i.float();case J.INT32:return i.int32();case J.INT64:return i.int64();case J.UINT64:return i.uint64();case J.FIXED64:return i.fixed64();case J.BYTES:return i.bytes();case J.FIXED32:return i.fixed32();case J.SFIXED32:return i.sfixed32();case J.SFIXED64:return i.sfixed64();case J.SINT64:return i.sint64();case J.UINT32:return i.uint32();case J.SINT32:return i.sint32()}}function Iu(i,e,t,n){Mt(e!==void 0);const s=i.repeated;switch(i.kind){case"scalar":case"enum":let r=i.kind=="enum"?J.INT32:i.T;if(s)if(Mt(Array.isArray(e)),i.packed)$g(t,r,i.no,e);else for(const a of e)xr(t,r,i.no,a);else xr(t,r,i.no,e);break;case"message":if(s){Mt(Array.isArray(e));for(const a of e)Du(t,n,i,a)}else Du(t,n,i,e);break;case"map":Mt(typeof e=="object"&&e!=null);for(const[a,o]of Object.entries(e))jg(t,n,i,a,o);break}}function jg(i,e,t,n,s){i.tag(t.no,kt.LengthDelimited),i.fork();let r=n;switch(t.K){case J.INT32:case J.FIXED32:case J.UINT32:case J.SFIXED32:case J.SINT32:r=Number.parseInt(n);break;case J.BOOL:Mt(n=="true"||n=="false"),r=n=="true";break}switch(xr(i,t.K,1,r),t.V.kind){case"scalar":xr(i,t.V.T,2,s);break;case"enum":xr(i,J.INT32,2,s);break;case"message":Mt(s!==void 0),i.tag(2,kt.LengthDelimited).bytes(s.toBinary(e));break}i.join()}function Du(i,e,t,n){const s=Cu(t.T,n);t.delimited?i.tag(t.no,kt.StartGroup).raw(s.toBinary(e)).tag(t.no,kt.EndGroup):i.tag(t.no,kt.LengthDelimited).bytes(s.toBinary(e))}function xr(i,e,t,n){Mt(n!==void 0);let[s,r]=Lu(e);i.tag(t,s)[r](n)}function $g(i,e,t,n){if(!n.length)return;i.tag(t,kt.LengthDelimited).fork();let[,s]=Lu(e);for(let r=0;r<n.length;r++)i[s](n[r]);i.join()}function Lu(i){let e=kt.Varint;switch(i){case J.BYTES:case J.STRING:e=kt.LengthDelimited;break;case J.DOUBLE:case J.FIXED64:case J.SFIXED64:e=kt.Bit64;break;case J.FIXED32:case J.SFIXED32:case J.FLOAT:e=kt.Bit32;break}const t=J[i].toLowerCase();return[e,t]}function Xg(){return{setEnumType:lu,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"&&!ci(l,c.T)?l=new c.T(l):c&&c.kind==="scalar"&&c.T===J.BYTES&&(l=Tr(l)),r[s]={case:o,value:l};break;case"scalar":case"enum":let d=a[s];n.T===J.BYTES&&(d=n.repeated?d.map(Tr):Tr(d)),r[s]=d;break;case"map":switch(n.V.kind){case"scalar":case"enum":if(n.V.T===J.BYTES)for(const[f,g]of Object.entries(a[s]))r[s][f]=Tr(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=>ci(h,u)?h:new u(h));else{const h=a[s];u.fieldWrapper?u.typeName==="google.protobuf.BytesValue"?r[s]=Tr(h):r[s]=h:r[s]=ci(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)=>Di(n.T,a,r[o]));case"enum":return s.every((a,o)=>Di(J.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&&!ci(a)&&(a=n.T.fieldWrapper.wrapField(a)),o!==void 0&&!ci(o)&&(o=n.T.fieldWrapper.wrapField(o))),n.T.equals(a,o);case"enum":return Di(J.INT32,s,r);case"scalar":return Di(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 Di(J.INT32,s.value,r.value);case"scalar":return Di(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=>Di(J.INT32,s[h],r[h]));case"scalar":const u=n.V.T;return l.every(h=>Di(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(pa);else if(s.kind=="map"){a=n[s.localName];for(const[o,c]of Object.entries(r))a[o]=pa(c)}else s.kind=="oneof"?a=s.findField(r.case)?{case:r.case,value:pa(r.value)}:{case:void 0}:a=pa(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 pa(i){if(i===void 0)return i;if(ci(i))return i.clone();if(i instanceof Uint8Array){const e=new Uint8Array(i.byteLength);return e.set(i),e}return i}function Tr(i){return i instanceof Uint8Array?i:new Uint8Array(i)}function Kg(i,e,t){return{syntax:i,json:Fg(),bin:Hg(),util:Object.assign(Object.assign({},Xg()),{newFieldList:e,initFields:t}),makeMessageType(n,s,r){return Tg(this,n,s,r)},makeEnum:xg,makeEnumType:du,getEnumType:Sg,makeExtension(n,s,r){return kg(this,n,s,r)}}}class Yg{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 Nu(i,e){const t=Uu(i);return e?t:nv(tv(t))}function Jg(i){return Nu(i,!1)}const Zg=Uu;function Uu(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 Qg=new Set(["constructor","toString","toJSON","valueOf"]),ev=new Set(["getType","clone","equals","fromBinary","fromJson","fromJsonString","toBinary","toJson","toJsonString","toObject"]),Ou=i=>"".concat(i,"$"),tv=i=>ev.has(i)?Ou(i):i,nv=i=>Qg.has(i)?Ou(i):i;class iv{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=Jg(e)}addField(e){Mt(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 sv(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=Nu(d.name,d.oneof!==void 0),u.jsonName=(t=d.jsonName)!==null&&t!==void 0?t:Zg(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:Ii.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!=J.BYTES&&d.T!=J.STRING),d.oneof!==void 0){const h=typeof d.oneof=="string"?d.oneof:d.oneof.name;(!l||l.name!=h)&&(l=new iv(h)),u.oneof=l,l.addField(u)}c.push(u)}return c}const z=Kg("proto3",i=>new Yg(i,e=>sv(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]=ws(e.T,e.L);break}}});class rn extends No{constructor(e){super(),this.seconds=Et.zero,this.nanos=0,z.util.initPartial(e,this)}fromJson(e,t){if(typeof e!="string")throw new Error("cannot decode google.protobuf.Timestamp from JSON: ".concat(z.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=Et.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 rn.fromDate(new Date)}static fromDate(e){const t=e.getTime();return new rn({seconds:Et.parse(Math.floor(t/1e3)),nanos:t%1e3*1e6})}static fromBinary(e,t){return new rn().fromBinary(e,t)}static fromJson(e,t){return new rn().fromJson(e,t)}static fromJsonString(e,t){return new rn().fromJsonString(e,t)}static equals(e,t){return z.util.equals(rn,e,t)}}rn.runtime=z,rn.typeName="google.protobuf.Timestamp",rn.fields=z.util.newFieldList(()=>[{no:1,name:"seconds",kind:"scalar",T:3},{no:2,name:"nanos",kind:"scalar",T:5}]);const rv=z.makeMessageType("livekit.MetricsBatch",()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:rn},{no:3,name:"str_data",kind:"scalar",T:9,repeated:!0},{no:4,name:"time_series",kind:"message",T:av,repeated:!0},{no:5,name:"events",kind:"message",T:cv,repeated:!0}]),av=z.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:ov,repeated:!0},{no:5,name:"rid",kind:"scalar",T:13}]),ov=z.makeMessageType("livekit.MetricSample",()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:rn},{no:3,name:"value",kind:"scalar",T:2}]),cv=z.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:rn},{no:7,name:"normalized_end_timestamp",kind:"message",T:rn,opt:!0},{no:8,name:"metadata",kind:"scalar",T:9},{no:9,name:"rid",kind:"scalar",T:13}]),Fu=z.makeEnum("livekit.BackupCodecPolicy",[{no:0,name:"PREFER_REGRESSION"},{no:1,name:"SIMULCAST"},{no:2,name:"REGRESSION"}]),wn=z.makeEnum("livekit.TrackType",[{no:0,name:"AUDIO"},{no:1,name:"VIDEO"},{no:2,name:"DATA"}]),Lt=z.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"}]),Vo=z.makeEnum("livekit.VideoQuality",[{no:0,name:"LOW"},{no:1,name:"MEDIUM"},{no:2,name:"HIGH"},{no:3,name:"OFF"}]),Cr=z.makeEnum("livekit.ConnectionQuality",[{no:0,name:"POOR"},{no:1,name:"GOOD"},{no:2,name:"EXCELLENT"},{no:3,name:"LOST"}]),Er=z.makeEnum("livekit.ClientConfigSetting",[{no:0,name:"UNSET"},{no:1,name:"DISABLED"},{no:2,name:"ENABLED"}]),An=z.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"}]),Rs=z.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"}]),lv=z.makeEnum("livekit.SubscriptionError",[{no:0,name:"SE_UNKNOWN"},{no:1,name:"SE_CODEC_UNSUPPORTED"},{no:2,name:"SE_TRACK_NOTFOUND"}]),Ht=z.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"}]),ma=z.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:ga,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:Zu}]),ga=z.makeMessageType("livekit.Codec",()=>[{no:1,name:"mime",kind:"scalar",T:9},{no:2,name:"fmtp_line",kind:"scalar",T:9}]),dv=z.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:z.getEnumType(Lt),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}]),ns=z.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:z.getEnumType(Ps)},{no:4,name:"tracks",kind:"message",T:ks,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:dv},{no:12,name:"region",kind:"scalar",T:9},{no:13,name:"is_publisher",kind:"scalar",T:8},{no:14,name:"kind",kind:"enum",T:z.getEnumType(Mr)},{no:15,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:16,name:"disconnect_reason",kind:"enum",T:z.getEnumType(An)},{no:18,name:"kind_details",kind:"enum",T:z.getEnumType(uv),repeated:!0}]),Ps=z.makeEnum("livekit.ParticipantInfo.State",[{no:0,name:"JOINING"},{no:1,name:"JOINED"},{no:2,name:"ACTIVE"},{no:3,name:"DISCONNECTED"}]),Mr=z.makeEnum("livekit.ParticipantInfo.Kind",[{no:0,name:"STANDARD"},{no:1,name:"INGRESS"},{no:2,name:"EGRESS"},{no:3,name:"SIP"},{no:4,name:"AGENT"}]),uv=z.makeEnum("livekit.ParticipantInfo.KindDetail",[{no:0,name:"CLOUD_AGENT"},{no:1,name:"FORWARDED"}]),hn=z.makeEnum("livekit.Encryption.Type",[{no:0,name:"NONE"},{no:1,name:"GCM"},{no:2,name:"CUSTOM"}]),hv=z.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:is,repeated:!0}]),ks=z.makeMessageType("livekit.TrackInfo",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"type",kind:"enum",T:z.getEnumType(wn)},{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:z.getEnumType(Lt)},{no:10,name:"layers",kind:"message",T:is,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:hv,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:z.getEnumType(hn)},{no:17,name:"stream",kind:"scalar",T:9},{no:18,name:"version",kind:"message",T:Zu},{no:19,name:"audio_features",kind:"enum",T:z.getEnumType(Ht),repeated:!0},{no:20,name:"backup_codec_policy",kind:"enum",T:z.getEnumType(Fu)}]),is=z.makeMessageType("livekit.VideoLayer",()=>[{no:1,name:"quality",kind:"enum",T:z.getEnumType(Vo)},{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}]),an=z.makeMessageType("livekit.DataPacket",()=>[{no:1,name:"kind",kind:"enum",T:z.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:Vu,oneof:"value"},{no:3,name:"speaker",kind:"message",T:fv,oneof:"value"},{no:6,name:"sip_dtmf",kind:"message",T:zu,oneof:"value"},{no:7,name:"transcription",kind:"message",T:pv,oneof:"value"},{no:8,name:"metrics",kind:"message",T:rv,oneof:"value"},{no:9,name:"chat_message",kind:"message",T:zo,oneof:"value"},{no:10,name:"rpc_request",kind:"message",T:Gu,oneof:"value"},{no:11,name:"rpc_ack",kind:"message",T:Hu,oneof:"value"},{no:12,name:"rpc_response",kind:"message",T:Wu,oneof:"value"},{no:13,name:"stream_header",kind:"message",T:Ho,oneof:"value"},{no:14,name:"stream_chunk",kind:"message",T:Wo,oneof:"value"},{no:15,name:"stream_trailer",kind:"message",T:qo,oneof:"value"},{no:16,name:"sequence",kind:"scalar",T:13},{no:17,name:"participant_sid",kind:"scalar",T:9}]),We=z.makeEnum("livekit.DataPacket.Kind",[{no:0,name:"RELIABLE"},{no:1,name:"LOSSY"}]),fv=z.makeMessageType("livekit.ActiveSpeakerUpdate",()=>[{no:1,name:"speakers",kind:"message",T:Bu,repeated:!0}]),Bu=z.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}]),Vu=z.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}]),zu=z.makeMessageType("livekit.SipDTMF",()=>[{no:3,name:"code",kind:"scalar",T:13},{no:4,name:"digit",kind:"scalar",T:9}]),pv=z.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=z.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}]),zo=z.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}]),Gu=z.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}]),Hu=z.makeMessageType("livekit.RpcAck",()=>[{no:1,name:"request_id",kind:"scalar",T:9}]),Wu=z.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:qu,oneof:"value"}]),qu=z.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}]),ju=z.makeMessageType("livekit.ParticipantTracks",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"track_sids",kind:"scalar",T:9,repeated:!0}]),$u=z.makeMessageType("livekit.ServerInfo",()=>[{no:1,name:"edition",kind:"enum",T:z.getEnumType(Xu)},{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}]),Xu=z.makeEnum("livekit.ServerInfo.Edition",[{no:0,name:"Standard"},{no:1,name:"Cloud"}]),gv=z.makeMessageType("livekit.ClientInfo",()=>[{no:1,name:"sdk",kind:"enum",T:z.getEnumType(Ku)},{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}]),Ku=z.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"}]),Yu=z.makeMessageType("livekit.ClientConfiguration",()=>[{no:1,name:"video",kind:"message",T:Ju},{no:2,name:"screen",kind:"message",T:Ju},{no:3,name:"resume_connection",kind:"enum",T:z.getEnumType(Er)},{no:4,name:"disabled_codecs",kind:"message",T:vv},{no:5,name:"force_relay",kind:"enum",T:z.getEnumType(Er)}]),Ju=z.makeMessageType("livekit.VideoConfiguration",()=>[{no:1,name:"hardware_encoder",kind:"enum",T:z.getEnumType(Er)}]),vv=z.makeMessageType("livekit.DisabledCodecs",()=>[{no:1,name:"codecs",kind:"message",T:ga,repeated:!0},{no:2,name:"publish",kind:"message",T:ga,repeated:!0}]),Zu=z.makeMessageType("livekit.TimedVersion",()=>[{no:1,name:"unix_micro",kind:"scalar",T:3},{no:2,name:"ticks",kind:"scalar",T:5}]),Go=z.makeEnum("livekit.DataStream.OperationType",[{no:0,name:"CREATE"},{no:1,name:"UPDATE"},{no:2,name:"DELETE"},{no:3,name:"REACTION"}]),Qu=z.makeMessageType("livekit.DataStream.TextHeader",()=>[{no:1,name:"operation_type",kind:"enum",T:z.getEnumType(Go)},{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"}),eh=z.makeMessageType("livekit.DataStream.ByteHeader",()=>[{no:1,name:"name",kind:"scalar",T:9}],{localName:"DataStream_ByteHeader"}),Ho=z.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:z.getEnumType(hn)},{no:8,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:9,name:"text_header",kind:"message",T:Qu,oneof:"content_header"},{no:10,name:"byte_header",kind:"message",T:eh,oneof:"content_header"}],{localName:"DataStream_Header"}),Wo=z.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"}),qo=z.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"}),Rn=z.makeEnum("livekit.SignalTarget",[{no:0,name:"PUBLISHER"},{no:1,name:"SUBSCRIBER"}]),jo=z.makeEnum("livekit.StreamState",[{no:0,name:"ACTIVE"},{no:1,name:"PAUSED"}]),bv=z.makeEnum("livekit.CandidateProtocol",[{no:0,name:"UDP"},{no:1,name:"TCP"},{no:2,name:"TLS"}]),_v=z.makeMessageType("livekit.SignalRequest",()=>[{no:1,name:"offer",kind:"message",T:ss,oneof:"message"},{no:2,name:"answer",kind:"message",T:ss,oneof:"message"},{no:3,name:"trickle",kind:"message",T:Ko,oneof:"message"},{no:4,name:"add_track",kind:"message",T:Xo,oneof:"message"},{no:5,name:"mute",kind:"message",T:Yo,oneof:"message"},{no:6,name:"subscription",kind:"message",T:va,oneof:"message"},{no:7,name:"track_setting",kind:"message",T:nh,oneof:"message"},{no:8,name:"leave",kind:"message",T:ba,oneof:"message"},{no:10,name:"update_layers",kind:"message",T:sh,oneof:"message"},{no:11,name:"subscription_permission",kind:"message",T:ch,oneof:"message"},{no:12,name:"sync_state",kind:"message",T:lh,oneof:"message"},{no:13,name:"simulate",kind:"message",T:Hn,oneof:"message"},{no:14,name:"ping",kind:"scalar",T:3,oneof:"message"},{no:15,name:"update_metadata",kind:"message",T:rh,oneof:"message"},{no:16,name:"ping_req",kind:"message",T:hh,oneof:"message"},{no:17,name:"update_audio_track",kind:"message",T:ih,oneof:"message"},{no:18,name:"update_video_track",kind:"message",T:Cv,oneof:"message"}]),th=z.makeMessageType("livekit.SignalResponse",()=>[{no:1,name:"join",kind:"message",T:yv,oneof:"message"},{no:2,name:"answer",kind:"message",T:ss,oneof:"message"},{no:3,name:"offer",kind:"message",T:ss,oneof:"message"},{no:4,name:"trickle",kind:"message",T:Ko,oneof:"message"},{no:5,name:"update",kind:"message",T:Tv,oneof:"message"},{no:6,name:"track_published",kind:"message",T:Jo,oneof:"message"},{no:8,name:"leave",kind:"message",T:ba,oneof:"message"},{no:9,name:"mute",kind:"message",T:Yo,oneof:"message"},{no:10,name:"speakers_changed",kind:"message",T:Ev,oneof:"message"},{no:11,name:"room_update",kind:"message",T:Mv,oneof:"message"},{no:12,name:"connection_quality",kind:"message",T:Av,oneof:"message"},{no:13,name:"stream_state_update",kind:"message",T:Pv,oneof:"message"},{no:14,name:"subscribed_quality_update",kind:"message",T:Iv,oneof:"message"},{no:15,name:"subscription_permission_update",kind:"message",T:Dv,oneof:"message"},{no:16,name:"refresh_token",kind:"scalar",T:9,oneof:"message"},{no:17,name:"track_unpublished",kind:"message",T:xv,oneof:"message"},{no:18,name:"pong",kind:"scalar",T:3,oneof:"message"},{no:19,name:"reconnect",kind:"message",T:Sv,oneof:"message"},{no:20,name:"pong_resp",kind:"message",T:Nv,oneof:"message"},{no:21,name:"subscription_response",kind:"message",T:Fv,oneof:"message"},{no:22,name:"request_response",kind:"message",T:Bv,oneof:"message"},{no:23,name:"track_subscribed",kind:"message",T:Vv,oneof:"message"},{no:24,name:"room_moved",kind:"message",T:Lv,oneof:"message"}]),$o=z.makeMessageType("livekit.SimulcastCodec",()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"cid",kind:"scalar",T:9}]),Xo=z.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:z.getEnumType(wn)},{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:z.getEnumType(Lt)},{no:9,name:"layers",kind:"message",T:is,repeated:!0},{no:10,name:"simulcast_codecs",kind:"message",T:$o,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:z.getEnumType(hn)},{no:15,name:"stream",kind:"scalar",T:9},{no:16,name:"backup_codec_policy",kind:"enum",T:z.getEnumType(Fu)},{no:17,name:"audio_features",kind:"enum",T:z.getEnumType(Ht),repeated:!0}]),Ko=z.makeMessageType("livekit.TrickleRequest",()=>[{no:1,name:"candidateInit",kind:"scalar",T:9},{no:2,name:"target",kind:"enum",T:z.getEnumType(Rn)},{no:3,name:"final",kind:"scalar",T:8}]),Yo=z.makeMessageType("livekit.MuteTrackRequest",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"muted",kind:"scalar",T:8}]),yv=z.makeMessageType("livekit.JoinResponse",()=>[{no:1,name:"room",kind:"message",T:ma},{no:2,name:"participant",kind:"message",T:ns},{no:3,name:"other_participants",kind:"message",T:ns,repeated:!0},{no:4,name:"server_version",kind:"scalar",T:9},{no:5,name:"ice_servers",kind:"message",T:ah,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:Yu},{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:$u},{no:13,name:"sif_trailer",kind:"scalar",T:12},{no:14,name:"enabled_publish_codecs",kind:"message",T:ga,repeated:!0},{no:15,name:"fast_publish",kind:"scalar",T:8}]),Sv=z.makeMessageType("livekit.ReconnectResponse",()=>[{no:1,name:"ice_servers",kind:"message",T:ah,repeated:!0},{no:2,name:"client_configuration",kind:"message",T:Yu},{no:3,name:"server_info",kind:"message",T:$u},{no:4,name:"last_message_seq",kind:"scalar",T:13}]),Jo=z.makeMessageType("livekit.TrackPublishedResponse",()=>[{no:1,name:"cid",kind:"scalar",T:9},{no:2,name:"track",kind:"message",T:ks}]),xv=z.makeMessageType("livekit.TrackUnpublishedResponse",()=>[{no:1,name:"track_sid",kind:"scalar",T:9}]),ss=z.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}]),Tv=z.makeMessageType("livekit.ParticipantUpdate",()=>[{no:1,name:"participants",kind:"message",T:ns,repeated:!0}]),va=z.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:ju,repeated:!0}]),nh=z.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:z.getEnumType(Vo)},{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}]),ih=z.makeMessageType("livekit.UpdateLocalAudioTrack",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"features",kind:"enum",T:z.getEnumType(Ht),repeated:!0}]),Cv=z.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}]),ba=z.makeMessageType("livekit.LeaveRequest",()=>[{no:1,name:"can_reconnect",kind:"scalar",T:8},{no:2,name:"reason",kind:"enum",T:z.getEnumType(An)},{no:3,name:"action",kind:"enum",T:z.getEnumType(Is)},{no:4,name:"regions",kind:"message",T:Uv}]),Is=z.makeEnum("livekit.LeaveRequest.Action",[{no:0,name:"DISCONNECT"},{no:1,name:"RESUME"},{no:2,name:"RECONNECT"}]),sh=z.makeMessageType("livekit.UpdateVideoLayers",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"layers",kind:"message",T:is,repeated:!0}]),rh=z.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}]),ah=z.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}]),Ev=z.makeMessageType("livekit.SpeakersChanged",()=>[{no:1,name:"speakers",kind:"message",T:Bu,repeated:!0}]),Mv=z.makeMessageType("livekit.RoomUpdate",()=>[{no:1,name:"room",kind:"message",T:ma}]),wv=z.makeMessageType("livekit.ConnectionQualityInfo",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"quality",kind:"enum",T:z.getEnumType(Cr)},{no:3,name:"score",kind:"scalar",T:2}]),Av=z.makeMessageType("livekit.ConnectionQualityUpdate",()=>[{no:1,name:"updates",kind:"message",T:wv,repeated:!0}]),Rv=z.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:z.getEnumType(jo)}]),Pv=z.makeMessageType("livekit.StreamStateUpdate",()=>[{no:1,name:"stream_states",kind:"message",T:Rv,repeated:!0}]),Zo=z.makeMessageType("livekit.SubscribedQuality",()=>[{no:1,name:"quality",kind:"enum",T:z.getEnumType(Vo)},{no:2,name:"enabled",kind:"scalar",T:8}]),kv=z.makeMessageType("livekit.SubscribedCodec",()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"qualities",kind:"message",T:Zo,repeated:!0}]),Iv=z.makeMessageType("livekit.SubscribedQualityUpdate",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribed_qualities",kind:"message",T:Zo,repeated:!0},{no:3,name:"subscribed_codecs",kind:"message",T:kv,repeated:!0}]),oh=z.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}]),ch=z.makeMessageType("livekit.SubscriptionPermission",()=>[{no:1,name:"all_participants",kind:"scalar",T:8},{no:2,name:"track_permissions",kind:"message",T:oh,repeated:!0}]),Dv=z.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}]),Lv=z.makeMessageType("livekit.RoomMovedResponse",()=>[{no:1,name:"room",kind:"message",T:ma},{no:2,name:"token",kind:"scalar",T:9},{no:3,name:"participant",kind:"message",T:ns},{no:4,name:"other_participants",kind:"message",T:ns,repeated:!0}]),lh=z.makeMessageType("livekit.SyncState",()=>[{no:1,name:"answer",kind:"message",T:ss},{no:2,name:"subscription",kind:"message",T:va},{no:3,name:"publish_tracks",kind:"message",T:Jo,repeated:!0},{no:4,name:"data_channels",kind:"message",T:uh,repeated:!0},{no:5,name:"offer",kind:"message",T:ss},{no:6,name:"track_sids_disabled",kind:"scalar",T:9,repeated:!0},{no:7,name:"datachannel_receive_states",kind:"message",T:dh,repeated:!0}]),dh=z.makeMessageType("livekit.DataChannelReceiveState",()=>[{no:1,name:"publisher_sid",kind:"scalar",T:9},{no:2,name:"last_seq",kind:"scalar",T:13}]),uh=z.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:z.getEnumType(Rn)}]),Hn=z.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:z.getEnumType(bv),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"}]),hh=z.makeMessageType("livekit.Ping",()=>[{no:1,name:"timestamp",kind:"scalar",T:3},{no:2,name:"rtt",kind:"scalar",T:3}]),Nv=z.makeMessageType("livekit.Pong",()=>[{no:1,name:"last_ping_timestamp",kind:"scalar",T:3},{no:2,name:"timestamp",kind:"scalar",T:3}]),Uv=z.makeMessageType("livekit.RegionSettings",()=>[{no:1,name:"regions",kind:"message",T:Ov,repeated:!0}]),Ov=z.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}]),Fv=z.makeMessageType("livekit.SubscriptionResponse",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"err",kind:"enum",T:z.getEnumType(lv)}]),Bv=z.makeMessageType("livekit.RequestResponse",()=>[{no:1,name:"request_id",kind:"scalar",T:13},{no:2,name:"reason",kind:"enum",T:z.getEnumType(Qo)},{no:3,name:"message",kind:"scalar",T:9}]),Qo=z.makeEnum("livekit.RequestResponse.Reason",[{no:0,name:"OK"},{no:1,name:"NOT_FOUND"},{no:2,name:"NOT_ALLOWED"},{no:3,name:"LIMIT_EXCEEDED"}]),Vv=z.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 _a={exports:{}},Gv=_a.exports,fh;function Hv(){return fh||(fh=1,function(i){(function(e,t){i.exports?i.exports=t():e.log=t()})(Gv,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 U=(s[R]||"silent").toUpperCase();if(!(typeof window===t||!S)){try{window.localStorage[S]=U;return}catch{}try{window.document.cookie=encodeURIComponent(S)+"="+U+";"}catch{}}}function A(){var R;if(!(typeof window===t||!S)){try{R=window.localStorage[S]}catch{}if(typeof R===t)try{var U=window.document.cookie,B=encodeURIComponent(S),q=U.indexOf(B+"=");q!==-1&&(R=/^([^;]+)/.exec(U.slice(q+B.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 y(R){var U=R;if(typeof U=="string"&&p.levels[U.toUpperCase()]!==void 0&&(U=p.levels[U.toUpperCase()]),typeof U=="number"&&U>=0&&U<=p.levels.SILENT)return U;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,U){return b=y(R),U!==!1&&M(b),d.call(p)},p.setDefaultLevel=function(R){C=y(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=y(a.getLevel())),d.call(p),a===p)for(var R in r)r[R].rebuild()},x=y(a?a.getLevel():"WARN");var T=A();T!=null&&(b=y(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})}(_a)),_a.exports}var ya=Hv(),ec;(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"})(ec||(ec={}));var Pn;(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"})(Pn||(Pn={}));let Ke=ya.getLogger("livekit");Object.values(Pn).map(i=>ya.getLogger(i)),Ke.setDefaultLevel(ec.info);function li(i){const e=ya.getLogger(i);return e.setDefaultLevel(Ke.getLevel()),e}const Wv=ya.getLogger("lk-e2ee"),wr=7e3,qv=[0,300,2*2*300,3*3*300,4*4*300,wr,wr,wr,wr,wr];class jv{constructor(e){this._retryDelays=e!==void 0?[...e]:qv}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 $v(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 ph(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 di(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 ph=="function"?ph(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 Sa={exports:{}},mh;function Xv(){if(mh)return Sa.exports;mh=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)}Sa.exports=r,Sa.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",y=this._events;if(y!==void 0)k=k&&y.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 U=y[S];if(U===void 0)return!1;if(typeof U=="function")e(U,this,M);else for(var B=U.length,q=g(U,B),A=0;A<B;++A)e(q[A],this,M);return!0};function l(b,S,M,A){var k,y,T;if(o(M),y=b._events,y===void 0?(y=b._events=Object.create(null),b._eventsCount=0):(y.newListener!==void 0&&(b.emit("newListener",S,M.listener?M.listener:M),y=b._events),T=y[S]),T===void 0)T=y[S]=M,++b._eventsCount;else if(typeof T=="function"?T=y[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,y,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(y=-1,T=A.length-1;T>=0;T--)if(A[T]===M||A[T].listener===M){R=A[T].listener,y=T;break}if(y<0)return this;y===0?A.shift():v(A,y),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 y=Object.keys(A),T;for(k=0;k<y.length;++k)T=y[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,y),A(T)}function y(){typeof b.removeListener=="function"&&b.removeListener("error",k),M([].slice.call(arguments))}C(b,S,y,{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(y){A.once&&b.removeEventListener(S,k),M(y)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof b)}return Sa.exports}var Wn=Xv();let gh=!0,vh=!0;function Ar(i,e,t){const n=i.match(e);return n&&n.length>=t&&parseFloat(n[t],10)}function rs(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 Kv(i){return typeof i!="boolean"?new Error("Argument type: "+typeof i+". Please use a boolean."):(gh=i,i?"adapter.js logging disabled":"adapter.js logging enabled")}function Yv(i){return typeof i!="boolean"?new Error("Argument type: "+typeof i+". Please use a boolean."):(vh=!i,"adapter.js deprecation warnings "+(i?"disabled":"enabled"))}function bh(){if(typeof window=="object"){if(gh)return;typeof console<"u"&&typeof console.log=="function"&&console.log.apply(console,arguments)}}function tc(i,e){vh&&console.warn(i+" is deprecated, please use "+e+" instead.")}function Jv(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(Ar(t.userAgent,/Firefox\/(\d+)\./,1));else if(t.webkitGetUserMedia||i.isSecureContext===!1&&i.webkitRTCPeerConnection)e.browser="chrome",e.version=parseInt(Ar(t.userAgent,/Chrom(e|ium)\/(\d+)\./,2));else if(i.RTCPeerConnection&&t.userAgent.match(/AppleWebKit\/(\d+)\./))e.browser="safari",e.version=parseInt(Ar(t.userAgent,/AppleWebKit\/(\d+)\./,1)),e.supportsUnifiedPlan=i.RTCRtpTransceiver&&"currentDirection"in i.RTCRtpTransceiver.prototype,e._safariVersion=Ar(t.userAgent,/Version\/(\d+(\.?\d+))/,1);else return e.browser="Not a supported browser.",e;return e}function _h(i){return Object.prototype.toString.call(i)==="[object Object]"}function yh(i){return _h(i)?Object.keys(i).reduce(function(e,t){const n=_h(i[t]),s=n?yh(i[t]):i[t],r=n&&!Object.keys(s).length;return s===void 0||r?e:Object.assign(e,{[t]:s})},{}):i}function nc(i,e,t){!e||t.has(e.id)||(t.set(e.id,e),Object.keys(e).forEach(n=>{n.endsWith("Id")?nc(i,i.get(e[n]),t):n.endsWith("Ids")&&e[n].forEach(s=>{nc(i,i.get(s),t)})}))}function Sh(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&&nc(i,o,s)})}),s}const xh=bh;function Th(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),xh("chrome: "+JSON.stringify(o)),c(o)})}o.video=n(o.video)}return xh("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 Ch(i){i.MediaStream=i.MediaStream||i.webkitMediaStream}function Eh(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 rs(i,"track",e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e))}function Mh(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 wh(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=>Sh(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}),rs(i,"track",n=>(n.receiver._pc=n.srcElement,n)),i.RTCRtpReceiver.prototype.getStats=function(){const s=this;return this._pc.getStats().then(r=>Sh(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 Ah(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 Rh(i,e){if(!i.RTCPeerConnection)return;if(i.RTCPeerConnection.prototype.addTrack&&e.version>=65)return Ah(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 ic(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 Ph(i,e){rs(i,"negotiationneeded",t=>{const n=t.target;if(!((e.version<72||n.getConfiguration&&n.getConfiguration().sdpSemantics==="plan-b")&&n.signalingState!=="stable"))return t})}var kh=Object.freeze({__proto__:null,fixNegotiationNeeded:Ph,shimAddTrackRemoveTrack:Rh,shimAddTrackRemoveTrackWithNative:Ah,shimGetSendersWithDtmf:Mh,shimGetUserMedia:Th,shimMediaStream:Ch,shimOnTrack:Eh,shimPeerConnection:ic,shimSenderReceiverGetStats:wh});function Ih(i,e){const t=i&&i.navigator,n=i&&i.MediaStreamTrack;if(t.getUserMedia=function(s,r,a){tc("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 Zv(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 Dh(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 sc(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 Lh(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 Nh(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}),rs(i,"track",t=>(t.receiver._pc=t.srcElement,t)),i.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function Uh(i){!i.RTCPeerConnection||"removeStream"in i.RTCPeerConnection.prototype||(i.RTCPeerConnection.prototype.removeStream=function(t){tc("removeStream","removeTrack"),this.getSenders().forEach(n=>{n.track&&t.getTracks().includes(n.track)&&this.removeTrack(n)})})}function Oh(i){i.DataChannel&&!i.RTCDataChannel&&(i.RTCDataChannel=i.DataChannel)}function Fh(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 Bh(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 Vh(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 zh(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 Gh=Object.freeze({__proto__:null,shimAddTransceiver:Fh,shimCreateAnswer:zh,shimCreateOffer:Vh,shimGetDisplayMedia:Zv,shimGetParameters:Bh,shimGetUserMedia:Ih,shimOnTrack:Dh,shimPeerConnection:sc,shimRTCDataChannel:Oh,shimReceiverGetStats:Nh,shimRemoveStream:Uh,shimSenderGetStats:Lh});function Hh(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 Wh(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 qh(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 jh(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($h(s))}!e.getUserMedia&&e.mediaDevices&&e.mediaDevices.getUserMedia&&(e.getUserMedia=(function(n,s,r){e.mediaDevices.getUserMedia(n).then(s,r)}).bind(e))}function $h(i){return i&&i.video!==void 0?Object.assign({},i,{video:yh(i.video)}):i}function Xh(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?(tc("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 Kh(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 Yh(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 Jh(i){typeof i!="object"||i.AudioContext||(i.AudioContext=i.webkitAudioContext)}var Zh=Object.freeze({__proto__:null,shimAudioContext:Jh,shimCallbacksAPI:qh,shimConstraints:$h,shimCreateOfferLegacy:Yh,shimGetUserMedia:jh,shimLocalStreamsAPI:Hh,shimRTCIceServerUrls:Xh,shimRemoteStreamsAPI:Wh,shimTrackEventTransceiver:Kh}),rc={exports:{}},Qh;function Qv(){return Qh||(Qh=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,17 +79,17 @@ 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}(rc)),rc.exports}var ef=Qv(),Ds=zv(ef),e0=fg({__proto__:null,default:Ds},[ef]);function xa(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=Ds.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,rs(i,"icecandidate",t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new i.RTCIceCandidate(t.candidate),writable:"false"}),t))}function ac(i){!i.RTCIceCandidate||i.RTCIceCandidate&&"relayProtocol"in i.RTCIceCandidate.prototype||rs(i,"icecandidate",e=>{if(e.candidate){const t=Ds.parseCandidate(e.candidate.candidate);t.type==="relay"&&(e.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[t.priority>>24])}return e})}function Ta(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=Ds.splitSections(o.sdp);return c.shift(),c.some(l=>{const d=Ds.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=Ds.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 Ca(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},rs(i,"datachannel",n=>(e(n.channel,n.target),n))}function oc(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 cc(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 Ea(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 Ma(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 t0=Object.freeze({__proto__:null,removeExtmapAllowMixed:cc,shimAddIceCandidateNullOrEmpty:Ea,shimConnectionState:oc,shimMaxMessageSize:Ta,shimParameterlessSetLocalDescription:Ma,shimRTCIceCandidate:xa,shimRTCIceCandidateRelayProtocol:ac,shimSendThrowTypeError:Ca});function n0(){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=bh,n=Jv(i),s={browserDetails:n,commonShim:t0,extractVersion:Ar,disableLog:Kv,disableWarnings:Yv,sdp:e0};switch(n.browser){case"chrome":if(!kh||!ic||!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=kh,Ea(i,n),Ma(i),Th(i,n),Ch(i),ic(i,n),Eh(i),Rh(i,n),Mh(i),wh(i),Ph(i,n),xa(i),ac(i),oc(i),Ta(i,n),Ca(i),cc(i,n);break;case"firefox":if(!Gh||!sc||!e.shimFirefox)return t("Firefox shim is not included in this adapter release."),s;t("adapter.js shimming firefox."),s.browserShim=Gh,Ea(i,n),Ma(i),Ih(i,n),sc(i,n),Dh(i),Uh(i),Lh(i),Nh(i),Oh(i),Fh(i),Bh(i),Vh(i),zh(i),xa(i),oc(i),Ta(i,n),Ca(i);break;case"safari":if(!Zh||!e.shimSafari)return t("Safari shim is not included in this adapter release."),s;t("adapter.js shimming safari."),s.browserShim=Zh,Ea(i,n),Ma(i),Xh(i),Yh(i),qh(i),Hh(i),Wh(i),Kh(i),jh(i),Jh(i),xa(i),ac(i),Ta(i,n),Ca(i),cc(i,n);break;default:t("Unsupported browser!");break}return s}n0({window:typeof window>"u"?void 0:window});const i0=10,Rr="lk_e2ee",s0={sharedKey:!1,ratchetSalt:"LKFrameEncryptionKey",ratchetWindowSize:8,failureTolerance:i0,keyringSize:16};var Li;(function(i){i.SetKey="setKey",i.RatchetRequest="ratchetRequest",i.KeyRatcheted="keyRatcheted"})(Li||(Li={}));var tf;(function(i){i.KeyRatcheted="keyRatcheted"})(tf||(tf={}));var Ni;(function(i){i.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",i.EncryptionError="encryptionError"})(Ni||(Ni={}));var nf;(function(i){i.Error="cryptorError"})(nf||(nf={}));function r0(){return a0()||lc()}function lc(){return typeof window.RTCRtpScriptTransform<"u"}function a0(){return typeof window.RTCRtpSender<"u"&&typeof window.RTCRtpSender.prototype.createEncodedStreams<"u"}class cE extends Hn.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({},s0),e),this.on(Li.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(Li.SetKey,s)}getKeys(){return Array.from(this.keyInfoMap.values())}getOptions(){return this.options}ratchetKey(e,t){this.emit(Li.RatchetRequest,e,t)}}class ui extends Error{constructor(e,t){super(t||"an error has occured"),this.name="LiveKitError",this.code=e}}var Je;(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"})(Je||(Je={}));class pt extends ui{constructor(e,t,n,s){super(1,e),this.name="ConnectionError",this.status=n,this.reason=t,this.context=s,this.reasonName=Je[t]}}class dc extends ui{constructor(e){super(21,e??"device is unsupported"),this.name="DeviceUnsupportedError"}}class hi extends ui{constructor(e){super(20,e??"track is invalid"),this.name="TrackInvalidError"}}class o0 extends ui{constructor(e){super(10,e??"unsupported server"),this.name="UnsupportedServer"}}class Bt extends ui{constructor(e){super(12,e??"unexpected connection state"),this.name="UnexpectedConnectionState"}}class uc extends ui{constructor(e){super(13,e??"unable to negotiate"),this.name="NegotiationError"}}class sf extends ui{constructor(e,t){super(15,e),this.name="PublishTrackError",this.status=t}}class rf extends ui{constructor(e,t){super(15,e),this.reason=t,this.reasonName=typeof t=="string"?t:Qo[t]}}var Pn;(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"})(Pn||(Pn={}));class Ui extends ui{constructor(e,t){super(16,e),this.name="DataStreamError",this.reason=t,this.reasonName=Pn[t]}}var wa;(function(i){i.PermissionDenied="PermissionDenied",i.NotFound="NotFound",i.DeviceInUse="DeviceInUse",i.Other="Other"})(wa||(wa={})),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}(wa||(wa={}));var af;(function(i){i[i.InvalidKey=0]="InvalidKey",i[i.MissingKey=1]="MissingKey",i[i.InternalError=2]="InternalError"})(af||(af={}));var ne;(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"})(ne||(ne={}));var ce;(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"})(ce||(ce={}));var le;(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"})(le||(le={}));var ae;(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"})(ae||(ae={}));function c0(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 l0=/version\/(\d+(\.?_?\d+)+)/i;let hc;function fn(i){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;if(typeof navigator>"u")return;const t=navigator.userAgent.toLowerCase();if(hc===void 0||e){const n=d0.find(s=>{let{test:r}=s;return r.test(t)});hc=n==null?void 0:n.describe(t)}return hc}const d0=[{test:/firefox|iceweasel|fxios/i,describe(i){return{name:"Firefox",version:Aa(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,i),os:i.toLowerCase().includes("fxios")?"iOS":void 0,osVersion:fc(i)}}},{test:/chrom|crios|crmo/i,describe(i){return{name:"Chrome",version:Aa(/(?:chrome|chromium|crios|crmo)\/(\d+(\.?_?\d+)+)/i,i),os:i.toLowerCase().includes("crios")?"iOS":void 0,osVersion:fc(i)}}},{test:/safari|applewebkit/i,describe(i){return{name:"Safari",version:Aa(l0,i),os:i.includes("mobile/")?"iOS":"macOS",osVersion:fc(i)}}}];function Aa(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 fc(i){return i.includes("mac os")?Aa(/\(.+?(\d+_\d+(:?_\d+)?)/,i,1).replace(/_/g,"."):void 0}var u0="2.15.6";const h0=u0,f0=16;class $t{}$t.setTimeout=function(){return setTimeout(...arguments)},$t.setInterval=function(){return setInterval(...arguments)},$t.clearTimeout=function(){return clearTimeout(...arguments)},$t.clearInterval=function(){return clearInterval(...arguments)};const p0=5e3,Pr=[];var pn;(function(i){i[i.LOW=0]="LOW",i[i.MEDIUM=1]="MEDIUM",i[i.HIGH=2]="HIGH"})(pn||(pn={}));class Z extends Hn.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=Z.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(),p0):this.handleAppVisibilityChanged()},this.log=li((s=n.loggerName)!==null&&s!==void 0?s:Rn.Track),this.loggerContextCb=n.loggerContextCb,this.setMaxListeners(100),this.kind=t,this._mediaStreamTrack=e,this._mediaStreamID=e.id,this.source=Z.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===Z.Kind.Video&&(t="video"),this.attachedElements.length===0&&this.kind===Z.Kind.Video&&this.addAppVisibilityListener(),e||(t==="audio"&&(Pr.forEach(r=>{r.parentElement===null&&!e&&(e=r)}),e&&Pr.splice(Pr.indexOf(e),1)),e||(e=document.createElement(t))),this.attachedElements.includes(e)||this.attachedElements.push(e),Ls(this.mediaStreamTrack,e);const n=e.srcObject.getTracks(),s=n.some(r=>r.kind==="audio");return e.play().then(()=>{this.emit(s?ae.AudioPlaybackStarted:ae.VideoPlaybackStarted)}).catch(r=>{r.name==="NotAllowedError"?this.emit(s?ae.AudioPlaybackFailed:ae.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(ae.ElementAttached,e),e}detach(e){try{if(e){Ns(this.mediaStreamTrack,e);const n=this.attachedElements.indexOf(e);return n>=0&&(this.attachedElements.splice(n,1),this.recycleElement(e),this.emit(ae.ElementDetached,e)),e}const t=[];return this.attachedElements.forEach(n=>{Ns(this.mediaStreamTrack,n),t.push(n),this.recycleElement(n),this.emit(ae.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=li(e.loggerName)),e.loggerContextCb&&(this.loggerContextCb=e.loggerContextCb)}recycleElement(e){if(e instanceof HTMLAudioElement){let t=!0;e.pause(),Pr.forEach(n=>{n.parentElement||(t=!1)}),t&&Pr.push(e)}}handleAppVisibilityChanged(){return P(this,void 0,void 0,function*(){this.isInBackground=document.visibilityState==="hidden",!this.isInBackground&&this.kind===Z.Kind.Video&&setTimeout(()=>this.attachedElements.forEach(e=>e.play().catch(()=>{})),0)})}addAppVisibilityListener(){cn()?(this.isInBackground=document.visibilityState==="hidden",document.addEventListener("visibilitychange",this.appVisibilityChangedListener)):this.isInBackground=!1}removeAppVisibilityListener(){cn()&&document.removeEventListener("visibilitychange",this.appVisibilityChangedListener)}}function Ls(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)),(!os()||!(e instanceof HTMLVideoElement))&&(e.autoplay=!0),e.muted=t.getAudioTracks().length===0,e instanceof HTMLVideoElement&&(e.playsInline=!0),e.srcObject!==t&&(e.srcObject=t,(os()||as())&&e instanceof HTMLVideoElement&&setTimeout(()=>{e.srcObject=t,e.play().catch(()=>{})},0))}function Ns(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 Mn.AUDIO;case e.Video:return Mn.VIDEO;default:return Mn.DATA}}i.kindToProto=s;function r(l){switch(l){case Mn.AUDIO:return e.Audio;case Mn.VIDEO:return e.Video;default:return e.Unknown}}i.kindFromProto=r;function a(l){switch(l){case t.Camera:return Lt.CAMERA;case t.Microphone:return Lt.MICROPHONE;case t.ScreenShare:return Lt.SCREEN_SHARE;case t.ScreenShareAudio:return Lt.SCREEN_SHARE_AUDIO;default:return Lt.UNKNOWN}}i.sourceToProto=a;function o(l){switch(l){case Lt.CAMERA:return t.Camera;case Lt.MICROPHONE:return t.Microphone;case Lt.SCREEN_SHARE:return t.ScreenShare;case Lt.SCREEN_SHARE_AUDIO:return t.ScreenShareAudio;default:return t.Unknown}}i.sourceFromProto=o;function c(l){switch(l){case jo.ACTIVE:return n.Active;case jo.PAUSED:return n.Paused;default:return n.Unknown}}i.streamStateFromProto=c})(Z||(Z={}));class ut{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"],g0=["vp8","h264","vp9","av1","h265"];function v0(i){return!!m0.find(e=>e===i)}var of;(function(i){i[i.PREFER_REGRESSION=0]="PREFER_REGRESSION",i[i.SIMULCAST=1]="SIMULCAST",i[i.REGRESSION=2]="REGRESSION"})(of||(of={}));var pc;(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}})(pc||(pc={}));const kr={h90:new ut(160,90,9e4,20),h180:new ut(320,180,16e4,20),h216:new ut(384,216,18e4,20),h360:new ut(640,360,45e4,20),h540:new ut(960,540,8e5,25),h720:new ut(1280,720,17e5,30),h1080:new ut(1920,1080,3e6,30),h1440:new ut(2560,1440,5e6,30),h2160:new ut(3840,2160,8e6,30)},mc={h120:new ut(160,120,7e4,20),h180:new ut(240,180,125e3,20),h240:new ut(320,240,14e4,20),h360:new ut(480,360,33e4,20),h480:new ut(640,480,5e5,20),h540:new ut(720,540,6e5,25),h720:new ut(960,720,13e5,30),h1080:new ut(1440,1080,23e5,30),h1440:new ut(1920,1440,38e5,30)},gc={h360fps3:new ut(640,360,2e5,3,"medium"),h360fps15:new ut(640,360,4e5,15,"medium"),h720fps5:new ut(1280,720,8e5,5,"medium"),h720fps15:new ut(1280,720,15e5,15,"medium"),h720fps30:new ut(1280,720,2e6,30,"medium"),h1080fps15:new ut(1920,1080,25e5,15,"medium"),h1080fps30:new ut(1920,1080,5e6,30,"medium"),original:new ut(0,0,7e6,30,"medium")},b0="|",cf="https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension";function _0(i){const e=i.split(b0);return e.length>1?[e[0],i.substr(e[0].length+1)]:[i,""]}function on(i){return P(this,void 0,void 0,function*(){return new Promise(e=>$t.setTimeout(e,i))})}function vc(){return"addTransceiver"in RTCPeerConnection.prototype}function bc(){return"addTrack"in RTCPeerConnection.prototype}function y0(){if(!("getCapabilities"in RTCRtpSender)||os()||as())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 S0(){if(!("getCapabilities"in RTCRtpSender)||as())return!1;if(os()){const t=fn();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 Wn(i){return i==="av1"||i==="vp9"}function _c(i){return!document||Ir()?!1:(i||(i=document.createElement("audio")),"setSinkId"in i)}function x0(){return typeof RTCPeerConnection>"u"?!1:vc()||bc()}function as(){var i;return((i=fn())===null||i===void 0?void 0:i.name)==="Firefox"}function os(){var i;return((i=fn())===null||i===void 0?void 0:i.name)==="Safari"}function Ir(){const i=fn();return(i==null?void 0:i.name)==="Safari"||(i==null?void 0:i.os)==="iOS"}function T0(){const i=fn();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 C0(i){return i||(i=fn()),(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 lf(){var i,e;return cn()?(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 E0(){const i=fn(),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 cn(){return typeof document<"u"}function qn(){return navigator.product=="ReactNative"}function yc(i){return i.hostname.endsWith(".livekit.cloud")||i.hostname.endsWith(".livekit.run")}function df(){if(global&&global.LiveKitReactNativeGlobal)return global.LiveKitReactNativeGlobal}function uf(){if(!qn())return;let i=df();if(i)return i.platform}function hf(){if(cn())return window.devicePixelRatio;if(qn()){let i=df();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 M0(i){for(const e of i)e.target.handleResize(e)}function w0(i){for(const e of i)e.target.handleVisibilityChanged(e)}let Sc=null;const ff=()=>(Sc||(Sc=new ResizeObserver(M0)),Sc);let xc=null;const pf=()=>(xc||(xc=new IntersectionObserver(w0,{root:null,rootMargin:"0px"})),xc);function A0(){var i;const e=new gv({sdk:Ku.JS,protocol:f0,version:h0});return qn()&&(e.os=(i=uf())!==null&&i!==void 0?i:""),e}function mf(){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 Dr;function Tc(){if(!Dr){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(),[Dr]=n.stream.getAudioTracks(),!Dr)throw Error("Could not get empty media stream audio track");Dr.enabled=!1}return Dr.clone()}class $n{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 R0(i){return g0.includes(i)}function Oi(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 P0(i){return i.startsWith("http")?i.replace(/^(http)/,"ws"):i}function Cc(i){return i.startsWith("ws")?i.replace(/^(ws)/,"http"):i}function k0(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 I0(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 gf(i){switch(i.reason){case Je.LeaveRequest:return i.context;case Je.Cancelled:return wn.CLIENT_INITIATED;case Je.NotAllowed:return wn.USER_REJECTED;case Je.ServerUnreachable:return wn.JOIN_FAILURE;default:return wn.UNKNOWN_REASON}}function Ra(i){return i!==void 0?Number(i):void 0}function cs(i){return i!==void 0?BigInt(i):void 0}function Us(i){return!!i&&!(i instanceof MediaStreamTrack)&&i.isLocal}function Xn(i){return!!i&&i.kind==Z.Kind.Audio}function Fi(i){return!!i&&i.kind==Z.Kind.Video}function Bi(i){return Us(i)&&Fi(i)}function fi(i){return Us(i)&&Xn(i)}function Ec(i){return!!i&&!i.isLocal}function D0(i){return!!i&&!i.isLocal}function Mc(i){return Ec(i)&&Fi(i)}function L0(i){return i.isLocal}function N0(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 vf(i,e,t){var n,s,r,a;const{optionsWithoutProcessor:o,audioProcessor:c,videoProcessor:l}=yf(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&&(wc(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&&(wc(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 wc(i,e){return Object.keys(e).forEach(t=>{i[t]===void 0&&(i[t]=e[t])}),i}function Ac(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":wc(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 bf(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=_f();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 on(t),s.getByteTimeDomainData(a);const c=a.some(l=>l!==128&&l!==0);return n.close(),!c}return!1}()})}function _f(){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 U0(i){return i==="audioinput"?Z.Source.Microphone:i==="videoinput"?Z.Source.Camera:Z.Source.Unknown}function Rc(i){return i===Z.Source.Microphone?"audioinput":i===Z.Source.Camera?"videoinput":void 0}function O0(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,os()?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 Lr(i){return i.split("/")[1].toLowerCase()}function F0(i){const e=[];return i.forEach(t=>{t.track!==void 0&&e.push(new Jo({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 B0(){return typeof RTCRtpReceiver<"u"&&"getSynchronizationSources"in RTCRtpReceiver}function V0(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 yf(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:c0(e)}}function z0(i){switch(i){case Lt.CAMERA:return Z.Source.Camera;case Lt.MICROPHONE:return Z.Source.Microphone;case Lt.SCREEN_SHARE:return Z.Source.ScreenShare;case Lt.SCREEN_SHARE_AUDIO:return Z.Source.ScreenShareAudio;default:return Z.Source.Unknown}}function Sf(i,e){return i.width*i.height<e.width*e.height}function G0(i,e){var t;return(t=i.layers)===null||t===void 0?void 0:t.find(n=>n.quality===e)}class H0 extends Hn.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(Ni.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(Ni.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(Ni.ParticipantEncryptionStatusChanged,a.enabled,o)}break;case"ratchetKey":this.keyProvider.emit(Li.KeyRatcheted,a.ratchetResult,a.participantIdentity,a.keyIndex);break}},this.onWorkerError=t=>{Ke.error("e2ee worker encountered an error:",{error:t.error}),this.emit(Ni.EncryptionError,t.error)},this.keyProvider=e.keyProvider,this.worker=e.worker,this.encryptionEnabled=!1}setup(e){if(!r0())throw new dc("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:Wv.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(le.RTPVideoMapUpdate,t=>{this.postRTPMap(t)})}setupEventListeners(e,t){e.on(ne.TrackPublished,(n,s)=>this.setParticipantCryptorEnabled(n.trackInfo.encryption!==hn.NONE,s.identity)),e.on(ne.ConnectionStateChanged,n=>{n===st.Connected&&e.remoteParticipants.forEach(s=>{s.trackPublications.forEach(r=>{this.setParticipantCryptorEnabled(r.trackInfo.encryption!==hn.NONE,s.identity)})})}).on(ne.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(ne.TrackSubscribed,(n,s,r)=>{this.setupE2EEReceiver(n,r.identity,s.trackInfo)}).on(ne.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(ce.LocalSenderCreated,(n,s)=>P(this,void 0,void 0,function*(){this.setupE2EESender(s,n)})),e.localParticipant.on(ce.LocalTrackPublished,n=>{if(!Fi(n.track)||!Ir())return;const s={kind:"updateCodec",data:{trackId:n.track.mediaStreamID,codec:Lr(n.trackInfo.codecs[0].mimeType),participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(s)}),t.on(Li.SetKey,n=>this.postKey(n)).on(Li.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"?Lr(n.mimeType):void 0)}}setupE2EESender(e,t){if(!Us(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(lc()){const r={kind:"decode",participantIdentity:n,trackId:t,codec:s};e.transform=new RTCRtpScriptTransform(this.worker,r)}else{if(Rr 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:Rr in e}};this.worker.postMessage(o,[a,r])}e[Rr]=!0}})}handleSender(e,t,n){var s;if(!(Rr 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(lc()){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[Rr]=!0}}}const Pc="default";class Wt{constructor(){this._previousDevices=[]}static getInstance(){return this.instance===void 0&&(this.instance=new Wt),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=Wt.userMediaPromiseMap)===null||r===void 0?void 0:r.size)>0){Ke.debug("awaiting getUserMedia promise");try{t?yield Wt.userMediaPromiseMap.get(t):yield Promise.all(Wt.userMediaPromiseMap.values())}catch{Ke.warn("error waiting for media permissons")}}let a=yield navigator.mediaDevices.enumerateDevices();if(s&&!(os()&&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!==Pc)return t;const s=yield this.getDevices(e),r=s.find(o=>o.deviceId===Pc);if(!r){Ke.warn("could not reliably determine default device");return}const a=s.find(o=>o.deviceId!==Pc&&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?Wt.userMediaPromiseMap.has(e):Wt.userMediaPromiseMap.size>0}}Wt.mediaDeviceKinds=["audioinput","audiooutput","videoinput"],Wt.userMediaPromiseMap=new Map;var Nr;(function(i){i[i.WAITING=0]="WAITING",i[i.RUNNING=1]="RUNNING",i[i.COMPLETED=2]="COMPLETED"})(Nr||(Nr={}));class W0{constructor(){this.pendingTasks=new Map,this.taskMutex=new sn,this.nextTaskIndex=0}run(e){return P(this,void 0,void 0,function*(){const t={id:this.nextTaskIndex++,enqueuedAt:Date.now(),status:Nr.WAITING};this.pendingTasks.set(t.id,t);const n=yield this.taskMutex.lock();try{return t.executedAt=Date.now(),t.status=Nr.RUNNING,yield e()}finally{t.status=Nr.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 q0(i,e){const t=new URL(P0(i));return e.forEach((n,s)=>{t.searchParams.set(s,n)}),xf(t,"rtc")}function j0(i){const e=new URL(Cc(i));return xf(e,"validate")}function $0(i){return i.endsWith("/")?i:"".concat(i,"/")}function xf(i,e){return i.pathname="".concat($0(i.pathname)).concat(e),i.toString()}const X0=["syncState","trickle","offer","answer","simulate","leave"];function K0(i){const e=X0.indexOf(i.case)>=0;return Ke.trace("request allowed to bypass queue:",{canPass:e,req:i}),e}var Tt;(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"})(Tt||(Tt={}));class kc{get currentState(){return this.state}get isDisconnected(){return this.state===Tt.DISCONNECTING||this.state===Tt.DISCONNECTED}get isEstablishingConnection(){return this.state===Tt.CONNECTING||this.state===Tt.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=Tt.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=li((n=t.loggerName)!==null&&n!==void 0?n:Rn.Signal),this.loggerContextCb=t.loggerContextCb,this.useJSON=e,this.requestQueue=new W0,this.queuedRequests=[],this.closingLock=new sn,this.connectionLock=new sn,this.state=Tt.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=Tt.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=Tt.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=A0(),a=Y0(t,r,n),o=q0(e,a),c=j0(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 pt("room connection has been cancelled (signal)",Je.Cancelled))}),f=setTimeout(()=>{this.close(),d(new pt("room connection has timed out (signal)",Je.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!==Tt.CONNECTED){this.state=Tt.DISCONNECTED,clearTimeout(f);try{const m=yield fetch(c);if(m.status.toFixed(0).startsWith("4")){const p=yield m.text();d(new pt(p,Je.NotAllowed,m.status))}else d(new pt("Encountered unknown websocket error during connection: ".concat(v.toString()),Je.InternalError,m.status))}catch(m){d(new pt(m instanceof Error?m.message:"server was not reachable",Je.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=th.fromJson(b,{ignoreUnknownFields:!0})}else if(v.data instanceof ArrayBuffer)C=th.fromBinary(new Uint8Array(v.data));else{this.log.error("could not decode websocket message: ".concat(typeof v.data),this.logContext);return}if(this.state!==Tt.CONNECTED){let b=!1;if(((m=C.message)===null||m===void 0?void 0:m.case)==="join"?(this.state=Tt.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===Tt.RECONNECTING&&C.message.case!=="leave"?(this.state=Tt.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 pt("Received leave request while trying to (re)connect",Je.LeaveRequest,void 0,C.message.value.reason)):n.reconnect||d(new pt("did not receive join response, got ".concat((x=C.message)===null||x===void 0?void 0:x.case," instead"),Je.InternalError)),!b)return}this.signalLatency&&(yield on(this.signalLatency)),this.handleSignalResponse(C)}),this.ws.onclose=v=>{this.isEstablishingConnection&&d(new pt("Websocket got closed during a (re)connection attempt",Je.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=Tt.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,on(250)])),e.ws=void 0}}finally{t&&(e.state=Tt.DISCONNECTED),n()}}()})}sendOffer(e,t){this.log.debug("sending offer",Object.assign(Object.assign({},this.logContext),{offerSdp:e.sdp})),this.sendRequest({case:"offer",value:Pa(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:Pa(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 Ko({candidateInit:JSON.stringify(e),target:t})})}sendMuteTrack(e,t){return this.sendRequest({case:"mute",value:new Yo({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 rh({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 sh({trackSid:e,layers:t})})}sendUpdateSubscriptionPermissions(e,t){return this.sendRequest({case:"subscriptionPermission",value:new ch({allParticipants:e,trackPermissions:t})})}sendSimulateScenario(e){return this.sendRequest({case:"simulate",value:e})}sendPing(){return Promise.all([this.sendRequest({case:"ping",value:Et.parse(Date.now())}),this.sendRequest({case:"pingReq",value:new hh({timestamp:Et.parse(Date.now()),rtt:Et.parse(this.rtt)})})])}sendUpdateLocalAudioTrack(e,t){return this.sendRequest({case:"updateAudioTrack",value:new ih({trackSid:e,features:t})})}sendLeave(){return this.sendRequest({case:"leave",value:new ba({reason:wn.CLIENT_INITIATED,action:Is.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&&!K0(t)&&n.state===Tt.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 on(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 _v({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=Tf(s.value);this.onAnswer&&this.onAnswer(a,s.value.id)}else if(s.case==="offer"){const a=Tf(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===Tt.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=$t.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&&$t.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=$t.setInterval(()=>{this.sendPing()},this.pingIntervalDuration*1e3)}clearPingInterval(){this.log.debug("clearing ping interval",this.logContext),this.clearPingTimeout(),this.pingInterval&&$t.clearInterval(this.pingInterval)}}function Tf(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 Pa(i,e){return new ss({sdp:i.sdp,type:i.type,id:e})}function Y0(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",qn()?"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 Cf{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 J0{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 kn={},Ic={},Dc={exports:{}},Ef;function Lc(){if(Ef)return Dc.exports;Ef=1;var i=Dc.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")})}),Dc.exports}var Mf;function Z0(){return Mf||(Mf=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=Lc(),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}})})}}(Ic)),Ic}var Nc,wf;function Q0(){if(wf)return Nc;wf=1;var i=Lc(),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 Nc=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 Ea(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 Ma(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 t0=Object.freeze({__proto__:null,removeExtmapAllowMixed:cc,shimAddIceCandidateNullOrEmpty:Ea,shimConnectionState:oc,shimMaxMessageSize:Ta,shimParameterlessSetLocalDescription:Ma,shimRTCIceCandidate:xa,shimRTCIceCandidateRelayProtocol:ac,shimSendThrowTypeError:Ca});function n0(){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=bh,n=Jv(i),s={browserDetails:n,commonShim:t0,extractVersion:Ar,disableLog:Kv,disableWarnings:Yv,sdp:e0};switch(n.browser){case"chrome":if(!kh||!ic||!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=kh,Ea(i,n),Ma(i),Th(i,n),Ch(i),ic(i,n),Eh(i),Rh(i,n),Mh(i),wh(i),Ph(i,n),xa(i),ac(i),oc(i),Ta(i,n),Ca(i),cc(i,n);break;case"firefox":if(!Gh||!sc||!e.shimFirefox)return t("Firefox shim is not included in this adapter release."),s;t("adapter.js shimming firefox."),s.browserShim=Gh,Ea(i,n),Ma(i),Ih(i,n),sc(i,n),Dh(i),Uh(i),Lh(i),Nh(i),Oh(i),Fh(i),Bh(i),Vh(i),zh(i),xa(i),oc(i),Ta(i,n),Ca(i);break;case"safari":if(!Zh||!e.shimSafari)return t("Safari shim is not included in this adapter release."),s;t("adapter.js shimming safari."),s.browserShim=Zh,Ea(i,n),Ma(i),Xh(i),Yh(i),qh(i),Hh(i),Wh(i),Kh(i),jh(i),Jh(i),xa(i),ac(i),Ta(i,n),Ca(i),cc(i,n);break;default:t("Unsupported browser!");break}return s}n0({window:typeof window>"u"?void 0:window});const i0=10,Rr="lk_e2ee",s0={sharedKey:!1,ratchetSalt:"LKFrameEncryptionKey",ratchetWindowSize:8,failureTolerance:i0,keyringSize:16};var Li;(function(i){i.SetKey="setKey",i.RatchetRequest="ratchetRequest",i.KeyRatcheted="keyRatcheted"})(Li||(Li={}));var tf;(function(i){i.KeyRatcheted="keyRatcheted"})(tf||(tf={}));var Ni;(function(i){i.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",i.EncryptionError="encryptionError"})(Ni||(Ni={}));var nf;(function(i){i.Error="cryptorError"})(nf||(nf={}));function r0(){return a0()||lc()}function lc(){return typeof window.RTCRtpScriptTransform<"u"}function a0(){return typeof window.RTCRtpSender<"u"&&typeof window.RTCRtpSender.prototype.createEncodedStreams<"u"}class cE extends Wn.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({},s0),e),this.on(Li.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(Li.SetKey,s)}getKeys(){return Array.from(this.keyInfoMap.values())}getOptions(){return this.options}ratchetKey(e,t){this.emit(Li.RatchetRequest,e,t)}}class ui extends Error{constructor(e,t){super(t||"an error has occured"),this.name="LiveKitError",this.code=e}}var Je;(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"})(Je||(Je={}));class vt extends ui{constructor(e,t,n,s){super(1,e),this.name="ConnectionError",this.status=n,this.reason=t,this.context=s,this.reasonName=Je[t]}}class dc extends ui{constructor(e){super(21,e??"device is unsupported"),this.name="DeviceUnsupportedError"}}class hi extends ui{constructor(e){super(20,e??"track is invalid"),this.name="TrackInvalidError"}}class o0 extends ui{constructor(e){super(10,e??"unsupported server"),this.name="UnsupportedServer"}}class Bt extends ui{constructor(e){super(12,e??"unexpected connection state"),this.name="UnexpectedConnectionState"}}class uc extends ui{constructor(e){super(13,e??"unable to negotiate"),this.name="NegotiationError"}}class sf extends ui{constructor(e,t){super(15,e),this.name="PublishTrackError",this.status=t}}class rf extends ui{constructor(e,t){super(15,e),this.reason=t,this.reasonName=typeof t=="string"?t:Qo[t]}}var kn;(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"})(kn||(kn={}));class Ui extends ui{constructor(e,t){super(16,e),this.name="DataStreamError",this.reason=t,this.reasonName=kn[t]}}var wa;(function(i){i.PermissionDenied="PermissionDenied",i.NotFound="NotFound",i.DeviceInUse="DeviceInUse",i.Other="Other"})(wa||(wa={})),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}(wa||(wa={}));var af;(function(i){i[i.InvalidKey=0]="InvalidKey",i[i.MissingKey=1]="MissingKey",i[i.InternalError=2]="InternalError"})(af||(af={}));var ne;(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"})(ne||(ne={}));var ce;(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"})(ce||(ce={}));var le;(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"})(le||(le={}));var ae;(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"})(ae||(ae={}));function c0(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 l0=/version\/(\d+(\.?_?\d+)+)/i;let hc;function fn(i){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;if(typeof navigator>"u")return;const t=navigator.userAgent.toLowerCase();if(hc===void 0||e){const n=d0.find(s=>{let{test:r}=s;return r.test(t)});hc=n==null?void 0:n.describe(t)}return hc}const d0=[{test:/firefox|iceweasel|fxios/i,describe(i){return{name:"Firefox",version:Aa(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,i),os:i.toLowerCase().includes("fxios")?"iOS":void 0,osVersion:fc(i)}}},{test:/chrom|crios|crmo/i,describe(i){return{name:"Chrome",version:Aa(/(?:chrome|chromium|crios|crmo)\/(\d+(\.?_?\d+)+)/i,i),os:i.toLowerCase().includes("crios")?"iOS":void 0,osVersion:fc(i)}}},{test:/safari|applewebkit/i,describe(i){return{name:"Safari",version:Aa(l0,i),os:i.includes("mobile/")?"iOS":"macOS",osVersion:fc(i)}}}];function Aa(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 fc(i){return i.includes("mac os")?Aa(/\(.+?(\d+_\d+(:?_\d+)?)/,i,1).replace(/_/g,"."):void 0}var u0="2.15.6";const h0=u0,f0=16;class $t{}$t.setTimeout=function(){return setTimeout(...arguments)},$t.setInterval=function(){return setInterval(...arguments)},$t.clearTimeout=function(){return clearTimeout(...arguments)},$t.clearInterval=function(){return clearInterval(...arguments)};const p0=5e3,Pr=[];var pn;(function(i){i[i.LOW=0]="LOW",i[i.MEDIUM=1]="MEDIUM",i[i.HIGH=2]="HIGH"})(pn||(pn={}));class Z extends Wn.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=Z.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(),p0):this.handleAppVisibilityChanged()},this.log=li((s=n.loggerName)!==null&&s!==void 0?s:Pn.Track),this.loggerContextCb=n.loggerContextCb,this.setMaxListeners(100),this.kind=t,this._mediaStreamTrack=e,this._mediaStreamID=e.id,this.source=Z.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===Z.Kind.Video&&(t="video"),this.attachedElements.length===0&&this.kind===Z.Kind.Video&&this.addAppVisibilityListener(),e||(t==="audio"&&(Pr.forEach(r=>{r.parentElement===null&&!e&&(e=r)}),e&&Pr.splice(Pr.indexOf(e),1)),e||(e=document.createElement(t))),this.attachedElements.includes(e)||this.attachedElements.push(e),Ls(this.mediaStreamTrack,e);const n=e.srcObject.getTracks(),s=n.some(r=>r.kind==="audio");return e.play().then(()=>{this.emit(s?ae.AudioPlaybackStarted:ae.VideoPlaybackStarted)}).catch(r=>{r.name==="NotAllowedError"?this.emit(s?ae.AudioPlaybackFailed:ae.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(ae.ElementAttached,e),e}detach(e){try{if(e){Ns(this.mediaStreamTrack,e);const n=this.attachedElements.indexOf(e);return n>=0&&(this.attachedElements.splice(n,1),this.recycleElement(e),this.emit(ae.ElementDetached,e)),e}const t=[];return this.attachedElements.forEach(n=>{Ns(this.mediaStreamTrack,n),t.push(n),this.recycleElement(n),this.emit(ae.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=li(e.loggerName)),e.loggerContextCb&&(this.loggerContextCb=e.loggerContextCb)}recycleElement(e){if(e instanceof HTMLAudioElement){let t=!0;e.pause(),Pr.forEach(n=>{n.parentElement||(t=!1)}),t&&Pr.push(e)}}handleAppVisibilityChanged(){return P(this,void 0,void 0,function*(){this.isInBackground=document.visibilityState==="hidden",!this.isInBackground&&this.kind===Z.Kind.Video&&setTimeout(()=>this.attachedElements.forEach(e=>e.play().catch(()=>{})),0)})}addAppVisibilityListener(){cn()?(this.isInBackground=document.visibilityState==="hidden",document.addEventListener("visibilitychange",this.appVisibilityChangedListener)):this.isInBackground=!1}removeAppVisibilityListener(){cn()&&document.removeEventListener("visibilitychange",this.appVisibilityChangedListener)}}function Ls(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)),(!os()||!(e instanceof HTMLVideoElement))&&(e.autoplay=!0),e.muted=t.getAudioTracks().length===0,e instanceof HTMLVideoElement&&(e.playsInline=!0),e.srcObject!==t&&(e.srcObject=t,(os()||as())&&e instanceof HTMLVideoElement&&setTimeout(()=>{e.srcObject=t,e.play().catch(()=>{})},0))}function Ns(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 wn.AUDIO;case e.Video:return wn.VIDEO;default:return wn.DATA}}i.kindToProto=s;function r(l){switch(l){case wn.AUDIO:return e.Audio;case wn.VIDEO:return e.Video;default:return e.Unknown}}i.kindFromProto=r;function a(l){switch(l){case t.Camera:return Lt.CAMERA;case t.Microphone:return Lt.MICROPHONE;case t.ScreenShare:return Lt.SCREEN_SHARE;case t.ScreenShareAudio:return Lt.SCREEN_SHARE_AUDIO;default:return Lt.UNKNOWN}}i.sourceToProto=a;function o(l){switch(l){case Lt.CAMERA:return t.Camera;case Lt.MICROPHONE:return t.Microphone;case Lt.SCREEN_SHARE:return t.ScreenShare;case Lt.SCREEN_SHARE_AUDIO:return t.ScreenShareAudio;default:return t.Unknown}}i.sourceFromProto=o;function c(l){switch(l){case jo.ACTIVE:return n.Active;case jo.PAUSED:return n.Paused;default:return n.Unknown}}i.streamStateFromProto=c})(Z||(Z={}));class ut{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"],g0=["vp8","h264","vp9","av1","h265"];function v0(i){return!!m0.find(e=>e===i)}var of;(function(i){i[i.PREFER_REGRESSION=0]="PREFER_REGRESSION",i[i.SIMULCAST=1]="SIMULCAST",i[i.REGRESSION=2]="REGRESSION"})(of||(of={}));var pc;(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}})(pc||(pc={}));const kr={h90:new ut(160,90,9e4,20),h180:new ut(320,180,16e4,20),h216:new ut(384,216,18e4,20),h360:new ut(640,360,45e4,20),h540:new ut(960,540,8e5,25),h720:new ut(1280,720,17e5,30),h1080:new ut(1920,1080,3e6,30),h1440:new ut(2560,1440,5e6,30),h2160:new ut(3840,2160,8e6,30)},mc={h120:new ut(160,120,7e4,20),h180:new ut(240,180,125e3,20),h240:new ut(320,240,14e4,20),h360:new ut(480,360,33e4,20),h480:new ut(640,480,5e5,20),h540:new ut(720,540,6e5,25),h720:new ut(960,720,13e5,30),h1080:new ut(1440,1080,23e5,30),h1440:new ut(1920,1440,38e5,30)},gc={h360fps3:new ut(640,360,2e5,3,"medium"),h360fps15:new ut(640,360,4e5,15,"medium"),h720fps5:new ut(1280,720,8e5,5,"medium"),h720fps15:new ut(1280,720,15e5,15,"medium"),h720fps30:new ut(1280,720,2e6,30,"medium"),h1080fps15:new ut(1920,1080,25e5,15,"medium"),h1080fps30:new ut(1920,1080,5e6,30,"medium"),original:new ut(0,0,7e6,30,"medium")},b0="|",cf="https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension";function _0(i){const e=i.split(b0);return e.length>1?[e[0],i.substr(e[0].length+1)]:[i,""]}function on(i){return P(this,void 0,void 0,function*(){return new Promise(e=>$t.setTimeout(e,i))})}function vc(){return"addTransceiver"in RTCPeerConnection.prototype}function bc(){return"addTrack"in RTCPeerConnection.prototype}function y0(){if(!("getCapabilities"in RTCRtpSender)||os()||as())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 S0(){if(!("getCapabilities"in RTCRtpSender)||as())return!1;if(os()){const t=fn();if(t!=null&&t.version&&$n(t.version,"16")<0||(t==null?void 0:t.os)==="iOS"&&(t!=null&&t.osVersion)&&$n(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 qn(i){return i==="av1"||i==="vp9"}function _c(i){return!document||Ir()?!1:(i||(i=document.createElement("audio")),"setSinkId"in i)}function x0(){return typeof RTCPeerConnection>"u"?!1:vc()||bc()}function as(){var i;return((i=fn())===null||i===void 0?void 0:i.name)==="Firefox"}function os(){var i;return((i=fn())===null||i===void 0?void 0:i.name)==="Safari"}function Ir(){const i=fn();return(i==null?void 0:i.name)==="Safari"||(i==null?void 0:i.os)==="iOS"}function T0(){const i=fn();return(i==null?void 0:i.name)==="Safari"&&i.version.startsWith("17.")||(i==null?void 0:i.os)==="iOS"&&!!(i!=null&&i.osVersion)&&$n(i.osVersion,"17")>=0}function C0(i){return i||(i=fn()),(i==null?void 0:i.name)==="Safari"&&$n(i.version,"18.3")>0||(i==null?void 0:i.os)==="iOS"&&!!(i!=null&&i.osVersion)&&$n(i.osVersion,"18.3")>0}function lf(){var i,e;return cn()?(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 E0(){const i=fn(),e="17.2";if(i)return i.name!=="Safari"&&i.os!=="iOS"||i.os==="iOS"&&i.osVersion&&$n(i.osVersion,e)>=0?!0:i.name==="Safari"&&$n(i.version,e)>=0}function cn(){return typeof document<"u"}function jn(){return navigator.product=="ReactNative"}function yc(i){return i.hostname.endsWith(".livekit.cloud")||i.hostname.endsWith(".livekit.run")}function df(){if(global&&global.LiveKitReactNativeGlobal)return global.LiveKitReactNativeGlobal}function uf(){if(!jn())return;let i=df();if(i)return i.platform}function hf(){if(cn())return window.devicePixelRatio;if(jn()){let i=df();if(i)return i.devicePixelRatio}return 1}function $n(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 M0(i){for(const e of i)e.target.handleResize(e)}function w0(i){for(const e of i)e.target.handleVisibilityChanged(e)}let Sc=null;const ff=()=>(Sc||(Sc=new ResizeObserver(M0)),Sc);let xc=null;const pf=()=>(xc||(xc=new IntersectionObserver(w0,{root:null,rootMargin:"0px"})),xc);function A0(){var i;const e=new gv({sdk:Ku.JS,protocol:f0,version:h0});return jn()&&(e.os=(i=uf())!==null&&i!==void 0?i:""),e}function mf(){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 Dr;function Tc(){if(!Dr){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(),[Dr]=n.stream.getAudioTracks(),!Dr)throw Error("Could not get empty media stream audio track");Dr.enabled=!1}return Dr.clone()}class Xn{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 R0(i){return g0.includes(i)}function Oi(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 P0(i){return i.startsWith("http")?i.replace(/^(http)/,"ws"):i}function Cc(i){return i.startsWith("ws")?i.replace(/^(ws)/,"http"):i}function k0(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 I0(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 gf(i){switch(i.reason){case Je.LeaveRequest:return i.context;case Je.Cancelled:return An.CLIENT_INITIATED;case Je.NotAllowed:return An.USER_REJECTED;case Je.ServerUnreachable:return An.JOIN_FAILURE;default:return An.UNKNOWN_REASON}}function Ra(i){return i!==void 0?Number(i):void 0}function cs(i){return i!==void 0?BigInt(i):void 0}function Us(i){return!!i&&!(i instanceof MediaStreamTrack)&&i.isLocal}function Kn(i){return!!i&&i.kind==Z.Kind.Audio}function Fi(i){return!!i&&i.kind==Z.Kind.Video}function Bi(i){return Us(i)&&Fi(i)}function fi(i){return Us(i)&&Kn(i)}function Ec(i){return!!i&&!i.isLocal}function D0(i){return!!i&&!i.isLocal}function Mc(i){return Ec(i)&&Fi(i)}function L0(i){return i.isLocal}function N0(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 vf(i,e,t){var n,s,r,a;const{optionsWithoutProcessor:o,audioProcessor:c,videoProcessor:l}=yf(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&&(wc(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&&(wc(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 wc(i,e){return Object.keys(e).forEach(t=>{i[t]===void 0&&(i[t]=e[t])}),i}function Ac(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":wc(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 bf(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=_f();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 on(t),s.getByteTimeDomainData(a);const c=a.some(l=>l!==128&&l!==0);return n.close(),!c}return!1}()})}function _f(){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 U0(i){return i==="audioinput"?Z.Source.Microphone:i==="videoinput"?Z.Source.Camera:Z.Source.Unknown}function Rc(i){return i===Z.Source.Microphone?"audioinput":i===Z.Source.Camera?"videoinput":void 0}function O0(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,os()?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 Lr(i){return i.split("/")[1].toLowerCase()}function F0(i){const e=[];return i.forEach(t=>{t.track!==void 0&&e.push(new Jo({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 B0(){return typeof RTCRtpReceiver<"u"&&"getSynchronizationSources"in RTCRtpReceiver}function V0(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 yf(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:c0(e)}}function z0(i){switch(i){case Lt.CAMERA:return Z.Source.Camera;case Lt.MICROPHONE:return Z.Source.Microphone;case Lt.SCREEN_SHARE:return Z.Source.ScreenShare;case Lt.SCREEN_SHARE_AUDIO:return Z.Source.ScreenShareAudio;default:return Z.Source.Unknown}}function Sf(i,e){return i.width*i.height<e.width*e.height}function G0(i,e){var t;return(t=i.layers)===null||t===void 0?void 0:t.find(n=>n.quality===e)}class H0 extends Wn.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(Ni.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(Ni.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(Ni.ParticipantEncryptionStatusChanged,a.enabled,o)}break;case"ratchetKey":this.keyProvider.emit(Li.KeyRatcheted,a.ratchetResult,a.participantIdentity,a.keyIndex);break}},this.onWorkerError=t=>{Ke.error("e2ee worker encountered an error:",{error:t.error}),this.emit(Ni.EncryptionError,t.error)},this.keyProvider=e.keyProvider,this.worker=e.worker,this.encryptionEnabled=!1}setup(e){if(!r0())throw new dc("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:Wv.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(le.RTPVideoMapUpdate,t=>{this.postRTPMap(t)})}setupEventListeners(e,t){e.on(ne.TrackPublished,(n,s)=>this.setParticipantCryptorEnabled(n.trackInfo.encryption!==hn.NONE,s.identity)),e.on(ne.ConnectionStateChanged,n=>{n===st.Connected&&e.remoteParticipants.forEach(s=>{s.trackPublications.forEach(r=>{this.setParticipantCryptorEnabled(r.trackInfo.encryption!==hn.NONE,s.identity)})})}).on(ne.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(ne.TrackSubscribed,(n,s,r)=>{this.setupE2EEReceiver(n,r.identity,s.trackInfo)}).on(ne.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(ce.LocalSenderCreated,(n,s)=>P(this,void 0,void 0,function*(){this.setupE2EESender(s,n)})),e.localParticipant.on(ce.LocalTrackPublished,n=>{if(!Fi(n.track)||!Ir())return;const s={kind:"updateCodec",data:{trackId:n.track.mediaStreamID,codec:Lr(n.trackInfo.codecs[0].mimeType),participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(s)}),t.on(Li.SetKey,n=>this.postKey(n)).on(Li.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"?Lr(n.mimeType):void 0)}}setupE2EESender(e,t){if(!Us(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(lc()){const r={kind:"decode",participantIdentity:n,trackId:t,codec:s};e.transform=new RTCRtpScriptTransform(this.worker,r)}else{if(Rr 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:Rr in e}};this.worker.postMessage(o,[a,r])}e[Rr]=!0}})}handleSender(e,t,n){var s;if(!(Rr 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(lc()){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[Rr]=!0}}}const Pc="default";class Wt{constructor(){this._previousDevices=[]}static getInstance(){return this.instance===void 0&&(this.instance=new Wt),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=Wt.userMediaPromiseMap)===null||r===void 0?void 0:r.size)>0){Ke.debug("awaiting getUserMedia promise");try{t?yield Wt.userMediaPromiseMap.get(t):yield Promise.all(Wt.userMediaPromiseMap.values())}catch{Ke.warn("error waiting for media permissons")}}let a=yield navigator.mediaDevices.enumerateDevices();if(s&&!(os()&&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!==Pc)return t;const s=yield this.getDevices(e),r=s.find(o=>o.deviceId===Pc);if(!r){Ke.warn("could not reliably determine default device");return}const a=s.find(o=>o.deviceId!==Pc&&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?Wt.userMediaPromiseMap.has(e):Wt.userMediaPromiseMap.size>0}}Wt.mediaDeviceKinds=["audioinput","audiooutput","videoinput"],Wt.userMediaPromiseMap=new Map;var Nr;(function(i){i[i.WAITING=0]="WAITING",i[i.RUNNING=1]="RUNNING",i[i.COMPLETED=2]="COMPLETED"})(Nr||(Nr={}));class W0{constructor(){this.pendingTasks=new Map,this.taskMutex=new sn,this.nextTaskIndex=0}run(e){return P(this,void 0,void 0,function*(){const t={id:this.nextTaskIndex++,enqueuedAt:Date.now(),status:Nr.WAITING};this.pendingTasks.set(t.id,t);const n=yield this.taskMutex.lock();try{return t.executedAt=Date.now(),t.status=Nr.RUNNING,yield e()}finally{t.status=Nr.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 q0(i,e){const t=new URL(P0(i));return e.forEach((n,s)=>{t.searchParams.set(s,n)}),xf(t,"rtc")}function j0(i){const e=new URL(Cc(i));return xf(e,"validate")}function $0(i){return i.endsWith("/")?i:"".concat(i,"/")}function xf(i,e){return i.pathname="".concat($0(i.pathname)).concat(e),i.toString()}const X0=["syncState","trickle","offer","answer","simulate","leave"];function K0(i){const e=X0.indexOf(i.case)>=0;return Ke.trace("request allowed to bypass queue:",{canPass:e,req:i}),e}var Tt;(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"})(Tt||(Tt={}));class kc{get currentState(){return this.state}get isDisconnected(){return this.state===Tt.DISCONNECTING||this.state===Tt.DISCONNECTED}get isEstablishingConnection(){return this.state===Tt.CONNECTING||this.state===Tt.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=Tt.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=li((n=t.loggerName)!==null&&n!==void 0?n:Pn.Signal),this.loggerContextCb=t.loggerContextCb,this.useJSON=e,this.requestQueue=new W0,this.queuedRequests=[],this.closingLock=new sn,this.connectionLock=new sn,this.state=Tt.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=Tt.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=Tt.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=A0(),a=Y0(t,r,n),o=q0(e,a),c=j0(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 vt("room connection has been cancelled (signal)",Je.Cancelled))}),f=setTimeout(()=>{this.close(),d(new vt("room connection has timed out (signal)",Je.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!==Tt.CONNECTED){this.state=Tt.DISCONNECTED,clearTimeout(f);try{const m=yield fetch(c);if(m.status.toFixed(0).startsWith("4")){const p=yield m.text();d(new vt(p,Je.NotAllowed,m.status))}else d(new vt("Encountered unknown websocket error during connection: ".concat(v.toString()),Je.InternalError,m.status))}catch(m){d(new vt(m instanceof Error?m.message:"server was not reachable",Je.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=th.fromJson(b,{ignoreUnknownFields:!0})}else if(v.data instanceof ArrayBuffer)C=th.fromBinary(new Uint8Array(v.data));else{this.log.error("could not decode websocket message: ".concat(typeof v.data),this.logContext);return}if(this.state!==Tt.CONNECTED){let b=!1;if(((m=C.message)===null||m===void 0?void 0:m.case)==="join"?(this.state=Tt.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===Tt.RECONNECTING&&C.message.case!=="leave"?(this.state=Tt.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 vt("Received leave request while trying to (re)connect",Je.LeaveRequest,void 0,C.message.value.reason)):n.reconnect||d(new vt("did not receive join response, got ".concat((x=C.message)===null||x===void 0?void 0:x.case," instead"),Je.InternalError)),!b)return}this.signalLatency&&(yield on(this.signalLatency)),this.handleSignalResponse(C)}),this.ws.onclose=v=>{this.isEstablishingConnection&&d(new vt("Websocket got closed during a (re)connection attempt",Je.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=Tt.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,on(250)])),e.ws=void 0}}finally{t&&(e.state=Tt.DISCONNECTED),n()}}()})}sendOffer(e,t){this.log.debug("sending offer",Object.assign(Object.assign({},this.logContext),{offerSdp:e.sdp})),this.sendRequest({case:"offer",value:Pa(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:Pa(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 Ko({candidateInit:JSON.stringify(e),target:t})})}sendMuteTrack(e,t){return this.sendRequest({case:"mute",value:new Yo({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 rh({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 sh({trackSid:e,layers:t})})}sendUpdateSubscriptionPermissions(e,t){return this.sendRequest({case:"subscriptionPermission",value:new ch({allParticipants:e,trackPermissions:t})})}sendSimulateScenario(e){return this.sendRequest({case:"simulate",value:e})}sendPing(){return Promise.all([this.sendRequest({case:"ping",value:Et.parse(Date.now())}),this.sendRequest({case:"pingReq",value:new hh({timestamp:Et.parse(Date.now()),rtt:Et.parse(this.rtt)})})])}sendUpdateLocalAudioTrack(e,t){return this.sendRequest({case:"updateAudioTrack",value:new ih({trackSid:e,features:t})})}sendLeave(){return this.sendRequest({case:"leave",value:new ba({reason:An.CLIENT_INITIATED,action:Is.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&&!K0(t)&&n.state===Tt.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 on(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 _v({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=Tf(s.value);this.onAnswer&&this.onAnswer(a,s.value.id)}else if(s.case==="offer"){const a=Tf(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===Tt.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=$t.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&&$t.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=$t.setInterval(()=>{this.sendPing()},this.pingIntervalDuration*1e3)}clearPingInterval(){this.log.debug("clearing ping interval",this.logContext),this.clearPingTimeout(),this.pingInterval&&$t.clearInterval(this.pingInterval)}}function Tf(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 Pa(i,e){return new ss({sdp:i.sdp,type:i.type,id:e})}function Y0(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",jn()?"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 Cf{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 J0{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 In={},Ic={},Dc={exports:{}},Ef;function Lc(){if(Ef)return Dc.exports;Ef=1;var i=Dc.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")})}),Dc.exports}var Mf;function Z0(){return Mf||(Mf=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=Lc(),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}})})}}(Ic)),Ic}var Nc,wf;function Q0(){if(wf)return Nc;wf=1;var i=Lc(),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 Nc=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
- `},Nc}var Af;function eb(){if(Af)return kn;Af=1;var i=Z0(),e=Q0(),t=Lc();return kn.grammar=t,kn.write=e,kn.parse=i.parse,kn.parseParams=i.parseParams,kn.parseFmtpConfig=i.parseFmtpConfig,kn.parsePayloads=i.parsePayloads,kn.parseRemoteCandidates=i.parseRemoteCandidates,kn.parseImageAttributes=i.parseImageAttributes,kn.parseSimulcastStreamList=i.parseSimulcastStreamList,kn}var Vi=eb();function Uc(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 tb=.7,nb=20,Os={NegotiationStarted:"negotiationStarted",NegotiationComplete:"negotiationComplete",RTPVideoPayloadTypes:"rtpVideoPayloadTypes"};class Rf extends Hn.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=Uc(s=>P(this,void 0,void 0,function*(){this.emit(Os.NegotiationStarted);try{yield this.createAndSendOffer()}catch(r){if(s)s(r);else throw r}}),nb),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=li((n=t.loggerName)!==null&&n!==void 0?n:Rn.PCTransport),this.loggerOptions=t,this.config=e,this._pc=this.createPC(),this.offerLock=new sn}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}=ib(e);this.remoteStereoMids=r,this.remoteNackMids=a}else if(e.type==="answer"){const r=Vi.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=Vi.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(Os.NegotiationComplete),e.sdp&&Vi.parse(e.sdp).media.forEach(a=>{a.type==="video"&&this.emit(Os.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=Vi.parse((t=r.sdp)!==null&&t!==void 0?t:"");if(a.media.forEach(o=>{kf(o),o.type==="audio"?Pf(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||(Wn(c.codec)&&!os()&&this.ensureVideoDDExtensionForSVC(o,a),c.codec!=="av1"))return!0;const d=Math.round(c.maxbr*tb);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,Vi.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=Vi.parse((e=t.sdp)!==null&&e!==void 0?e:"");return n.media.forEach(s=>{kf(s),s.type==="audio"&&Pf(s,this.remoteStereoMids,this.remoteNackMids)}),yield this.setMungedSDP(t,Vi.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 Bt("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 Bt("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 uc(r)}})}ensureVideoDDExtensionForSVC(e,t){var n,s;if(!((n=e.ext)===null||n===void 0?void 0:n.some(a=>a.uri===cf))){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:cf})}}}function Pf(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 ib(i){var e;const t=[],n=[],s=Vi.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 kf(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 Oc="vp8",sb={audioPreset:pc.music,dtx:!0,red:!0,forceStereo:!1,simulcast:!0,screenShareEncoding:gc.h1080fps15.encoding,stopMicTrackOnMute:!1,videoCodec:Oc,backupCodec:!0,preConnectBuffer:!1},If={deviceId:{ideal:"default"},autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0,voiceIsolation:!0},Df={deviceId:{ideal:"default"},resolution:kr.h720.resolution},rb={adaptiveStream:!1,dynacast:!1,stopLocalTrackOnUnpublish:!0,reconnectPolicy:new jv,disconnectOnPageLeave:!0,webAudioMix:!1},Fc={autoSubscribe:!0,maxRetries:1,peerConnectionTimeout:15e3,websocketTimeout:15e3};var wt;(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"})(wt||(wt={}));class ab{get needsPublisher(){return this.isPublisherConnectionRequired}get needsSubscriber(){return this.isSubscriberConnectionRequired}get currentState(){return this.state}constructor(e,t,n){var s;this.peerConnectionTimeout=Fc.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=wt.CONNECTED:o.some(c=>c==="failed")?this.state=wt.FAILED:o.some(c=>c==="connecting")?this.state=wt.CONNECTING:o.every(c=>c==="closed")?this.state=wt.CLOSED:o.some(c=>c==="closed")?this.state=wt.CLOSING:o.every(c=>c==="new")&&(this.state=wt.NEW),a!==this.state&&(this.log.debug("pc state change: from ".concat(wt[a]," to ").concat(wt[this.state]),this.logContext),(r=this.onStateChange)===null||r===void 0||r.call(this,this.state,this.publisher.getConnectionState(),this.subscriber.getConnectionState()))},this.log=li((s=n.loggerName)!==null&&s!==void 0?s:Rn.PCManager),this.loggerOptions=n,this.isPublisherConnectionRequired=!t,this.isSubscriberConnectionRequired=t,this.publisher=new Rf(e,n),this.subscriber=new Rf(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,An.PUBLISHER)},this.subscriber.onIceCandidate=r=>{var a;(a=this.onIceCandidate)===null||a===void 0||a.call(this,r,An.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=wt.NEW,this.connectionLock=new sn,this.remoteOfferLock=new sn}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===An.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(Os.NegotiationStarted,()=>{e.signal.aborted||this.publisher.once(Os.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===An.PUBLISHER?this.publisher.getConnectedAddress():e===An.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),$t.clearTimeout(u),l(new pt("room connection has been cancelled",Je.Cancelled))};s!=null&&s.signal.aborted&&d(),s==null||s.signal.addEventListener("abort",d);const u=$t.setTimeout(()=>{s==null||s.signal.removeEventListener("abort",d),l(new pt("could not establish pc connection",Je.InternalError))},a);for(;this.state!==wt.CONNECTED;)if(yield on(50),s!=null&&s.signal.aborted){l(new pt("room connection has been cancelled",Je.Cancelled));return}$t.clearTimeout(u),s==null||s.signal.removeEventListener("abort",d),c()}))}()})}}class At extends Error{constructor(e,t,n){super(t),this.code=e,this.message=Nf(t,At.MAX_MESSAGE_BYTES),this.data=n?Nf(n,At.MAX_DATA_BYTES):void 0}static fromProto(e){return new At(e.code,e.message,e.data)}toProto(){return new qu({code:this.code,message:this.message,data:this.data})}static builtIn(e,t){return new At(At.ErrorCode[e],At.ErrorMessage[e],t)}}At.MAX_MESSAGE_BYTES=256,At.MAX_DATA_BYTES=15360,At.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},At.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 Lf=15360;function Bc(i){return new TextEncoder().encode(i).length}function Nf(i,e){if(Bc(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 Vc=2e3;function ka(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 zc=typeof MediaRecorder<"u";class ob{constructor(){throw new Error("MediaRecorder is not available in this environment")}}const cb=zc?MediaRecorder:ob;class lb extends cb{constructor(e,t){if(!zc)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 db(){return zc}const ub=1e3,hb=1e4;class Uf extends Z{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=Uc(()=>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(ae.Ended,this)},this.reacquireTrack=!1,this.providedByUser=s,this.muteLock=new sn,this.pauseUpstreamLock=new sn,this.trackChangeLock=new sn,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!==Z.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=>{Ns(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&&(Ls(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=>{Ls(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]:ub;return function*(){var n;if(e.kind===Z.Kind.Audio)throw new Error("cannot get dimensions for audio tracks");((n=fn())===null||n===void 0?void 0:n.os)==="iOS"&&(yield on(10));const s=Date.now();for(;Date.now()-s<t;){const r=e.dimensions;if(r)return r;yield on(50)}throw new hi("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===Oi(e)||(this._constraints.deviceId=e,this.isMuted)?!0:(yield this.restartTrack(),Oi(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===Z.Source.ScreenShare)return;const{deviceId:n,groupId:s}=e._mediaStreamTrack.getSettings(),r=e.kind===Z.Kind.Audio?"audioinput":"videoinput";return t?Wt.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 hi("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=$v(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===Z.Kind.Video?a.video=n||s?{deviceId:n,facingMode:s}:!0:a.audio=n?Object.assign({deviceId:n},r):!0,this.attachedElements.forEach(l=>{Ns(this.mediaStreamTrack,l)}),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.stop();const c=(yield navigator.mediaDevices.getUserMedia(a)).getTracks()[0];return this.kind===Z.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(ae.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?ae.Muted:ae.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),lf()&&(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(ae.UpstreamPaused,this);const n=fn();if((n==null?void 0:n.name)==="Safari"&&jn(n.version,"12.0")<0)throw new dc("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(ae.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(Ls(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&&(Ns(n._mediaStreamTrack,l),Ls(n.processor.processedTrack,l));yield(r=n.sender)===null||r===void 0?void 0:r.replaceTrack(n.processor.processedTrack)}n.emit(ae.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(ae.TrackProcessorUpdate))}()})}startPreConnectBuffer(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:100;if(!db()){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 lb(this,{mimeType:t})}this.localTrackRecorder.start(e),this.autoStopPreConnectBuffer=setTimeout(()=>{this.log.warn("preconnect buffer timed out, stopping recording automatically",this.logContext),this.stopPreConnectBuffer()},hb)}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 Ia extends Uf{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,Z.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=ka(a,this.prevStats)),this.prevStats=a}),this.handleKrispNoiseFilterEnable=()=>{this.isKrispNoiseFilterEnabled=!0,this.log.debug("Krisp noise filter enabled",this.logContext),this.emit(ae.AudioTrackFeatureUpdate,this,Ht.TF_ENHANCED_NOISE_CANCELLATION,!0)},this.handleKrispNoiseFilterDisable=()=>{this.isKrispNoiseFilterEnabled=!1,this.log.debug("Krisp noise filter disabled",this.logContext),this.emit(ae.AudioTrackFeatureUpdate,this,Ht.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===Z.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!==Oi(this._constraints.deviceId);return this.source===Z.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=Ac({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(){cn()&&(this.monitorInterval||(this.monitorInterval=setInterval(()=>{this.monitorSender()},Vc)))}setProcessor(e){return P(this,void 0,void 0,function*(){var t;const n=yield this.trackChangeLock.lock();try{if(!qn()&&!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(ae.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 bf(this);return e&&(this.isMuted||this.log.warn("silence detected on local audio track",this.logContext),this.emit(ae.AudioSilenceDetected)),e})}}function fb(i,e,t){switch(i.kind){case"audio":return new Ia(i,e,!1,void 0,t);case"video":return new Da(i,e,!1,t);default:throw new hi("unsupported track type: ".concat(i.kind))}}const pb=Object.values(kr),mb=Object.values(mc),gb=Object.values(gc),vb=[kr.h180,kr.h360],bb=[mc.h180,mc.h360],_b=i=>[{scaleResolutionDownBy:2,fps:i.encoding.maxFramerate}].map(t=>{var n,s;return new ut(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)}),Gc=["q","h","f"];function Hc(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=Sb(i,e,t,l),Ke.debug("using video encoding",a));const d=a.maxFramerate,u=new ut(e,t,a.maxBitrate,a.maxFramerate,a.priority);if(c&&Wn(l)){const g=new Bf(c),v=[];if(g.spatial>3)throw new Error("unsupported scalabilityMode: ".concat(c));const m=fn();if(Ir()||qn()||(m==null?void 0:m.name)==="Chrome"&&jn(m==null?void 0:m.version,"113")<0){const p=g.suffix=="h"?2:3,x=C0(m);for(let C=0;C<g.spatial;C+=1)v.push({rid:Gc[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=Ff(n==null?void 0:n.screenShareSimulcastLayers))!==null&&s!==void 0?s:Of(i,u):h=(r=Ff(n==null?void 0:n.videoSimulcastLayers))!==null&&r!==void 0?r:Of(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 Wc(e,t,[g,f,u],d);if(v>=480)return Wc(e,t,[g,u],d)}return Wc(e,t,[u])}function yb(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===Z.Source.ScreenShare&&t.simulcast&&(t.simulcast=!1),Hc(i.source===Z.Source.ScreenShare,c,l,t)}function Sb(i,e,t,n){const s=xb(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 xb(i,e,t){if(i)return gb;const n=e>t?e/t:t/e;return Math.abs(n-16/9)<Math.abs(n-4/3)?pb:mb}function Of(i,e){if(i)return _b(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)?vb:bb}function Wc(i,e,t,n){const s=[];if(t.forEach((r,a)=>{if(a>=Gc.length)return;const o=Math.min(i,e),l={rid:Gc[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=as()||a===0;r.encoding.priority&&u&&(l.priority=r.encoding.priority,l.networkPriority=r.encoding.priority),s.push(l)}),qn()&&uf()==="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 Ff(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 Bf{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 Tb(i){return i.source===Z.Source.ScreenShare||i.constraints.height&&Oi(i.constraints.height)>=1080?"maintain-resolution":"balanced"}const Cb=5e3;class Da extends Uf{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,Z.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(ae.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+=ka(l,h)}),this._currentBitrate=c}this.prevStats=a}),this.senderLock=new sn}get isSimulcast(){return!!(this.sender&&this.sender.getParameters().encodings.length>1)}startMonitor(e){var t;if(this.signalClient=e,!cn())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()},Vc))}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=di(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=di(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===Z.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===Z.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=pn.LOW;n<=pn.HIGH;n+=1)t.push(new Zo({quality:n,enabled:n<=e}));this.log.debug("setting publishing quality. max quality ".concat(e),this.logContext),this.setPublishingLayers(Wn(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=Ac({video:e});typeof u.video!="boolean"&&(o=u.video)}yield this.restart(o),this.isCpuConstrained=!1;try{for(var c=!0,l=di(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=di(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)},Cb))}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(Wn(e[0].codec),e[0].qualities),[];this.subscribedCodecs=e;const l=[];try{for(t=!0,n=di(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(Wn(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 Vf(u.sender,u.encodings,d.qualities,this.senderLock,Wn(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 Vf(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&&Wn(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),lf()&&this.isInBackground&&this.source===Z.Source.Camera&&(this._mediaStreamTrack.enabled=!1)})}}function Vf(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=zf(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),as()&&(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 zf(i){switch(i){case"f":return pn.HIGH;case"h":return pn.MEDIUM;case"q":return pn.LOW;default:return pn.HIGH}}function Gf(i,e,t,n){if(!t)return[new is({quality:pn.HIGH,width:i,height:e,bitrate:0,ssrc:0})];if(n){const s=t[0].scalabilityMode,r=new Bf(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 is({quality:Math.min(pn.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=zf((a=s.rid)!==null&&a!==void 0?a:"");return new is({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 Hf="_lossy",Wf="_reliable",Eb=2*1e3,qc="leave-reconnect",Mb=3e4;var In;(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"})(In||(In={}));class wb extends Hn.EventEmitter{get isClosed(){return this._isClosed}get pendingReconnect(){return!!this.reconnectTimeout}constructor(e){var t;super(),this.options=e,this.rtcConfig={},this.peerConnectionTimeout=Fc.peerConnectionTimeout,this.fullReconnectOnNext=!1,this.latestRemoteOfferId=0,this.subscriberPrimary=!1,this.pcState=In.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 Cf,this.reliableReceivedState=new J0(Mb),this.handleDataChannel=n=>P(this,[n],void 0,function(s){var r=this;let{channel:a}=s;return function*(){if(a){if(a.label===Wf)r.reliableDCSub=a;else if(a.label===Hf)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=an.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(le.ActiveSpeakersUpdate,c.value.value.speakers):(((r=c.value)===null||r===void 0?void 0:r.case)==="user"&&Rb(c,c.value.value),this.emit(le.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(le.Disconnected),this.close()},a=Date.now()-this.reconnectStart;let o=this.getNextRetryDelay({elapsedMs:a,retryCount:this.reconnectAttempts});if(o===null){r(a);return}n===qc&&(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=$t.setTimeout(()=>this.attemptReconnect(s).finally(()=>this.reconnectTimeout=void 0),o)},this.waitForRestarted=()=>new Promise((n,s)=>{this.pcState===In.Connected&&n();const r=()=>{this.off(le.Disconnected,a),n()},a=()=>{this.off(le.Restarted,r),s()};this.once(le.Restarted,r),this.once(le.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(le.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===Tt.RECONNECTING&&(this.clearReconnectTimeout(),this.attemptReconnect(Rs.RR_SIGNAL_DISCONNECTED))},this.log=li((t=e.loggerName)!==null&&t!==void 0?t:Rn.Engine),this.loggerOptions={loggerName:e.loggerName,loggerContextCb:()=>this.logContext},this.client=new kc(void 0,this.loggerOptions),this.client.signalLatency=this.options.expSignalLatency,this.reconnectPolicy=this.options.reconnectPolicy,this.registerOnLineListener(),this.closingLock=new sn,this.dataProcessLock=new sn,this.dcBufferStatus=new Map([[We.LOSSY,!0],[We.RELIABLE,!0]]),this.client.onParticipantUpdate=n=>this.emit(le.ParticipantUpdate,n),this.client.onConnectionQuality=n=>this.emit(le.ConnectionQualityUpdate,n),this.client.onRoomUpdate=n=>this.emit(le.RoomUpdate,n),this.client.onSubscriptionError=n=>this.emit(le.SubscriptionError,n),this.client.onSubscriptionPermissionUpdate=n=>this.emit(le.SubscriptionPermissionUpdate,n),this.client.onSpeakersChanged=n=>this.emit(le.SpeakersChanged,n),this.client.onStreamStateUpdate=n=>this.emit(le.StreamStateChanged,n),this.client.onRequestResponse=n=>this.emit(le.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(le.SignalConnected,r),r}catch(r){if(r instanceof pt&&r.reason===Je.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(le.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 Cf,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 hi("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 pt("publication of local track timed out, no response from server",Je.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!==wt.NEW)return;this.participantSid=(t=e.participant)===null||t===void 0?void 0:t.sid;const s=this.makeRTCConfiguration(e);this.pcManager=new ab(s,e.subscriberPrimary,this.loggerOptions),this.emit(le.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===wt.CONNECTED){const d=this.pcState===In.New;this.pcState=In.Connected,d&&this.emit(le.Connected,e)}else r===wt.FAILED&&this.pcState===In.Connected&&(this.pcState=In.Disconnected,this.handleDisconnect("peerconnection failed",o==="failed"?Rs.RR_SUBSCRIBER_FAILED:Rs.RR_PUBLISHER_FAILED));const c=this.client.isDisconnected||this.client.currentState===Tt.RECONNECTING,l=[wt.FAILED,wt.CLOSING,wt.CLOSED].includes(r);c&&l&&!this._isClosed&&this.emit(le.Offline)}),this.pcManager.onTrack=r=>{this.emit(le.MediaTrackAdded,r.track,r.streams[0],r.receiver)},Ab((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(le.LocalTrackUnpublished,e)},this.client.onLocalTrackSubscribed=e=>{this.emit(le.LocalTrackSubscribed,e)},this.client.onTokenRefresh=e=>{this.token=e},this.client.onRemoteMuteChanged=(e,t)=>{this.emit(le.RemoteMute,e,t)},this.client.onSubscribedQualityUpdate=e=>{this.emit(le.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(le.RoomMoved,e)},this.client.onClose=()=>{this.handleDisconnect("signal",Rs.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 Is.DISCONNECT:this.emit(le.Disconnected,e==null?void 0:e.reason),this.close();break;case Is.RECONNECT:this.fullReconnectOnNext=!0,this.handleDisconnect(qc);break;case Is.RESUME:this.handleDisconnect(qc)}}}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===Er.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(Hf,{ordered:!1,maxRetransmits:0}),this.reliableDC=this.pcManager.createPublisherDataChannel(Wf,{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(vc())return yield this.createTransceiverRTCRtpSender(e,t,n);if(bc())return this.log.warn("using add-track fallback",this.logContext),yield this.createRTCRtpSender(e.mediaStreamTrack);throw new Bt("Required webRTC APIs not supported on this device")})}createSimulcastSender(e,t,n,s){return P(this,void 0,void 0,function*(){if(vc())return this.createSimulcastTransceiverSender(e,t,n,s);if(bc())return this.log.debug("using add-track fallback",this.logContext),this.createRTCRtpSender(e.mediaStreamTrack);throw new Bt("Cannot stream on this device")})}createTransceiverRTCRtpSender(e,t,n){return P(this,void 0,void 0,function*(){if(!this.pcManager)throw new Bt("publisher is closed");const s=[];e.mediaStream&&s.push(e.mediaStream),Fi(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 Bt("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 Bt("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)===Er.DISABLED||((s=(n=this.pcManager)===null||n===void 0?void 0:n.currentState)!==null&&s!==void 0?s:wt.NEW)===wt.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 Bt?(this.log.debug("received unrecoverable error",Object.assign(Object.assign({},this.logContext),{error:r})),a=!1):r instanceof Fs||(this.fullReconnectOnNext=!0),a?this.handleDisconnect("reconnect",Rs.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(le.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 Bt("could not reconnect, url or token not saved");this.log.info("reconnecting, attempt: ".concat(this.reconnectAttempts),this.logContext),this.emit(le.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 Fs;r=yield this.join(e??this.url,this.token,this.signalOpts)}catch(a){throw a instanceof pt&&a.reason===Je.NotAllowed?new Bt("could not reconnect, token might be expired"):new Fs}if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(this.client.setReconnected(),this.emit(le.SignalRestarted,r),yield this.waitForPCReconnected(),this.client.currentState!==Tt.CONNECTED)throw new Fs("Signal connection got severed during reconnect");(t=this.regionUrlProvider)===null||t===void 0||t.resetAttempts(),this.emit(le.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 Bt("could not reconnect, url or token not saved");if(!this.pcManager)throw new Bt("publisher and subscriber connections unset");this.log.info("resuming signal connection, attempt ".concat(this.reconnectAttempts),this.logContext),this.emit(le.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 pt&&s.reason===Je.NotAllowed?new Bt("could not reconnect, token might be expired"):s instanceof pt&&s.reason===Je.LeaveRequest?s:new Fs(r)}if(this.emit(le.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!==Tt.CONNECTED)throw new Fs("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(le.Resumed)})}waitForPCInitialConnection(e,t){return P(this,void 0,void 0,function*(){if(!this.pcManager)throw new Bt("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(t,e)})}waitForPCReconnected(){return P(this,void 0,void 0,function*(){this.pcState=In.Reconnecting,this.log.debug("waiting for peer connection to reconnect",this.logContext);try{if(yield on(Eb),!this.pcManager)throw new Bt("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(void 0,this.peerConnectionTimeout),this.pcState=In.Connected}catch(e){throw this.pcState=In.Disconnected,new pt("could not establish PC connection, ".concat(e.message),Je.InternalError)}})}publishRpcResponse(e,t,n,s){return P(this,void 0,void 0,function*(){const r=new an({destinationIdentities:[e],kind:We.RELIABLE,value:{case:"rpcResponse",value:new Wu({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 an({destinationIdentities:[e],kind:We.RELIABLE,value:{case:"rpcAck",value:new Hu({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(le.Closing,s);!this.dcBufferStatus.get(e);)yield on(10);this.off(le.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 Bt("PC manager is closed");const a=s?n.pcManager.subscriber:n.pcManager.publisher,o=s?"Subscriber":"Publisher";if(!a)throw new pt("".concat(o," connection not set"),Je.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 on(50)}throw new pt("could not establish ".concat(o," connection, state: ").concat(a.getICEConnectionState()),Je.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!==wt.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 uc("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(le.Closing,s),this.pcManager.publisher.once(Os.RTPVideoPayloadTypes,r=>{const a=new Map;r.forEach(o=>{const c=o.codec.toLowerCase();R0(c)&&a.set(o.payload,c)}),this.emit(le.RTPVideoMapUpdate,a)});try{yield this.pcManager.negotiate(n),e()}catch(r){r instanceof uc&&(this.fullReconnectOnNext=!0),this.handleDisconnect("negotiation",Rs.RR_UNKNOWN),t(r)}finally{this.off(le.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 lh({answer:r?Pa({sdp:r.sdp,type:r.type}):void 0,offer:a?Pa({sdp:a.sdp,type:a.type}):void 0,subscription:new va({trackSids:c,subscribe:!o,participantTracks:[]}),publishTracks:F0(t),dataChannels:this.dataChannelsInfo(),trackSidsDisabled:l,datachannelReceiveStates:this.reliableReceivedState.map((d,u)=>new dh({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 uh({label:n.label,id:n.id,target:s}))};return t(this.dataChannelForKind(We.LOSSY),An.PUBLISHER),t(this.dataChannelForKind(We.RELIABLE),An.PUBLISHER),t(this.dataChannelForKind(We.LOSSY,!0),An.SUBSCRIBER),t(this.dataChannelForKind(We.RELIABLE,!0),An.SUBSCRIBER),e}clearReconnectTimeout(){this.reconnectTimeout&&$t.clearTimeout(this.reconnectTimeout)}clearPendingReconnect(){this.clearReconnectTimeout(),this.reconnectAttempts=0}registerOnLineListener(){cn()&&window.addEventListener("online",this.handleBrowserOnLine)}deregisterOnLineListener(){cn()&&window.removeEventListener("online",this.handleBrowserOnLine)}}class Fs extends Error{}function Ab(i){return i!==void 0&&i>13}function Rb(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 jc{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 yc(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(Pb(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 pt("Could not fetch region settings: ".concat(t.statusText),t.status===401?Je.NotAllowed:Je.InternalError,t.status)})}setServerReportedRegions(e){this.regionSettings=e,this.lastUpdateAt=Date.now()}}function Pb(i){return"".concat(i.protocol.replace("ws","http"),"//").concat(i.host,"/settings")}class qf{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 Ui("Not enough chunk(s) received - expected ".concat(this.totalByteSize," bytes of data total, only received ").concat(this.bytesReceived," bytes"),Pn.Incomplete);if(this.bytesReceived>this.totalByteSize)throw new Ui("Extra chunk(s) received - expected ".concat(this.totalByteSize," bytes of data total, received ").concat(this.bytesReceived," bytes"),Pn.LengthExceeded)}}constructor(e,t,n,s){this.reader=t,this.totalByteSize=n,this._info=e,this.bytesReceived=0,this.outOfBandFailureRejectingFuture=s}}class kb extends qf{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 $n,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=di(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 Ib extends qf{constructor(e,t,n,s){super(e,t,n,s),this.receivedChunks=new Map}handleChunkReceived(e){var t;const n=Ra(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 $n,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 Ui("Cannot decode datastream chunk ".concat(d.chunkIndex," as text: ").concat(h),Pn.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=di(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 Db{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 Ui('A text stream handler for topic "'.concat(e,'" has already been set.'),Pn.HandlerAlreadyRegistered);this.textStreamHandlers.set(e,t)}unregisterTextStreamHandler(e){this.textStreamHandlers.delete(e)}registerByteStreamHandler(e,t){if(this.byteStreamHandlers.has(e))throw new Ui('A byte stream handler for topic "'.concat(e,'" has already been set.'),Pn.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 Ui("Participant ".concat(e," unexpectedly disconnected in the middle of sending data"),Pn.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 $n,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:Ra(e.timestamp),attributes:e.attributes},c=new ReadableStream({start:l=>{if(r=l,this.textStreamControllers.has(e.streamId))throw new Ui("A data stream read is already in progress for a stream with id ".concat(e.streamId,"."),Pn.AlreadyOpened);this.byteStreamControllers.set(e.streamId,{info:o,controller:r,startTime:Date.now(),sendingParticipantIdentity:t,outOfBandFailureRejectingFuture:a})}});s(new kb(o,c,Ra(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 $n,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 Ui("A data stream read is already in progress for a stream with id ".concat(e.streamId,"."),Pn.AlreadyOpened);this.textStreamControllers.set(e.streamId,{info:o,controller:r,startTime:Date.now(),sendingParticipantIdentity:t,outOfBandFailureRejectingFuture:a})}});s(new Ib(o,c,Ra(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 jf{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 Lb extends jf{}class Nb extends jf{}const $f=15e3;class Ub{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 Ho({streamId:s,mimeType:r.mimeType,topic:r.topic,timestamp:cs(r.timestamp),totalLength:cs(e==null?void 0:e.totalSize),attributes:r.attributes,contentHeader:{case:"textHeader",value:new Qu({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"?Go.UPDATE:Go.CREATE})}}),o=e==null?void 0:e.destinationIdentities,c=new an({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 N0(g,$f)){yield d.waitForBufferStatusLow(We.RELIABLE);const m=new Wo({content:v,streamId:s,chunkIndex:cs(l)}),p=new an({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 qo({streamId:s}),v=new an({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(le.Closing,h);const f=new Lb(u,r,()=>this.engine.off(le.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 Ho({totalLength:cs((a=l.size)!==null&&a!==void 0?a:0),mimeType:l.mimeType,streamId:o,topic:l.topic,timestamp:cs(Date.now()),attributes:l.attributes,contentHeader:{case:"byteHeader",value:new eh({name:l.name})}}),u=new an({destinationIdentities:c,value:{case:"streamHeader",value:d}});yield this.engine.sendDataPacket(u,We.RELIABLE);let h=0;const f=new sn,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+$f);yield g.waitForBufferStatusLow(We.RELIABLE);const M=new an({destinationIdentities:c,value:{case:"streamChunk",value:new Wo({content:S,streamId:o,chunkIndex:cs(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 qo({streamId:o}),C=new an({destinationIdentities:c,value:{case:"streamTrailer",value:x}});yield g.sendDataPacket(C,We.RELIABLE)})},abort(x){v.error("Sink error:",x)}});return new Nb(m,l)})}}class Xf extends Z{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?ae.Muted:ae.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(ae.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(),Vc)),B0()&&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(ae.TimeSyncUpdate,{timestamp:s,rtpTimestamp:r}),this.rtpTimestamp=r)}};e()}}class Ob extends Xf{constructor(e,t,n,s,r,a){super(e,t,Z.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=ka(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;qn()&&this._mediaStreamTrack._setVolume(e),this.elementVolume=e}getVolume(){if(this.elementVolume)return this.elementVolume;if(qn())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(_c(t))return t.setSinkId(e)}))})}attach(e){const t=this.attachedElements.length===0;return e?super.attach(e):e=super.attach(),this.sinkId&&_c(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(ae.AudioPlaybackFailed,new Error("Audio Context couldn't be started automatically"))}).catch(s=>{this.emit(ae.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 $c=100;class Fb extends Xf{constructor(e,t,n,s,r){super(e,t,Z.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=ka(a,this.prevStats)),this.prevStats=a}),this.debouncedHandleResize=Uc(()=>{this.updateDimensions()},$c),this.adaptiveStreamSettings=s}get isAdaptiveStream(){return this.adaptiveStreamSettings!==void 0}setStreamState(e){super.setStreamState(e),console.log("setStreamState",e),e===Z.StreamState.Active&&this.updateVisibility()}get mediaStreamTrack(){return this._mediaStreamTrack}setMuted(e){super.setMuted(e),this.attachedElements.forEach(t=>{e?Ns(this._mediaStreamTrack,t):Ls(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 Bb(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<$c){$t.setTimeout(()=>{this.updateVisibility()},$c);return}this.lastVisible=o,this.emit(ae.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(ae.VideoDimensionsChanged,this.lastDimensions,this))}getPixelDensity(){var e;const t=(e=this.adaptiveStreamSettings)===null||e===void 0?void 0:e.pixelDensity;return t==="screen"?hf():t||(hf()>2?2:1)}}class Bb{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=Ur(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=Ur(this.element),(r=this.handleVisibilityChanged)===null||r===void 0||r.call(this)},this.onLeavePiP=()=>{var n;this.isPiP=Ur(this.element),(n=this.handleVisibilityChanged)===null||n===void 0||n.call(this)},this.element=e,this.isIntersecting=t??Xc(e),this.isPiP=cn()&&Ur(e),this.visibilityChangedAt=0}width(){return this.element.clientWidth}height(){return this.element.clientHeight}observe(){var e,t,n;this.isIntersecting=Xc(this.element),this.isPiP=Ur(this.element),this.element.handleResize=()=>{var s;(s=this.handleResize)===null||s===void 0||s.call(this)},this.element.handleVisibilityChanged=this.onVisibilityChanged,pf().observe(this.element),ff().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=pf())===null||e===void 0||e.unobserve(this.element),(t=ff())===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 Ur(i){var e,t;return document.pictureInPictureElement===i?!0:!((e=window.documentPictureInPicture)===null||e===void 0)&&e.window?Xc(i,(t=window.documentPictureInPicture)===null||t===void 0?void 0:t.window):!1}function Xc(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 pi extends Hn.EventEmitter{constructor(e,t,n,s){var r;super(),this.metadataMuted=!1,this.encryption=hn.NONE,this.log=Ke,this.handleMuted=()=>{this.emit(ae.Muted)},this.handleUnmuted=()=>{this.emit(ae.Unmuted)},this.log=li((r=s==null?void 0:s.loggerName)!==null&&r!==void 0?r:Rn.Publication),this.loggerContextCb=this.loggerContextCb,this.setMaxListeners(100),this.kind=e,this.trackSid=t,this.trackName=n,this.source=Z.Source.Unknown}setTrack(e){this.track&&(this.track.off(ae.Muted,this.handleMuted),this.track.off(ae.Unmuted,this.handleUnmuted)),this.track=e,e&&(e.on(ae.Muted,this.handleMuted),e.on(ae.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!==hn.NONE}get audioTrack(){if(Xn(this.track))return this.track}get videoTrack(){if(Fi(this.track))return this.track}updateInfo(e){this.trackSid=e.sid,this.trackName=e.name,this.source=Z.sourceFromProto(e.source),this.mimeType=e.mimeType,this.kind===Z.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={}))})(pi||(pi={}));class Kc extends pi{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(ae.Ended)},this.handleCpuConstrained=()=>{this.track&&Fi(this.track)&&this.emit(ae.CpuConstrained,this.track)},this.updateInfo(t),this.setTrack(n)}setTrack(e){this.track&&(this.track.off(ae.Ended,this.handleTrackEnded),this.track.off(ae.CpuConstrained,this.handleCpuConstrained)),super.setTrack(e),e&&(e.on(ae.Ended,this.handleTrackEnded),e.on(ae.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(Xn(this.track)){const t=this.track.getSourceTrackSettings(),n=new Set;return t.autoGainControl&&n.add(Ht.TF_AUTO_GAIN_CONTROL),t.echoCancellation&&n.add(Ht.TF_ECHO_CANCELLATION),t.noiseSuppression&&n.add(Ht.TF_NOISE_SUPPRESSION),t.channelCount&&t.channelCount>1&&n.add(Ht.TF_STEREO),!((e=this.options)===null||e===void 0)&&e.dtx||n.add(Ht.TF_NO_DTX),this.track.enhancedNoiseCancellation&&n.add(Ht.TF_ENHANCED_NOISE_CANCELLATION),Array.from(n.values())}else return[]}}function La(i,e){return P(this,void 0,void 0,function*(){i??(i={});let t=!1;const{audioProcessor:n,videoProcessor:s,optionsWithoutProcessor:r}=yf(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=vf(r,If,Df),l=Ac(c),d=navigator.mediaDevices.getUserMedia(l);r.audio&&(Wt.userMediaPromiseMap.set("audioinput",d),d.catch(()=>Wt.userMediaPromiseMap.delete("audioinput"))),r.video&&(Wt.userMediaPromiseMap.set("videoinput",d),d.catch(()=>Wt.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&&Oi(v.deviceId)!==p?v.deviceId=p:v||(v={deviceId:p});const x=fb(h,v,e);return x.kind===Z.Kind.Video?x.source=Z.Source.Camera:x.kind===Z.Kind.Audio&&(x.source=Z.Source.Microphone),x.mediaStream=u,Xn(x)&&n?yield x.setProcessor(n):Fi(x)&&s&&(yield x.setProcessor(s)),x})))}catch(u){if(!t)throw u;return La(Object.assign(Object.assign({},i),{audio:a,video:o}),e)}})}function Vb(i){return P(this,void 0,void 0,function*(){return(yield La({audio:!1,video:!0}))[0]})}function zb(i){return P(this,void 0,void 0,function*(){return(yield La({audio:!0,video:!1}))[0]})}var zi;(function(i){i.Excellent="excellent",i.Good="good",i.Poor="poor",i.Lost="lost",i.Unknown="unknown"})(zi||(zi={}));function Gb(i){switch(i){case Cr.EXCELLENT:return zi.Excellent;case Cr.GOOD:return zi.Good;case Cr.POOR:return zi.Poor;case Cr.LOST:return zi.Lost;default:return zi.Unknown}}class Kf extends Hn.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===Mr.AGENT}get isActive(){var e;return((e=this.participantInfo)===null||e===void 0?void 0:e.state)===Ps.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]:Mr.STANDARD;var c;super(),this.audioLevel=0,this.isSpeaking=!1,this._connectionQuality=zi.Unknown,this.log=Ke,this.log=li((c=a==null?void 0:a.loggerName)!==null&&c!==void 0?c:Rn.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 $n,this.once(ce.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(Z.Source.Camera);return!(!((e=t==null?void 0:t.isMuted)!==null&&e!==void 0)||e)}get isMicrophoneEnabled(){var e;const t=this.getTrackPublication(Z.Source.Microphone);return!(!((e=t==null?void 0:t.isMuted)!==null&&e!==void 0)||e)}get isScreenShareEnabled(){return!!this.getTrackPublication(Z.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===Ps.ACTIVE&&((t=this.participantInfo)===null||t===void 0?void 0:t.state)!==Ps.ACTIVE&&this.emit(ce.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(ce.ParticipantMetadataChanged,n)}_setName(e){const t=this.name!==e;this.name=e,t&&this.emit(ce.ParticipantNameChanged,e)}_setAttributes(e){const t=V0(this.attributes,e);this._attributes=e,Object.keys(t).length>0&&this.emit(ce.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(ce.ParticipantPermissionsChanged,c),l}setIsSpeaking(e){e!==this.isSpeaking&&(this.isSpeaking=e,e&&(this.lastSpokeAt=new Date),this.emit(ce.IsSpeakingChanged,e))}setConnectionQuality(e){const t=this._connectionQuality;this._connectionQuality=Gb(e),t!==this._connectionQuality&&this.emit(ce.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=>Xn(t.track)&&t.track.setAudioContext(e))}addTrackPublication(e){e.on(ae.Muted,()=>{this.emit(ce.TrackMuted,e)}),e.on(ae.Unmuted,()=>{this.emit(ce.TrackUnmuted,e)});const t=e;switch(t.track&&(t.track.sid=e.trackSid),this.trackPublications.set(e.trackSid,e),e.kind){case Z.Kind.Audio:this.audioTrackPublications.set(e.trackSid,e);break;case Z.Kind.Video:this.videoTrackPublications.set(e.trackSid,e);break}}}function Hb(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 oh({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 Wb extends Kf{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=hn.NONE,this.enabledPublishVideoCodecs=[],this.pendingAcks=new Map,this.pendingResponses=new Map,this.handleReconnecting=()=>{this.reconnectFuture||(this.reconnectFuture=new $n)},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 $n),(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!==Qo.OK&&u.reject(new rf(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=At.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=>Hb(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(ce.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=di(g),p;p=yield m.next(),c=p.done,!c;v=!0){u=p.value,v=!1;const x=u;v0(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===Z.Source.ScreenShare||o.source===Z.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(fi(o)||Bi(o))try{if(cn())try{const c=yield navigator==null?void 0:navigator.permissions.query({name:o.source===Z.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))),fi(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!==hn.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(le.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(le.Connected,this.handleReconnected).on(le.SignalConnected,this.handleSignalConnected).on(le.SignalRestarted,this.handleReconnected).on(le.SignalResumed,this.handleReconnected).on(le.Restarting,this.handleReconnecting).on(le.Resuming,this.handleReconnecting).on(le.LocalTrackUnpublished,this.handleLocalTrackUnpublished).on(le.SubscribedQualityUpdate,this.handleSubscribedQualityUpdate).on(le.Closing,this.handleClosing).on(le.SignalRequestResponse,this.handleSignalRequestResponse).on(le.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 on(50)}c(new rf("Request to update local metadata timed out","TimeoutError"))}catch(u){u instanceof Error&&c(u)}}))}()})}setCameraEnabled(e,t,n){return this.setTrackEnabled(Z.Source.Camera,e,t,n)}setMicrophoneEnabled(e,t,n){return this.setTrackEnabled(Z.Source.Microphone,e,t,n)}setScreenShareEnabled(e,t,n){return this.setTrackEnabled(Z.Source.ScreenShare,e,t,n)}setPermissions(e){const t=this.permissions,n=super.setPermissions(e);return n&&t&&this.emit(ce.ParticipantPermissionsChanged,t),n}setE2EEEnabled(e){return P(this,void 0,void 0,function*(){this.encryptionType=e?hn.GCM:hn.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 Z.Source.Camera:c=yield this.createTracks({video:(r=n)!==null&&r!==void 0?r:!0});break;case Z.Source.Microphone:c=yield this.createTracks({audio:(a=n)!==null&&a!==void 0?a:!0});break;case Z.Source.ScreenShare:c=yield this.createScreenTracks(Object.assign({},n));break;default:throw new hi(e)}}catch(l){throw c==null||c.forEach(d=>{d.stop()}),l instanceof Error&&this.emit(ce.MediaDevicesError,l,Rc(e)),this.pendingPublishing.delete(e),l}for(const l of c){const d=Object.assign(Object.assign({},this.roomOptions.publishDefaults),n);e===Z.Source.Microphone&&Xn(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===Z.Source.ScreenShare){o=yield this.unpublishTrack(o.track);const c=this.getTrackPublication(Z.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(Z.Source.Camera)||this.pendingPublishing.has(Z.Source.Microphone))){this.pendingPublishing.add(Z.Source.Camera),this.pendingPublishing.add(Z.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(Z.Source.Camera),this.pendingPublishing.delete(Z.Source.Microphone)}}})}createTracks(e){return P(this,void 0,void 0,function*(){var t,n;e??(e={});const s=vf(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 La(s,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext})).map(o=>(Xn(o)&&(this.microphoneError=void 0,o.setAudioContext(this.audioContext),o.source=Z.Source.Microphone,this.emit(ce.AudioStreamAcquired)),Fi(o)&&(this.cameraError=void 0,o.source=Z.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 dc("getDisplayMedia not supported");e.resolution===void 0&&!T0()&&(e.resolution=gc.h1080fps30.resolution);const t=O0(e),n=yield navigator.mediaDevices.getDisplayMedia(t),s=n.getVideoTracks();if(s.length===0)throw new hi("no video track found");const r=new Da(s[0],void 0,!1,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});r.source=Z.Source.ScreenShare,e.contentHint&&(r.mediaStreamTrack.contentHint=e.contentHint);const a=[r];if(n.getAudioTracks().length>0){this.emit(ce.AudioStreamAcquired);const o=new Ia(n.getAudioTracks()[0],void 0,!1,this.audioContext,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});o.source=Z.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;fi(n)&&n.setAudioContext(r.audioContext),yield(o=r.reconnectFuture)===null||o===void 0?void 0:o.promise,r.republishPromise&&!a&&(yield r.republishPromise),Us(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 Z.Source.Microphone:p="audioinput";break;case Z.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 Ia(n,u,!0,r.audioContext,{loggerName:r.roomOptions.loggerName,loggerContextCb:()=>r.logContext});break;case"video":n=new Da(n,u,!0,{loggerName:r.roomOptions.loggerName,loggerContextCb:()=>r.logContext});break;default:throw new hi("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);!E0()&&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!==Tt.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 sf("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 $n),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 sf("failed to publish track, insufficient permissions",403);Array.from(this.trackPublications.values()).find(y=>Us(e)&&y.source===e.source)&&e.source!==Z.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&&Xn(e)&&(e.stopOnMute=!0),e.source===Z.Source.ScreenShare&&as()&&(t.simulcast=!1),t.videoCodec==="av1"&&!y0()&&(t.videoCodec=void 0),t.videoCodec==="vp9"&&!S0()&&(t.videoCodec=void 0),t.videoCodec===void 0&&(t.videoCodec=Oc),this.enabledPublishVideoCodecs.length>0&&(this.enabledPublishVideoCodecs.some(y=>t.videoCodec===Lr(y.mime))||(t.videoCodec=Lr(this.enabledPublishVideoCodecs[0].mime)));const v=t.videoCodec;e.on(ae.Muted,this.onTrackMuted),e.on(ae.Unmuted,this.onTrackUnmuted),e.on(ae.Ended,this.handleTrackEnded),e.on(ae.UpstreamPaused,this.onTrackUpstreamPaused),e.on(ae.UpstreamResumed,this.onTrackUpstreamResumed),e.on(ae.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate);const m=[],p=!(!((s=t.dtx)!==null&&s!==void 0)||s),x=e.getSourceTrackSettings();x.autoGainControl&&m.push(Ht.TF_AUTO_GAIN_CONTROL),x.echoCancellation&&m.push(Ht.TF_ECHO_CANCELLATION),x.noiseSuppression&&m.push(Ht.TF_NOISE_SUPPRESSION),x.channelCount&&x.channelCount>1&&m.push(Ht.TF_STEREO),p&&m.push(Ht.TF_NO_DTX),fi(e)&&e.hasPreConnectBuffer&&m.push(Ht.TF_PRECONNECT_BUFFER);const C=new Xo({cid:e.mediaStreamTrack.id,name:t.name,type:Z.kindToProto(e.kind),muted:e.isMuted,source:Z.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===Z.Kind.Video){let y={width:0,height:0};try{y=yield e.waitForDimensions()}catch{const R=(o=(a=this.roomOptions.videoCaptureDefaults)===null||a===void 0?void 0:a.resolution)!==null&&o!==void 0?o:kr.h720.resolution;y={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:y}))}C.width=y.width,C.height=y.height,Bi(e)&&(Wn(v)&&(e.source===Z.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 $o({codec:v,cid:e.mediaStreamTrack.id})],t.backupCodec===!0&&(t.backupCodec={codec:Oc}),t.backupCodec&&v!==t.backupCodec.codec&&C.encryption===hn.NONE&&(this.roomOptions.dynacast||(this.roomOptions.dynacast=!0),C.simulcastCodecs.push(new $o({codec:t.backupCodec.codec,cid:""})))),b=Hc(e.source===Z.Source.ScreenShare,C.width,C.height,t),C.layers=Gf(C.width,C.height,b,Wn(t.videoCodec))}else e.kind===Z.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 Bt("cannot publish track when not connected");const S=()=>P(this,void 0,void 0,function*(){var y,T,R;if(!this.engine.pcManager)throw new Bt("pcManager is not ready");if(e.sender=yield this.engine.createSender(e,t,b),this.emit(ce.LocalSenderCreated,e.sender,e),Bi(e)&&((y=t.degradationPreference)!==null&&y!==void 0||(t.degradationPreference=Tb(e)),e.setDegradationPreference(t.degradationPreference)),b)if(as()&&e.kind===Z.Kind.Audio){let U;for(const B of this.engine.pcManager.publisher.getTransceivers())if(B.sender===e.sender){U=B;break}U&&this.engine.pcManager.publisher.setTrackCodecBitrate({transceiver:U,codec:"opus",maxbr:!((T=b[0])===null||T===void 0)&&T.maxBitrate?b[0].maxBitrate/1e3:0})}else e.codec&&Wn(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((y,T)=>P(this,void 0,void 0,function*(){var R;try{M=yield this.engine.addTrack(C),y(M)}catch(U){e.sender&&(!((R=this.engine.pcManager)===null||R===void 0)&&R.publisher)&&(this.engine.pcManager.publisher.removeTrack(e.sender),yield this.engine.negotiate().catch(B=>{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:B}))})),T(U)}}));if(this.enabledPublishVideoCodecs.length>0)M=(yield Promise.all([A,S()]))[0];else{M=yield A;let y;if(M.codecs.forEach(T=>{y===void 0&&(y=T.mimeType)}),y&&e.kind===Z.Kind.Video){const T=Lr(y);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=Hc(e.source===Z.Source.ScreenShare,C.width,C.height,t))}yield S()}const k=new Kc(e.kind,M,e,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});if(k.on(ae.CpuConstrained,y=>this.onTrackCpuConstrained(y,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})),Bi(e)?e.startMonitor(this.engine.client):fi(e)&&e.startMonitor(),this.addTrackPublication(k),this.emit(ce.LocalTrackPublished,k),fi(e)&&M.audioFeatures.includes(Ht.TF_PRECONNECT_BUFFER)){const y=e.getPreConnectBuffer(),T=e.getPreConnectBufferMimeType();this.on(ce.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()}}),y&&new Promise((U,B)=>P(this,void 0,void 0,function*(){var q,K,H,W,te,ve;try{this.log.debug("waiting for agent",Object.assign(Object.assign({},this.logContext),Xe(e)));const Be=setTimeout(()=>{B(new Error("agent not active within 10 seconds"))},1e4),Ct=yield this.waitUntilActiveAgentPresent();clearTimeout(Be),this.log.debug("sending preconnect buffer",Object.assign(Object.assign({},this.logContext),Xe(e)));const ht=yield this.streamBytes({name:"preconnect-buffer",mimeType:T,topic:"lk.agent.pre-connect-audio-buffer",destinationIdentities:[Ct.identity],attributes:{trackId:k.trackSid,sampleRate:String((te=x.sampleRate)!==null&&te!==void 0?te:"48000"),channels:String((ve=x.channelCount)!==null&&ve!==void 0?ve:"1")}});try{for(var de=!0,_e=di(y),Ve;Ve=yield _e.next(),q=Ve.done,!q;de=!0){W=Ve.value,de=!1;const X=W;yield ht.write(X)}}catch(X){K={error:X}}finally{try{!de&&!q&&(H=_e.return)&&(yield H.call(_e))}finally{if(K)throw K.error}}yield ht.close(),U()}catch(Be){B(Be)}})).then(()=>{this.log.debug("preconnect buffer sent successfully",Object.assign(Object.assign({},this.logContext),Xe(e)))}).catch(U=>{this.log.error("error sending preconnect buffer",Object.assign(Object.assign(Object.assign({},this.logContext),Xe(e)),{error:U}))})}return k})}get isLocal(){return!0}publishAdditionalCodecForTrack(e,t,n){return P(this,void 0,void 0,function*(){var s;if(this.encryptionType!==hn.NONE)return;let r;if(this.trackPublications.forEach(f=>{f.track&&f.track===e&&(r=f)}),!r)throw new hi("track is not published");if(!Bi(e))throw new hi("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=yb(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 Xo({cid:c.mediaStreamTrack.id,type:Z.kindToProto(e.kind),muted:e.isMuted,source:Z.sourceToProto(e.source),sid:e.sid,simulcastCodecs:[{codec:a.videoCodec,cid:c.mediaStreamTrack.id}]});if(l.layers=Gf(l.width,l.height,o),!this.engine||this.engine.isClosed)throw new Bt("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(Us(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(ae.Muted,this.onTrackMuted),e.off(ae.Unmuted,this.onTrackUnmuted),e.off(ae.Ended,this.handleTrackEnded),e.off(ae.UpstreamPaused,this.onTrackUpstreamPaused),e.off(ae.UpstreamResumed,this.onTrackUpstreamResumed),e.off(ae.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<wt.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),Bi(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 Z.Kind.Audio:this.audioTrackPublications.delete(r.trackSid);break;case Z.Kind.Video:this.videoTrackPublications.delete(r.trackSid);break}return this.emit(ce.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!==Z.Source.ScreenShare&&l.source!==Z.Source.ScreenShareAudio&&(fi(l)||Bi(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 an({kind:r,value:{case:"user",value:new Vu({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 an({kind:We.RELIABLE,value:{case:"sipDtmf",value:new zu({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 an({value:{case:"chatMessage",value:new zo(Object.assign(Object.assign({},n),{timestamp:Et.parse(n.timestamp)}))}});return yield this.engine.sendDataPacket(s,We.RELIABLE),this.emit(ce.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 an({value:{case:"chatMessage",value:new zo(Object.assign(Object.assign({},n),{timestamp:Et.parse(n.timestamp),editTimestamp:Et.parse(n.editTimestamp)}))}});return yield this.engine.sendDataPacket(s,We.RELIABLE),this.emit(ce.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(Bc(a)>Lf){d(At.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(At.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(At.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(At.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 an({destinationIdentities:[e],kind:We.RELIABLE,value:{case:"rpcRequest",value:new Gu({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,At.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 $n),this.activeAgentFuture.promise)}getPublicationForTrack(e){let t;return this.trackPublications.forEach(n=>{const s=n.track;s&&(e instanceof MediaStreamTrack?(fi(s)||Bi(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 on(20)}})}}class qb extends pi{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(ae.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 va({trackSids:[this.trackSid],subscribe:this.subscribed,participantTracks:[new ju({participantSid:"",trackSids:[this.trackSid]})]});this.emit(ae.UpdateSubscription,s),this.emitSubscriptionUpdateIfChanged(t),this.emitPermissionUpdateIfChanged(n)}get subscriptionStatus(){return this.subscribed===!1?pi.SubscriptionStatus.Unsubscribed:super.isSubscribed?pi.SubscriptionStatus.Subscribed:pi.SubscriptionStatus.Desired}get permissionStatus(){return this.allowed?pi.PermissionStatus.Allowed:pi.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||(Mc(this.track)&&(this.requestedVideoDimensions=e),this.requestedMaxQuality=void 0,this.emitTrackUpdate()))}setVideoFPS(e){this.isManualOperationAllowed()&&Mc(this.track)&&this.fps!==e&&(this.fps=e,this.emitTrackUpdate())}get videoQuality(){var e;return(e=this.requestedMaxQuality)!==null&&e!==void 0?e:pn.HIGH}setTrack(e){const t=this.subscriptionStatus,n=this.permissionStatus,s=this.track;s!==e&&(s&&(s.off(ae.VideoDimensionsChanged,this.handleVideoDimensionsChange),s.off(ae.VisibilityChanged,this.handleVisibilityChange),s.off(ae.Ended,this.handleEnded),s.detach(),s.stopMonitor(),this.emit(ae.Unsubscribed,s)),super.setTrack(e),e&&(e.sid=this.trackSid,e.on(ae.VideoDimensionsChanged,this.handleVideoDimensionsChange),e.on(ae.VisibilityChanged,this.handleVisibilityChange),e.on(ae.Ended,this.handleEnded),this.emit(ae.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(ae.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?ae.Muted:ae.Unmuted)}emitSubscriptionUpdateIfChanged(e){const t=this.subscriptionStatus;e!==t&&this.emit(ae.SubscriptionStatusChanged,t,e)}emitPermissionUpdateIfChanged(e){this.permissionStatus!==e&&this.emit(ae.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 Mc(this.track)&&this.track.isAdaptiveStream}emitTrackUpdate(){const e=new nh({trackSids:[this.trackSid],disabled:!this.isEnabled,fps:this.fps});if(this.kind===Z.Kind.Video){let t=this.requestedVideoDimensions;if(this.videoDimensionsAdaptiveStream!==void 0)if(t)Sf(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=G0(this.trackInfo,this.requestedMaxQuality);n&&Sf(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:pn.HIGH})),e.quality=pn.HIGH)}this.emit(ae.UpdateSettings,e)}}class Na extends Kf{static fromParticipantInfo(e,t,n){return new Na(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]:Mr.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(ae.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(ae.UpdateSubscription,t=>{t.participantTracks.forEach(n=>{n.participantSid=this.sid}),this.signalClient.sendUpdateSubscription(t)}),e.on(ae.SubscriptionPermissionChanged,t=>{this.emit(ce.TrackSubscriptionPermissionChanged,e,t)}),e.on(ae.SubscriptionStatusChanged,t=>{this.emit(ce.TrackSubscriptionStatusChanged,e,t)}),e.on(ae.Subscribed,t=>{this.emit(ce.TrackSubscribed,t,e)}),e.on(ae.Unsubscribed,t=>{this.emit(ce.TrackUnsubscribed,t,e)}),e.on(ae.SubscriptionFailed,t=>{this.emit(ce.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]:Z.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]:Z.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(ce.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(ce.TrackSubscriptionFailed,t);return}const c=e.kind==="video";let l;return c?l=new Fb(e,t,s,r):l=new Ob(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)&&Ec(l)&&Xn(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=Z.kindFromProto(s.type);if(!c)return;o=new qb(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!==Z.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(ce.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 Z.Kind.Audio:this.audioTrackPublications.delete(e);break;case Z.Kind.Video:this.videoTrackPublications.delete(e);break}t&&this.emit(ce.TrackUnpublished,n)}setAudioOutput(e){return P(this,void 0,void 0,function*(){this.audioOutput=e;const t=[];this.audioTrackPublications.forEach(n=>{var s;Xn(n.track)&&Ec(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 st;(function(i){i.Disconnected="disconnected",i.Connecting="connecting",i.Connected="connected",i.Reconnecting="reconnecting",i.SignalReconnecting="signalReconnecting"})(st||(st={}));const jb=4*1e3;class Bs extends Hn.EventEmitter{constructor(e){var t,n,s,r;if(super(),t=this,this.state=st.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(!x0())throw qn()?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===st.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(st.Connecting),((l=this.regionUrlProvider)===null||l===void 0?void 0:l.getServerUrl().toString())!==a&&(this.regionUrl=void 0,this.regionUrlProvider=void 0),yc(new URL(a))&&(this.regionUrlProvider===void 0?this.regionUrlProvider=new jc(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 pt&&C.reason!==Je.Cancelled&&C.reason!==Je.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 pt&&(S.status===401||S.reason===Je.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,gf(C)),g(C))}else{let b=wn.UNKNOWN_REASON;C instanceof pt&&(b=gf(C)),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,b),g(C)}}}),h=this.regionUrl;return this.regionUrl=void 0,this.connectFuture=new $n((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 o0("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===st.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({},Fc),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(ne.SignalConnected)}catch(h){yield this.engine.close(),this.recreateEngine();const f=new pt("could not establish signal connection",Je.ServerUnreachable);throw h instanceof Error&&(f.message="".concat(f.message,": ").concat(h.message)),h instanceof pt&&(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 pt("Connection attempt aborted",Je.Cancelled);try{yield this.engine.waitForPCInitialConnection(this.connOptions.peerConnectionTimeout,l)}catch(h){throw yield this.engine.close(),this.recreateEngine(),h}cn()&&this.options.disconnectOnPageLeave&&(window.addEventListener("pagehide",this.onPageLeave),window.addEventListener("beforeunload",this.onPageLeave)),cn()&&document.addEventListener("freeze",this.onPageLeave),this.setAndEmitConnectionState(st.Connected),this.emit(ne.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===st.Disconnected){l.log.debug("already disconnected",l.logContext);return}l.log.info("disconnect from room",Object.assign({},l.logContext)),(l.state===st.Connecting||l.state===st.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 pt("Client initiated disconnect",Je.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,wn.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=fn();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=Tc();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(ne.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(st.Reconnecting)&&this.emit(ne.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(st.Connected),this.emit(ne.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===Ps.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(ne.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(ne.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=Z.streamStateFromProto(o.state);l.track.setStreamState(d),d!==l.track.streamState&&(c.emit(ce.TrackStreamStateChanged,l,l.track.streamState),this.emitWhenConnected(ne.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(ne.DataReceived,o.payload,a,c,o.topic),a==null||a.emit(ce.DataReceived,o.payload,c)},this.handleSipDtmf=(a,o)=>{this.emit(ne.SipDTMFReceived,o,a),a==null||a.emit(ce.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=k0(o,this.transcriptionReceivedTimes);l==null||l.emit(ae.TranscriptionReceived,d),c==null||c.emit(ce.TranscriptionReceived,d,l),this.emit(ne.TranscriptionReceived,d,c,l)},this.handleChatMessage=(a,o)=>{const c=I0(o);this.emit(ne.ChatMessage,c,a)},this.handleMetrics=(a,o)=>{this.emit(ne.MetricsReceived,a,o)},this.handleDataStream=a=>{this.incomingDataStreamManager.handleDataStreamPacket(a)},this.bufferedSegments=new Map,this.handleAudioPlaybackStarted=()=>{this.canPlaybackAudio||(this.audioEnabled=!0,this.emit(ne.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(ne.AudioPlaybackStatusChanged,!1))},this.handleVideoPlaybackStarted=()=>{this.isVideoPlaybackBlocked&&(this.isVideoPlaybackBlocked=!1,this.emit(ne.VideoPlaybackStatusChanged,!0))},this.handleVideoPlaybackFailed=()=>{this.isVideoPlaybackBlocked||(this.isVideoPlaybackBlocked=!0,this.emit(ne.VideoPlaybackStatusChanged,!1))},this.handleDeviceChange=()=>P(this,void 0,void 0,function*(){var a;((a=fn())===null||a===void 0?void 0:a.os)!=="iOS"&&(yield this.selectDefaultDevices()),this.emit(ne.MediaDevicesChanged)}),this.handleRoomUpdate=a=>{const o=this.roomInfo;this.roomInfo=a,o&&o.metadata!==a.metadata&&this.emitWhenConnected(ne.RoomMetadataChanged,a.metadata),(o==null?void 0:o.activeRecording)!==a.activeRecording&&this.emitWhenConnected(ne.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(ne.ParticipantMetadataChanged,a,this.localParticipant)},this.onLocalParticipantNameChanged=a=>{this.emit(ne.ParticipantNameChanged,a,this.localParticipant)},this.onLocalAttributesChanged=a=>{this.emit(ne.ParticipantAttributesChanged,a,this.localParticipant)},this.onLocalTrackMuted=a=>{this.emit(ne.TrackMuted,a,this.localParticipant)},this.onLocalTrackUnmuted=a=>{this.emit(ne.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(ae.TrackProcessorUpdate,this.onTrackProcessorUpdate),(c=a.track)===null||c===void 0||c.on(ae.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(ne.LocalTrackPublished,a,this.localParticipant),fi(a.track)&&(yield a.track.checkForSilence())&&this.emit(ne.LocalAudioSilenceDetected,a);const f=yield(h=a.track)===null||h===void 0?void 0:h.getDeviceId(!1),g=Rc(a.source);g&&f&&f!==this.localParticipant.activeDeviceMap.get(g)&&(this.localParticipant.activeDeviceMap.set(g,f),this.emit(ne.ActiveDeviceChanged,g,f))}),this.onLocalTrackUnpublished=a=>{var o,c;(o=a.track)===null||o===void 0||o.off(ae.TrackProcessorUpdate,this.onTrackProcessorUpdate),(c=a.track)===null||c===void 0||c.off(ae.Restarted,this.onLocalTrackRestarted),this.emit(ne.LocalTrackUnpublished,a,this.localParticipant)},this.onLocalTrackRestarted=a=>P(this,void 0,void 0,function*(){const o=yield a.getDeviceId(!1),c=Rc(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(ne.ActiveDeviceChanged,c,o))}),this.onLocalConnectionQualityChanged=a=>{this.emit(ne.ConnectionQualityChanged,a,this.localParticipant)},this.onMediaDevicesError=(a,o)=>{this.emit(ne.MediaDevicesError,a,o)},this.onLocalParticipantPermissionsChanged=a=>{this.emit(ne.ParticipantPermissionsChanged,a,this.localParticipant)},this.onLocalChatMessageSent=a=>{this.emit(ne.ChatMessage,a,this.localParticipant)},this.setMaxListeners(100),this.remoteParticipants=new Map,this.sidToIdentity=new Map,this.options=Object.assign(Object.assign({},rb),e),this.log=li((n=this.options.loggerName)!==null&&n!==void 0?n:Rn.Room),this.transcriptionReceivedTimes=new Map,this.options.audioCaptureDefaults=Object.assign(Object.assign({},If),e==null?void 0:e.audioCaptureDefaults),this.options.videoCaptureDefaults=Object.assign(Object.assign({},Df),e==null?void 0:e.videoCaptureDefaults),this.options.publishDefaults=Object.assign(Object.assign({},sb),e==null?void 0:e.publishDefaults),this.maybeCreateEngine(),this.incomingDataStreamManager=new Db,this.outgoingDataStreamManager=new Ub(this.engine,this.log),this.disconnectLock=new sn,this.localParticipant=new Wb("","",this.engine,this.options,this.rpcHandlers,this.outgoingDataStreamManager),this.options.videoCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("videoinput",Oi(this.options.videoCaptureDefaults.deviceId)),this.options.audioCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("audioinput",Oi(this.options.audioCaptureDefaults.deviceId)),!((s=this.options.audioOutput)===null||s===void 0)&&s.deviceId&&this.switchActiveDevice("audiooutput",Oi(this.options.audioOutput.deviceId)).catch(a=>this.log.warn("Could not set audio output: ".concat(a.message),this.logContext)),this.options.e2ee&&this.setupE2EE(),cn()){const a=new AbortController;(r=navigator.mediaDevices)===null||r===void 0||r.addEventListener("devicechange",this.handleDeviceChange,{signal:a.signal}),Bs.cleanupRegistry&&Bs.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 H0(this.options.e2ee),this.e2eeManager.on(Ni.ParticipantEncryptionStatusChanged,(t,n)=>{L0(n)&&(this.isE2EEEnabled=t),this.emit(ne.ParticipantEncryptionStatusChanged,t,n)}),this.e2eeManager.on(Ni.EncryptionError,t=>this.emit(ne.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===st.Disconnected?"":this.roomInfo&&this.roomInfo.sid!==""?this.roomInfo.sid:new Promise((e,t)=>{const n=s=>{s.sid!==""&&(this.engine.off(le.RoomUpdate,n),e(s.sid))};this.engine.on(le.RoomUpdate,n),this.once(ne.Disconnected,()=>{this.engine.off(le.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 wb(this.options),this.engine.on(le.ParticipantUpdate,this.handleParticipantUpdates).on(le.RoomUpdate,this.handleRoomUpdate).on(le.SpeakersChanged,this.handleSpeakersChanged).on(le.StreamStateChanged,this.handleStreamStateUpdate).on(le.ConnectionQualityUpdate,this.handleConnectionQualityUpdate).on(le.SubscriptionError,this.handleSubscriptionError).on(le.SubscriptionPermissionUpdate,this.handleSubscriptionPermissionUpdate).on(le.MediaTrackAdded,(e,t,n)=>{this.onTrackAdded(e,t,n)}).on(le.Disconnected,e=>{this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e)}).on(le.ActiveSpeakersUpdate,this.handleActiveSpeakersUpdate).on(le.DataPacketReceived,this.handleDataPacket).on(le.Resuming,()=>{this.clearConnectionReconcile(),this.isResuming=!0,this.log.info("Resuming signal connection",this.logContext),this.setAndEmitConnectionState(st.SignalReconnecting)&&this.emit(ne.SignalReconnecting)}).on(le.Resumed,()=>{this.registerConnectionReconcile(),this.isResuming=!1,this.log.info("Resumed signal connection",this.logContext),this.updateSubscriptions(),this.emitBufferedEvents(),this.setAndEmitConnectionState(st.Connected)&&this.emit(ne.Reconnected)}).on(le.SignalResumed,()=>{this.bufferedEvents=[],(this.state===st.Reconnecting||this.isResuming)&&this.sendSyncState()}).on(le.Restarting,this.handleRestarting).on(le.SignalRestarted,this.handleSignalRestarted).on(le.Offline,()=>{this.setAndEmitConnectionState(st.Reconnecting)&&this.emit(ne.Reconnecting)}).on(le.DCBufferStatusChanged,(e,t)=>{this.emit(ne.DCBufferStatusChanged,e,t)}).on(le.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(ce.LocalTrackSubscribed,t),this.emitWhenConnected(ne.LocalTrackSubscribed,t,this.localParticipant)}).on(le.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(ne.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 Wt.getInstance().getDevices(e,t)}prepareConnection(e,t){return P(this,void 0,void 0,function*(){if(this.state===st.Disconnected){this.log.debug("prepareConnection to ".concat(e),this.logContext);try{if(yc(new URL(e))&&t){this.regionUrlProvider=new jc(e,t);const n=yield this.regionUrlProvider.getNextBestRegionUrl();n&&this.state===st.Disconnected&&(this.regionUrl=n,yield fetch(Cc(n),{method:"HEAD"}),this.log.debug("prepared connection to ".concat(n),this.logContext))}else yield fetch(Cc(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 Gn({scenario:{case:"speakerUpdate",value:3}});break;case"node-failure":s=new Gn({scenario:{case:"nodeFailure",value:!0}});break;case"server-leave":s=new Gn({scenario:{case:"serverLeave",value:!0}});break;case"migration":s=new Gn({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 Gn({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 Gn({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 Gn({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 ba({reason:wn.CLIENT_INITIATED,action:Is.RECONNECT}))});break;case"subscriber-bandwidth":if(t===void 0||typeof t!="number")throw new Error("subscriber-bandwidth requires a number as argument");s=new Gn({scenario:{case:"subscriberBandwidth",value:cs(t)}});break;case"leave-full-reconnect":s=new Gn({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===Z.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===Z.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,!_c()&&!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 Wt.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(ne.ActiveDeviceChanged,n,s)),g}()})}setupLocalParticipantEvents(){this.localParticipant.on(ce.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).on(ce.ParticipantNameChanged,this.onLocalParticipantNameChanged).on(ce.AttributesChanged,this.onLocalAttributesChanged).on(ce.TrackMuted,this.onLocalTrackMuted).on(ce.TrackUnmuted,this.onLocalTrackUnmuted).on(ce.LocalTrackPublished,this.onLocalTrackPublished).on(ce.LocalTrackUnpublished,this.onLocalTrackUnpublished).on(ce.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).on(ce.MediaDevicesError,this.onMediaDevicesError).on(ce.AudioStreamAcquired,this.startAudio).on(ce.ChatMessage,this.onLocalChatMessageSent).on(ce.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===st.Connecting||this.state===st.Reconnecting){const u=()=>{this.onTrackAdded(e,t,n),h()},h=()=>{this.off(ne.Reconnected,u),this.off(ne.Connected,u),this.off(ne.Disconnected,h)};this.once(ne.Reconnected,u),this.once(ne.Connected,u),this.once(ne.Disconnected,h);return}if(this.state===st.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=_0(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(ne.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!==st.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(ce.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).off(ce.ParticipantNameChanged,this.onLocalParticipantNameChanged).off(ce.AttributesChanged,this.onLocalAttributesChanged).off(ce.TrackMuted,this.onLocalTrackMuted).off(ce.TrackUnmuted,this.onLocalTrackUnmuted).off(ce.LocalTrackPublished,this.onLocalTrackPublished).off(ce.LocalTrackUnpublished,this.onLocalTrackUnpublished).off(ce.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).off(ce.MediaDevicesError,this.onMediaDevicesError).off(ce.AudioStreamAcquired,this.startAudio).off(ce.ChatMessage,this.onLocalChatMessageSent).off(ce.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),cn()&&(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(st.Disconnected),this.emit(ne.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(ne.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,At.builtIn("UNSUPPORTED_VERSION"));return}const o=this.rpcHandlers.get(n);if(!o){yield this.engine.publishRpcResponse(e,t,null,At.builtIn("UNSUPPORTED_METHOD"));return}let c=null,l=null;try{const d=yield o({requestId:t,callerIdentity:e,payload:s,responseTimeout:r});Bc(d)>Lf?(c=At.builtIn("RESPONSE_PAYLOAD_TOO_LARGE"),console.warn("RPC Response payload too large for ".concat(n))):l=d}catch(d){d instanceof At?c=d:(console.warn("Uncaught error returned by RPC handler for ".concat(n,". Returning APPLICATION_ERROR instead."),d),c=At.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=Wt.getInstance().previousDevices,r=yield Wt.getInstance().getDevices(void 0,!1),a=fn();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(ne.ActiveDeviceChanged,c.kind,c.deviceId)}const o=["audiooutput","audioinput","videoinput"];for(let c of o){const l=U0(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"&&!Ir()||c==="videoinput"||u.length>0&&!u.find(f=>f.deviceId===this.getActiveDevice(c))&&(c!=="audiooutput"||!Ir())&&(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=_f())!==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(),on(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(ne.AudioPlaybackStatusChanged,n))})}createParticipant(e,t){var n;let s;return t?s=Na.fromParticipantInfo(this.engine.client,t,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}):s=new Na(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(ne.ParticipantConnected,n),n.on(ce.TrackPublished,s=>{this.emitWhenConnected(ne.TrackPublished,s,n)}).on(ce.TrackSubscribed,(s,r)=>{s.kind===Z.Kind.Audio?(s.on(ae.AudioPlaybackStarted,this.handleAudioPlaybackStarted),s.on(ae.AudioPlaybackFailed,this.handleAudioPlaybackFailed)):s.kind===Z.Kind.Video&&(s.on(ae.VideoPlaybackFailed,this.handleVideoPlaybackFailed),s.on(ae.VideoPlaybackStarted,this.handleVideoPlaybackStarted)),this.emit(ne.TrackSubscribed,s,r,n)}).on(ce.TrackUnpublished,s=>{this.emit(ne.TrackUnpublished,s,n)}).on(ce.TrackUnsubscribed,(s,r)=>{this.emit(ne.TrackUnsubscribed,s,r,n)}).on(ce.TrackMuted,s=>{this.emitWhenConnected(ne.TrackMuted,s,n)}).on(ce.TrackUnmuted,s=>{this.emitWhenConnected(ne.TrackUnmuted,s,n)}).on(ce.ParticipantMetadataChanged,s=>{this.emitWhenConnected(ne.ParticipantMetadataChanged,s,n)}).on(ce.ParticipantNameChanged,s=>{this.emitWhenConnected(ne.ParticipantNameChanged,s,n)}).on(ce.AttributesChanged,s=>{this.emitWhenConnected(ne.ParticipantAttributesChanged,s,n)}).on(ce.ConnectionQualityChanged,s=>{this.emitWhenConnected(ne.ConnectionQualityChanged,s,n)}).on(ce.ParticipantPermissionsChanged,s=>{this.emitWhenConnected(ne.ParticipantPermissionsChanged,s,n)}).on(ce.TrackSubscriptionStatusChanged,(s,r)=>{this.emitWhenConnected(ne.TrackSubscriptionStatusChanged,s,r,n)}).on(ce.TrackSubscriptionFailed,(s,r)=>{this.emit(ne.TrackSubscriptionFailed,s,n,r)}).on(ce.TrackSubscriptionPermissionChanged,(s,r)=>{this.emitWhenConnected(ne.TrackSubscriptionPermissionChanged,s,r,n)}).on(ce.Active,()=>{this.emitWhenConnected(ne.ParticipantActive,n),n.kind===Mr.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&&D0(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=$t.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,wn.STATE_MISMATCH))):e=0},jb)}clearConnectionReconcile(){this.connectionReconcileInterval&&$t.clearInterval(this.connectionReconcileInterval)}setAndEmitConnectionState(e){return e===this.state?!1:(this.state=e,this.emit(ne.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===st.Reconnecting||this.isResuming||!this.engine||this.engine.pendingReconnect)this.bufferedEvents.push([e,n]);else if(this.state===st.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 ma({sid:"RM_SIMULATED",name:"simulated-room",emptyTimeout:0,maxParticipants:0,creationTime:Et.parse(new Date().getTime()),metadata:"",numParticipants:1,numPublishers:1,turnPassword:"",enabledCodecs:[],activeRecording:!1}),this.localParticipant.updateInfo(new ns({identity:"simulated-local",name:"local-name"})),this.setupLocalParticipantEvents(),this.emit(ne.SignalConnected),this.emit(ne.Connected),this.setAndEmitConnectionState(st.Connected),s.video){const a=new Kc(Z.Kind.Video,new ks({source:Lt.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:Mn.AUDIO,name:"video-dummy"}),new Da(s.useRealTracks?(yield window.navigator.mediaDevices.getUserMedia({video:!0})).getVideoTracks()[0]:mf(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(ce.LocalTrackPublished,a)}if(s.audio){const a=new Kc(Z.Kind.Audio,new ks({source:Lt.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:Mn.AUDIO}),new Ia(s.useRealTracks?(yield navigator.mediaDevices.getUserMedia({audio:!0})).getAudioTracks()[0]:Tc(),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(ce.LocalTrackPublished,a)}for(let a=0;a<r.count-1;a+=1){let o=new ns({sid:Math.floor(Math.random()*1e4).toString(),identity:"simulated-".concat(a),state:Ps.ACTIVE,tracks:[],joinedAt:Et.parse(Date.now())});const c=this.getOrCreateParticipant(o.identity,o);if(r.video){const l=mf(160*((n=r.aspectRatios[a%r.aspectRatios.length])!==null&&n!==void 0?n:1),160,!1,!0),d=new ks({source:Lt.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:Mn.AUDIO});c.addSubscribedMediaTrack(l,d.sid,new MediaStream([l]),new RTCRtpReceiver),o.tracks=[...o.tracks,d]}if(r.audio){const l=Tc(),d=new ks({source:Lt.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:Mn.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!==ne.ActiveSpeakersChanged&&e!==ne.TranscriptionReceived){const r=Yf(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)}}Bs.cleanupRegistry=typeof FinalizationRegistry<"u"&&new FinalizationRegistry(i=>{i()});function Yf(i){return i.map(e=>{if(e)return Array.isArray(e)?Yf(e):typeof e=="object"?"logContext"in e?e.logContext:void 0:e})}var Dn;(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"})(Dn||(Dn={}));class Gi extends Hn.EventEmitter{constructor(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.status=Dn.IDLE,this.logs=[],this.options={},this.url=e,this.token=t,this.name=this.constructor.name,this.room=new Bs(n.roomOptions),this.connectOptions=n.connectOptions,this.options=n}run(e){return P(this,void 0,void 0,function*(){if(this.status!==Dn.IDLE)throw Error("check is running already");this.setStatus(Dn.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!==Dn.SKIPPED&&this.setStatus(this.isSuccess()?Dn.SUCCESS:Dn.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===st.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!==st.Disconnected&&(yield this.room.disconnect(),yield new Promise(e=>setTimeout(e,500)))})}skip(){this.setStatus(Dn.SKIPPED)}switchProtocol(e){return P(this,void 0,void 0,function*(){let t=!1,n=!1;if(this.room.on(ne.Reconnecting,()=>{t=!0}),this.room.once(ne.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 on(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 $b extends Gi{get description(){return"Cloud regions"}perform(){return P(this,void 0,void 0,function*(){const e=new jc(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 Yc=1e4;class Xb extends Gi{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/(Yc/1e3)*100).toFixed(2),"%")),n.qualityLimitationDurations.cpu>0&&this.appendWarning("cpu limited ".concat((n.qualityLimitationDurations.cpu/(Yc/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,Yc)),clearInterval(u),o.stop(),t.remove(),yield this.disconnect(),d})}}class Kb extends Gi{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 bf(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 Yb extends Gi{get description(){return"Can publish video"}perform(){return P(this,void 0,void 0,function*(){var e;const t=yield this.connect(),n=yield Vb();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 Jb extends Gi{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(ne.SignalReconnecting,o).on(ne.Reconnecting,o).on(ne.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!==st.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 Zb extends Gi{get description(){return"Can connect via TURN"}perform(){return P(this,void 0,void 0,function*(){var e,t;const n=new kc,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 Qb extends Gi{get description(){return"Establishing WebRTC connection"}perform(){return P(this,void 0,void 0,function*(){let e=!1,t=!1;this.room.on(ne.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&&(e_(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 e_(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 t_ extends Gi{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 kc;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)===Xu.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 lE extends Hn.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:Dn.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!==Dn.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(t_)})}checkWebRTC(){return P(this,void 0,void 0,function*(){return this.createAndRunCheck(Qb)})}checkTURN(){return P(this,void 0,void 0,function*(){return this.createAndRunCheck(Zb)})}checkReconnect(){return P(this,void 0,void 0,function*(){return this.createAndRunCheck(Jb)})}checkPublishAudio(){return P(this,void 0,void 0,function*(){return this.createAndRunCheck(Kb)})}checkPublishVideo(){return P(this,void 0,void 0,function*(){return this.createAndRunCheck(Yb)})}checkConnectionProtocol(){return P(this,void 0,void 0,function*(){const e=yield this.createAndRunCheck(Xb);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($b)})}}class Jc extends EventTarget{constructor(){super(),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.audioElements=new Map,this.audioContainer=null,this.wasConnectedBeforeHidden=!1,this.isPageVisible=!0,this.reconnectAttempts=0,this.maxReconnectAttempts=3,this.isReconnecting=!1,this.isDestroyed=!1,this.pendingTimers=new Set,this.isAppleDevice=/iPhone|iPad|iPod|Macintosh|Mac OS/i.test(navigator.userAgent),this.boundHandleVisibilityChange=this.handleVisibilityChange.bind(this),this.boundHandlePageHide=this.handlePageHide.bind(this),this.boundHandlePageShow=this.handlePageShow.bind(this),this.boundHandleOnline=this.handleOnline.bind(this),this.boundHandleOffline=this.handleOffline.bind(this),this.createAudioContainer(),this.setupLifecycleListeners()}createAudioContainer(){this.audioContainer=document.createElement("div"),this.audioContainer.id=`livekit-audio-${Date.now()}-${Math.random().toString(36).slice(2,9)}`,this.audioContainer.style.cssText="position:absolute;width:0;height:0;overflow:hidden;pointer-events:none;",document.body.appendChild(this.audioContainer)}scheduleTimer(e,t){const n=setTimeout(()=>{this.pendingTimers.delete(n),this.isDestroyed||e()},t);return this.pendingTimers.add(n),n}clearAllTimers(){this.pendingTimers.forEach(e=>clearTimeout(e)),this.pendingTimers.clear()}setupLifecycleListeners(){document.addEventListener("visibilitychange",this.boundHandleVisibilityChange),window.addEventListener("pagehide",this.boundHandlePageHide),window.addEventListener("pageshow",this.boundHandlePageShow),window.addEventListener("online",this.boundHandleOnline),window.addEventListener("offline",this.boundHandleOffline)}removeLifecycleListeners(){document.removeEventListener("visibilitychange",this.boundHandleVisibilityChange),window.removeEventListener("pagehide",this.boundHandlePageHide),window.removeEventListener("pageshow",this.boundHandlePageShow),window.removeEventListener("online",this.boundHandleOnline),window.removeEventListener("offline",this.boundHandleOffline)}handleVisibilityChange(){var t;const e=this.isPageVisible;this.isPageVisible=document.visibilityState==="visible",!this.isPageVisible&&e?(console.log("[LiveKit] Page hidden, pausing media"),this.wasConnectedBeforeHidden=((t=this.room)==null?void 0:t.state)==="connected",this.pauseAllAudio()):this.isPageVisible&&!e&&(console.log("[LiveKit] Page visible, resuming"),this.resumeAfterVisibilityChange())}handlePageHide(e){e.persisted||this.cleanupBeforeUnload()}handlePageShow(e){e.persisted&&(console.log("[LiveKit] Page restored from cache"),this.resumeAfterVisibilityChange())}handleOnline(){var e;console.log("[LiveKit] Network online"),this.wasConnectedBeforeHidden&&((e=this.room)==null?void 0:e.state)!=="connected"&&this.attemptReconnect()}handleOffline(){console.log("[LiveKit] Network offline")}pauseAllAudio(){this.audioElements.forEach(e=>{try{e.pause()}catch(t){console.warn("[LiveKit] Failed to pause audio:",t)}})}async resumeAllAudio(){for(const[,e]of this.audioElements)try{await e.play()}catch(t){console.warn("[LiveKit] Failed to resume audio (may need user interaction):",t),this.audioPlaybackPrompt=!0,this.dispatchEvent(new CustomEvent("audio-playback-status-changed",{detail:{canPlayback:!1}}))}}async resumeAfterVisibilityChange(){this.room&&(this.room.state==="connected"?await this.resumeAllAudio():this.wasConnectedBeforeHidden&&(console.log("[LiveKit] Connection lost while hidden, attempting reconnect"),this.attemptReconnect()))}async attemptReconnect(){var e;if(this.isReconnecting){console.log("[LiveKit] Reconnect already in progress, skipping");return}if(this.reconnectAttempts>=this.maxReconnectAttempts){console.error("[LiveKit] Max reconnect attempts reached"),this.cleanupRoom(),this.dispatchEvent(new CustomEvent("error",{detail:{error:"Connection lost. Please restart the call."}}));return}this.isReconnecting=!0,this.reconnectAttempts++,console.log(`[LiveKit] Reconnect attempt ${this.reconnectAttempts}/${this.maxReconnectAttempts}`);try{((e=this.room)==null?void 0:e.state)==="disconnected"&&(this.cleanupRoom(),this.dispatchEvent(new CustomEvent("error",{detail:{error:"Connection lost. Please restart the call."}})))}finally{this.isReconnecting=!1}}cleanupRoom(){if(this.room){try{this.room.disconnect()}catch(e){console.warn("[LiveKit] Error disconnecting room during cleanup:",e)}this.room=null}this.cleanupAudioElements()}cleanupBeforeUnload(){this.room&&(this.room.disconnect(),this.room=null),this.cleanupAudioElements()}cleanupAudioElements(){this.audioElements.forEach((e,t)=>{try{e.pause(),e.srcObject=null,e.remove()}catch(n){console.warn("[LiveKit] Failed to cleanup audio element:",n)}this.audioElements.delete(t)})}removeAudioContainer(){if(this.audioContainer){try{this.audioContainer.remove()}catch(e){console.warn("[LiveKit] Failed to remove audio container:",e)}this.audioContainer=null}}destroy(){if(this.isDestroyed=!0,this.clearAllTimers(),this.removeLifecycleListeners(),this.cleanupAudioElements(),this.removeAudioContainer(),this.room){try{this.room.disconnect()}catch(e){console.warn("[LiveKit] Error disconnecting room during destroy:",e)}this.room=null}}async playAudioElement(e){try{if(!e.paused)return!0;const t=e.play();return t!==void 0&&await t,!0}catch(t){return t instanceof Error&&t.name==="NotAllowedError"?(console.log("[LiveKit] Autoplay blocked, user interaction required"),!1):t instanceof Error&&t.name==="AbortError"?(console.log("[LiveKit] Play interrupted"),!1):(console.warn("[LiveKit] Failed to play audio:",t),!1)}}async fetchWithTimeout(e,t,n=15e3){const s=new AbortController,r=setTimeout(()=>s.abort(),n);try{return await fetch(e,{...t,signal:s.signal})}finally{clearTimeout(r)}}async connectWithTimeout(e,t,n,s=2e4){return new Promise((r,a)=>{const o=setTimeout(()=>{a(new Error("Connection timeout"))},s);e.connect(t,n).then(()=>{clearTimeout(o),r()}).catch(c=>{clearTimeout(o),a(c)})})}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.callStatus=e,this.dispatchEvent(new CustomEvent("status-changed",{detail:e})))}async makeCall({agentId:e}){if(this.room&&this.room.state==="connected")return;let t=null;try{t=await navigator.mediaDevices.getUserMedia({audio:!0,video:!1}),console.log("Microphone permission granted")}catch(n){console.warn("Microphone permission denied or not available:",n)}this.updateStatus("connecting"),this.error=null,this.isReady=!1,this.room&&(await this.room.disconnect(),this.room=null);try{const n=new Bs({webAudioMix:!0});this.room=n,this.setupRoomEventListeners(n);let s;try{s=await this.fetchWithTimeout(`${this.serviceUrl}/create-room-token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({metadata:{agent_id:e,timestamp:Date.now(),is_apple_device:this.isAppleDevice}})},15e3)}catch(l){throw l instanceof Error&&l.name==="AbortError"?new Error("Request timeout - please check your connection"):l}if(!s.ok){const l=await s.text();throw new Error(`Failed to get room token: ${s.status} ${l}`)}const{token:r,url:a,room_name:o,user_identity:c}=await s.json();this.roomName=o,this.userIdentity=c,this.reconnectAttempts=0,this.wasConnectedBeforeHidden=!1,await this.connectWithTimeout(n,a,r,2e4),this.updateStatus("connected"),this.isReady=!0,requestAnimationFrame(()=>{this.scheduleTimer(async()=>{if(this.isDestroyed||!this.room||this.room.state!=="connected"){t&&t.getTracks().forEach(l=>l.stop());return}if(t)try{const l=!this.isAppleDevice;await n.localParticipant.setMicrophoneEnabled(!0,{echoCancellation:l,noiseSuppression:l,autoGainControl:l}),this.microphoneEnabled=!0,this.dispatchEvent(new CustomEvent("microphone-enabled")),t.getTracks().forEach(d=>d.stop()),this.scheduleTimer(()=>{if(!(this.isDestroyed||!this.room||this.room.state!=="connected"))try{const d=Array.from(n.localParticipant.audioTrackPublications.values()).find(u=>u.kind==="audio");if(d!=null&&d.track){const u=d.track.mediaStreamTrack;u&&this.dispatchEvent(new CustomEvent("local-audio-track",{detail:u}))}}catch(d){console.warn("[LiveKit] Error getting local audio track:",d)}},100)}catch(l){console.warn("Could not enable microphone on connect:",l),this.microphoneEnabled=!1,this.dispatchEvent(new CustomEvent("microphone-disabled"))}else this.microphoneEnabled=!1,this.dispatchEvent(new CustomEvent("microphone-disabled"))},50)}),this.dispatchEvent(new CustomEvent("room-connected",{detail:{roomName:o,identity:c}}))}catch(n){t&&t.getTracks().forEach(s=>s.stop()),this.error=`Connection failed: ${n instanceof Error?n.message:String(n)}`,this.updateStatus("error"),this.isReady=!1,this.room=null,this.dispatchEvent(new CustomEvent("error",{detail:{error:this.error}}))}}setupRoomEventListeners(e){e.on(ne.Connected,()=>{this.updateStatus("connected"),this.isReady=!0,this.reconnectAttempts=0}),e.on(ne.Disconnected,()=>{this.updateStatus("disconnected"),this.connectedParticipants=[],this.microphoneEnabled=!1,this.audioPlaybackPrompt=!1,this.room=null,this.isReady=!1,this.cleanupAudioElements(),this.dispatchEvent(new CustomEvent("disconnected"))}),e.on(ne.Reconnecting,()=>{console.log("[LiveKit] Reconnecting..."),this.dispatchEvent(new CustomEvent("status-changed",{detail:"connecting"}))}),e.on(ne.Reconnected,()=>{console.log("[LiveKit] Reconnected successfully"),this.reconnectAttempts=0,this.isReconnecting=!1,this.resumeAllAudio().catch(t=>{console.warn("[LiveKit] Failed to resume audio after reconnect:",t)}),this.dispatchEvent(new CustomEvent("status-changed",{detail:"connected"}))}),e.on(ne.SignalReconnecting,()=>{console.log("[LiveKit] Signal reconnecting...")}),e.on(ne.ParticipantConnected,t=>{this.connectedParticipants=[...this.connectedParticipants,t.identity];const n=t.identity.includes("agent")||t.identity.includes("voice-assistant")||t.identity.includes("AJ_");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(ne.ParticipantDisconnected,t=>{this.connectedParticipants=this.connectedParticipants.filter(s=>s!==t.identity);const n=t.identity.includes("agent")||t.identity.includes("voice-assistant")||t.identity.includes("AJ_");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(ne.TrackSubscribed,(t,n,s)=>{if(t.kind==="audio"){const r=this.audioElements.get(s.identity);if(r){try{r.pause(),r.srcObject=null,r.remove()}catch(c){console.warn("[LiveKit] Failed to remove existing audio element:",c)}this.audioElements.delete(s.identity)}const a=t.attach();a.setAttribute("playsinline","true"),a.setAttribute("webkit-playsinline","true"),a.dataset.participantId=s.identity,this.isAppleDevice&&(a.volume=.8),this.audioContainer?this.audioContainer.appendChild(a):(console.warn("[LiveKit] Audio container not found, appending to body"),document.body.appendChild(a)),this.audioElements.set(s.identity,a),this.playAudioElement(a).then(c=>{c||(this.audioPlaybackPrompt=!0,this.dispatchEvent(new CustomEvent("audio-playback-status-changed",{detail:{canPlayback:!1}})))}),this.dispatchEvent(new CustomEvent("audio-track-added",{detail:{participant:s.identity,element:a}}));const o=t.mediaStreamTrack;o&&this.dispatchEvent(new CustomEvent("audio-track",{detail:o}))}}),e.on(ne.TrackUnsubscribed,(t,n,s)=>{const r=this.audioElements.get(s.identity);r&&(r.pause(),r.srcObject=null,r.remove(),this.audioElements.delete(s.identity)),t.detach(),this.dispatchEvent(new CustomEvent("audio-track-removed",{detail:{participant:s.identity}}))}),e.on(ne.MediaDevicesError,t=>{this.error=`Media device error: ${t.message}`,this.updateStatus("error"),this.dispatchEvent(new CustomEvent("error",{detail:{error:this.error}}))}),e.on(ne.AudioPlaybackStatusChanged,async()=>{e.canPlaybackAudio||this.connectedParticipants.some(n=>n.includes("agent")||n.includes("voice-assistant")||n.includes("AJ_"))&&!this.audioPlaybackPrompt&&(this.updateStatus("agent-connected"),this.audioPlaybackPrompt=!0),this.dispatchEvent(new CustomEvent("audio-playback-status-changed",{detail:{canPlayback:e.canPlaybackAudio}}))})}async toggleMicrophone(){if(this.room)try{if(this.microphoneEnabled)await this.room.localParticipant.setMicrophoneEnabled(!1),this.microphoneEnabled=!1,this.dispatchEvent(new CustomEvent("microphone-disabled"));else{const e=!this.isAppleDevice;await this.room.localParticipant.setMicrophoneEnabled(!0,{echoCancellation:e,noiseSuppression:e,autoGainControl:e}),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}}))}}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.wasConnectedBeforeHidden=!1,this.reconnectAttempts=0,this.isReconnecting=!1,this.cleanupAudioElements(),this.updateStatus("disconnected"),this.dispatchEvent(new CustomEvent("call-ended")),this.scheduleTimer(async()=>{try{await e.disconnect()}catch(t){console.warn("Error during room disconnect:",t)}},0)}}class n_ extends EventTarget{constructor(){super(...arguments),this._status="unknown",this.intervalId=null,this._serviceUrl="",this.INTERVAL_MS=3e4,this.TIMEOUT_MS=5e3,this.refCount=0}get isHealthy(){return this._status!=="unhealthy"}get status(){return this._status}set serviceUrl(e){this._serviceUrl!==e&&(this._serviceUrl=e,this.intervalId!==null&&this.check())}get serviceUrl(){return this._serviceUrl}start(){this.refCount++,this.intervalId===null&&(this.check(),this.intervalId=setInterval(()=>this.check(),this.INTERVAL_MS))}stop(){this.refCount=Math.max(0,this.refCount-1),!(this.refCount>0)&&(this.intervalId!==null&&(clearInterval(this.intervalId),this.intervalId=null),this._status="unknown")}async check(){if(!this._serviceUrl){this.updateStatus("unknown");return}try{const e=new AbortController,t=setTimeout(()=>e.abort(),this.TIMEOUT_MS),n=await fetch(`${this._serviceUrl}/health`,{method:"GET",signal:e.signal});clearTimeout(t),this.updateStatus(n.ok?"healthy":"unhealthy")}catch{this.updateStatus("unhealthy")}}updateStatus(e){this._status!==e&&(this._status=e,this.dispatchEvent(new CustomEvent("health-changed",{detail:e})))}}const Hi=new n_;class Zc{get isHealthy(){return Hi.isHealthy}get status(){return Hi.status}set serviceUrl(e){Hi.serviceUrl=e}get serviceUrl(){return Hi.serviceUrl}start(){Hi.start()}stop(){Hi.stop()}addEventListener(e,t){e==="health-changed"&&Hi.addEventListener(e,t)}removeEventListener(e,t){e==="health-changed"&&Hi.removeEventListener(e,t)}}/**
84
+ `},Nc}var Af;function eb(){if(Af)return In;Af=1;var i=Z0(),e=Q0(),t=Lc();return In.grammar=t,In.write=e,In.parse=i.parse,In.parseParams=i.parseParams,In.parseFmtpConfig=i.parseFmtpConfig,In.parsePayloads=i.parsePayloads,In.parseRemoteCandidates=i.parseRemoteCandidates,In.parseImageAttributes=i.parseImageAttributes,In.parseSimulcastStreamList=i.parseSimulcastStreamList,In}var Vi=eb();function Uc(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 tb=.7,nb=20,Os={NegotiationStarted:"negotiationStarted",NegotiationComplete:"negotiationComplete",RTPVideoPayloadTypes:"rtpVideoPayloadTypes"};class Rf extends Wn.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=Uc(s=>P(this,void 0,void 0,function*(){this.emit(Os.NegotiationStarted);try{yield this.createAndSendOffer()}catch(r){if(s)s(r);else throw r}}),nb),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=li((n=t.loggerName)!==null&&n!==void 0?n:Pn.PCTransport),this.loggerOptions=t,this.config=e,this._pc=this.createPC(),this.offerLock=new sn}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}=ib(e);this.remoteStereoMids=r,this.remoteNackMids=a}else if(e.type==="answer"){const r=Vi.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=Vi.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(Os.NegotiationComplete),e.sdp&&Vi.parse(e.sdp).media.forEach(a=>{a.type==="video"&&this.emit(Os.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=Vi.parse((t=r.sdp)!==null&&t!==void 0?t:"");if(a.media.forEach(o=>{kf(o),o.type==="audio"?Pf(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||(qn(c.codec)&&!os()&&this.ensureVideoDDExtensionForSVC(o,a),c.codec!=="av1"))return!0;const d=Math.round(c.maxbr*tb);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,Vi.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=Vi.parse((e=t.sdp)!==null&&e!==void 0?e:"");return n.media.forEach(s=>{kf(s),s.type==="audio"&&Pf(s,this.remoteStereoMids,this.remoteNackMids)}),yield this.setMungedSDP(t,Vi.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 Bt("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 Bt("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 uc(r)}})}ensureVideoDDExtensionForSVC(e,t){var n,s;if(!((n=e.ext)===null||n===void 0?void 0:n.some(a=>a.uri===cf))){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:cf})}}}function Pf(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 ib(i){var e;const t=[],n=[],s=Vi.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 kf(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 Oc="vp8",sb={audioPreset:pc.music,dtx:!0,red:!0,forceStereo:!1,simulcast:!0,screenShareEncoding:gc.h1080fps15.encoding,stopMicTrackOnMute:!1,videoCodec:Oc,backupCodec:!0,preConnectBuffer:!1},If={deviceId:{ideal:"default"},autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0,voiceIsolation:!0},Df={deviceId:{ideal:"default"},resolution:kr.h720.resolution},rb={adaptiveStream:!1,dynacast:!1,stopLocalTrackOnUnpublish:!0,reconnectPolicy:new jv,disconnectOnPageLeave:!0,webAudioMix:!1},Fc={autoSubscribe:!0,maxRetries:1,peerConnectionTimeout:15e3,websocketTimeout:15e3};var wt;(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"})(wt||(wt={}));class ab{get needsPublisher(){return this.isPublisherConnectionRequired}get needsSubscriber(){return this.isSubscriberConnectionRequired}get currentState(){return this.state}constructor(e,t,n){var s;this.peerConnectionTimeout=Fc.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=wt.CONNECTED:o.some(c=>c==="failed")?this.state=wt.FAILED:o.some(c=>c==="connecting")?this.state=wt.CONNECTING:o.every(c=>c==="closed")?this.state=wt.CLOSED:o.some(c=>c==="closed")?this.state=wt.CLOSING:o.every(c=>c==="new")&&(this.state=wt.NEW),a!==this.state&&(this.log.debug("pc state change: from ".concat(wt[a]," to ").concat(wt[this.state]),this.logContext),(r=this.onStateChange)===null||r===void 0||r.call(this,this.state,this.publisher.getConnectionState(),this.subscriber.getConnectionState()))},this.log=li((s=n.loggerName)!==null&&s!==void 0?s:Pn.PCManager),this.loggerOptions=n,this.isPublisherConnectionRequired=!t,this.isSubscriberConnectionRequired=t,this.publisher=new Rf(e,n),this.subscriber=new Rf(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,Rn.PUBLISHER)},this.subscriber.onIceCandidate=r=>{var a;(a=this.onIceCandidate)===null||a===void 0||a.call(this,r,Rn.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=wt.NEW,this.connectionLock=new sn,this.remoteOfferLock=new sn}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===Rn.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(Os.NegotiationStarted,()=>{e.signal.aborted||this.publisher.once(Os.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===Rn.PUBLISHER?this.publisher.getConnectedAddress():e===Rn.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),$t.clearTimeout(u),l(new vt("room connection has been cancelled",Je.Cancelled))};s!=null&&s.signal.aborted&&d(),s==null||s.signal.addEventListener("abort",d);const u=$t.setTimeout(()=>{s==null||s.signal.removeEventListener("abort",d),l(new vt("could not establish pc connection",Je.InternalError))},a);for(;this.state!==wt.CONNECTED;)if(yield on(50),s!=null&&s.signal.aborted){l(new vt("room connection has been cancelled",Je.Cancelled));return}$t.clearTimeout(u),s==null||s.signal.removeEventListener("abort",d),c()}))}()})}}class At extends Error{constructor(e,t,n){super(t),this.code=e,this.message=Nf(t,At.MAX_MESSAGE_BYTES),this.data=n?Nf(n,At.MAX_DATA_BYTES):void 0}static fromProto(e){return new At(e.code,e.message,e.data)}toProto(){return new qu({code:this.code,message:this.message,data:this.data})}static builtIn(e,t){return new At(At.ErrorCode[e],At.ErrorMessage[e],t)}}At.MAX_MESSAGE_BYTES=256,At.MAX_DATA_BYTES=15360,At.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},At.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 Lf=15360;function Bc(i){return new TextEncoder().encode(i).length}function Nf(i,e){if(Bc(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 Vc=2e3;function ka(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 zc=typeof MediaRecorder<"u";class ob{constructor(){throw new Error("MediaRecorder is not available in this environment")}}const cb=zc?MediaRecorder:ob;class lb extends cb{constructor(e,t){if(!zc)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 db(){return zc}const ub=1e3,hb=1e4;class Uf extends Z{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=Uc(()=>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(ae.Ended,this)},this.reacquireTrack=!1,this.providedByUser=s,this.muteLock=new sn,this.pauseUpstreamLock=new sn,this.trackChangeLock=new sn,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!==Z.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=>{Ns(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&&(Ls(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=>{Ls(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]:ub;return function*(){var n;if(e.kind===Z.Kind.Audio)throw new Error("cannot get dimensions for audio tracks");((n=fn())===null||n===void 0?void 0:n.os)==="iOS"&&(yield on(10));const s=Date.now();for(;Date.now()-s<t;){const r=e.dimensions;if(r)return r;yield on(50)}throw new hi("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===Oi(e)||(this._constraints.deviceId=e,this.isMuted)?!0:(yield this.restartTrack(),Oi(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===Z.Source.ScreenShare)return;const{deviceId:n,groupId:s}=e._mediaStreamTrack.getSettings(),r=e.kind===Z.Kind.Audio?"audioinput":"videoinput";return t?Wt.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 hi("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=$v(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===Z.Kind.Video?a.video=n||s?{deviceId:n,facingMode:s}:!0:a.audio=n?Object.assign({deviceId:n},r):!0,this.attachedElements.forEach(l=>{Ns(this.mediaStreamTrack,l)}),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.stop();const c=(yield navigator.mediaDevices.getUserMedia(a)).getTracks()[0];return this.kind===Z.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(ae.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?ae.Muted:ae.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),lf()&&(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(ae.UpstreamPaused,this);const n=fn();if((n==null?void 0:n.name)==="Safari"&&$n(n.version,"12.0")<0)throw new dc("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(ae.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(Ls(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&&(Ns(n._mediaStreamTrack,l),Ls(n.processor.processedTrack,l));yield(r=n.sender)===null||r===void 0?void 0:r.replaceTrack(n.processor.processedTrack)}n.emit(ae.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(ae.TrackProcessorUpdate))}()})}startPreConnectBuffer(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:100;if(!db()){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 lb(this,{mimeType:t})}this.localTrackRecorder.start(e),this.autoStopPreConnectBuffer=setTimeout(()=>{this.log.warn("preconnect buffer timed out, stopping recording automatically",this.logContext),this.stopPreConnectBuffer()},hb)}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 Ia extends Uf{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,Z.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=ka(a,this.prevStats)),this.prevStats=a}),this.handleKrispNoiseFilterEnable=()=>{this.isKrispNoiseFilterEnabled=!0,this.log.debug("Krisp noise filter enabled",this.logContext),this.emit(ae.AudioTrackFeatureUpdate,this,Ht.TF_ENHANCED_NOISE_CANCELLATION,!0)},this.handleKrispNoiseFilterDisable=()=>{this.isKrispNoiseFilterEnabled=!1,this.log.debug("Krisp noise filter disabled",this.logContext),this.emit(ae.AudioTrackFeatureUpdate,this,Ht.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===Z.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!==Oi(this._constraints.deviceId);return this.source===Z.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=Ac({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(){cn()&&(this.monitorInterval||(this.monitorInterval=setInterval(()=>{this.monitorSender()},Vc)))}setProcessor(e){return P(this,void 0,void 0,function*(){var t;const n=yield this.trackChangeLock.lock();try{if(!jn()&&!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(ae.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 bf(this);return e&&(this.isMuted||this.log.warn("silence detected on local audio track",this.logContext),this.emit(ae.AudioSilenceDetected)),e})}}function fb(i,e,t){switch(i.kind){case"audio":return new Ia(i,e,!1,void 0,t);case"video":return new Da(i,e,!1,t);default:throw new hi("unsupported track type: ".concat(i.kind))}}const pb=Object.values(kr),mb=Object.values(mc),gb=Object.values(gc),vb=[kr.h180,kr.h360],bb=[mc.h180,mc.h360],_b=i=>[{scaleResolutionDownBy:2,fps:i.encoding.maxFramerate}].map(t=>{var n,s;return new ut(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)}),Gc=["q","h","f"];function Hc(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=Sb(i,e,t,l),Ke.debug("using video encoding",a));const d=a.maxFramerate,u=new ut(e,t,a.maxBitrate,a.maxFramerate,a.priority);if(c&&qn(l)){const g=new Bf(c),v=[];if(g.spatial>3)throw new Error("unsupported scalabilityMode: ".concat(c));const m=fn();if(Ir()||jn()||(m==null?void 0:m.name)==="Chrome"&&$n(m==null?void 0:m.version,"113")<0){const p=g.suffix=="h"?2:3,x=C0(m);for(let C=0;C<g.spatial;C+=1)v.push({rid:Gc[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=Ff(n==null?void 0:n.screenShareSimulcastLayers))!==null&&s!==void 0?s:Of(i,u):h=(r=Ff(n==null?void 0:n.videoSimulcastLayers))!==null&&r!==void 0?r:Of(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 Wc(e,t,[g,f,u],d);if(v>=480)return Wc(e,t,[g,u],d)}return Wc(e,t,[u])}function yb(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===Z.Source.ScreenShare&&t.simulcast&&(t.simulcast=!1),Hc(i.source===Z.Source.ScreenShare,c,l,t)}function Sb(i,e,t,n){const s=xb(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 xb(i,e,t){if(i)return gb;const n=e>t?e/t:t/e;return Math.abs(n-16/9)<Math.abs(n-4/3)?pb:mb}function Of(i,e){if(i)return _b(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)?vb:bb}function Wc(i,e,t,n){const s=[];if(t.forEach((r,a)=>{if(a>=Gc.length)return;const o=Math.min(i,e),l={rid:Gc[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=as()||a===0;r.encoding.priority&&u&&(l.priority=r.encoding.priority,l.networkPriority=r.encoding.priority),s.push(l)}),jn()&&uf()==="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 Ff(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 Bf{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 Tb(i){return i.source===Z.Source.ScreenShare||i.constraints.height&&Oi(i.constraints.height)>=1080?"maintain-resolution":"balanced"}const Cb=5e3;class Da extends Uf{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,Z.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(ae.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+=ka(l,h)}),this._currentBitrate=c}this.prevStats=a}),this.senderLock=new sn}get isSimulcast(){return!!(this.sender&&this.sender.getParameters().encodings.length>1)}startMonitor(e){var t;if(this.signalClient=e,!cn())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()},Vc))}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=di(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=di(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===Z.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===Z.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=pn.LOW;n<=pn.HIGH;n+=1)t.push(new Zo({quality:n,enabled:n<=e}));this.log.debug("setting publishing quality. max quality ".concat(e),this.logContext),this.setPublishingLayers(qn(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=Ac({video:e});typeof u.video!="boolean"&&(o=u.video)}yield this.restart(o),this.isCpuConstrained=!1;try{for(var c=!0,l=di(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=di(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)},Cb))}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(qn(e[0].codec),e[0].qualities),[];this.subscribedCodecs=e;const l=[];try{for(t=!0,n=di(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(qn(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 Vf(u.sender,u.encodings,d.qualities,this.senderLock,qn(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 Vf(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&&qn(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),lf()&&this.isInBackground&&this.source===Z.Source.Camera&&(this._mediaStreamTrack.enabled=!1)})}}function Vf(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=zf(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),as()&&(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 zf(i){switch(i){case"f":return pn.HIGH;case"h":return pn.MEDIUM;case"q":return pn.LOW;default:return pn.HIGH}}function Gf(i,e,t,n){if(!t)return[new is({quality:pn.HIGH,width:i,height:e,bitrate:0,ssrc:0})];if(n){const s=t[0].scalabilityMode,r=new Bf(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 is({quality:Math.min(pn.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=zf((a=s.rid)!==null&&a!==void 0?a:"");return new is({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 Hf="_lossy",Wf="_reliable",Eb=2*1e3,qc="leave-reconnect",Mb=3e4;var Dn;(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"})(Dn||(Dn={}));class wb extends Wn.EventEmitter{get isClosed(){return this._isClosed}get pendingReconnect(){return!!this.reconnectTimeout}constructor(e){var t;super(),this.options=e,this.rtcConfig={},this.peerConnectionTimeout=Fc.peerConnectionTimeout,this.fullReconnectOnNext=!1,this.latestRemoteOfferId=0,this.subscriberPrimary=!1,this.pcState=Dn.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 Cf,this.reliableReceivedState=new J0(Mb),this.handleDataChannel=n=>P(this,[n],void 0,function(s){var r=this;let{channel:a}=s;return function*(){if(a){if(a.label===Wf)r.reliableDCSub=a;else if(a.label===Hf)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=an.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(le.ActiveSpeakersUpdate,c.value.value.speakers):(((r=c.value)===null||r===void 0?void 0:r.case)==="user"&&Rb(c,c.value.value),this.emit(le.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(le.Disconnected),this.close()},a=Date.now()-this.reconnectStart;let o=this.getNextRetryDelay({elapsedMs:a,retryCount:this.reconnectAttempts});if(o===null){r(a);return}n===qc&&(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=$t.setTimeout(()=>this.attemptReconnect(s).finally(()=>this.reconnectTimeout=void 0),o)},this.waitForRestarted=()=>new Promise((n,s)=>{this.pcState===Dn.Connected&&n();const r=()=>{this.off(le.Disconnected,a),n()},a=()=>{this.off(le.Restarted,r),s()};this.once(le.Restarted,r),this.once(le.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(le.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===Tt.RECONNECTING&&(this.clearReconnectTimeout(),this.attemptReconnect(Rs.RR_SIGNAL_DISCONNECTED))},this.log=li((t=e.loggerName)!==null&&t!==void 0?t:Pn.Engine),this.loggerOptions={loggerName:e.loggerName,loggerContextCb:()=>this.logContext},this.client=new kc(void 0,this.loggerOptions),this.client.signalLatency=this.options.expSignalLatency,this.reconnectPolicy=this.options.reconnectPolicy,this.registerOnLineListener(),this.closingLock=new sn,this.dataProcessLock=new sn,this.dcBufferStatus=new Map([[We.LOSSY,!0],[We.RELIABLE,!0]]),this.client.onParticipantUpdate=n=>this.emit(le.ParticipantUpdate,n),this.client.onConnectionQuality=n=>this.emit(le.ConnectionQualityUpdate,n),this.client.onRoomUpdate=n=>this.emit(le.RoomUpdate,n),this.client.onSubscriptionError=n=>this.emit(le.SubscriptionError,n),this.client.onSubscriptionPermissionUpdate=n=>this.emit(le.SubscriptionPermissionUpdate,n),this.client.onSpeakersChanged=n=>this.emit(le.SpeakersChanged,n),this.client.onStreamStateUpdate=n=>this.emit(le.StreamStateChanged,n),this.client.onRequestResponse=n=>this.emit(le.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(le.SignalConnected,r),r}catch(r){if(r instanceof vt&&r.reason===Je.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(le.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 Cf,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 hi("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 vt("publication of local track timed out, no response from server",Je.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!==wt.NEW)return;this.participantSid=(t=e.participant)===null||t===void 0?void 0:t.sid;const s=this.makeRTCConfiguration(e);this.pcManager=new ab(s,e.subscriberPrimary,this.loggerOptions),this.emit(le.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===wt.CONNECTED){const d=this.pcState===Dn.New;this.pcState=Dn.Connected,d&&this.emit(le.Connected,e)}else r===wt.FAILED&&this.pcState===Dn.Connected&&(this.pcState=Dn.Disconnected,this.handleDisconnect("peerconnection failed",o==="failed"?Rs.RR_SUBSCRIBER_FAILED:Rs.RR_PUBLISHER_FAILED));const c=this.client.isDisconnected||this.client.currentState===Tt.RECONNECTING,l=[wt.FAILED,wt.CLOSING,wt.CLOSED].includes(r);c&&l&&!this._isClosed&&this.emit(le.Offline)}),this.pcManager.onTrack=r=>{this.emit(le.MediaTrackAdded,r.track,r.streams[0],r.receiver)},Ab((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(le.LocalTrackUnpublished,e)},this.client.onLocalTrackSubscribed=e=>{this.emit(le.LocalTrackSubscribed,e)},this.client.onTokenRefresh=e=>{this.token=e},this.client.onRemoteMuteChanged=(e,t)=>{this.emit(le.RemoteMute,e,t)},this.client.onSubscribedQualityUpdate=e=>{this.emit(le.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(le.RoomMoved,e)},this.client.onClose=()=>{this.handleDisconnect("signal",Rs.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 Is.DISCONNECT:this.emit(le.Disconnected,e==null?void 0:e.reason),this.close();break;case Is.RECONNECT:this.fullReconnectOnNext=!0,this.handleDisconnect(qc);break;case Is.RESUME:this.handleDisconnect(qc)}}}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===Er.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(Hf,{ordered:!1,maxRetransmits:0}),this.reliableDC=this.pcManager.createPublisherDataChannel(Wf,{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(vc())return yield this.createTransceiverRTCRtpSender(e,t,n);if(bc())return this.log.warn("using add-track fallback",this.logContext),yield this.createRTCRtpSender(e.mediaStreamTrack);throw new Bt("Required webRTC APIs not supported on this device")})}createSimulcastSender(e,t,n,s){return P(this,void 0,void 0,function*(){if(vc())return this.createSimulcastTransceiverSender(e,t,n,s);if(bc())return this.log.debug("using add-track fallback",this.logContext),this.createRTCRtpSender(e.mediaStreamTrack);throw new Bt("Cannot stream on this device")})}createTransceiverRTCRtpSender(e,t,n){return P(this,void 0,void 0,function*(){if(!this.pcManager)throw new Bt("publisher is closed");const s=[];e.mediaStream&&s.push(e.mediaStream),Fi(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 Bt("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 Bt("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)===Er.DISABLED||((s=(n=this.pcManager)===null||n===void 0?void 0:n.currentState)!==null&&s!==void 0?s:wt.NEW)===wt.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 Bt?(this.log.debug("received unrecoverable error",Object.assign(Object.assign({},this.logContext),{error:r})),a=!1):r instanceof Fs||(this.fullReconnectOnNext=!0),a?this.handleDisconnect("reconnect",Rs.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(le.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 Bt("could not reconnect, url or token not saved");this.log.info("reconnecting, attempt: ".concat(this.reconnectAttempts),this.logContext),this.emit(le.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 Fs;r=yield this.join(e??this.url,this.token,this.signalOpts)}catch(a){throw a instanceof vt&&a.reason===Je.NotAllowed?new Bt("could not reconnect, token might be expired"):new Fs}if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(this.client.setReconnected(),this.emit(le.SignalRestarted,r),yield this.waitForPCReconnected(),this.client.currentState!==Tt.CONNECTED)throw new Fs("Signal connection got severed during reconnect");(t=this.regionUrlProvider)===null||t===void 0||t.resetAttempts(),this.emit(le.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 Bt("could not reconnect, url or token not saved");if(!this.pcManager)throw new Bt("publisher and subscriber connections unset");this.log.info("resuming signal connection, attempt ".concat(this.reconnectAttempts),this.logContext),this.emit(le.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 vt&&s.reason===Je.NotAllowed?new Bt("could not reconnect, token might be expired"):s instanceof vt&&s.reason===Je.LeaveRequest?s:new Fs(r)}if(this.emit(le.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!==Tt.CONNECTED)throw new Fs("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(le.Resumed)})}waitForPCInitialConnection(e,t){return P(this,void 0,void 0,function*(){if(!this.pcManager)throw new Bt("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(t,e)})}waitForPCReconnected(){return P(this,void 0,void 0,function*(){this.pcState=Dn.Reconnecting,this.log.debug("waiting for peer connection to reconnect",this.logContext);try{if(yield on(Eb),!this.pcManager)throw new Bt("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(void 0,this.peerConnectionTimeout),this.pcState=Dn.Connected}catch(e){throw this.pcState=Dn.Disconnected,new vt("could not establish PC connection, ".concat(e.message),Je.InternalError)}})}publishRpcResponse(e,t,n,s){return P(this,void 0,void 0,function*(){const r=new an({destinationIdentities:[e],kind:We.RELIABLE,value:{case:"rpcResponse",value:new Wu({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 an({destinationIdentities:[e],kind:We.RELIABLE,value:{case:"rpcAck",value:new Hu({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(le.Closing,s);!this.dcBufferStatus.get(e);)yield on(10);this.off(le.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 Bt("PC manager is closed");const a=s?n.pcManager.subscriber:n.pcManager.publisher,o=s?"Subscriber":"Publisher";if(!a)throw new vt("".concat(o," connection not set"),Je.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 on(50)}throw new vt("could not establish ".concat(o," connection, state: ").concat(a.getICEConnectionState()),Je.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!==wt.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 uc("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(le.Closing,s),this.pcManager.publisher.once(Os.RTPVideoPayloadTypes,r=>{const a=new Map;r.forEach(o=>{const c=o.codec.toLowerCase();R0(c)&&a.set(o.payload,c)}),this.emit(le.RTPVideoMapUpdate,a)});try{yield this.pcManager.negotiate(n),e()}catch(r){r instanceof uc&&(this.fullReconnectOnNext=!0),this.handleDisconnect("negotiation",Rs.RR_UNKNOWN),t(r)}finally{this.off(le.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 lh({answer:r?Pa({sdp:r.sdp,type:r.type}):void 0,offer:a?Pa({sdp:a.sdp,type:a.type}):void 0,subscription:new va({trackSids:c,subscribe:!o,participantTracks:[]}),publishTracks:F0(t),dataChannels:this.dataChannelsInfo(),trackSidsDisabled:l,datachannelReceiveStates:this.reliableReceivedState.map((d,u)=>new dh({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 uh({label:n.label,id:n.id,target:s}))};return t(this.dataChannelForKind(We.LOSSY),Rn.PUBLISHER),t(this.dataChannelForKind(We.RELIABLE),Rn.PUBLISHER),t(this.dataChannelForKind(We.LOSSY,!0),Rn.SUBSCRIBER),t(this.dataChannelForKind(We.RELIABLE,!0),Rn.SUBSCRIBER),e}clearReconnectTimeout(){this.reconnectTimeout&&$t.clearTimeout(this.reconnectTimeout)}clearPendingReconnect(){this.clearReconnectTimeout(),this.reconnectAttempts=0}registerOnLineListener(){cn()&&window.addEventListener("online",this.handleBrowserOnLine)}deregisterOnLineListener(){cn()&&window.removeEventListener("online",this.handleBrowserOnLine)}}class Fs extends Error{}function Ab(i){return i!==void 0&&i>13}function Rb(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 jc{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 yc(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(Pb(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 vt("Could not fetch region settings: ".concat(t.statusText),t.status===401?Je.NotAllowed:Je.InternalError,t.status)})}setServerReportedRegions(e){this.regionSettings=e,this.lastUpdateAt=Date.now()}}function Pb(i){return"".concat(i.protocol.replace("ws","http"),"//").concat(i.host,"/settings")}class qf{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 Ui("Not enough chunk(s) received - expected ".concat(this.totalByteSize," bytes of data total, only received ").concat(this.bytesReceived," bytes"),kn.Incomplete);if(this.bytesReceived>this.totalByteSize)throw new Ui("Extra chunk(s) received - expected ".concat(this.totalByteSize," bytes of data total, received ").concat(this.bytesReceived," bytes"),kn.LengthExceeded)}}constructor(e,t,n,s){this.reader=t,this.totalByteSize=n,this._info=e,this.bytesReceived=0,this.outOfBandFailureRejectingFuture=s}}class kb extends qf{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 Xn,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=di(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 Ib extends qf{constructor(e,t,n,s){super(e,t,n,s),this.receivedChunks=new Map}handleChunkReceived(e){var t;const n=Ra(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 Xn,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 Ui("Cannot decode datastream chunk ".concat(d.chunkIndex," as text: ").concat(h),kn.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=di(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 Db{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 Ui('A text stream handler for topic "'.concat(e,'" has already been set.'),kn.HandlerAlreadyRegistered);this.textStreamHandlers.set(e,t)}unregisterTextStreamHandler(e){this.textStreamHandlers.delete(e)}registerByteStreamHandler(e,t){if(this.byteStreamHandlers.has(e))throw new Ui('A byte stream handler for topic "'.concat(e,'" has already been set.'),kn.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 Ui("Participant ".concat(e," unexpectedly disconnected in the middle of sending data"),kn.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 Xn,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:Ra(e.timestamp),attributes:e.attributes},c=new ReadableStream({start:l=>{if(r=l,this.textStreamControllers.has(e.streamId))throw new Ui("A data stream read is already in progress for a stream with id ".concat(e.streamId,"."),kn.AlreadyOpened);this.byteStreamControllers.set(e.streamId,{info:o,controller:r,startTime:Date.now(),sendingParticipantIdentity:t,outOfBandFailureRejectingFuture:a})}});s(new kb(o,c,Ra(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 Xn,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 Ui("A data stream read is already in progress for a stream with id ".concat(e.streamId,"."),kn.AlreadyOpened);this.textStreamControllers.set(e.streamId,{info:o,controller:r,startTime:Date.now(),sendingParticipantIdentity:t,outOfBandFailureRejectingFuture:a})}});s(new Ib(o,c,Ra(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 jf{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 Lb extends jf{}class Nb extends jf{}const $f=15e3;class Ub{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 Ho({streamId:s,mimeType:r.mimeType,topic:r.topic,timestamp:cs(r.timestamp),totalLength:cs(e==null?void 0:e.totalSize),attributes:r.attributes,contentHeader:{case:"textHeader",value:new Qu({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"?Go.UPDATE:Go.CREATE})}}),o=e==null?void 0:e.destinationIdentities,c=new an({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 N0(g,$f)){yield d.waitForBufferStatusLow(We.RELIABLE);const m=new Wo({content:v,streamId:s,chunkIndex:cs(l)}),p=new an({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 qo({streamId:s}),v=new an({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(le.Closing,h);const f=new Lb(u,r,()=>this.engine.off(le.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 Ho({totalLength:cs((a=l.size)!==null&&a!==void 0?a:0),mimeType:l.mimeType,streamId:o,topic:l.topic,timestamp:cs(Date.now()),attributes:l.attributes,contentHeader:{case:"byteHeader",value:new eh({name:l.name})}}),u=new an({destinationIdentities:c,value:{case:"streamHeader",value:d}});yield this.engine.sendDataPacket(u,We.RELIABLE);let h=0;const f=new sn,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+$f);yield g.waitForBufferStatusLow(We.RELIABLE);const M=new an({destinationIdentities:c,value:{case:"streamChunk",value:new Wo({content:S,streamId:o,chunkIndex:cs(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 qo({streamId:o}),C=new an({destinationIdentities:c,value:{case:"streamTrailer",value:x}});yield g.sendDataPacket(C,We.RELIABLE)})},abort(x){v.error("Sink error:",x)}});return new Nb(m,l)})}}class Xf extends Z{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?ae.Muted:ae.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(ae.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(),Vc)),B0()&&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(ae.TimeSyncUpdate,{timestamp:s,rtpTimestamp:r}),this.rtpTimestamp=r)}};e()}}class Ob extends Xf{constructor(e,t,n,s,r,a){super(e,t,Z.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=ka(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;jn()&&this._mediaStreamTrack._setVolume(e),this.elementVolume=e}getVolume(){if(this.elementVolume)return this.elementVolume;if(jn())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(_c(t))return t.setSinkId(e)}))})}attach(e){const t=this.attachedElements.length===0;return e?super.attach(e):e=super.attach(),this.sinkId&&_c(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(ae.AudioPlaybackFailed,new Error("Audio Context couldn't be started automatically"))}).catch(s=>{this.emit(ae.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 $c=100;class Fb extends Xf{constructor(e,t,n,s,r){super(e,t,Z.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=ka(a,this.prevStats)),this.prevStats=a}),this.debouncedHandleResize=Uc(()=>{this.updateDimensions()},$c),this.adaptiveStreamSettings=s}get isAdaptiveStream(){return this.adaptiveStreamSettings!==void 0}setStreamState(e){super.setStreamState(e),console.log("setStreamState",e),e===Z.StreamState.Active&&this.updateVisibility()}get mediaStreamTrack(){return this._mediaStreamTrack}setMuted(e){super.setMuted(e),this.attachedElements.forEach(t=>{e?Ns(this._mediaStreamTrack,t):Ls(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 Bb(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<$c){$t.setTimeout(()=>{this.updateVisibility()},$c);return}this.lastVisible=o,this.emit(ae.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(ae.VideoDimensionsChanged,this.lastDimensions,this))}getPixelDensity(){var e;const t=(e=this.adaptiveStreamSettings)===null||e===void 0?void 0:e.pixelDensity;return t==="screen"?hf():t||(hf()>2?2:1)}}class Bb{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=Ur(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=Ur(this.element),(r=this.handleVisibilityChanged)===null||r===void 0||r.call(this)},this.onLeavePiP=()=>{var n;this.isPiP=Ur(this.element),(n=this.handleVisibilityChanged)===null||n===void 0||n.call(this)},this.element=e,this.isIntersecting=t??Xc(e),this.isPiP=cn()&&Ur(e),this.visibilityChangedAt=0}width(){return this.element.clientWidth}height(){return this.element.clientHeight}observe(){var e,t,n;this.isIntersecting=Xc(this.element),this.isPiP=Ur(this.element),this.element.handleResize=()=>{var s;(s=this.handleResize)===null||s===void 0||s.call(this)},this.element.handleVisibilityChanged=this.onVisibilityChanged,pf().observe(this.element),ff().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=pf())===null||e===void 0||e.unobserve(this.element),(t=ff())===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 Ur(i){var e,t;return document.pictureInPictureElement===i?!0:!((e=window.documentPictureInPicture)===null||e===void 0)&&e.window?Xc(i,(t=window.documentPictureInPicture)===null||t===void 0?void 0:t.window):!1}function Xc(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 pi extends Wn.EventEmitter{constructor(e,t,n,s){var r;super(),this.metadataMuted=!1,this.encryption=hn.NONE,this.log=Ke,this.handleMuted=()=>{this.emit(ae.Muted)},this.handleUnmuted=()=>{this.emit(ae.Unmuted)},this.log=li((r=s==null?void 0:s.loggerName)!==null&&r!==void 0?r:Pn.Publication),this.loggerContextCb=this.loggerContextCb,this.setMaxListeners(100),this.kind=e,this.trackSid=t,this.trackName=n,this.source=Z.Source.Unknown}setTrack(e){this.track&&(this.track.off(ae.Muted,this.handleMuted),this.track.off(ae.Unmuted,this.handleUnmuted)),this.track=e,e&&(e.on(ae.Muted,this.handleMuted),e.on(ae.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!==hn.NONE}get audioTrack(){if(Kn(this.track))return this.track}get videoTrack(){if(Fi(this.track))return this.track}updateInfo(e){this.trackSid=e.sid,this.trackName=e.name,this.source=Z.sourceFromProto(e.source),this.mimeType=e.mimeType,this.kind===Z.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={}))})(pi||(pi={}));class Kc extends pi{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(ae.Ended)},this.handleCpuConstrained=()=>{this.track&&Fi(this.track)&&this.emit(ae.CpuConstrained,this.track)},this.updateInfo(t),this.setTrack(n)}setTrack(e){this.track&&(this.track.off(ae.Ended,this.handleTrackEnded),this.track.off(ae.CpuConstrained,this.handleCpuConstrained)),super.setTrack(e),e&&(e.on(ae.Ended,this.handleTrackEnded),e.on(ae.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(Kn(this.track)){const t=this.track.getSourceTrackSettings(),n=new Set;return t.autoGainControl&&n.add(Ht.TF_AUTO_GAIN_CONTROL),t.echoCancellation&&n.add(Ht.TF_ECHO_CANCELLATION),t.noiseSuppression&&n.add(Ht.TF_NOISE_SUPPRESSION),t.channelCount&&t.channelCount>1&&n.add(Ht.TF_STEREO),!((e=this.options)===null||e===void 0)&&e.dtx||n.add(Ht.TF_NO_DTX),this.track.enhancedNoiseCancellation&&n.add(Ht.TF_ENHANCED_NOISE_CANCELLATION),Array.from(n.values())}else return[]}}function La(i,e){return P(this,void 0,void 0,function*(){i??(i={});let t=!1;const{audioProcessor:n,videoProcessor:s,optionsWithoutProcessor:r}=yf(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=vf(r,If,Df),l=Ac(c),d=navigator.mediaDevices.getUserMedia(l);r.audio&&(Wt.userMediaPromiseMap.set("audioinput",d),d.catch(()=>Wt.userMediaPromiseMap.delete("audioinput"))),r.video&&(Wt.userMediaPromiseMap.set("videoinput",d),d.catch(()=>Wt.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&&Oi(v.deviceId)!==p?v.deviceId=p:v||(v={deviceId:p});const x=fb(h,v,e);return x.kind===Z.Kind.Video?x.source=Z.Source.Camera:x.kind===Z.Kind.Audio&&(x.source=Z.Source.Microphone),x.mediaStream=u,Kn(x)&&n?yield x.setProcessor(n):Fi(x)&&s&&(yield x.setProcessor(s)),x})))}catch(u){if(!t)throw u;return La(Object.assign(Object.assign({},i),{audio:a,video:o}),e)}})}function Vb(i){return P(this,void 0,void 0,function*(){return(yield La({audio:!1,video:!0}))[0]})}function zb(i){return P(this,void 0,void 0,function*(){return(yield La({audio:!0,video:!1}))[0]})}var zi;(function(i){i.Excellent="excellent",i.Good="good",i.Poor="poor",i.Lost="lost",i.Unknown="unknown"})(zi||(zi={}));function Gb(i){switch(i){case Cr.EXCELLENT:return zi.Excellent;case Cr.GOOD:return zi.Good;case Cr.POOR:return zi.Poor;case Cr.LOST:return zi.Lost;default:return zi.Unknown}}class Kf extends Wn.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===Mr.AGENT}get isActive(){var e;return((e=this.participantInfo)===null||e===void 0?void 0:e.state)===Ps.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]:Mr.STANDARD;var c;super(),this.audioLevel=0,this.isSpeaking=!1,this._connectionQuality=zi.Unknown,this.log=Ke,this.log=li((c=a==null?void 0:a.loggerName)!==null&&c!==void 0?c:Pn.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 Xn,this.once(ce.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(Z.Source.Camera);return!(!((e=t==null?void 0:t.isMuted)!==null&&e!==void 0)||e)}get isMicrophoneEnabled(){var e;const t=this.getTrackPublication(Z.Source.Microphone);return!(!((e=t==null?void 0:t.isMuted)!==null&&e!==void 0)||e)}get isScreenShareEnabled(){return!!this.getTrackPublication(Z.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===Ps.ACTIVE&&((t=this.participantInfo)===null||t===void 0?void 0:t.state)!==Ps.ACTIVE&&this.emit(ce.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(ce.ParticipantMetadataChanged,n)}_setName(e){const t=this.name!==e;this.name=e,t&&this.emit(ce.ParticipantNameChanged,e)}_setAttributes(e){const t=V0(this.attributes,e);this._attributes=e,Object.keys(t).length>0&&this.emit(ce.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(ce.ParticipantPermissionsChanged,c),l}setIsSpeaking(e){e!==this.isSpeaking&&(this.isSpeaking=e,e&&(this.lastSpokeAt=new Date),this.emit(ce.IsSpeakingChanged,e))}setConnectionQuality(e){const t=this._connectionQuality;this._connectionQuality=Gb(e),t!==this._connectionQuality&&this.emit(ce.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=>Kn(t.track)&&t.track.setAudioContext(e))}addTrackPublication(e){e.on(ae.Muted,()=>{this.emit(ce.TrackMuted,e)}),e.on(ae.Unmuted,()=>{this.emit(ce.TrackUnmuted,e)});const t=e;switch(t.track&&(t.track.sid=e.trackSid),this.trackPublications.set(e.trackSid,e),e.kind){case Z.Kind.Audio:this.audioTrackPublications.set(e.trackSid,e);break;case Z.Kind.Video:this.videoTrackPublications.set(e.trackSid,e);break}}}function Hb(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 oh({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 Wb extends Kf{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=hn.NONE,this.enabledPublishVideoCodecs=[],this.pendingAcks=new Map,this.pendingResponses=new Map,this.handleReconnecting=()=>{this.reconnectFuture||(this.reconnectFuture=new Xn)},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 Xn),(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!==Qo.OK&&u.reject(new rf(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=At.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=>Hb(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(ce.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=di(g),p;p=yield m.next(),c=p.done,!c;v=!0){u=p.value,v=!1;const x=u;v0(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===Z.Source.ScreenShare||o.source===Z.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(fi(o)||Bi(o))try{if(cn())try{const c=yield navigator==null?void 0:navigator.permissions.query({name:o.source===Z.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))),fi(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!==hn.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(le.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(le.Connected,this.handleReconnected).on(le.SignalConnected,this.handleSignalConnected).on(le.SignalRestarted,this.handleReconnected).on(le.SignalResumed,this.handleReconnected).on(le.Restarting,this.handleReconnecting).on(le.Resuming,this.handleReconnecting).on(le.LocalTrackUnpublished,this.handleLocalTrackUnpublished).on(le.SubscribedQualityUpdate,this.handleSubscribedQualityUpdate).on(le.Closing,this.handleClosing).on(le.SignalRequestResponse,this.handleSignalRequestResponse).on(le.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 on(50)}c(new rf("Request to update local metadata timed out","TimeoutError"))}catch(u){u instanceof Error&&c(u)}}))}()})}setCameraEnabled(e,t,n){return this.setTrackEnabled(Z.Source.Camera,e,t,n)}setMicrophoneEnabled(e,t,n){return this.setTrackEnabled(Z.Source.Microphone,e,t,n)}setScreenShareEnabled(e,t,n){return this.setTrackEnabled(Z.Source.ScreenShare,e,t,n)}setPermissions(e){const t=this.permissions,n=super.setPermissions(e);return n&&t&&this.emit(ce.ParticipantPermissionsChanged,t),n}setE2EEEnabled(e){return P(this,void 0,void 0,function*(){this.encryptionType=e?hn.GCM:hn.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 Z.Source.Camera:c=yield this.createTracks({video:(r=n)!==null&&r!==void 0?r:!0});break;case Z.Source.Microphone:c=yield this.createTracks({audio:(a=n)!==null&&a!==void 0?a:!0});break;case Z.Source.ScreenShare:c=yield this.createScreenTracks(Object.assign({},n));break;default:throw new hi(e)}}catch(l){throw c==null||c.forEach(d=>{d.stop()}),l instanceof Error&&this.emit(ce.MediaDevicesError,l,Rc(e)),this.pendingPublishing.delete(e),l}for(const l of c){const d=Object.assign(Object.assign({},this.roomOptions.publishDefaults),n);e===Z.Source.Microphone&&Kn(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===Z.Source.ScreenShare){o=yield this.unpublishTrack(o.track);const c=this.getTrackPublication(Z.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(Z.Source.Camera)||this.pendingPublishing.has(Z.Source.Microphone))){this.pendingPublishing.add(Z.Source.Camera),this.pendingPublishing.add(Z.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(Z.Source.Camera),this.pendingPublishing.delete(Z.Source.Microphone)}}})}createTracks(e){return P(this,void 0,void 0,function*(){var t,n;e??(e={});const s=vf(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 La(s,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext})).map(o=>(Kn(o)&&(this.microphoneError=void 0,o.setAudioContext(this.audioContext),o.source=Z.Source.Microphone,this.emit(ce.AudioStreamAcquired)),Fi(o)&&(this.cameraError=void 0,o.source=Z.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 dc("getDisplayMedia not supported");e.resolution===void 0&&!T0()&&(e.resolution=gc.h1080fps30.resolution);const t=O0(e),n=yield navigator.mediaDevices.getDisplayMedia(t),s=n.getVideoTracks();if(s.length===0)throw new hi("no video track found");const r=new Da(s[0],void 0,!1,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});r.source=Z.Source.ScreenShare,e.contentHint&&(r.mediaStreamTrack.contentHint=e.contentHint);const a=[r];if(n.getAudioTracks().length>0){this.emit(ce.AudioStreamAcquired);const o=new Ia(n.getAudioTracks()[0],void 0,!1,this.audioContext,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});o.source=Z.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;fi(n)&&n.setAudioContext(r.audioContext),yield(o=r.reconnectFuture)===null||o===void 0?void 0:o.promise,r.republishPromise&&!a&&(yield r.republishPromise),Us(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 Z.Source.Microphone:p="audioinput";break;case Z.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 Ia(n,u,!0,r.audioContext,{loggerName:r.roomOptions.loggerName,loggerContextCb:()=>r.logContext});break;case"video":n=new Da(n,u,!0,{loggerName:r.roomOptions.loggerName,loggerContextCb:()=>r.logContext});break;default:throw new hi("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);!E0()&&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!==Tt.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 sf("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 Xn),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 sf("failed to publish track, insufficient permissions",403);Array.from(this.trackPublications.values()).find(y=>Us(e)&&y.source===e.source)&&e.source!==Z.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&&Kn(e)&&(e.stopOnMute=!0),e.source===Z.Source.ScreenShare&&as()&&(t.simulcast=!1),t.videoCodec==="av1"&&!y0()&&(t.videoCodec=void 0),t.videoCodec==="vp9"&&!S0()&&(t.videoCodec=void 0),t.videoCodec===void 0&&(t.videoCodec=Oc),this.enabledPublishVideoCodecs.length>0&&(this.enabledPublishVideoCodecs.some(y=>t.videoCodec===Lr(y.mime))||(t.videoCodec=Lr(this.enabledPublishVideoCodecs[0].mime)));const v=t.videoCodec;e.on(ae.Muted,this.onTrackMuted),e.on(ae.Unmuted,this.onTrackUnmuted),e.on(ae.Ended,this.handleTrackEnded),e.on(ae.UpstreamPaused,this.onTrackUpstreamPaused),e.on(ae.UpstreamResumed,this.onTrackUpstreamResumed),e.on(ae.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate);const m=[],p=!(!((s=t.dtx)!==null&&s!==void 0)||s),x=e.getSourceTrackSettings();x.autoGainControl&&m.push(Ht.TF_AUTO_GAIN_CONTROL),x.echoCancellation&&m.push(Ht.TF_ECHO_CANCELLATION),x.noiseSuppression&&m.push(Ht.TF_NOISE_SUPPRESSION),x.channelCount&&x.channelCount>1&&m.push(Ht.TF_STEREO),p&&m.push(Ht.TF_NO_DTX),fi(e)&&e.hasPreConnectBuffer&&m.push(Ht.TF_PRECONNECT_BUFFER);const C=new Xo({cid:e.mediaStreamTrack.id,name:t.name,type:Z.kindToProto(e.kind),muted:e.isMuted,source:Z.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===Z.Kind.Video){let y={width:0,height:0};try{y=yield e.waitForDimensions()}catch{const R=(o=(a=this.roomOptions.videoCaptureDefaults)===null||a===void 0?void 0:a.resolution)!==null&&o!==void 0?o:kr.h720.resolution;y={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:y}))}C.width=y.width,C.height=y.height,Bi(e)&&(qn(v)&&(e.source===Z.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 $o({codec:v,cid:e.mediaStreamTrack.id})],t.backupCodec===!0&&(t.backupCodec={codec:Oc}),t.backupCodec&&v!==t.backupCodec.codec&&C.encryption===hn.NONE&&(this.roomOptions.dynacast||(this.roomOptions.dynacast=!0),C.simulcastCodecs.push(new $o({codec:t.backupCodec.codec,cid:""})))),b=Hc(e.source===Z.Source.ScreenShare,C.width,C.height,t),C.layers=Gf(C.width,C.height,b,qn(t.videoCodec))}else e.kind===Z.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 Bt("cannot publish track when not connected");const S=()=>P(this,void 0,void 0,function*(){var y,T,R;if(!this.engine.pcManager)throw new Bt("pcManager is not ready");if(e.sender=yield this.engine.createSender(e,t,b),this.emit(ce.LocalSenderCreated,e.sender,e),Bi(e)&&((y=t.degradationPreference)!==null&&y!==void 0||(t.degradationPreference=Tb(e)),e.setDegradationPreference(t.degradationPreference)),b)if(as()&&e.kind===Z.Kind.Audio){let U;for(const B of this.engine.pcManager.publisher.getTransceivers())if(B.sender===e.sender){U=B;break}U&&this.engine.pcManager.publisher.setTrackCodecBitrate({transceiver:U,codec:"opus",maxbr:!((T=b[0])===null||T===void 0)&&T.maxBitrate?b[0].maxBitrate/1e3:0})}else e.codec&&qn(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((y,T)=>P(this,void 0,void 0,function*(){var R;try{M=yield this.engine.addTrack(C),y(M)}catch(U){e.sender&&(!((R=this.engine.pcManager)===null||R===void 0)&&R.publisher)&&(this.engine.pcManager.publisher.removeTrack(e.sender),yield this.engine.negotiate().catch(B=>{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:B}))})),T(U)}}));if(this.enabledPublishVideoCodecs.length>0)M=(yield Promise.all([A,S()]))[0];else{M=yield A;let y;if(M.codecs.forEach(T=>{y===void 0&&(y=T.mimeType)}),y&&e.kind===Z.Kind.Video){const T=Lr(y);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=Hc(e.source===Z.Source.ScreenShare,C.width,C.height,t))}yield S()}const k=new Kc(e.kind,M,e,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});if(k.on(ae.CpuConstrained,y=>this.onTrackCpuConstrained(y,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})),Bi(e)?e.startMonitor(this.engine.client):fi(e)&&e.startMonitor(),this.addTrackPublication(k),this.emit(ce.LocalTrackPublished,k),fi(e)&&M.audioFeatures.includes(Ht.TF_PRECONNECT_BUFFER)){const y=e.getPreConnectBuffer(),T=e.getPreConnectBufferMimeType();this.on(ce.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()}}),y&&new Promise((U,B)=>P(this,void 0,void 0,function*(){var q,K,H,W,te,ve;try{this.log.debug("waiting for agent",Object.assign(Object.assign({},this.logContext),Xe(e)));const Be=setTimeout(()=>{B(new Error("agent not active within 10 seconds"))},1e4),Ct=yield this.waitUntilActiveAgentPresent();clearTimeout(Be),this.log.debug("sending preconnect buffer",Object.assign(Object.assign({},this.logContext),Xe(e)));const mt=yield this.streamBytes({name:"preconnect-buffer",mimeType:T,topic:"lk.agent.pre-connect-audio-buffer",destinationIdentities:[Ct.identity],attributes:{trackId:k.trackSid,sampleRate:String((te=x.sampleRate)!==null&&te!==void 0?te:"48000"),channels:String((ve=x.channelCount)!==null&&ve!==void 0?ve:"1")}});try{for(var de=!0,_e=di(y),Ve;Ve=yield _e.next(),q=Ve.done,!q;de=!0){W=Ve.value,de=!1;const X=W;yield mt.write(X)}}catch(X){K={error:X}}finally{try{!de&&!q&&(H=_e.return)&&(yield H.call(_e))}finally{if(K)throw K.error}}yield mt.close(),U()}catch(Be){B(Be)}})).then(()=>{this.log.debug("preconnect buffer sent successfully",Object.assign(Object.assign({},this.logContext),Xe(e)))}).catch(U=>{this.log.error("error sending preconnect buffer",Object.assign(Object.assign(Object.assign({},this.logContext),Xe(e)),{error:U}))})}return k})}get isLocal(){return!0}publishAdditionalCodecForTrack(e,t,n){return P(this,void 0,void 0,function*(){var s;if(this.encryptionType!==hn.NONE)return;let r;if(this.trackPublications.forEach(f=>{f.track&&f.track===e&&(r=f)}),!r)throw new hi("track is not published");if(!Bi(e))throw new hi("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=yb(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 Xo({cid:c.mediaStreamTrack.id,type:Z.kindToProto(e.kind),muted:e.isMuted,source:Z.sourceToProto(e.source),sid:e.sid,simulcastCodecs:[{codec:a.videoCodec,cid:c.mediaStreamTrack.id}]});if(l.layers=Gf(l.width,l.height,o),!this.engine||this.engine.isClosed)throw new Bt("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(Us(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(ae.Muted,this.onTrackMuted),e.off(ae.Unmuted,this.onTrackUnmuted),e.off(ae.Ended,this.handleTrackEnded),e.off(ae.UpstreamPaused,this.onTrackUpstreamPaused),e.off(ae.UpstreamResumed,this.onTrackUpstreamResumed),e.off(ae.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<wt.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),Bi(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 Z.Kind.Audio:this.audioTrackPublications.delete(r.trackSid);break;case Z.Kind.Video:this.videoTrackPublications.delete(r.trackSid);break}return this.emit(ce.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!==Z.Source.ScreenShare&&l.source!==Z.Source.ScreenShareAudio&&(fi(l)||Bi(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 an({kind:r,value:{case:"user",value:new Vu({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 an({kind:We.RELIABLE,value:{case:"sipDtmf",value:new zu({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 an({value:{case:"chatMessage",value:new zo(Object.assign(Object.assign({},n),{timestamp:Et.parse(n.timestamp)}))}});return yield this.engine.sendDataPacket(s,We.RELIABLE),this.emit(ce.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 an({value:{case:"chatMessage",value:new zo(Object.assign(Object.assign({},n),{timestamp:Et.parse(n.timestamp),editTimestamp:Et.parse(n.editTimestamp)}))}});return yield this.engine.sendDataPacket(s,We.RELIABLE),this.emit(ce.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(Bc(a)>Lf){d(At.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&&$n((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(At.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(At.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(At.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 an({destinationIdentities:[e],kind:We.RELIABLE,value:{case:"rpcRequest",value:new Gu({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,At.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 Xn),this.activeAgentFuture.promise)}getPublicationForTrack(e){let t;return this.trackPublications.forEach(n=>{const s=n.track;s&&(e instanceof MediaStreamTrack?(fi(s)||Bi(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 on(20)}})}}class qb extends pi{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(ae.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 va({trackSids:[this.trackSid],subscribe:this.subscribed,participantTracks:[new ju({participantSid:"",trackSids:[this.trackSid]})]});this.emit(ae.UpdateSubscription,s),this.emitSubscriptionUpdateIfChanged(t),this.emitPermissionUpdateIfChanged(n)}get subscriptionStatus(){return this.subscribed===!1?pi.SubscriptionStatus.Unsubscribed:super.isSubscribed?pi.SubscriptionStatus.Subscribed:pi.SubscriptionStatus.Desired}get permissionStatus(){return this.allowed?pi.PermissionStatus.Allowed:pi.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||(Mc(this.track)&&(this.requestedVideoDimensions=e),this.requestedMaxQuality=void 0,this.emitTrackUpdate()))}setVideoFPS(e){this.isManualOperationAllowed()&&Mc(this.track)&&this.fps!==e&&(this.fps=e,this.emitTrackUpdate())}get videoQuality(){var e;return(e=this.requestedMaxQuality)!==null&&e!==void 0?e:pn.HIGH}setTrack(e){const t=this.subscriptionStatus,n=this.permissionStatus,s=this.track;s!==e&&(s&&(s.off(ae.VideoDimensionsChanged,this.handleVideoDimensionsChange),s.off(ae.VisibilityChanged,this.handleVisibilityChange),s.off(ae.Ended,this.handleEnded),s.detach(),s.stopMonitor(),this.emit(ae.Unsubscribed,s)),super.setTrack(e),e&&(e.sid=this.trackSid,e.on(ae.VideoDimensionsChanged,this.handleVideoDimensionsChange),e.on(ae.VisibilityChanged,this.handleVisibilityChange),e.on(ae.Ended,this.handleEnded),this.emit(ae.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(ae.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?ae.Muted:ae.Unmuted)}emitSubscriptionUpdateIfChanged(e){const t=this.subscriptionStatus;e!==t&&this.emit(ae.SubscriptionStatusChanged,t,e)}emitPermissionUpdateIfChanged(e){this.permissionStatus!==e&&this.emit(ae.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 Mc(this.track)&&this.track.isAdaptiveStream}emitTrackUpdate(){const e=new nh({trackSids:[this.trackSid],disabled:!this.isEnabled,fps:this.fps});if(this.kind===Z.Kind.Video){let t=this.requestedVideoDimensions;if(this.videoDimensionsAdaptiveStream!==void 0)if(t)Sf(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=G0(this.trackInfo,this.requestedMaxQuality);n&&Sf(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:pn.HIGH})),e.quality=pn.HIGH)}this.emit(ae.UpdateSettings,e)}}class Na extends Kf{static fromParticipantInfo(e,t,n){return new Na(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]:Mr.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(ae.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(ae.UpdateSubscription,t=>{t.participantTracks.forEach(n=>{n.participantSid=this.sid}),this.signalClient.sendUpdateSubscription(t)}),e.on(ae.SubscriptionPermissionChanged,t=>{this.emit(ce.TrackSubscriptionPermissionChanged,e,t)}),e.on(ae.SubscriptionStatusChanged,t=>{this.emit(ce.TrackSubscriptionStatusChanged,e,t)}),e.on(ae.Subscribed,t=>{this.emit(ce.TrackSubscribed,t,e)}),e.on(ae.Unsubscribed,t=>{this.emit(ce.TrackUnsubscribed,t,e)}),e.on(ae.SubscriptionFailed,t=>{this.emit(ce.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]:Z.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]:Z.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(ce.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(ce.TrackSubscriptionFailed,t);return}const c=e.kind==="video";let l;return c?l=new Fb(e,t,s,r):l=new Ob(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)&&Ec(l)&&Kn(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=Z.kindFromProto(s.type);if(!c)return;o=new qb(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!==Z.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(ce.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 Z.Kind.Audio:this.audioTrackPublications.delete(e);break;case Z.Kind.Video:this.videoTrackPublications.delete(e);break}t&&this.emit(ce.TrackUnpublished,n)}setAudioOutput(e){return P(this,void 0,void 0,function*(){this.audioOutput=e;const t=[];this.audioTrackPublications.forEach(n=>{var s;Kn(n.track)&&Ec(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 st;(function(i){i.Disconnected="disconnected",i.Connecting="connecting",i.Connected="connected",i.Reconnecting="reconnecting",i.SignalReconnecting="signalReconnecting"})(st||(st={}));const jb=4*1e3;class Bs extends Wn.EventEmitter{constructor(e){var t,n,s,r;if(super(),t=this,this.state=st.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(!x0())throw jn()?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===st.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(st.Connecting),((l=this.regionUrlProvider)===null||l===void 0?void 0:l.getServerUrl().toString())!==a&&(this.regionUrl=void 0,this.regionUrlProvider=void 0),yc(new URL(a))&&(this.regionUrlProvider===void 0?this.regionUrlProvider=new jc(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 vt&&C.reason!==Je.Cancelled&&C.reason!==Je.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 vt&&(S.status===401||S.reason===Je.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,gf(C)),g(C))}else{let b=An.UNKNOWN_REASON;C instanceof vt&&(b=gf(C)),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,b),g(C)}}}),h=this.regionUrl;return this.regionUrl=void 0,this.connectFuture=new Xn((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 o0("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===st.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({},Fc),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(ne.SignalConnected)}catch(h){yield this.engine.close(),this.recreateEngine();const f=new vt("could not establish signal connection",Je.ServerUnreachable);throw h instanceof Error&&(f.message="".concat(f.message,": ").concat(h.message)),h instanceof vt&&(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 vt("Connection attempt aborted",Je.Cancelled);try{yield this.engine.waitForPCInitialConnection(this.connOptions.peerConnectionTimeout,l)}catch(h){throw yield this.engine.close(),this.recreateEngine(),h}cn()&&this.options.disconnectOnPageLeave&&(window.addEventListener("pagehide",this.onPageLeave),window.addEventListener("beforeunload",this.onPageLeave)),cn()&&document.addEventListener("freeze",this.onPageLeave),this.setAndEmitConnectionState(st.Connected),this.emit(ne.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===st.Disconnected){l.log.debug("already disconnected",l.logContext);return}l.log.info("disconnect from room",Object.assign({},l.logContext)),(l.state===st.Connecting||l.state===st.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 vt("Client initiated disconnect",Je.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,An.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=fn();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=Tc();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(ne.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(st.Reconnecting)&&this.emit(ne.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(st.Connected),this.emit(ne.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===Ps.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(ne.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(ne.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=Z.streamStateFromProto(o.state);l.track.setStreamState(d),d!==l.track.streamState&&(c.emit(ce.TrackStreamStateChanged,l,l.track.streamState),this.emitWhenConnected(ne.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(ne.DataReceived,o.payload,a,c,o.topic),a==null||a.emit(ce.DataReceived,o.payload,c)},this.handleSipDtmf=(a,o)=>{this.emit(ne.SipDTMFReceived,o,a),a==null||a.emit(ce.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=k0(o,this.transcriptionReceivedTimes);l==null||l.emit(ae.TranscriptionReceived,d),c==null||c.emit(ce.TranscriptionReceived,d,l),this.emit(ne.TranscriptionReceived,d,c,l)},this.handleChatMessage=(a,o)=>{const c=I0(o);this.emit(ne.ChatMessage,c,a)},this.handleMetrics=(a,o)=>{this.emit(ne.MetricsReceived,a,o)},this.handleDataStream=a=>{this.incomingDataStreamManager.handleDataStreamPacket(a)},this.bufferedSegments=new Map,this.handleAudioPlaybackStarted=()=>{this.canPlaybackAudio||(this.audioEnabled=!0,this.emit(ne.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(ne.AudioPlaybackStatusChanged,!1))},this.handleVideoPlaybackStarted=()=>{this.isVideoPlaybackBlocked&&(this.isVideoPlaybackBlocked=!1,this.emit(ne.VideoPlaybackStatusChanged,!0))},this.handleVideoPlaybackFailed=()=>{this.isVideoPlaybackBlocked||(this.isVideoPlaybackBlocked=!0,this.emit(ne.VideoPlaybackStatusChanged,!1))},this.handleDeviceChange=()=>P(this,void 0,void 0,function*(){var a;((a=fn())===null||a===void 0?void 0:a.os)!=="iOS"&&(yield this.selectDefaultDevices()),this.emit(ne.MediaDevicesChanged)}),this.handleRoomUpdate=a=>{const o=this.roomInfo;this.roomInfo=a,o&&o.metadata!==a.metadata&&this.emitWhenConnected(ne.RoomMetadataChanged,a.metadata),(o==null?void 0:o.activeRecording)!==a.activeRecording&&this.emitWhenConnected(ne.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(ne.ParticipantMetadataChanged,a,this.localParticipant)},this.onLocalParticipantNameChanged=a=>{this.emit(ne.ParticipantNameChanged,a,this.localParticipant)},this.onLocalAttributesChanged=a=>{this.emit(ne.ParticipantAttributesChanged,a,this.localParticipant)},this.onLocalTrackMuted=a=>{this.emit(ne.TrackMuted,a,this.localParticipant)},this.onLocalTrackUnmuted=a=>{this.emit(ne.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(ae.TrackProcessorUpdate,this.onTrackProcessorUpdate),(c=a.track)===null||c===void 0||c.on(ae.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(ne.LocalTrackPublished,a,this.localParticipant),fi(a.track)&&(yield a.track.checkForSilence())&&this.emit(ne.LocalAudioSilenceDetected,a);const f=yield(h=a.track)===null||h===void 0?void 0:h.getDeviceId(!1),g=Rc(a.source);g&&f&&f!==this.localParticipant.activeDeviceMap.get(g)&&(this.localParticipant.activeDeviceMap.set(g,f),this.emit(ne.ActiveDeviceChanged,g,f))}),this.onLocalTrackUnpublished=a=>{var o,c;(o=a.track)===null||o===void 0||o.off(ae.TrackProcessorUpdate,this.onTrackProcessorUpdate),(c=a.track)===null||c===void 0||c.off(ae.Restarted,this.onLocalTrackRestarted),this.emit(ne.LocalTrackUnpublished,a,this.localParticipant)},this.onLocalTrackRestarted=a=>P(this,void 0,void 0,function*(){const o=yield a.getDeviceId(!1),c=Rc(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(ne.ActiveDeviceChanged,c,o))}),this.onLocalConnectionQualityChanged=a=>{this.emit(ne.ConnectionQualityChanged,a,this.localParticipant)},this.onMediaDevicesError=(a,o)=>{this.emit(ne.MediaDevicesError,a,o)},this.onLocalParticipantPermissionsChanged=a=>{this.emit(ne.ParticipantPermissionsChanged,a,this.localParticipant)},this.onLocalChatMessageSent=a=>{this.emit(ne.ChatMessage,a,this.localParticipant)},this.setMaxListeners(100),this.remoteParticipants=new Map,this.sidToIdentity=new Map,this.options=Object.assign(Object.assign({},rb),e),this.log=li((n=this.options.loggerName)!==null&&n!==void 0?n:Pn.Room),this.transcriptionReceivedTimes=new Map,this.options.audioCaptureDefaults=Object.assign(Object.assign({},If),e==null?void 0:e.audioCaptureDefaults),this.options.videoCaptureDefaults=Object.assign(Object.assign({},Df),e==null?void 0:e.videoCaptureDefaults),this.options.publishDefaults=Object.assign(Object.assign({},sb),e==null?void 0:e.publishDefaults),this.maybeCreateEngine(),this.incomingDataStreamManager=new Db,this.outgoingDataStreamManager=new Ub(this.engine,this.log),this.disconnectLock=new sn,this.localParticipant=new Wb("","",this.engine,this.options,this.rpcHandlers,this.outgoingDataStreamManager),this.options.videoCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("videoinput",Oi(this.options.videoCaptureDefaults.deviceId)),this.options.audioCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("audioinput",Oi(this.options.audioCaptureDefaults.deviceId)),!((s=this.options.audioOutput)===null||s===void 0)&&s.deviceId&&this.switchActiveDevice("audiooutput",Oi(this.options.audioOutput.deviceId)).catch(a=>this.log.warn("Could not set audio output: ".concat(a.message),this.logContext)),this.options.e2ee&&this.setupE2EE(),cn()){const a=new AbortController;(r=navigator.mediaDevices)===null||r===void 0||r.addEventListener("devicechange",this.handleDeviceChange,{signal:a.signal}),Bs.cleanupRegistry&&Bs.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 H0(this.options.e2ee),this.e2eeManager.on(Ni.ParticipantEncryptionStatusChanged,(t,n)=>{L0(n)&&(this.isE2EEEnabled=t),this.emit(ne.ParticipantEncryptionStatusChanged,t,n)}),this.e2eeManager.on(Ni.EncryptionError,t=>this.emit(ne.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===st.Disconnected?"":this.roomInfo&&this.roomInfo.sid!==""?this.roomInfo.sid:new Promise((e,t)=>{const n=s=>{s.sid!==""&&(this.engine.off(le.RoomUpdate,n),e(s.sid))};this.engine.on(le.RoomUpdate,n),this.once(ne.Disconnected,()=>{this.engine.off(le.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 wb(this.options),this.engine.on(le.ParticipantUpdate,this.handleParticipantUpdates).on(le.RoomUpdate,this.handleRoomUpdate).on(le.SpeakersChanged,this.handleSpeakersChanged).on(le.StreamStateChanged,this.handleStreamStateUpdate).on(le.ConnectionQualityUpdate,this.handleConnectionQualityUpdate).on(le.SubscriptionError,this.handleSubscriptionError).on(le.SubscriptionPermissionUpdate,this.handleSubscriptionPermissionUpdate).on(le.MediaTrackAdded,(e,t,n)=>{this.onTrackAdded(e,t,n)}).on(le.Disconnected,e=>{this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e)}).on(le.ActiveSpeakersUpdate,this.handleActiveSpeakersUpdate).on(le.DataPacketReceived,this.handleDataPacket).on(le.Resuming,()=>{this.clearConnectionReconcile(),this.isResuming=!0,this.log.info("Resuming signal connection",this.logContext),this.setAndEmitConnectionState(st.SignalReconnecting)&&this.emit(ne.SignalReconnecting)}).on(le.Resumed,()=>{this.registerConnectionReconcile(),this.isResuming=!1,this.log.info("Resumed signal connection",this.logContext),this.updateSubscriptions(),this.emitBufferedEvents(),this.setAndEmitConnectionState(st.Connected)&&this.emit(ne.Reconnected)}).on(le.SignalResumed,()=>{this.bufferedEvents=[],(this.state===st.Reconnecting||this.isResuming)&&this.sendSyncState()}).on(le.Restarting,this.handleRestarting).on(le.SignalRestarted,this.handleSignalRestarted).on(le.Offline,()=>{this.setAndEmitConnectionState(st.Reconnecting)&&this.emit(ne.Reconnecting)}).on(le.DCBufferStatusChanged,(e,t)=>{this.emit(ne.DCBufferStatusChanged,e,t)}).on(le.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(ce.LocalTrackSubscribed,t),this.emitWhenConnected(ne.LocalTrackSubscribed,t,this.localParticipant)}).on(le.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(ne.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 Wt.getInstance().getDevices(e,t)}prepareConnection(e,t){return P(this,void 0,void 0,function*(){if(this.state===st.Disconnected){this.log.debug("prepareConnection to ".concat(e),this.logContext);try{if(yc(new URL(e))&&t){this.regionUrlProvider=new jc(e,t);const n=yield this.regionUrlProvider.getNextBestRegionUrl();n&&this.state===st.Disconnected&&(this.regionUrl=n,yield fetch(Cc(n),{method:"HEAD"}),this.log.debug("prepared connection to ".concat(n),this.logContext))}else yield fetch(Cc(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 Hn({scenario:{case:"speakerUpdate",value:3}});break;case"node-failure":s=new Hn({scenario:{case:"nodeFailure",value:!0}});break;case"server-leave":s=new Hn({scenario:{case:"serverLeave",value:!0}});break;case"migration":s=new Hn({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 Hn({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 Hn({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 Hn({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 ba({reason:An.CLIENT_INITIATED,action:Is.RECONNECT}))});break;case"subscriber-bandwidth":if(t===void 0||typeof t!="number")throw new Error("subscriber-bandwidth requires a number as argument");s=new Hn({scenario:{case:"subscriberBandwidth",value:cs(t)}});break;case"leave-full-reconnect":s=new Hn({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===Z.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===Z.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,!_c()&&!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 Wt.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(ne.ActiveDeviceChanged,n,s)),g}()})}setupLocalParticipantEvents(){this.localParticipant.on(ce.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).on(ce.ParticipantNameChanged,this.onLocalParticipantNameChanged).on(ce.AttributesChanged,this.onLocalAttributesChanged).on(ce.TrackMuted,this.onLocalTrackMuted).on(ce.TrackUnmuted,this.onLocalTrackUnmuted).on(ce.LocalTrackPublished,this.onLocalTrackPublished).on(ce.LocalTrackUnpublished,this.onLocalTrackUnpublished).on(ce.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).on(ce.MediaDevicesError,this.onMediaDevicesError).on(ce.AudioStreamAcquired,this.startAudio).on(ce.ChatMessage,this.onLocalChatMessageSent).on(ce.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===st.Connecting||this.state===st.Reconnecting){const u=()=>{this.onTrackAdded(e,t,n),h()},h=()=>{this.off(ne.Reconnected,u),this.off(ne.Connected,u),this.off(ne.Disconnected,h)};this.once(ne.Reconnected,u),this.once(ne.Connected,u),this.once(ne.Disconnected,h);return}if(this.state===st.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=_0(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(ne.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!==st.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(ce.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).off(ce.ParticipantNameChanged,this.onLocalParticipantNameChanged).off(ce.AttributesChanged,this.onLocalAttributesChanged).off(ce.TrackMuted,this.onLocalTrackMuted).off(ce.TrackUnmuted,this.onLocalTrackUnmuted).off(ce.LocalTrackPublished,this.onLocalTrackPublished).off(ce.LocalTrackUnpublished,this.onLocalTrackUnpublished).off(ce.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).off(ce.MediaDevicesError,this.onMediaDevicesError).off(ce.AudioStreamAcquired,this.startAudio).off(ce.ChatMessage,this.onLocalChatMessageSent).off(ce.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),cn()&&(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(st.Disconnected),this.emit(ne.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(ne.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,At.builtIn("UNSUPPORTED_VERSION"));return}const o=this.rpcHandlers.get(n);if(!o){yield this.engine.publishRpcResponse(e,t,null,At.builtIn("UNSUPPORTED_METHOD"));return}let c=null,l=null;try{const d=yield o({requestId:t,callerIdentity:e,payload:s,responseTimeout:r});Bc(d)>Lf?(c=At.builtIn("RESPONSE_PAYLOAD_TOO_LARGE"),console.warn("RPC Response payload too large for ".concat(n))):l=d}catch(d){d instanceof At?c=d:(console.warn("Uncaught error returned by RPC handler for ".concat(n,". Returning APPLICATION_ERROR instead."),d),c=At.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=Wt.getInstance().previousDevices,r=yield Wt.getInstance().getDevices(void 0,!1),a=fn();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(ne.ActiveDeviceChanged,c.kind,c.deviceId)}const o=["audiooutput","audioinput","videoinput"];for(let c of o){const l=U0(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"&&!Ir()||c==="videoinput"||u.length>0&&!u.find(f=>f.deviceId===this.getActiveDevice(c))&&(c!=="audiooutput"||!Ir())&&(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=_f())!==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(),on(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(ne.AudioPlaybackStatusChanged,n))})}createParticipant(e,t){var n;let s;return t?s=Na.fromParticipantInfo(this.engine.client,t,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}):s=new Na(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(ne.ParticipantConnected,n),n.on(ce.TrackPublished,s=>{this.emitWhenConnected(ne.TrackPublished,s,n)}).on(ce.TrackSubscribed,(s,r)=>{s.kind===Z.Kind.Audio?(s.on(ae.AudioPlaybackStarted,this.handleAudioPlaybackStarted),s.on(ae.AudioPlaybackFailed,this.handleAudioPlaybackFailed)):s.kind===Z.Kind.Video&&(s.on(ae.VideoPlaybackFailed,this.handleVideoPlaybackFailed),s.on(ae.VideoPlaybackStarted,this.handleVideoPlaybackStarted)),this.emit(ne.TrackSubscribed,s,r,n)}).on(ce.TrackUnpublished,s=>{this.emit(ne.TrackUnpublished,s,n)}).on(ce.TrackUnsubscribed,(s,r)=>{this.emit(ne.TrackUnsubscribed,s,r,n)}).on(ce.TrackMuted,s=>{this.emitWhenConnected(ne.TrackMuted,s,n)}).on(ce.TrackUnmuted,s=>{this.emitWhenConnected(ne.TrackUnmuted,s,n)}).on(ce.ParticipantMetadataChanged,s=>{this.emitWhenConnected(ne.ParticipantMetadataChanged,s,n)}).on(ce.ParticipantNameChanged,s=>{this.emitWhenConnected(ne.ParticipantNameChanged,s,n)}).on(ce.AttributesChanged,s=>{this.emitWhenConnected(ne.ParticipantAttributesChanged,s,n)}).on(ce.ConnectionQualityChanged,s=>{this.emitWhenConnected(ne.ConnectionQualityChanged,s,n)}).on(ce.ParticipantPermissionsChanged,s=>{this.emitWhenConnected(ne.ParticipantPermissionsChanged,s,n)}).on(ce.TrackSubscriptionStatusChanged,(s,r)=>{this.emitWhenConnected(ne.TrackSubscriptionStatusChanged,s,r,n)}).on(ce.TrackSubscriptionFailed,(s,r)=>{this.emit(ne.TrackSubscriptionFailed,s,n,r)}).on(ce.TrackSubscriptionPermissionChanged,(s,r)=>{this.emitWhenConnected(ne.TrackSubscriptionPermissionChanged,s,r,n)}).on(ce.Active,()=>{this.emitWhenConnected(ne.ParticipantActive,n),n.kind===Mr.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&&D0(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=$t.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,An.STATE_MISMATCH))):e=0},jb)}clearConnectionReconcile(){this.connectionReconcileInterval&&$t.clearInterval(this.connectionReconcileInterval)}setAndEmitConnectionState(e){return e===this.state?!1:(this.state=e,this.emit(ne.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===st.Reconnecting||this.isResuming||!this.engine||this.engine.pendingReconnect)this.bufferedEvents.push([e,n]);else if(this.state===st.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 ma({sid:"RM_SIMULATED",name:"simulated-room",emptyTimeout:0,maxParticipants:0,creationTime:Et.parse(new Date().getTime()),metadata:"",numParticipants:1,numPublishers:1,turnPassword:"",enabledCodecs:[],activeRecording:!1}),this.localParticipant.updateInfo(new ns({identity:"simulated-local",name:"local-name"})),this.setupLocalParticipantEvents(),this.emit(ne.SignalConnected),this.emit(ne.Connected),this.setAndEmitConnectionState(st.Connected),s.video){const a=new Kc(Z.Kind.Video,new ks({source:Lt.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:wn.AUDIO,name:"video-dummy"}),new Da(s.useRealTracks?(yield window.navigator.mediaDevices.getUserMedia({video:!0})).getVideoTracks()[0]:mf(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(ce.LocalTrackPublished,a)}if(s.audio){const a=new Kc(Z.Kind.Audio,new ks({source:Lt.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:wn.AUDIO}),new Ia(s.useRealTracks?(yield navigator.mediaDevices.getUserMedia({audio:!0})).getAudioTracks()[0]:Tc(),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(ce.LocalTrackPublished,a)}for(let a=0;a<r.count-1;a+=1){let o=new ns({sid:Math.floor(Math.random()*1e4).toString(),identity:"simulated-".concat(a),state:Ps.ACTIVE,tracks:[],joinedAt:Et.parse(Date.now())});const c=this.getOrCreateParticipant(o.identity,o);if(r.video){const l=mf(160*((n=r.aspectRatios[a%r.aspectRatios.length])!==null&&n!==void 0?n:1),160,!1,!0),d=new ks({source:Lt.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:wn.AUDIO});c.addSubscribedMediaTrack(l,d.sid,new MediaStream([l]),new RTCRtpReceiver),o.tracks=[...o.tracks,d]}if(r.audio){const l=Tc(),d=new ks({source:Lt.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:wn.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!==ne.ActiveSpeakersChanged&&e!==ne.TranscriptionReceived){const r=Yf(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)}}Bs.cleanupRegistry=typeof FinalizationRegistry<"u"&&new FinalizationRegistry(i=>{i()});function Yf(i){return i.map(e=>{if(e)return Array.isArray(e)?Yf(e):typeof e=="object"?"logContext"in e?e.logContext:void 0:e})}var Ln;(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"})(Ln||(Ln={}));class Gi extends Wn.EventEmitter{constructor(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.status=Ln.IDLE,this.logs=[],this.options={},this.url=e,this.token=t,this.name=this.constructor.name,this.room=new Bs(n.roomOptions),this.connectOptions=n.connectOptions,this.options=n}run(e){return P(this,void 0,void 0,function*(){if(this.status!==Ln.IDLE)throw Error("check is running already");this.setStatus(Ln.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!==Ln.SKIPPED&&this.setStatus(this.isSuccess()?Ln.SUCCESS:Ln.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===st.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!==st.Disconnected&&(yield this.room.disconnect(),yield new Promise(e=>setTimeout(e,500)))})}skip(){this.setStatus(Ln.SKIPPED)}switchProtocol(e){return P(this,void 0,void 0,function*(){let t=!1,n=!1;if(this.room.on(ne.Reconnecting,()=>{t=!0}),this.room.once(ne.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 on(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 $b extends Gi{get description(){return"Cloud regions"}perform(){return P(this,void 0,void 0,function*(){const e=new jc(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 Yc=1e4;class Xb extends Gi{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/(Yc/1e3)*100).toFixed(2),"%")),n.qualityLimitationDurations.cpu>0&&this.appendWarning("cpu limited ".concat((n.qualityLimitationDurations.cpu/(Yc/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,Yc)),clearInterval(u),o.stop(),t.remove(),yield this.disconnect(),d})}}class Kb extends Gi{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 bf(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 Yb extends Gi{get description(){return"Can publish video"}perform(){return P(this,void 0,void 0,function*(){var e;const t=yield this.connect(),n=yield Vb();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 Jb extends Gi{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(ne.SignalReconnecting,o).on(ne.Reconnecting,o).on(ne.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!==st.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 Zb extends Gi{get description(){return"Can connect via TURN"}perform(){return P(this,void 0,void 0,function*(){var e,t;const n=new kc,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 Qb extends Gi{get description(){return"Establishing WebRTC connection"}perform(){return P(this,void 0,void 0,function*(){let e=!1,t=!1;this.room.on(ne.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&&(e_(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 e_(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 t_ extends Gi{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 kc;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)===Xu.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 lE extends Wn.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:Ln.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!==Ln.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(t_)})}checkWebRTC(){return P(this,void 0,void 0,function*(){return this.createAndRunCheck(Qb)})}checkTURN(){return P(this,void 0,void 0,function*(){return this.createAndRunCheck(Zb)})}checkReconnect(){return P(this,void 0,void 0,function*(){return this.createAndRunCheck(Jb)})}checkPublishAudio(){return P(this,void 0,void 0,function*(){return this.createAndRunCheck(Kb)})}checkPublishVideo(){return P(this,void 0,void 0,function*(){return this.createAndRunCheck(Yb)})}checkConnectionProtocol(){return P(this,void 0,void 0,function*(){const e=yield this.createAndRunCheck(Xb);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($b)})}}class Jc extends EventTarget{constructor(){super(),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.audioElements=new Map,this.audioContainer=null,this.wasConnectedBeforeHidden=!1,this.isPageVisible=!0,this.reconnectAttempts=0,this.maxReconnectAttempts=3,this.isReconnecting=!1,this.isDestroyed=!1,this.pendingTimers=new Set,this.isAppleDevice=/iPhone|iPad|iPod|Macintosh|Mac OS/i.test(navigator.userAgent),this.boundHandleVisibilityChange=this.handleVisibilityChange.bind(this),this.boundHandlePageHide=this.handlePageHide.bind(this),this.boundHandlePageShow=this.handlePageShow.bind(this),this.boundHandleOnline=this.handleOnline.bind(this),this.boundHandleOffline=this.handleOffline.bind(this),this.createAudioContainer(),this.setupLifecycleListeners()}createAudioContainer(){this.audioContainer=document.createElement("div"),this.audioContainer.id=`livekit-audio-${Date.now()}-${Math.random().toString(36).slice(2,9)}`,this.audioContainer.style.cssText="position:absolute;width:0;height:0;overflow:hidden;pointer-events:none;",document.body.appendChild(this.audioContainer)}scheduleTimer(e,t){const n=setTimeout(()=>{this.pendingTimers.delete(n),this.isDestroyed||e()},t);return this.pendingTimers.add(n),n}clearAllTimers(){this.pendingTimers.forEach(e=>clearTimeout(e)),this.pendingTimers.clear()}setupLifecycleListeners(){document.addEventListener("visibilitychange",this.boundHandleVisibilityChange),window.addEventListener("pagehide",this.boundHandlePageHide),window.addEventListener("pageshow",this.boundHandlePageShow),window.addEventListener("online",this.boundHandleOnline),window.addEventListener("offline",this.boundHandleOffline)}removeLifecycleListeners(){document.removeEventListener("visibilitychange",this.boundHandleVisibilityChange),window.removeEventListener("pagehide",this.boundHandlePageHide),window.removeEventListener("pageshow",this.boundHandlePageShow),window.removeEventListener("online",this.boundHandleOnline),window.removeEventListener("offline",this.boundHandleOffline)}handleVisibilityChange(){var t;const e=this.isPageVisible;this.isPageVisible=document.visibilityState==="visible",!this.isPageVisible&&e?(console.log("[LiveKit] Page hidden, pausing media"),this.wasConnectedBeforeHidden=((t=this.room)==null?void 0:t.state)==="connected",this.pauseAllAudio()):this.isPageVisible&&!e&&(console.log("[LiveKit] Page visible, resuming"),this.resumeAfterVisibilityChange())}handlePageHide(e){e.persisted||this.cleanupBeforeUnload()}handlePageShow(e){e.persisted&&(console.log("[LiveKit] Page restored from cache"),this.resumeAfterVisibilityChange())}handleOnline(){var e;console.log("[LiveKit] Network online"),this.wasConnectedBeforeHidden&&((e=this.room)==null?void 0:e.state)!=="connected"&&this.attemptReconnect()}handleOffline(){console.log("[LiveKit] Network offline")}pauseAllAudio(){this.audioElements.forEach(e=>{try{e.pause()}catch(t){console.warn("[LiveKit] Failed to pause audio:",t)}})}async resumeAllAudio(){for(const[,e]of this.audioElements)try{await e.play()}catch(t){console.warn("[LiveKit] Failed to resume audio (may need user interaction):",t),this.audioPlaybackPrompt=!0,this.dispatchEvent(new CustomEvent("audio-playback-status-changed",{detail:{canPlayback:!1}}))}}async resumeAfterVisibilityChange(){this.room&&(this.room.state==="connected"?await this.resumeAllAudio():this.wasConnectedBeforeHidden&&(console.log("[LiveKit] Connection lost while hidden, attempting reconnect"),this.attemptReconnect()))}async attemptReconnect(){var e;if(this.isReconnecting){console.log("[LiveKit] Reconnect already in progress, skipping");return}if(this.reconnectAttempts>=this.maxReconnectAttempts){console.error("[LiveKit] Max reconnect attempts reached"),this.cleanupRoom(),this.dispatchEvent(new CustomEvent("error",{detail:{error:"Connection lost. Please restart the call."}}));return}this.isReconnecting=!0,this.reconnectAttempts++,console.log(`[LiveKit] Reconnect attempt ${this.reconnectAttempts}/${this.maxReconnectAttempts}`);try{((e=this.room)==null?void 0:e.state)==="disconnected"&&(this.cleanupRoom(),this.dispatchEvent(new CustomEvent("error",{detail:{error:"Connection lost. Please restart the call."}})))}finally{this.isReconnecting=!1}}cleanupRoom(){if(this.room){try{this.room.disconnect()}catch(e){console.warn("[LiveKit] Error disconnecting room during cleanup:",e)}this.room=null}this.cleanupAudioElements()}cleanupBeforeUnload(){this.room&&(this.room.disconnect(),this.room=null),this.cleanupAudioElements()}cleanupAudioElements(){this.audioElements.forEach((e,t)=>{try{e.pause(),e.srcObject=null,e.remove()}catch(n){console.warn("[LiveKit] Failed to cleanup audio element:",n)}this.audioElements.delete(t)})}removeAudioContainer(){if(this.audioContainer){try{this.audioContainer.remove()}catch(e){console.warn("[LiveKit] Failed to remove audio container:",e)}this.audioContainer=null}}destroy(){if(this.isDestroyed=!0,this.clearAllTimers(),this.removeLifecycleListeners(),this.cleanupAudioElements(),this.removeAudioContainer(),this.room){try{this.room.disconnect()}catch(e){console.warn("[LiveKit] Error disconnecting room during destroy:",e)}this.room=null}}async playAudioElement(e){try{if(!e.paused)return!0;const t=e.play();return t!==void 0&&await t,!0}catch(t){return t instanceof Error&&t.name==="NotAllowedError"?(console.log("[LiveKit] Autoplay blocked, user interaction required"),!1):t instanceof Error&&t.name==="AbortError"?(console.log("[LiveKit] Play interrupted"),!1):(console.warn("[LiveKit] Failed to play audio:",t),!1)}}async fetchWithTimeout(e,t,n=15e3){const s=new AbortController,r=setTimeout(()=>s.abort(),n);try{return await fetch(e,{...t,signal:s.signal})}finally{clearTimeout(r)}}async connectWithTimeout(e,t,n,s=2e4){return new Promise((r,a)=>{const o=setTimeout(()=>{a(new Error("Connection timeout"))},s);e.connect(t,n).then(()=>{clearTimeout(o),r()}).catch(c=>{clearTimeout(o),a(c)})})}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.callStatus=e,this.dispatchEvent(new CustomEvent("status-changed",{detail:e})))}async makeCall({agentId:e}){if(this.room&&this.room.state==="connected")return;if(this.updateStatus("connecting"),this.isAppleDevice)try{const n=new Audio("data:audio/wav;base64,UklGRiQAAABXQVZFZm10IBAAAAABAAEARKwAAIhYAQACABAAZGF0YQAAAAA=");n.volume=.001,n.play().then(()=>{n.pause(),n.remove(),console.log("[LiveKit] iOS audio playback unlocked")}).catch(()=>{n.remove()})}catch(n){console.warn("[LiveKit] Failed to unlock iOS audio:",n)}const t=navigator.mediaDevices.getUserMedia({audio:!0,video:!1}).then(n=>(console.log("Microphone permission granted"),n)).catch(n=>(console.warn("Microphone permission denied or not available:",n),null));this.error=null,this.isReady=!1,this.room&&(await this.room.disconnect(),this.room=null);try{const n=new Bs({webAudioMix:!0});this.room=n,this.setupRoomEventListeners(n);let s;try{s=await this.fetchWithTimeout(`${this.serviceUrl}/create-room-token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({metadata:{agent_id:e,timestamp:Date.now(),is_apple_device:this.isAppleDevice}})},15e3)}catch(l){throw l instanceof Error&&l.name==="AbortError"?new Error("Request timeout - please check your connection"):l}if(!s.ok){const l=await s.text();throw new Error(`Failed to get room token: ${s.status} ${l}`)}const{token:r,url:a,room_name:o,user_identity:c}=await s.json();this.roomName=o,this.userIdentity=c,this.reconnectAttempts=0,this.wasConnectedBeforeHidden=!1,await this.connectWithTimeout(n,a,r,2e4);try{await Promise.race([n.startAudio(),new Promise(l=>setTimeout(l,3e3))]),console.log("[LiveKit] Audio playback started")}catch(l){console.warn("[LiveKit] Failed to start audio:",l)}this.updateStatus("connected"),this.isReady=!0,requestAnimationFrame(()=>{this.scheduleTimer(async()=>{if(this.isDestroyed||!this.room||this.room.state!=="connected"){t.then(d=>{d&&d.getTracks().forEach(u=>u.stop())});return}const l=await Promise.race([t,new Promise(d=>setTimeout(()=>d(null),5e3))]);if(l)try{await n.localParticipant.setMicrophoneEnabled(!0,{echoCancellation:!0,noiseSuppression:!0,autoGainControl:!this.isAppleDevice}),this.microphoneEnabled=!0,this.dispatchEvent(new CustomEvent("microphone-enabled")),l.getTracks().forEach(d=>d.stop()),this.scheduleTimer(()=>{if(!(this.isDestroyed||!this.room||this.room.state!=="connected"))try{const d=Array.from(n.localParticipant.audioTrackPublications.values()).find(u=>u.kind==="audio");if(d!=null&&d.track){const u=d.track.mediaStreamTrack;u&&this.dispatchEvent(new CustomEvent("local-audio-track",{detail:u}))}}catch(d){console.warn("[LiveKit] Error getting local audio track:",d)}},100)}catch(d){console.warn("Could not enable microphone on connect:",d),this.microphoneEnabled=!1,this.dispatchEvent(new CustomEvent("microphone-disabled"))}else this.microphoneEnabled=!1,this.dispatchEvent(new CustomEvent("microphone-disabled"))},50)}),this.dispatchEvent(new CustomEvent("room-connected",{detail:{roomName:o,identity:c}}))}catch(n){t.then(s=>{s&&s.getTracks().forEach(r=>r.stop())}),this.error=`Connection failed: ${n instanceof Error?n.message:String(n)}`,this.updateStatus("error"),this.isReady=!1,this.room=null,this.dispatchEvent(new CustomEvent("error",{detail:{error:this.error}}))}}setupRoomEventListeners(e){e.on(ne.Connected,()=>{this.updateStatus("connected"),this.isReady=!0,this.reconnectAttempts=0}),e.on(ne.Disconnected,()=>{this.updateStatus("disconnected"),this.connectedParticipants=[],this.microphoneEnabled=!1,this.audioPlaybackPrompt=!1,this.room=null,this.isReady=!1,this.cleanupAudioElements(),this.dispatchEvent(new CustomEvent("disconnected"))}),e.on(ne.Reconnecting,()=>{console.log("[LiveKit] Reconnecting..."),this.dispatchEvent(new CustomEvent("status-changed",{detail:"connecting"}))}),e.on(ne.Reconnected,()=>{console.log("[LiveKit] Reconnected successfully"),this.reconnectAttempts=0,this.isReconnecting=!1,this.resumeAllAudio().catch(t=>{console.warn("[LiveKit] Failed to resume audio after reconnect:",t)}),this.dispatchEvent(new CustomEvent("status-changed",{detail:"connected"}))}),e.on(ne.SignalReconnecting,()=>{console.log("[LiveKit] Signal reconnecting...")}),e.on(ne.ParticipantConnected,t=>{this.connectedParticipants=[...this.connectedParticipants,t.identity];const n=t.identity.includes("agent")||t.identity.includes("voice-assistant")||t.identity.includes("AJ_");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(ne.ParticipantDisconnected,t=>{this.connectedParticipants=this.connectedParticipants.filter(s=>s!==t.identity);const n=t.identity.includes("agent")||t.identity.includes("voice-assistant")||t.identity.includes("AJ_");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(ne.TrackSubscribed,(t,n,s)=>{if(t.kind==="audio"){const r=this.audioElements.get(s.identity);if(r){try{r.pause(),r.srcObject=null,r.remove()}catch(c){console.warn("[LiveKit] Failed to remove existing audio element:",c)}this.audioElements.delete(s.identity)}const a=t.attach();a.setAttribute("playsinline","true"),a.setAttribute("webkit-playsinline","true"),a.dataset.participantId=s.identity,this.isAppleDevice&&(a.volume=.8),this.audioContainer?this.audioContainer.appendChild(a):(console.warn("[LiveKit] Audio container not found, appending to body"),document.body.appendChild(a)),this.audioElements.set(s.identity,a),this.playAudioElement(a).then(c=>{c||(this.audioPlaybackPrompt=!0,this.dispatchEvent(new CustomEvent("audio-playback-status-changed",{detail:{canPlayback:!1}})))}),this.dispatchEvent(new CustomEvent("audio-track-added",{detail:{participant:s.identity,element:a}}));const o=t.mediaStreamTrack;o&&this.dispatchEvent(new CustomEvent("audio-track",{detail:o}))}}),e.on(ne.TrackUnsubscribed,(t,n,s)=>{const r=this.audioElements.get(s.identity);r&&(r.pause(),r.srcObject=null,r.remove(),this.audioElements.delete(s.identity)),t.detach(),this.dispatchEvent(new CustomEvent("audio-track-removed",{detail:{participant:s.identity}}))}),e.on(ne.MediaDevicesError,t=>{this.error=`Media device error: ${t.message}`,this.updateStatus("error"),this.dispatchEvent(new CustomEvent("error",{detail:{error:this.error}}))}),e.on(ne.AudioPlaybackStatusChanged,async()=>{e.canPlaybackAudio||this.connectedParticipants.some(n=>n.includes("agent")||n.includes("voice-assistant")||n.includes("AJ_"))&&!this.audioPlaybackPrompt&&(this.updateStatus("agent-connected"),this.audioPlaybackPrompt=!0),this.dispatchEvent(new CustomEvent("audio-playback-status-changed",{detail:{canPlayback:e.canPlaybackAudio}}))})}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:!this.isAppleDevice}),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}}))}}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.wasConnectedBeforeHidden=!1,this.reconnectAttempts=0,this.isReconnecting=!1,this.cleanupAudioElements(),this.updateStatus("disconnected"),this.dispatchEvent(new CustomEvent("call-ended")),this.scheduleTimer(async()=>{try{await e.disconnect()}catch(t){console.warn("Error during room disconnect:",t)}},0)}}class n_ extends EventTarget{constructor(){super(...arguments),this._status="unknown",this.intervalId=null,this._serviceUrl="",this.INTERVAL_MS=3e4,this.TIMEOUT_MS=5e3,this.refCount=0}get isHealthy(){return this._status!=="unhealthy"}get status(){return this._status}set serviceUrl(e){this._serviceUrl!==e&&(this._serviceUrl=e,this.intervalId!==null&&this.check())}get serviceUrl(){return this._serviceUrl}start(){this.refCount++,this.intervalId===null&&(this.check(),this.intervalId=setInterval(()=>this.check(),this.INTERVAL_MS))}stop(){this.refCount=Math.max(0,this.refCount-1),!(this.refCount>0)&&(this.intervalId!==null&&(clearInterval(this.intervalId),this.intervalId=null),this._status="unknown")}async check(){if(!this._serviceUrl){this.updateStatus("unknown");return}try{const e=new AbortController,t=setTimeout(()=>e.abort(),this.TIMEOUT_MS),n=await fetch(`${this._serviceUrl}/health`,{method:"GET",signal:e.signal});clearTimeout(t),this.updateStatus(n.ok?"healthy":"unhealthy")}catch{this.updateStatus("unhealthy")}}updateStatus(e){this._status!==e&&(this._status=e,this.dispatchEvent(new CustomEvent("health-changed",{detail:e})))}}const Hi=new n_;class Zc{get isHealthy(){return Hi.isHealthy}get status(){return Hi.status}set serviceUrl(e){Hi.serviceUrl=e}get serviceUrl(){return Hi.serviceUrl}start(){Hi.start()}stop(){Hi.stop()}addEventListener(e,t){e==="health-changed"&&Hi.addEventListener(e,t)}removeEventListener(e,t){e==="health-changed"&&Hi.removeEventListener(e,t)}}/**
85
85
  * @license
86
86
  * Copyright 2010-2025 Three.js Authors
87
87
  * SPDX-License-Identifier: MIT
88
- */const Qc="182",i_=0,Jf=1,s_=2,Ua=1,r_=2,Or=3,mi=0,Zt=1,gi=2,vi=0,Vs=1,el=2,Zf=3,Qf=4,a_=5,ls=100,o_=101,c_=102,l_=103,d_=104,u_=200,h_=201,f_=202,p_=203,tl=204,nl=205,m_=206,g_=207,v_=208,b_=209,__=210,y_=211,S_=212,x_=213,T_=214,il=0,sl=1,rl=2,zs=3,al=4,ol=5,cl=6,ll=7,ep=0,C_=1,E_=2,Kn=0,tp=1,np=2,ip=3,sp=4,rp=5,ap=6,op=7,cp=300,ds=301,Gs=302,dl=303,ul=304,Oa=306,hl=1e3,bi=1001,fl=1002,Xt=1003,M_=1004,Fa=1005,Kt=1006,pl=1007,us=1008,yn=1009,lp=1010,dp=1011,Fr=1012,ml=1013,Yn=1014,Jn=1015,_i=1016,gl=1017,vl=1018,Br=1020,up=35902,hp=35899,fp=1021,pp=1022,Ln=1023,yi=1026,hs=1027,mp=1028,bl=1029,Hs=1030,_l=1031,yl=1033,Ba=33776,Va=33777,za=33778,Ga=33779,Sl=35840,xl=35841,Tl=35842,Cl=35843,El=36196,Ml=37492,wl=37496,Al=37488,Rl=37489,Pl=37490,kl=37491,Il=37808,Dl=37809,Ll=37810,Nl=37811,Ul=37812,Ol=37813,Fl=37814,Bl=37815,Vl=37816,zl=37817,Gl=37818,Hl=37819,Wl=37820,ql=37821,jl=36492,$l=36494,Xl=36495,Kl=36283,Yl=36284,Jl=36285,Zl=36286,w_=3200,A_=0,R_=1,Wi="",Sn="srgb",Ws="srgb-linear",Ha="linear",ot="srgb",qs=7680,gp=519,P_=512,k_=513,I_=514,Ql=515,D_=516,L_=517,ed=518,N_=519,vp=35044,bp="300 es",Zn=2e3,Wa=2001;function _p(i){for(let e=i.length-1;e>=0;--e)if(i[e]>=65535)return!0;return!1}function qa(i){return document.createElementNS("http://www.w3.org/1999/xhtml",i)}function U_(){const i=qa("canvas");return i.style.display="block",i}const yp={};function Sp(...i){const e="THREE."+i.shift();console.log(e,...i)}function Oe(...i){const e="THREE."+i.shift();console.warn(e,...i)}function tt(...i){const e="THREE."+i.shift();console.error(e,...i)}function Vr(...i){const e=i.join(" ");e in yp||(yp[e]=!0,Oe(...i))}function O_(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 Yt=["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"],td=Math.PI/180,nd=180/Math.PI;function zr(){const i=Math.random()*4294967295|0,e=Math.random()*4294967295|0,t=Math.random()*4294967295|0,n=Math.random()*4294967295|0;return(Yt[i&255]+Yt[i>>8&255]+Yt[i>>16&255]+Yt[i>>24&255]+"-"+Yt[e&255]+Yt[e>>8&255]+"-"+Yt[e>>16&15|64]+Yt[e>>24&255]+"-"+Yt[t&63|128]+Yt[t>>8&255]+"-"+Yt[t>>16&255]+Yt[t>>24&255]+Yt[n&255]+Yt[n>>8&255]+Yt[n>>16&255]+Yt[n>>24&255]).toLowerCase()}function Ye(i,e,t){return Math.max(e,Math.min(t,i))}function F_(i,e){return(i%e+e)%e}function id(i,e,t){return(1-t)*i+t*e}function Gr(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 ln(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 rt{constructor(e=0,t=0){rt.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=Ye(this.x,e.x,t.x),this.y=Ye(this.y,e.y,t.y),this}clampScalar(e,t){return this.x=Ye(this.x,e,t),this.y=Ye(this.y,e,t),this}clampLength(e,t){const n=this.length();return this.divideScalar(n||1).multiplyScalar(Ye(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(Ye(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 Hr{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(Ye(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 F{constructor(e=0,t=0,n=0){F.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(xp.setFromEuler(e))}applyAxisAngle(e,t){return this.applyQuaternion(xp.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=Ye(this.x,e.x,t.x),this.y=Ye(this.y,e.y,t.y),this.z=Ye(this.z,e.z,t.z),this}clampScalar(e,t){return this.x=Ye(this.x,e,t),this.y=Ye(this.y,e,t),this.z=Ye(this.z,e,t),this}clampLength(e,t){const n=this.length();return this.divideScalar(n||1).multiplyScalar(Ye(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 sd.copy(this).projectOnVector(e),this.sub(sd)}reflect(e){return this.sub(sd.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(Ye(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 sd=new F,xp=new Hr;class ze{constructor(e,t,n,s,r,a,o,c,l){ze.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(rd.makeScale(e,t)),this}rotate(e){return this.premultiply(rd.makeRotation(-e)),this}translate(e,t){return this.premultiply(rd.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 rd=new ze,Tp=new ze().set(.4123908,.3575843,.1804808,.212639,.7151687,.0721923,.0193308,.1191948,.9505322),Cp=new ze().set(3.2409699,-1.5373832,-.4986108,-.9692436,1.8759675,.0415551,.0556301,-.203977,1.0569715);function B_(){const i={enabled:!0,workingColorSpace:Ws,spaces:{},convert:function(s,r,a){return this.enabled===!1||r===a||!r||!a||(this.spaces[r].transfer===ot&&(s.r=Si(s.r),s.g=Si(s.g),s.b=Si(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===ot&&(s.r=$s(s.r),s.g=$s(s.g),s.b=$s(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===Wi?Ha: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 Vr("ColorManagement: .fromWorkingColorSpace() has been renamed to .workingToColorSpace()."),i.workingToColorSpace(s,r)},toWorkingColorSpace:function(s,r){return Vr("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({[Ws]:{primaries:e,whitePoint:n,transfer:Ha,toXYZ:Tp,fromXYZ:Cp,luminanceCoefficients:t,workingColorSpaceConfig:{unpackColorSpace:Sn},outputColorSpaceConfig:{drawingBufferColorSpace:Sn}},[Sn]:{primaries:e,whitePoint:n,transfer:ot,toXYZ:Tp,fromXYZ:Cp,luminanceCoefficients:t,outputColorSpaceConfig:{drawingBufferColorSpace:Sn}}}),i}const Qe=B_();function Si(i){return i<.04045?i*.0773993808:Math.pow(i*.9478672986+.0521327014,2.4)}function $s(i){return i<.0031308?i*12.92:1.055*Math.pow(i,.41666)-.055}let Xs;class V_{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{Xs===void 0&&(Xs=qa("canvas")),Xs.width=e.width,Xs.height=e.height;const s=Xs.getContext("2d");e instanceof ImageData?s.putImageData(e,0,0):s.drawImage(e,0,0,e.width,e.height),n=Xs}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=qa("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]=Si(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(Si(t[n]/255)*255):t[n]=Si(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 z_=0;class ad{constructor(e=null){this.isSource=!0,Object.defineProperty(this,"id",{value:z_++}),this.uuid=zr(),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(od(s[a].image)):r.push(od(s[a]))}else r=od(s);n.url=r}return t||(e.images[this.uuid]=n),n}}function od(i){return typeof HTMLImageElement<"u"&&i instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&i instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&i instanceof ImageBitmap?V_.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 G_=0;const cd=new F;class Qt extends js{constructor(e=Qt.DEFAULT_IMAGE,t=Qt.DEFAULT_MAPPING,n=bi,s=bi,r=Kt,a=us,o=Ln,c=yn,l=Qt.DEFAULT_ANISOTROPY,d=Wi){super(),this.isTexture=!0,Object.defineProperty(this,"id",{value:G_++}),this.uuid=zr(),this.name="",this.source=new ad(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 rt(0,0),this.repeat=new rt(1,1),this.center=new rt(0,0),this.rotation=0,this.matrixAutoUpdate=!0,this.matrix=new ze,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(cd).x}get height(){return this.source.getSize(cd).y}get depth(){return this.source.getSize(cd).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!==cp)return e;if(e.applyMatrix3(this.matrix),e.x<0||e.x>1)switch(this.wrapS){case hl:e.x=e.x-Math.floor(e.x);break;case bi:e.x=e.x<0?0:1;break;case fl: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 hl:e.y=e.y-Math.floor(e.y);break;case bi:e.y=e.y<0?0:1;break;case fl: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++}}Qt.DEFAULT_IMAGE=null,Qt.DEFAULT_MAPPING=cp,Qt.DEFAULT_ANISOTROPY=1;class It{constructor(e=0,t=0,n=0,s=1){It.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=Ye(this.x,e.x,t.x),this.y=Ye(this.y,e.y,t.y),this.z=Ye(this.z,e.z,t.z),this.w=Ye(this.w,e.w,t.w),this}clampScalar(e,t){return this.x=Ye(this.x,e,t),this.y=Ye(this.y,e,t),this.z=Ye(this.z,e,t),this.w=Ye(this.w,e,t),this}clampLength(e,t){const n=this.length();return this.divideScalar(n||1).multiplyScalar(Ye(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 H_ extends js{constructor(e=1,t=1,n={}){super(),n=Object.assign({generateMipmaps:!1,internalFormat:null,minFilter:Kt,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 It(0,0,e,t),this.scissorTest=!1,this.viewport=new It(0,0,e,t);const s={width:e,height:t,depth:n.depth},r=new Qt(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:Kt,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 ad(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 Qn extends H_{constructor(e=1,t=1,n={}){super(e,t,n),this.isWebGLRenderTarget=!0}}class Ep extends Qt{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=Xt,this.minFilter=Xt,this.wrapR=bi,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1,this.layerUpdates=new Set}addLayerUpdate(e){this.layerUpdates.add(e)}clearLayerUpdates(){this.layerUpdates.clear()}}class W_ extends Qt{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=Xt,this.minFilter=Xt,this.wrapR=bi,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}}class Wr{constructor(e=new F(1/0,1/0,1/0),t=new F(-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(Nn.fromArray(e,t));return this}setFromBufferAttribute(e){this.makeEmpty();for(let t=0,n=e.count;t<n;t++)this.expandByPoint(Nn.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=Nn.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,Nn):Nn.fromBufferAttribute(r,a),Nn.applyMatrix4(e.matrixWorld),this.expandByPoint(Nn);else e.boundingBox!==void 0?(e.boundingBox===null&&e.computeBoundingBox(),ja.copy(e.boundingBox)):(n.boundingBox===null&&n.computeBoundingBox(),ja.copy(n.boundingBox)),ja.applyMatrix4(e.matrixWorld),this.union(ja)}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,Nn),Nn.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(qr),$a.subVectors(this.max,qr),Ks.subVectors(e.a,qr),Ys.subVectors(e.b,qr),Js.subVectors(e.c,qr),qi.subVectors(Ys,Ks),ji.subVectors(Js,Ys),fs.subVectors(Ks,Js);let t=[0,-qi.z,qi.y,0,-ji.z,ji.y,0,-fs.z,fs.y,qi.z,0,-qi.x,ji.z,0,-ji.x,fs.z,0,-fs.x,-qi.y,qi.x,0,-ji.y,ji.x,0,-fs.y,fs.x,0];return!ld(t,Ks,Ys,Js,$a)||(t=[1,0,0,0,1,0,0,0,1],!ld(t,Ks,Ys,Js,$a))?!1:(Xa.crossVectors(qi,ji),t=[Xa.x,Xa.y,Xa.z],ld(t,Ks,Ys,Js,$a))}clampPoint(e,t){return t.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,Nn).distanceTo(e)}getBoundingSphere(e){return this.isEmpty()?e.makeEmpty():(this.getCenter(e.center),e.radius=this.getSize(Nn).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:(xi[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(e),xi[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(e),xi[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(e),xi[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(e),xi[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(e),xi[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(e),xi[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(e),xi[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(e),this.setFromPoints(xi),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 xi=[new F,new F,new F,new F,new F,new F,new F,new F],Nn=new F,ja=new Wr,Ks=new F,Ys=new F,Js=new F,qi=new F,ji=new F,fs=new F,qr=new F,$a=new F,Xa=new F,ps=new F;function ld(i,e,t,n,s){for(let r=0,a=i.length-3;r<=a;r+=3){ps.fromArray(i,r);const o=s.x*Math.abs(ps.x)+s.y*Math.abs(ps.y)+s.z*Math.abs(ps.z),c=e.dot(ps),l=t.dot(ps),d=n.dot(ps);if(Math.max(-Math.max(c,l,d),Math.min(c,l,d))>o)return!1}return!0}const q_=new Wr,jr=new F,dd=new F;class ud{constructor(e=new F,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):q_.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;jr.subVectors(e,this.center);const t=jr.lengthSq();if(t>this.radius*this.radius){const n=Math.sqrt(t),s=(n-this.radius)*.5;this.center.addScaledVector(jr,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):(dd.subVectors(e.center,this.center).setLength(e.radius),this.expandByPoint(jr.copy(e.center).add(dd)),this.expandByPoint(jr.copy(e.center).sub(dd))),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 Ti=new F,hd=new F,Ka=new F,$i=new F,fd=new F,Ya=new F,pd=new F;class j_{constructor(e=new F,t=new F(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,Ti)),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=Ti.subVectors(e,this.origin).dot(this.direction);return t<0?this.origin.distanceToSquared(e):(Ti.copy(this.origin).addScaledVector(this.direction,t),Ti.distanceToSquared(e))}distanceSqToSegment(e,t,n,s){hd.copy(e).add(t).multiplyScalar(.5),Ka.copy(t).sub(e).normalize(),$i.copy(this.origin).sub(hd);const r=e.distanceTo(t)*.5,a=-this.direction.dot(Ka),o=$i.dot(this.direction),c=-$i.dot(Ka),l=$i.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(hd).addScaledVector(Ka,h),f}intersectSphere(e,t){Ti.subVectors(e.center,this.origin);const n=Ti.dot(this.direction),s=Ti.dot(Ti)-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,Ti)!==null}intersectTriangle(e,t,n,s,r){fd.subVectors(t,e),Ya.subVectors(n,e),pd.crossVectors(fd,Ya);let a=this.direction.dot(pd),o;if(a>0){if(s)return null;o=1}else if(a<0)o=-1,a=-a;else return null;$i.subVectors(this.origin,e);const c=o*this.direction.dot(Ya.crossVectors($i,Ya));if(c<0)return null;const l=o*this.direction.dot(fd.cross($i));if(l<0||c+l>a)return null;const d=-o*$i.dot(pd);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 Nt{constructor(e,t,n,s,r,a,o,c,l,d,u,h,f,g,v,m){Nt.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 Nt().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/Zs.setFromMatrixColumn(e,0).length(),r=1/Zs.setFromMatrixColumn(e,1).length(),a=1/Zs.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($_,e,X_)}lookAt(e,t,n){const s=this.elements;return mn.subVectors(e,t),mn.lengthSq()===0&&(mn.z=1),mn.normalize(),Xi.crossVectors(n,mn),Xi.lengthSq()===0&&(Math.abs(n.z)===1?mn.x+=1e-4:mn.z+=1e-4,mn.normalize(),Xi.crossVectors(n,mn)),Xi.normalize(),Ja.crossVectors(mn,Xi),s[0]=Xi.x,s[4]=Ja.x,s[8]=mn.x,s[1]=Xi.y,s[5]=Ja.y,s[9]=mn.y,s[2]=Xi.z,s[6]=Ja.z,s[10]=mn.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],y=s[12],T=s[1],R=s[5],U=s[9],B=s[13],q=s[2],K=s[6],H=s[10],W=s[14],te=s[3],ve=s[7],de=s[11],_e=s[15];return r[0]=a*M+o*T+c*q+l*te,r[4]=a*A+o*R+c*K+l*ve,r[8]=a*k+o*U+c*H+l*de,r[12]=a*y+o*B+c*W+l*_e,r[1]=d*M+u*T+h*q+f*te,r[5]=d*A+u*R+h*K+f*ve,r[9]=d*k+u*U+h*H+f*de,r[13]=d*y+u*B+h*W+f*_e,r[2]=g*M+v*T+m*q+p*te,r[6]=g*A+v*R+m*K+p*ve,r[10]=g*k+v*U+m*H+p*de,r[14]=g*y+v*B+m*W+p*_e,r[3]=x*M+C*T+b*q+S*te,r[7]=x*A+C*R+b*K+S*ve,r[11]=x*k+C*U+b*H+S*de,r[15]=x*y+C*B+b*W+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=Zs.set(s[0],s[1],s[2]).length();const a=Zs.set(s[4],s[5],s[6]).length(),o=Zs.set(s[8],s[9],s[10]).length();this.determinant()<0&&(r=-r),Un.copy(this);const l=1/r,d=1/a,u=1/o;return Un.elements[0]*=l,Un.elements[1]*=l,Un.elements[2]*=l,Un.elements[4]*=d,Un.elements[5]*=d,Un.elements[6]*=d,Un.elements[8]*=u,Un.elements[9]*=u,Un.elements[10]*=u,t.setFromRotationMatrix(Un),n.x=r,n.y=a,n.z=o,this}makePerspective(e,t,n,s,r,a,o=Zn,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===Zn)g=-(a+r)/(a-r),v=-2*a*r/(a-r);else if(o===Wa)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=Zn,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===Zn)g=-2/(a-r),v=-(a+r)/(a-r);else if(o===Wa)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 Zs=new F,Un=new Nt,$_=new F(0,0,0),X_=new F(1,1,1),Xi=new F,Ja=new F,mn=new F,Mp=new Nt,wp=new Hr;class Ci{constructor(e=0,t=0,n=0,s=Ci.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(Ye(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(-Ye(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(Ye(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(-Ye(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(Ye(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(-Ye(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 Mp.makeRotationFromQuaternion(e),this.setFromRotationMatrix(Mp,t,n)}setFromVector3(e,t=this._order){return this.set(e.x,e.y,e.z,t)}reorder(e){return wp.setFromEuler(this),this.setFromQuaternion(wp,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}}Ci.DEFAULT_ORDER="XYZ";class Ap{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 K_=0;const Rp=new F,Qs=new Hr,Ei=new Nt,Za=new F,$r=new F,Y_=new F,J_=new Hr,Pp=new F(1,0,0),kp=new F(0,1,0),Ip=new F(0,0,1),Dp={type:"added"},Z_={type:"removed"},er={type:"childadded",child:null},md={type:"childremoved",child:null};class gn extends js{constructor(){super(),this.isObject3D=!0,Object.defineProperty(this,"id",{value:K_++}),this.uuid=zr(),this.name="",this.type="Object3D",this.parent=null,this.children=[],this.up=gn.DEFAULT_UP.clone();const e=new F,t=new Ci,n=new Hr,s=new F(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 Nt},normalMatrix:{value:new ze}}),this.matrix=new Nt,this.matrixWorld=new Nt,this.matrixAutoUpdate=gn.DEFAULT_MATRIX_AUTO_UPDATE,this.matrixWorldAutoUpdate=gn.DEFAULT_MATRIX_WORLD_AUTO_UPDATE,this.matrixWorldNeedsUpdate=!1,this.layers=new Ap,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 Qs.setFromAxisAngle(e,t),this.quaternion.multiply(Qs),this}rotateOnWorldAxis(e,t){return Qs.setFromAxisAngle(e,t),this.quaternion.premultiply(Qs),this}rotateX(e){return this.rotateOnAxis(Pp,e)}rotateY(e){return this.rotateOnAxis(kp,e)}rotateZ(e){return this.rotateOnAxis(Ip,e)}translateOnAxis(e,t){return Rp.copy(e).applyQuaternion(this.quaternion),this.position.add(Rp.multiplyScalar(t)),this}translateX(e){return this.translateOnAxis(Pp,e)}translateY(e){return this.translateOnAxis(kp,e)}translateZ(e){return this.translateOnAxis(Ip,e)}localToWorld(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(this.matrixWorld)}worldToLocal(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(Ei.copy(this.matrixWorld).invert())}lookAt(e,t,n){e.isVector3?Za.copy(e):Za.set(e,t,n);const s=this.parent;this.updateWorldMatrix(!0,!1),$r.setFromMatrixPosition(this.matrixWorld),this.isCamera||this.isLight?Ei.lookAt($r,Za,this.up):Ei.lookAt(Za,$r,this.up),this.quaternion.setFromRotationMatrix(Ei),s&&(Ei.extractRotation(s.matrixWorld),Qs.setFromRotationMatrix(Ei),this.quaternion.premultiply(Qs.invert()))}add(e){if(arguments.length>1){for(let t=0;t<arguments.length;t++)this.add(arguments[t]);return this}return e===this?(tt("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(Dp),er.child=e,this.dispatchEvent(er),er.child=null):tt("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(Z_),md.child=e,this.dispatchEvent(md),md.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),Ei.copy(this.matrixWorld).invert(),e.parent!==null&&(e.parent.updateWorldMatrix(!0,!1),Ei.multiply(e.parent.matrixWorld)),e.applyMatrix4(Ei),e.removeFromParent(),e.parent=this,this.children.push(e),e.updateWorldMatrix(!1,!0),e.dispatchEvent(Dp),er.child=e,this.dispatchEvent(er),er.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($r,e,Y_),e}getWorldScale(e){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose($r,J_,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}}gn.DEFAULT_UP=new F(0,1,0),gn.DEFAULT_MATRIX_AUTO_UPDATE=!0,gn.DEFAULT_MATRIX_WORLD_AUTO_UPDATE=!0;const On=new F,Mi=new F,gd=new F,wi=new F,tr=new F,nr=new F,Lp=new F,vd=new F,bd=new F,_d=new F,yd=new It,Sd=new It,xd=new It;class Fn{constructor(e=new F,t=new F,n=new F){this.a=e,this.b=t,this.c=n}static getNormal(e,t,n,s){s.subVectors(n,t),On.subVectors(e,t),s.cross(On);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){On.subVectors(s,t),Mi.subVectors(n,t),gd.subVectors(e,t);const a=On.dot(On),o=On.dot(Mi),c=On.dot(gd),l=Mi.dot(Mi),d=Mi.dot(gd),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,wi)===null?!1:wi.x>=0&&wi.y>=0&&wi.x+wi.y<=1}static getInterpolation(e,t,n,s,r,a,o,c){return this.getBarycoord(e,t,n,s,wi)===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,wi.x),c.addScaledVector(a,wi.y),c.addScaledVector(o,wi.z),c)}static getInterpolatedAttribute(e,t,n,s,r,a){return yd.setScalar(0),Sd.setScalar(0),xd.setScalar(0),yd.fromBufferAttribute(e,t),Sd.fromBufferAttribute(e,n),xd.fromBufferAttribute(e,s),a.setScalar(0),a.addScaledVector(yd,r.x),a.addScaledVector(Sd,r.y),a.addScaledVector(xd,r.z),a}static isFrontFacing(e,t,n,s){return On.subVectors(n,t),Mi.subVectors(e,t),On.cross(Mi).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 On.subVectors(this.c,this.b),Mi.subVectors(this.a,this.b),On.cross(Mi).length()*.5}getMidpoint(e){return e.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(e){return Fn.getNormal(this.a,this.b,this.c,e)}getPlane(e){return e.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(e,t){return Fn.getBarycoord(e,this.a,this.b,this.c,t)}getInterpolation(e,t,n,s,r){return Fn.getInterpolation(e,this.a,this.b,this.c,t,n,s,r)}containsPoint(e){return Fn.containsPoint(e,this.a,this.b,this.c)}isFrontFacing(e){return Fn.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;tr.subVectors(s,n),nr.subVectors(r,n),vd.subVectors(e,n);const c=tr.dot(vd),l=nr.dot(vd);if(c<=0&&l<=0)return t.copy(n);bd.subVectors(e,s);const d=tr.dot(bd),u=nr.dot(bd);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(tr,a);_d.subVectors(e,r);const f=tr.dot(_d),g=nr.dot(_d);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(nr,o);const m=d*g-f*u;if(m<=0&&u-d>=0&&f-g>=0)return Lp.subVectors(r,s),o=(u-d)/(u-d+(f-g)),t.copy(s).addScaledVector(Lp,o);const p=1/(m+v+h);return a=v*p,o=h*p,t.copy(n).addScaledVector(tr,a).addScaledVector(nr,o)}equals(e){return e.a.equals(this.a)&&e.b.equals(this.b)&&e.c.equals(this.c)}}const Np={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},Ki={h:0,s:0,l:0},Qa={h:0,s:0,l:0};function Td(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 Ze{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=Sn){return e=Math.floor(e),this.r=(e>>16&255)/255,this.g=(e>>8&255)/255,this.b=(e&255)/255,Qe.colorSpaceToWorking(this,t),this}setRGB(e,t,n,s=Qe.workingColorSpace){return this.r=e,this.g=t,this.b=n,Qe.colorSpaceToWorking(this,s),this}setHSL(e,t,n,s=Qe.workingColorSpace){if(e=F_(e,1),t=Ye(t,0,1),n=Ye(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=Td(a,r,e+1/3),this.g=Td(a,r,e),this.b=Td(a,r,e-1/3)}return Qe.colorSpaceToWorking(this,s),this}setStyle(e,t=Sn){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=Sn){const n=Np[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=Si(e.r),this.g=Si(e.g),this.b=Si(e.b),this}copyLinearToSRGB(e){return this.r=$s(e.r),this.g=$s(e.g),this.b=$s(e.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(e=Sn){return Qe.workingToColorSpace(Jt.copy(this),e),Math.round(Ye(Jt.r*255,0,255))*65536+Math.round(Ye(Jt.g*255,0,255))*256+Math.round(Ye(Jt.b*255,0,255))}getHexString(e=Sn){return("000000"+this.getHex(e).toString(16)).slice(-6)}getHSL(e,t=Qe.workingColorSpace){Qe.workingToColorSpace(Jt.copy(this),t);const n=Jt.r,s=Jt.g,r=Jt.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=Qe.workingColorSpace){return Qe.workingToColorSpace(Jt.copy(this),t),e.r=Jt.r,e.g=Jt.g,e.b=Jt.b,e}getStyle(e=Sn){Qe.workingToColorSpace(Jt.copy(this),e);const t=Jt.r,n=Jt.g,s=Jt.b;return e!==Sn?`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(Ki),this.setHSL(Ki.h+e,Ki.s+t,Ki.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(Ki),e.getHSL(Qa);const n=id(Ki.h,Qa.h,t),s=id(Ki.s,Qa.s,t),r=id(Ki.l,Qa.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 Jt=new Ze;Ze.NAMES=Np;let Q_=0;class eo extends js{constructor(){super(),this.isMaterial=!0,Object.defineProperty(this,"id",{value:Q_++}),this.uuid=zr(),this.name="",this.type="Material",this.blending=Vs,this.side=mi,this.vertexColors=!1,this.opacity=1,this.transparent=!1,this.alphaHash=!1,this.blendSrc=tl,this.blendDst=nl,this.blendEquation=ls,this.blendSrcAlpha=null,this.blendDstAlpha=null,this.blendEquationAlpha=null,this.blendColor=new Ze(0,0,0),this.blendAlpha=0,this.depthFunc=zs,this.depthTest=!0,this.depthWrite=!0,this.stencilWriteMask=255,this.stencilFunc=gp,this.stencilRef=0,this.stencilFuncMask=255,this.stencilFail=qs,this.stencilZFail=qs,this.stencilZPass=qs,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!==Vs&&(n.blending=this.blending),this.side!==mi&&(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!==tl&&(n.blendSrc=this.blendSrc),this.blendDst!==nl&&(n.blendDst=this.blendDst),this.blendEquation!==ls&&(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!==zs&&(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!==gp&&(n.stencilFunc=this.stencilFunc),this.stencilRef!==0&&(n.stencilRef=this.stencilRef),this.stencilFuncMask!==255&&(n.stencilFuncMask=this.stencilFuncMask),this.stencilFail!==qs&&(n.stencilFail=this.stencilFail),this.stencilZFail!==qs&&(n.stencilZFail=this.stencilZFail),this.stencilZPass!==qs&&(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 Up extends eo{constructor(e){super(),this.isMeshBasicMaterial=!0,this.type="MeshBasicMaterial",this.color=new Ze(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 Ci,this.combine=ep,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 Ut=new F,to=new rt;let ey=0;class ei{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:ey++}),this.name="",this.array=e,this.itemSize=t,this.count=e!==void 0?e.length/t:0,this.normalized=n,this.usage=vp,this.updateRanges=[],this.gpuType=Jn,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++)to.fromBufferAttribute(this,t),to.applyMatrix3(e),this.setXY(t,to.x,to.y);else if(this.itemSize===3)for(let t=0,n=this.count;t<n;t++)Ut.fromBufferAttribute(this,t),Ut.applyMatrix3(e),this.setXYZ(t,Ut.x,Ut.y,Ut.z);return this}applyMatrix4(e){for(let t=0,n=this.count;t<n;t++)Ut.fromBufferAttribute(this,t),Ut.applyMatrix4(e),this.setXYZ(t,Ut.x,Ut.y,Ut.z);return this}applyNormalMatrix(e){for(let t=0,n=this.count;t<n;t++)Ut.fromBufferAttribute(this,t),Ut.applyNormalMatrix(e),this.setXYZ(t,Ut.x,Ut.y,Ut.z);return this}transformDirection(e){for(let t=0,n=this.count;t<n;t++)Ut.fromBufferAttribute(this,t),Ut.transformDirection(e),this.setXYZ(t,Ut.x,Ut.y,Ut.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=Gr(n,this.array)),n}setComponent(e,t,n){return this.normalized&&(n=ln(n,this.array)),this.array[e*this.itemSize+t]=n,this}getX(e){let t=this.array[e*this.itemSize];return this.normalized&&(t=Gr(t,this.array)),t}setX(e,t){return this.normalized&&(t=ln(t,this.array)),this.array[e*this.itemSize]=t,this}getY(e){let t=this.array[e*this.itemSize+1];return this.normalized&&(t=Gr(t,this.array)),t}setY(e,t){return this.normalized&&(t=ln(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=Gr(t,this.array)),t}setZ(e,t){return this.normalized&&(t=ln(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=Gr(t,this.array)),t}setW(e,t){return this.normalized&&(t=ln(t,this.array)),this.array[e*this.itemSize+3]=t,this}setXY(e,t,n){return e*=this.itemSize,this.normalized&&(t=ln(t,this.array),n=ln(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=ln(t,this.array),n=ln(n,this.array),s=ln(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=ln(t,this.array),n=ln(n,this.array),s=ln(s,this.array),r=ln(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!==vp&&(e.usage=this.usage),e}}class Op extends ei{constructor(e,t,n){super(new Uint16Array(e),t,n)}}class Fp extends ei{constructor(e,t,n){super(new Uint32Array(e),t,n)}}class en extends ei{constructor(e,t,n){super(new Float32Array(e),t,n)}}let ty=0;const xn=new Nt,Cd=new gn,ir=new F,vn=new Wr,Xr=new Wr,qt=new F;class Bn extends js{constructor(){super(),this.isBufferGeometry=!0,Object.defineProperty(this,"id",{value:ty++}),this.uuid=zr(),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(_p(e)?Fp:Op)(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 ze().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 xn.makeRotationFromQuaternion(e),this.applyMatrix4(xn),this}rotateX(e){return xn.makeRotationX(e),this.applyMatrix4(xn),this}rotateY(e){return xn.makeRotationY(e),this.applyMatrix4(xn),this}rotateZ(e){return xn.makeRotationZ(e),this.applyMatrix4(xn),this}translate(e,t,n){return xn.makeTranslation(e,t,n),this.applyMatrix4(xn),this}scale(e,t,n){return xn.makeScale(e,t,n),this.applyMatrix4(xn),this}lookAt(e){return Cd.lookAt(e),Cd.updateMatrix(),this.applyMatrix4(Cd.matrix),this}center(){return this.computeBoundingBox(),this.boundingBox.getCenter(ir).negate(),this.translate(ir.x,ir.y,ir.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 en(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 Wr);const e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute){tt("BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.",this),this.boundingBox.set(new F(-1/0,-1/0,-1/0),new F(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];vn.setFromBufferAttribute(r),this.morphTargetsRelative?(qt.addVectors(this.boundingBox.min,vn.min),this.boundingBox.expandByPoint(qt),qt.addVectors(this.boundingBox.max,vn.max),this.boundingBox.expandByPoint(qt)):(this.boundingBox.expandByPoint(vn.min),this.boundingBox.expandByPoint(vn.max))}}else this.boundingBox.makeEmpty();(isNaN(this.boundingBox.min.x)||isNaN(this.boundingBox.min.y)||isNaN(this.boundingBox.min.z))&&tt('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 ud);const e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute){tt("BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.",this),this.boundingSphere.set(new F,1/0);return}if(e){const n=this.boundingSphere.center;if(vn.setFromBufferAttribute(e),t)for(let r=0,a=t.length;r<a;r++){const o=t[r];Xr.setFromBufferAttribute(o),this.morphTargetsRelative?(qt.addVectors(vn.min,Xr.min),vn.expandByPoint(qt),qt.addVectors(vn.max,Xr.max),vn.expandByPoint(qt)):(vn.expandByPoint(Xr.min),vn.expandByPoint(Xr.max))}vn.getCenter(n);let s=0;for(let r=0,a=e.count;r<a;r++)qt.fromBufferAttribute(e,r),s=Math.max(s,n.distanceToSquared(qt));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++)qt.fromBufferAttribute(o,l),c&&(ir.fromBufferAttribute(e,l),qt.add(ir)),s=Math.max(s,n.distanceToSquared(qt))}this.boundingSphere.radius=Math.sqrt(s),isNaN(this.boundingSphere.radius)&&tt('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){tt("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 ei(new Float32Array(4*n.count),4));const a=this.getAttribute("tangent"),o=[],c=[];for(let k=0;k<n.count;k++)o[k]=new F,c[k]=new F;const l=new F,d=new F,u=new F,h=new rt,f=new rt,g=new rt,v=new F,m=new F;function p(k,y,T){l.fromBufferAttribute(n,k),d.fromBufferAttribute(n,y),u.fromBufferAttribute(n,T),h.fromBufferAttribute(r,k),f.fromBufferAttribute(r,y),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[y].add(v),o[T].add(v),c[k].add(m),c[y].add(m),c[T].add(m))}let x=this.groups;x.length===0&&(x=[{start:0,count:e.count}]);for(let k=0,y=x.length;k<y;++k){const T=x[k],R=T.start,U=T.count;for(let B=R,q=R+U;B<q;B+=3)p(e.getX(B+0),e.getX(B+1),e.getX(B+2))}const C=new F,b=new F,S=new F,M=new F;function A(k){S.fromBufferAttribute(s,k),M.copy(S);const y=o[k];C.copy(y),C.sub(S.multiplyScalar(S.dot(y))).normalize(),b.crossVectors(M,y);const R=b.dot(c[k])<0?-1:1;a.setXYZW(k,C.x,C.y,C.z,R)}for(let k=0,y=x.length;k<y;++k){const T=x[k],R=T.start,U=T.count;for(let B=R,q=R+U;B<q;B+=3)A(e.getX(B+0)),A(e.getX(B+1)),A(e.getX(B+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 ei(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 F,r=new F,a=new F,o=new F,c=new F,l=new F,d=new F,u=new F;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++)qt.fromBufferAttribute(e,t),qt.normalize(),e.setXYZ(t,qt.x,qt.y,qt.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 ei(h,d,u)}if(this.index===null)return Oe("BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed."),this;const t=new Bn,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 Bp=new Nt,ms=new j_,no=new ud,Vp=new F,io=new F,so=new F,ro=new F,Ed=new F,ao=new F,zp=new F,oo=new F;class Vn extends gn{constructor(e=new Bn,t=new Up){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){ao.set(0,0,0);for(let c=0,l=r.length;c<l;c++){const d=o[c],u=r[c];d!==0&&(Ed.fromBufferAttribute(u,e),a?ao.addScaledVector(Ed,d):ao.addScaledVector(Ed.sub(t),d))}t.add(ao)}return t}raycast(e,t){const n=this.geometry,s=this.material,r=this.matrixWorld;s!==void 0&&(n.boundingSphere===null&&n.computeBoundingSphere(),no.copy(n.boundingSphere),no.applyMatrix4(r),ms.copy(e.ray).recast(e.near),!(no.containsPoint(ms.origin)===!1&&(ms.intersectSphere(no,Vp)===null||ms.origin.distanceToSquared(Vp)>(e.far-e.near)**2))&&(Bp.copy(r).invert(),ms.copy(e.ray).applyMatrix4(Bp),!(n.boundingBox!==null&&ms.intersectsBox(n.boundingBox)===!1)&&this._computeIntersections(e,t,ms)))}_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=co(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=co(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=co(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=co(this,a,e,n,l,d,u,x,C,b),s&&(s.faceIndex=Math.floor(m/3),t.push(s))}}}}function ny(i,e,t,n,s,r,a,o){let c;if(e.side===Zt?c=n.intersectTriangle(a,r,s,!0,o):c=n.intersectTriangle(s,r,a,e.side===mi,o),c===null)return null;oo.copy(o),oo.applyMatrix4(i.matrixWorld);const l=t.ray.origin.distanceTo(oo);return l<t.near||l>t.far?null:{distance:l,point:oo.clone(),object:i}}function co(i,e,t,n,s,r,a,o,c,l){i.getVertexPosition(o,io),i.getVertexPosition(c,so),i.getVertexPosition(l,ro);const d=ny(i,e,t,n,io,so,ro,zp);if(d){const u=new F;Fn.getBarycoord(zp,io,so,ro,u),s&&(d.uv=Fn.getInterpolatedAttribute(s,o,c,l,u,new rt)),r&&(d.uv1=Fn.getInterpolatedAttribute(r,o,c,l,u,new rt)),a&&(d.normal=Fn.getInterpolatedAttribute(a,o,c,l,u,new F),d.normal.dot(n.direction)>0&&d.normal.multiplyScalar(-1));const h={a:o,b:c,c:l,normal:new F,materialIndex:0};Fn.getNormal(io,so,ro,h.normal),d.face=h,d.barycoord=u}return d}class Kr extends Bn{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 en(l,3)),this.setAttribute("normal",new en(d,3)),this.setAttribute("uv",new en(u,2));function g(v,m,p,x,C,b,S,M,A,k,y){const T=b/A,R=S/k,U=b/2,B=S/2,q=M/2,K=A+1,H=k+1;let W=0,te=0;const ve=new F;for(let de=0;de<H;de++){const _e=de*R-B;for(let Ve=0;Ve<K;Ve++){const Be=Ve*T-U;ve[v]=Be*x,ve[m]=_e*C,ve[p]=q,l.push(ve.x,ve.y,ve.z),ve[v]=0,ve[m]=0,ve[p]=M>0?1:-1,d.push(ve.x,ve.y,ve.z),u.push(Ve/A),u.push(1-de/k),W+=1}}for(let de=0;de<k;de++)for(let _e=0;_e<A;_e++){const Ve=h+_e+K*de,Be=h+_e+K*(de+1),Ct=h+(_e+1)+K*(de+1),ht=h+(_e+1)+K*de;c.push(Ve,Be,ht),c.push(Be,Ct,ht),te+=6}o.addGroup(f,te,y),f+=te,h+=W}}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new Kr(e.width,e.height,e.depth,e.widthSegments,e.heightSegments,e.depthSegments)}}function sr(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 tn(i){const e={};for(let t=0;t<i.length;t++){const n=sr(i[t]);for(const s in n)e[s]=n[s]}return e}function iy(i){const e=[];for(let t=0;t<i.length;t++)e.push(i[t].clone());return e}function Gp(i){const e=i.getRenderTarget();return e===null?i.outputColorSpace:e.isXRRenderTarget===!0?e.texture.colorSpace:Qe.workingColorSpace}const sy={clone:sr,merge:tn};var ry=`void main() {
88
+ */const Qc="182",i_=0,Jf=1,s_=2,Ua=1,r_=2,Or=3,mi=0,Zt=1,gi=2,vi=0,Vs=1,el=2,Zf=3,Qf=4,a_=5,ls=100,o_=101,c_=102,l_=103,d_=104,u_=200,h_=201,f_=202,p_=203,tl=204,nl=205,m_=206,g_=207,v_=208,b_=209,__=210,y_=211,S_=212,x_=213,T_=214,il=0,sl=1,rl=2,zs=3,al=4,ol=5,cl=6,ll=7,ep=0,C_=1,E_=2,Yn=0,tp=1,np=2,ip=3,sp=4,rp=5,ap=6,op=7,cp=300,ds=301,Gs=302,dl=303,ul=304,Oa=306,hl=1e3,bi=1001,fl=1002,Xt=1003,M_=1004,Fa=1005,Kt=1006,pl=1007,us=1008,Sn=1009,lp=1010,dp=1011,Fr=1012,ml=1013,Jn=1014,Zn=1015,_i=1016,gl=1017,vl=1018,Br=1020,up=35902,hp=35899,fp=1021,pp=1022,Nn=1023,yi=1026,hs=1027,mp=1028,bl=1029,Hs=1030,_l=1031,yl=1033,Ba=33776,Va=33777,za=33778,Ga=33779,Sl=35840,xl=35841,Tl=35842,Cl=35843,El=36196,Ml=37492,wl=37496,Al=37488,Rl=37489,Pl=37490,kl=37491,Il=37808,Dl=37809,Ll=37810,Nl=37811,Ul=37812,Ol=37813,Fl=37814,Bl=37815,Vl=37816,zl=37817,Gl=37818,Hl=37819,Wl=37820,ql=37821,jl=36492,$l=36494,Xl=36495,Kl=36283,Yl=36284,Jl=36285,Zl=36286,w_=3200,A_=0,R_=1,Wi="",xn="srgb",Ws="srgb-linear",Ha="linear",ot="srgb",qs=7680,gp=519,P_=512,k_=513,I_=514,Ql=515,D_=516,L_=517,ed=518,N_=519,vp=35044,bp="300 es",Qn=2e3,Wa=2001;function _p(i){for(let e=i.length-1;e>=0;--e)if(i[e]>=65535)return!0;return!1}function qa(i){return document.createElementNS("http://www.w3.org/1999/xhtml",i)}function U_(){const i=qa("canvas");return i.style.display="block",i}const yp={};function Sp(...i){const e="THREE."+i.shift();console.log(e,...i)}function Oe(...i){const e="THREE."+i.shift();console.warn(e,...i)}function tt(...i){const e="THREE."+i.shift();console.error(e,...i)}function Vr(...i){const e=i.join(" ");e in yp||(yp[e]=!0,Oe(...i))}function O_(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 Yt=["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"],td=Math.PI/180,nd=180/Math.PI;function zr(){const i=Math.random()*4294967295|0,e=Math.random()*4294967295|0,t=Math.random()*4294967295|0,n=Math.random()*4294967295|0;return(Yt[i&255]+Yt[i>>8&255]+Yt[i>>16&255]+Yt[i>>24&255]+"-"+Yt[e&255]+Yt[e>>8&255]+"-"+Yt[e>>16&15|64]+Yt[e>>24&255]+"-"+Yt[t&63|128]+Yt[t>>8&255]+"-"+Yt[t>>16&255]+Yt[t>>24&255]+Yt[n&255]+Yt[n>>8&255]+Yt[n>>16&255]+Yt[n>>24&255]).toLowerCase()}function Ye(i,e,t){return Math.max(e,Math.min(t,i))}function F_(i,e){return(i%e+e)%e}function id(i,e,t){return(1-t)*i+t*e}function Gr(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 ln(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 rt{constructor(e=0,t=0){rt.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=Ye(this.x,e.x,t.x),this.y=Ye(this.y,e.y,t.y),this}clampScalar(e,t){return this.x=Ye(this.x,e,t),this.y=Ye(this.y,e,t),this}clampLength(e,t){const n=this.length();return this.divideScalar(n||1).multiplyScalar(Ye(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(Ye(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 Hr{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(Ye(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 F{constructor(e=0,t=0,n=0){F.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(xp.setFromEuler(e))}applyAxisAngle(e,t){return this.applyQuaternion(xp.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=Ye(this.x,e.x,t.x),this.y=Ye(this.y,e.y,t.y),this.z=Ye(this.z,e.z,t.z),this}clampScalar(e,t){return this.x=Ye(this.x,e,t),this.y=Ye(this.y,e,t),this.z=Ye(this.z,e,t),this}clampLength(e,t){const n=this.length();return this.divideScalar(n||1).multiplyScalar(Ye(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 sd.copy(this).projectOnVector(e),this.sub(sd)}reflect(e){return this.sub(sd.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(Ye(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 sd=new F,xp=new Hr;class ze{constructor(e,t,n,s,r,a,o,c,l){ze.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(rd.makeScale(e,t)),this}rotate(e){return this.premultiply(rd.makeRotation(-e)),this}translate(e,t){return this.premultiply(rd.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 rd=new ze,Tp=new ze().set(.4123908,.3575843,.1804808,.212639,.7151687,.0721923,.0193308,.1191948,.9505322),Cp=new ze().set(3.2409699,-1.5373832,-.4986108,-.9692436,1.8759675,.0415551,.0556301,-.203977,1.0569715);function B_(){const i={enabled:!0,workingColorSpace:Ws,spaces:{},convert:function(s,r,a){return this.enabled===!1||r===a||!r||!a||(this.spaces[r].transfer===ot&&(s.r=Si(s.r),s.g=Si(s.g),s.b=Si(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===ot&&(s.r=$s(s.r),s.g=$s(s.g),s.b=$s(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===Wi?Ha: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 Vr("ColorManagement: .fromWorkingColorSpace() has been renamed to .workingToColorSpace()."),i.workingToColorSpace(s,r)},toWorkingColorSpace:function(s,r){return Vr("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({[Ws]:{primaries:e,whitePoint:n,transfer:Ha,toXYZ:Tp,fromXYZ:Cp,luminanceCoefficients:t,workingColorSpaceConfig:{unpackColorSpace:xn},outputColorSpaceConfig:{drawingBufferColorSpace:xn}},[xn]:{primaries:e,whitePoint:n,transfer:ot,toXYZ:Tp,fromXYZ:Cp,luminanceCoefficients:t,outputColorSpaceConfig:{drawingBufferColorSpace:xn}}}),i}const Qe=B_();function Si(i){return i<.04045?i*.0773993808:Math.pow(i*.9478672986+.0521327014,2.4)}function $s(i){return i<.0031308?i*12.92:1.055*Math.pow(i,.41666)-.055}let Xs;class V_{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{Xs===void 0&&(Xs=qa("canvas")),Xs.width=e.width,Xs.height=e.height;const s=Xs.getContext("2d");e instanceof ImageData?s.putImageData(e,0,0):s.drawImage(e,0,0,e.width,e.height),n=Xs}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=qa("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]=Si(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(Si(t[n]/255)*255):t[n]=Si(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 z_=0;class ad{constructor(e=null){this.isSource=!0,Object.defineProperty(this,"id",{value:z_++}),this.uuid=zr(),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(od(s[a].image)):r.push(od(s[a]))}else r=od(s);n.url=r}return t||(e.images[this.uuid]=n),n}}function od(i){return typeof HTMLImageElement<"u"&&i instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&i instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&i instanceof ImageBitmap?V_.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 G_=0;const cd=new F;class Qt extends js{constructor(e=Qt.DEFAULT_IMAGE,t=Qt.DEFAULT_MAPPING,n=bi,s=bi,r=Kt,a=us,o=Nn,c=Sn,l=Qt.DEFAULT_ANISOTROPY,d=Wi){super(),this.isTexture=!0,Object.defineProperty(this,"id",{value:G_++}),this.uuid=zr(),this.name="",this.source=new ad(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 rt(0,0),this.repeat=new rt(1,1),this.center=new rt(0,0),this.rotation=0,this.matrixAutoUpdate=!0,this.matrix=new ze,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(cd).x}get height(){return this.source.getSize(cd).y}get depth(){return this.source.getSize(cd).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!==cp)return e;if(e.applyMatrix3(this.matrix),e.x<0||e.x>1)switch(this.wrapS){case hl:e.x=e.x-Math.floor(e.x);break;case bi:e.x=e.x<0?0:1;break;case fl: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 hl:e.y=e.y-Math.floor(e.y);break;case bi:e.y=e.y<0?0:1;break;case fl: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++}}Qt.DEFAULT_IMAGE=null,Qt.DEFAULT_MAPPING=cp,Qt.DEFAULT_ANISOTROPY=1;class It{constructor(e=0,t=0,n=0,s=1){It.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=Ye(this.x,e.x,t.x),this.y=Ye(this.y,e.y,t.y),this.z=Ye(this.z,e.z,t.z),this.w=Ye(this.w,e.w,t.w),this}clampScalar(e,t){return this.x=Ye(this.x,e,t),this.y=Ye(this.y,e,t),this.z=Ye(this.z,e,t),this.w=Ye(this.w,e,t),this}clampLength(e,t){const n=this.length();return this.divideScalar(n||1).multiplyScalar(Ye(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 H_ extends js{constructor(e=1,t=1,n={}){super(),n=Object.assign({generateMipmaps:!1,internalFormat:null,minFilter:Kt,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 It(0,0,e,t),this.scissorTest=!1,this.viewport=new It(0,0,e,t);const s={width:e,height:t,depth:n.depth},r=new Qt(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:Kt,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 ad(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 ei extends H_{constructor(e=1,t=1,n={}){super(e,t,n),this.isWebGLRenderTarget=!0}}class Ep extends Qt{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=Xt,this.minFilter=Xt,this.wrapR=bi,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1,this.layerUpdates=new Set}addLayerUpdate(e){this.layerUpdates.add(e)}clearLayerUpdates(){this.layerUpdates.clear()}}class W_ extends Qt{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=Xt,this.minFilter=Xt,this.wrapR=bi,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}}class Wr{constructor(e=new F(1/0,1/0,1/0),t=new F(-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(Un.fromArray(e,t));return this}setFromBufferAttribute(e){this.makeEmpty();for(let t=0,n=e.count;t<n;t++)this.expandByPoint(Un.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=Un.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,Un):Un.fromBufferAttribute(r,a),Un.applyMatrix4(e.matrixWorld),this.expandByPoint(Un);else e.boundingBox!==void 0?(e.boundingBox===null&&e.computeBoundingBox(),ja.copy(e.boundingBox)):(n.boundingBox===null&&n.computeBoundingBox(),ja.copy(n.boundingBox)),ja.applyMatrix4(e.matrixWorld),this.union(ja)}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,Un),Un.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(qr),$a.subVectors(this.max,qr),Ks.subVectors(e.a,qr),Ys.subVectors(e.b,qr),Js.subVectors(e.c,qr),qi.subVectors(Ys,Ks),ji.subVectors(Js,Ys),fs.subVectors(Ks,Js);let t=[0,-qi.z,qi.y,0,-ji.z,ji.y,0,-fs.z,fs.y,qi.z,0,-qi.x,ji.z,0,-ji.x,fs.z,0,-fs.x,-qi.y,qi.x,0,-ji.y,ji.x,0,-fs.y,fs.x,0];return!ld(t,Ks,Ys,Js,$a)||(t=[1,0,0,0,1,0,0,0,1],!ld(t,Ks,Ys,Js,$a))?!1:(Xa.crossVectors(qi,ji),t=[Xa.x,Xa.y,Xa.z],ld(t,Ks,Ys,Js,$a))}clampPoint(e,t){return t.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,Un).distanceTo(e)}getBoundingSphere(e){return this.isEmpty()?e.makeEmpty():(this.getCenter(e.center),e.radius=this.getSize(Un).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:(xi[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(e),xi[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(e),xi[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(e),xi[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(e),xi[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(e),xi[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(e),xi[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(e),xi[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(e),this.setFromPoints(xi),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 xi=[new F,new F,new F,new F,new F,new F,new F,new F],Un=new F,ja=new Wr,Ks=new F,Ys=new F,Js=new F,qi=new F,ji=new F,fs=new F,qr=new F,$a=new F,Xa=new F,ps=new F;function ld(i,e,t,n,s){for(let r=0,a=i.length-3;r<=a;r+=3){ps.fromArray(i,r);const o=s.x*Math.abs(ps.x)+s.y*Math.abs(ps.y)+s.z*Math.abs(ps.z),c=e.dot(ps),l=t.dot(ps),d=n.dot(ps);if(Math.max(-Math.max(c,l,d),Math.min(c,l,d))>o)return!1}return!0}const q_=new Wr,jr=new F,dd=new F;class ud{constructor(e=new F,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):q_.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;jr.subVectors(e,this.center);const t=jr.lengthSq();if(t>this.radius*this.radius){const n=Math.sqrt(t),s=(n-this.radius)*.5;this.center.addScaledVector(jr,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):(dd.subVectors(e.center,this.center).setLength(e.radius),this.expandByPoint(jr.copy(e.center).add(dd)),this.expandByPoint(jr.copy(e.center).sub(dd))),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 Ti=new F,hd=new F,Ka=new F,$i=new F,fd=new F,Ya=new F,pd=new F;class j_{constructor(e=new F,t=new F(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,Ti)),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=Ti.subVectors(e,this.origin).dot(this.direction);return t<0?this.origin.distanceToSquared(e):(Ti.copy(this.origin).addScaledVector(this.direction,t),Ti.distanceToSquared(e))}distanceSqToSegment(e,t,n,s){hd.copy(e).add(t).multiplyScalar(.5),Ka.copy(t).sub(e).normalize(),$i.copy(this.origin).sub(hd);const r=e.distanceTo(t)*.5,a=-this.direction.dot(Ka),o=$i.dot(this.direction),c=-$i.dot(Ka),l=$i.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(hd).addScaledVector(Ka,h),f}intersectSphere(e,t){Ti.subVectors(e.center,this.origin);const n=Ti.dot(this.direction),s=Ti.dot(Ti)-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,Ti)!==null}intersectTriangle(e,t,n,s,r){fd.subVectors(t,e),Ya.subVectors(n,e),pd.crossVectors(fd,Ya);let a=this.direction.dot(pd),o;if(a>0){if(s)return null;o=1}else if(a<0)o=-1,a=-a;else return null;$i.subVectors(this.origin,e);const c=o*this.direction.dot(Ya.crossVectors($i,Ya));if(c<0)return null;const l=o*this.direction.dot(fd.cross($i));if(l<0||c+l>a)return null;const d=-o*$i.dot(pd);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 Nt{constructor(e,t,n,s,r,a,o,c,l,d,u,h,f,g,v,m){Nt.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 Nt().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/Zs.setFromMatrixColumn(e,0).length(),r=1/Zs.setFromMatrixColumn(e,1).length(),a=1/Zs.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($_,e,X_)}lookAt(e,t,n){const s=this.elements;return mn.subVectors(e,t),mn.lengthSq()===0&&(mn.z=1),mn.normalize(),Xi.crossVectors(n,mn),Xi.lengthSq()===0&&(Math.abs(n.z)===1?mn.x+=1e-4:mn.z+=1e-4,mn.normalize(),Xi.crossVectors(n,mn)),Xi.normalize(),Ja.crossVectors(mn,Xi),s[0]=Xi.x,s[4]=Ja.x,s[8]=mn.x,s[1]=Xi.y,s[5]=Ja.y,s[9]=mn.y,s[2]=Xi.z,s[6]=Ja.z,s[10]=mn.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],y=s[12],T=s[1],R=s[5],U=s[9],B=s[13],q=s[2],K=s[6],H=s[10],W=s[14],te=s[3],ve=s[7],de=s[11],_e=s[15];return r[0]=a*M+o*T+c*q+l*te,r[4]=a*A+o*R+c*K+l*ve,r[8]=a*k+o*U+c*H+l*de,r[12]=a*y+o*B+c*W+l*_e,r[1]=d*M+u*T+h*q+f*te,r[5]=d*A+u*R+h*K+f*ve,r[9]=d*k+u*U+h*H+f*de,r[13]=d*y+u*B+h*W+f*_e,r[2]=g*M+v*T+m*q+p*te,r[6]=g*A+v*R+m*K+p*ve,r[10]=g*k+v*U+m*H+p*de,r[14]=g*y+v*B+m*W+p*_e,r[3]=x*M+C*T+b*q+S*te,r[7]=x*A+C*R+b*K+S*ve,r[11]=x*k+C*U+b*H+S*de,r[15]=x*y+C*B+b*W+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=Zs.set(s[0],s[1],s[2]).length();const a=Zs.set(s[4],s[5],s[6]).length(),o=Zs.set(s[8],s[9],s[10]).length();this.determinant()<0&&(r=-r),On.copy(this);const l=1/r,d=1/a,u=1/o;return On.elements[0]*=l,On.elements[1]*=l,On.elements[2]*=l,On.elements[4]*=d,On.elements[5]*=d,On.elements[6]*=d,On.elements[8]*=u,On.elements[9]*=u,On.elements[10]*=u,t.setFromRotationMatrix(On),n.x=r,n.y=a,n.z=o,this}makePerspective(e,t,n,s,r,a,o=Qn,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===Qn)g=-(a+r)/(a-r),v=-2*a*r/(a-r);else if(o===Wa)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=Qn,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===Qn)g=-2/(a-r),v=-(a+r)/(a-r);else if(o===Wa)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 Zs=new F,On=new Nt,$_=new F(0,0,0),X_=new F(1,1,1),Xi=new F,Ja=new F,mn=new F,Mp=new Nt,wp=new Hr;class Ci{constructor(e=0,t=0,n=0,s=Ci.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(Ye(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(-Ye(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(Ye(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(-Ye(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(Ye(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(-Ye(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 Mp.makeRotationFromQuaternion(e),this.setFromRotationMatrix(Mp,t,n)}setFromVector3(e,t=this._order){return this.set(e.x,e.y,e.z,t)}reorder(e){return wp.setFromEuler(this),this.setFromQuaternion(wp,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}}Ci.DEFAULT_ORDER="XYZ";class Ap{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 K_=0;const Rp=new F,Qs=new Hr,Ei=new Nt,Za=new F,$r=new F,Y_=new F,J_=new Hr,Pp=new F(1,0,0),kp=new F(0,1,0),Ip=new F(0,0,1),Dp={type:"added"},Z_={type:"removed"},er={type:"childadded",child:null},md={type:"childremoved",child:null};class gn extends js{constructor(){super(),this.isObject3D=!0,Object.defineProperty(this,"id",{value:K_++}),this.uuid=zr(),this.name="",this.type="Object3D",this.parent=null,this.children=[],this.up=gn.DEFAULT_UP.clone();const e=new F,t=new Ci,n=new Hr,s=new F(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 Nt},normalMatrix:{value:new ze}}),this.matrix=new Nt,this.matrixWorld=new Nt,this.matrixAutoUpdate=gn.DEFAULT_MATRIX_AUTO_UPDATE,this.matrixWorldAutoUpdate=gn.DEFAULT_MATRIX_WORLD_AUTO_UPDATE,this.matrixWorldNeedsUpdate=!1,this.layers=new Ap,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 Qs.setFromAxisAngle(e,t),this.quaternion.multiply(Qs),this}rotateOnWorldAxis(e,t){return Qs.setFromAxisAngle(e,t),this.quaternion.premultiply(Qs),this}rotateX(e){return this.rotateOnAxis(Pp,e)}rotateY(e){return this.rotateOnAxis(kp,e)}rotateZ(e){return this.rotateOnAxis(Ip,e)}translateOnAxis(e,t){return Rp.copy(e).applyQuaternion(this.quaternion),this.position.add(Rp.multiplyScalar(t)),this}translateX(e){return this.translateOnAxis(Pp,e)}translateY(e){return this.translateOnAxis(kp,e)}translateZ(e){return this.translateOnAxis(Ip,e)}localToWorld(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(this.matrixWorld)}worldToLocal(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(Ei.copy(this.matrixWorld).invert())}lookAt(e,t,n){e.isVector3?Za.copy(e):Za.set(e,t,n);const s=this.parent;this.updateWorldMatrix(!0,!1),$r.setFromMatrixPosition(this.matrixWorld),this.isCamera||this.isLight?Ei.lookAt($r,Za,this.up):Ei.lookAt(Za,$r,this.up),this.quaternion.setFromRotationMatrix(Ei),s&&(Ei.extractRotation(s.matrixWorld),Qs.setFromRotationMatrix(Ei),this.quaternion.premultiply(Qs.invert()))}add(e){if(arguments.length>1){for(let t=0;t<arguments.length;t++)this.add(arguments[t]);return this}return e===this?(tt("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(Dp),er.child=e,this.dispatchEvent(er),er.child=null):tt("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(Z_),md.child=e,this.dispatchEvent(md),md.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),Ei.copy(this.matrixWorld).invert(),e.parent!==null&&(e.parent.updateWorldMatrix(!0,!1),Ei.multiply(e.parent.matrixWorld)),e.applyMatrix4(Ei),e.removeFromParent(),e.parent=this,this.children.push(e),e.updateWorldMatrix(!1,!0),e.dispatchEvent(Dp),er.child=e,this.dispatchEvent(er),er.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($r,e,Y_),e}getWorldScale(e){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose($r,J_,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}}gn.DEFAULT_UP=new F(0,1,0),gn.DEFAULT_MATRIX_AUTO_UPDATE=!0,gn.DEFAULT_MATRIX_WORLD_AUTO_UPDATE=!0;const Fn=new F,Mi=new F,gd=new F,wi=new F,tr=new F,nr=new F,Lp=new F,vd=new F,bd=new F,_d=new F,yd=new It,Sd=new It,xd=new It;class Bn{constructor(e=new F,t=new F,n=new F){this.a=e,this.b=t,this.c=n}static getNormal(e,t,n,s){s.subVectors(n,t),Fn.subVectors(e,t),s.cross(Fn);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){Fn.subVectors(s,t),Mi.subVectors(n,t),gd.subVectors(e,t);const a=Fn.dot(Fn),o=Fn.dot(Mi),c=Fn.dot(gd),l=Mi.dot(Mi),d=Mi.dot(gd),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,wi)===null?!1:wi.x>=0&&wi.y>=0&&wi.x+wi.y<=1}static getInterpolation(e,t,n,s,r,a,o,c){return this.getBarycoord(e,t,n,s,wi)===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,wi.x),c.addScaledVector(a,wi.y),c.addScaledVector(o,wi.z),c)}static getInterpolatedAttribute(e,t,n,s,r,a){return yd.setScalar(0),Sd.setScalar(0),xd.setScalar(0),yd.fromBufferAttribute(e,t),Sd.fromBufferAttribute(e,n),xd.fromBufferAttribute(e,s),a.setScalar(0),a.addScaledVector(yd,r.x),a.addScaledVector(Sd,r.y),a.addScaledVector(xd,r.z),a}static isFrontFacing(e,t,n,s){return Fn.subVectors(n,t),Mi.subVectors(e,t),Fn.cross(Mi).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 Fn.subVectors(this.c,this.b),Mi.subVectors(this.a,this.b),Fn.cross(Mi).length()*.5}getMidpoint(e){return e.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(e){return Bn.getNormal(this.a,this.b,this.c,e)}getPlane(e){return e.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(e,t){return Bn.getBarycoord(e,this.a,this.b,this.c,t)}getInterpolation(e,t,n,s,r){return Bn.getInterpolation(e,this.a,this.b,this.c,t,n,s,r)}containsPoint(e){return Bn.containsPoint(e,this.a,this.b,this.c)}isFrontFacing(e){return Bn.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;tr.subVectors(s,n),nr.subVectors(r,n),vd.subVectors(e,n);const c=tr.dot(vd),l=nr.dot(vd);if(c<=0&&l<=0)return t.copy(n);bd.subVectors(e,s);const d=tr.dot(bd),u=nr.dot(bd);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(tr,a);_d.subVectors(e,r);const f=tr.dot(_d),g=nr.dot(_d);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(nr,o);const m=d*g-f*u;if(m<=0&&u-d>=0&&f-g>=0)return Lp.subVectors(r,s),o=(u-d)/(u-d+(f-g)),t.copy(s).addScaledVector(Lp,o);const p=1/(m+v+h);return a=v*p,o=h*p,t.copy(n).addScaledVector(tr,a).addScaledVector(nr,o)}equals(e){return e.a.equals(this.a)&&e.b.equals(this.b)&&e.c.equals(this.c)}}const Np={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},Ki={h:0,s:0,l:0},Qa={h:0,s:0,l:0};function Td(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 Ze{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=xn){return e=Math.floor(e),this.r=(e>>16&255)/255,this.g=(e>>8&255)/255,this.b=(e&255)/255,Qe.colorSpaceToWorking(this,t),this}setRGB(e,t,n,s=Qe.workingColorSpace){return this.r=e,this.g=t,this.b=n,Qe.colorSpaceToWorking(this,s),this}setHSL(e,t,n,s=Qe.workingColorSpace){if(e=F_(e,1),t=Ye(t,0,1),n=Ye(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=Td(a,r,e+1/3),this.g=Td(a,r,e),this.b=Td(a,r,e-1/3)}return Qe.colorSpaceToWorking(this,s),this}setStyle(e,t=xn){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=xn){const n=Np[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=Si(e.r),this.g=Si(e.g),this.b=Si(e.b),this}copyLinearToSRGB(e){return this.r=$s(e.r),this.g=$s(e.g),this.b=$s(e.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(e=xn){return Qe.workingToColorSpace(Jt.copy(this),e),Math.round(Ye(Jt.r*255,0,255))*65536+Math.round(Ye(Jt.g*255,0,255))*256+Math.round(Ye(Jt.b*255,0,255))}getHexString(e=xn){return("000000"+this.getHex(e).toString(16)).slice(-6)}getHSL(e,t=Qe.workingColorSpace){Qe.workingToColorSpace(Jt.copy(this),t);const n=Jt.r,s=Jt.g,r=Jt.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=Qe.workingColorSpace){return Qe.workingToColorSpace(Jt.copy(this),t),e.r=Jt.r,e.g=Jt.g,e.b=Jt.b,e}getStyle(e=xn){Qe.workingToColorSpace(Jt.copy(this),e);const t=Jt.r,n=Jt.g,s=Jt.b;return e!==xn?`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(Ki),this.setHSL(Ki.h+e,Ki.s+t,Ki.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(Ki),e.getHSL(Qa);const n=id(Ki.h,Qa.h,t),s=id(Ki.s,Qa.s,t),r=id(Ki.l,Qa.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 Jt=new Ze;Ze.NAMES=Np;let Q_=0;class eo extends js{constructor(){super(),this.isMaterial=!0,Object.defineProperty(this,"id",{value:Q_++}),this.uuid=zr(),this.name="",this.type="Material",this.blending=Vs,this.side=mi,this.vertexColors=!1,this.opacity=1,this.transparent=!1,this.alphaHash=!1,this.blendSrc=tl,this.blendDst=nl,this.blendEquation=ls,this.blendSrcAlpha=null,this.blendDstAlpha=null,this.blendEquationAlpha=null,this.blendColor=new Ze(0,0,0),this.blendAlpha=0,this.depthFunc=zs,this.depthTest=!0,this.depthWrite=!0,this.stencilWriteMask=255,this.stencilFunc=gp,this.stencilRef=0,this.stencilFuncMask=255,this.stencilFail=qs,this.stencilZFail=qs,this.stencilZPass=qs,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!==Vs&&(n.blending=this.blending),this.side!==mi&&(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!==tl&&(n.blendSrc=this.blendSrc),this.blendDst!==nl&&(n.blendDst=this.blendDst),this.blendEquation!==ls&&(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!==zs&&(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!==gp&&(n.stencilFunc=this.stencilFunc),this.stencilRef!==0&&(n.stencilRef=this.stencilRef),this.stencilFuncMask!==255&&(n.stencilFuncMask=this.stencilFuncMask),this.stencilFail!==qs&&(n.stencilFail=this.stencilFail),this.stencilZFail!==qs&&(n.stencilZFail=this.stencilZFail),this.stencilZPass!==qs&&(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 Up extends eo{constructor(e){super(),this.isMeshBasicMaterial=!0,this.type="MeshBasicMaterial",this.color=new Ze(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 Ci,this.combine=ep,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 Ut=new F,to=new rt;let ey=0;class ti{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:ey++}),this.name="",this.array=e,this.itemSize=t,this.count=e!==void 0?e.length/t:0,this.normalized=n,this.usage=vp,this.updateRanges=[],this.gpuType=Zn,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++)to.fromBufferAttribute(this,t),to.applyMatrix3(e),this.setXY(t,to.x,to.y);else if(this.itemSize===3)for(let t=0,n=this.count;t<n;t++)Ut.fromBufferAttribute(this,t),Ut.applyMatrix3(e),this.setXYZ(t,Ut.x,Ut.y,Ut.z);return this}applyMatrix4(e){for(let t=0,n=this.count;t<n;t++)Ut.fromBufferAttribute(this,t),Ut.applyMatrix4(e),this.setXYZ(t,Ut.x,Ut.y,Ut.z);return this}applyNormalMatrix(e){for(let t=0,n=this.count;t<n;t++)Ut.fromBufferAttribute(this,t),Ut.applyNormalMatrix(e),this.setXYZ(t,Ut.x,Ut.y,Ut.z);return this}transformDirection(e){for(let t=0,n=this.count;t<n;t++)Ut.fromBufferAttribute(this,t),Ut.transformDirection(e),this.setXYZ(t,Ut.x,Ut.y,Ut.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=Gr(n,this.array)),n}setComponent(e,t,n){return this.normalized&&(n=ln(n,this.array)),this.array[e*this.itemSize+t]=n,this}getX(e){let t=this.array[e*this.itemSize];return this.normalized&&(t=Gr(t,this.array)),t}setX(e,t){return this.normalized&&(t=ln(t,this.array)),this.array[e*this.itemSize]=t,this}getY(e){let t=this.array[e*this.itemSize+1];return this.normalized&&(t=Gr(t,this.array)),t}setY(e,t){return this.normalized&&(t=ln(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=Gr(t,this.array)),t}setZ(e,t){return this.normalized&&(t=ln(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=Gr(t,this.array)),t}setW(e,t){return this.normalized&&(t=ln(t,this.array)),this.array[e*this.itemSize+3]=t,this}setXY(e,t,n){return e*=this.itemSize,this.normalized&&(t=ln(t,this.array),n=ln(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=ln(t,this.array),n=ln(n,this.array),s=ln(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=ln(t,this.array),n=ln(n,this.array),s=ln(s,this.array),r=ln(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!==vp&&(e.usage=this.usage),e}}class Op extends ti{constructor(e,t,n){super(new Uint16Array(e),t,n)}}class Fp extends ti{constructor(e,t,n){super(new Uint32Array(e),t,n)}}class en extends ti{constructor(e,t,n){super(new Float32Array(e),t,n)}}let ty=0;const Tn=new Nt,Cd=new gn,ir=new F,vn=new Wr,Xr=new Wr,qt=new F;class Vn extends js{constructor(){super(),this.isBufferGeometry=!0,Object.defineProperty(this,"id",{value:ty++}),this.uuid=zr(),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(_p(e)?Fp:Op)(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 ze().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 Tn.makeRotationFromQuaternion(e),this.applyMatrix4(Tn),this}rotateX(e){return Tn.makeRotationX(e),this.applyMatrix4(Tn),this}rotateY(e){return Tn.makeRotationY(e),this.applyMatrix4(Tn),this}rotateZ(e){return Tn.makeRotationZ(e),this.applyMatrix4(Tn),this}translate(e,t,n){return Tn.makeTranslation(e,t,n),this.applyMatrix4(Tn),this}scale(e,t,n){return Tn.makeScale(e,t,n),this.applyMatrix4(Tn),this}lookAt(e){return Cd.lookAt(e),Cd.updateMatrix(),this.applyMatrix4(Cd.matrix),this}center(){return this.computeBoundingBox(),this.boundingBox.getCenter(ir).negate(),this.translate(ir.x,ir.y,ir.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 en(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 Wr);const e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute){tt("BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.",this),this.boundingBox.set(new F(-1/0,-1/0,-1/0),new F(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];vn.setFromBufferAttribute(r),this.morphTargetsRelative?(qt.addVectors(this.boundingBox.min,vn.min),this.boundingBox.expandByPoint(qt),qt.addVectors(this.boundingBox.max,vn.max),this.boundingBox.expandByPoint(qt)):(this.boundingBox.expandByPoint(vn.min),this.boundingBox.expandByPoint(vn.max))}}else this.boundingBox.makeEmpty();(isNaN(this.boundingBox.min.x)||isNaN(this.boundingBox.min.y)||isNaN(this.boundingBox.min.z))&&tt('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 ud);const e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute){tt("BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.",this),this.boundingSphere.set(new F,1/0);return}if(e){const n=this.boundingSphere.center;if(vn.setFromBufferAttribute(e),t)for(let r=0,a=t.length;r<a;r++){const o=t[r];Xr.setFromBufferAttribute(o),this.morphTargetsRelative?(qt.addVectors(vn.min,Xr.min),vn.expandByPoint(qt),qt.addVectors(vn.max,Xr.max),vn.expandByPoint(qt)):(vn.expandByPoint(Xr.min),vn.expandByPoint(Xr.max))}vn.getCenter(n);let s=0;for(let r=0,a=e.count;r<a;r++)qt.fromBufferAttribute(e,r),s=Math.max(s,n.distanceToSquared(qt));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++)qt.fromBufferAttribute(o,l),c&&(ir.fromBufferAttribute(e,l),qt.add(ir)),s=Math.max(s,n.distanceToSquared(qt))}this.boundingSphere.radius=Math.sqrt(s),isNaN(this.boundingSphere.radius)&&tt('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){tt("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 ti(new Float32Array(4*n.count),4));const a=this.getAttribute("tangent"),o=[],c=[];for(let k=0;k<n.count;k++)o[k]=new F,c[k]=new F;const l=new F,d=new F,u=new F,h=new rt,f=new rt,g=new rt,v=new F,m=new F;function p(k,y,T){l.fromBufferAttribute(n,k),d.fromBufferAttribute(n,y),u.fromBufferAttribute(n,T),h.fromBufferAttribute(r,k),f.fromBufferAttribute(r,y),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[y].add(v),o[T].add(v),c[k].add(m),c[y].add(m),c[T].add(m))}let x=this.groups;x.length===0&&(x=[{start:0,count:e.count}]);for(let k=0,y=x.length;k<y;++k){const T=x[k],R=T.start,U=T.count;for(let B=R,q=R+U;B<q;B+=3)p(e.getX(B+0),e.getX(B+1),e.getX(B+2))}const C=new F,b=new F,S=new F,M=new F;function A(k){S.fromBufferAttribute(s,k),M.copy(S);const y=o[k];C.copy(y),C.sub(S.multiplyScalar(S.dot(y))).normalize(),b.crossVectors(M,y);const R=b.dot(c[k])<0?-1:1;a.setXYZW(k,C.x,C.y,C.z,R)}for(let k=0,y=x.length;k<y;++k){const T=x[k],R=T.start,U=T.count;for(let B=R,q=R+U;B<q;B+=3)A(e.getX(B+0)),A(e.getX(B+1)),A(e.getX(B+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 ti(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 F,r=new F,a=new F,o=new F,c=new F,l=new F,d=new F,u=new F;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++)qt.fromBufferAttribute(e,t),qt.normalize(),e.setXYZ(t,qt.x,qt.y,qt.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 ti(h,d,u)}if(this.index===null)return Oe("BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed."),this;const t=new Vn,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 Bp=new Nt,ms=new j_,no=new ud,Vp=new F,io=new F,so=new F,ro=new F,Ed=new F,ao=new F,zp=new F,oo=new F;class zn extends gn{constructor(e=new Vn,t=new Up){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){ao.set(0,0,0);for(let c=0,l=r.length;c<l;c++){const d=o[c],u=r[c];d!==0&&(Ed.fromBufferAttribute(u,e),a?ao.addScaledVector(Ed,d):ao.addScaledVector(Ed.sub(t),d))}t.add(ao)}return t}raycast(e,t){const n=this.geometry,s=this.material,r=this.matrixWorld;s!==void 0&&(n.boundingSphere===null&&n.computeBoundingSphere(),no.copy(n.boundingSphere),no.applyMatrix4(r),ms.copy(e.ray).recast(e.near),!(no.containsPoint(ms.origin)===!1&&(ms.intersectSphere(no,Vp)===null||ms.origin.distanceToSquared(Vp)>(e.far-e.near)**2))&&(Bp.copy(r).invert(),ms.copy(e.ray).applyMatrix4(Bp),!(n.boundingBox!==null&&ms.intersectsBox(n.boundingBox)===!1)&&this._computeIntersections(e,t,ms)))}_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=co(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=co(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=co(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=co(this,a,e,n,l,d,u,x,C,b),s&&(s.faceIndex=Math.floor(m/3),t.push(s))}}}}function ny(i,e,t,n,s,r,a,o){let c;if(e.side===Zt?c=n.intersectTriangle(a,r,s,!0,o):c=n.intersectTriangle(s,r,a,e.side===mi,o),c===null)return null;oo.copy(o),oo.applyMatrix4(i.matrixWorld);const l=t.ray.origin.distanceTo(oo);return l<t.near||l>t.far?null:{distance:l,point:oo.clone(),object:i}}function co(i,e,t,n,s,r,a,o,c,l){i.getVertexPosition(o,io),i.getVertexPosition(c,so),i.getVertexPosition(l,ro);const d=ny(i,e,t,n,io,so,ro,zp);if(d){const u=new F;Bn.getBarycoord(zp,io,so,ro,u),s&&(d.uv=Bn.getInterpolatedAttribute(s,o,c,l,u,new rt)),r&&(d.uv1=Bn.getInterpolatedAttribute(r,o,c,l,u,new rt)),a&&(d.normal=Bn.getInterpolatedAttribute(a,o,c,l,u,new F),d.normal.dot(n.direction)>0&&d.normal.multiplyScalar(-1));const h={a:o,b:c,c:l,normal:new F,materialIndex:0};Bn.getNormal(io,so,ro,h.normal),d.face=h,d.barycoord=u}return d}class Kr extends Vn{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 en(l,3)),this.setAttribute("normal",new en(d,3)),this.setAttribute("uv",new en(u,2));function g(v,m,p,x,C,b,S,M,A,k,y){const T=b/A,R=S/k,U=b/2,B=S/2,q=M/2,K=A+1,H=k+1;let W=0,te=0;const ve=new F;for(let de=0;de<H;de++){const _e=de*R-B;for(let Ve=0;Ve<K;Ve++){const Be=Ve*T-U;ve[v]=Be*x,ve[m]=_e*C,ve[p]=q,l.push(ve.x,ve.y,ve.z),ve[v]=0,ve[m]=0,ve[p]=M>0?1:-1,d.push(ve.x,ve.y,ve.z),u.push(Ve/A),u.push(1-de/k),W+=1}}for(let de=0;de<k;de++)for(let _e=0;_e<A;_e++){const Ve=h+_e+K*de,Be=h+_e+K*(de+1),Ct=h+(_e+1)+K*(de+1),mt=h+(_e+1)+K*de;c.push(Ve,Be,mt),c.push(Be,Ct,mt),te+=6}o.addGroup(f,te,y),f+=te,h+=W}}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new Kr(e.width,e.height,e.depth,e.widthSegments,e.heightSegments,e.depthSegments)}}function sr(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 tn(i){const e={};for(let t=0;t<i.length;t++){const n=sr(i[t]);for(const s in n)e[s]=n[s]}return e}function iy(i){const e=[];for(let t=0;t<i.length;t++)e.push(i[t].clone());return e}function Gp(i){const e=i.getRenderTarget();return e===null?i.outputColorSpace:e.isXRRenderTarget===!0?e.texture.colorSpace:Qe.workingColorSpace}const sy={clone:sr,merge:tn};var ry=`void main() {
89
89
  gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
90
90
  }`,ay=`void main() {
91
91
  gl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );
92
- }`;class Tn extends eo{constructor(e){super(),this.isShaderMaterial=!0,this.type="ShaderMaterial",this.defines={},this.uniforms={},this.uniformsGroups=[],this.vertexShader=ry,this.fragmentShader=ay,this.linewidth=1,this.wireframe=!1,this.wireframeLinewidth=1,this.fog=!1,this.lights=!1,this.clipping=!1,this.forceSinglePass=!0,this.extensions={clipCullDistance:!1,multiDraw:!1},this.defaultAttributeValues={color:[1,1,1],uv:[0,0],uv1:[0,0]},this.index0AttributeName=void 0,this.uniformsNeedUpdate=!1,this.glslVersion=null,e!==void 0&&this.setValues(e)}copy(e){return super.copy(e),this.fragmentShader=e.fragmentShader,this.vertexShader=e.vertexShader,this.uniforms=sr(e.uniforms),this.uniformsGroups=iy(e.uniformsGroups),this.defines=Object.assign({},e.defines),this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.fog=e.fog,this.lights=e.lights,this.clipping=e.clipping,this.extensions=Object.assign({},e.extensions),this.glslVersion=e.glslVersion,this.defaultAttributeValues=Object.assign({},e.defaultAttributeValues),this.index0AttributeName=e.index0AttributeName,this.uniformsNeedUpdate=e.uniformsNeedUpdate,this}toJSON(e){const t=super.toJSON(e);t.glslVersion=this.glslVersion,t.uniforms={};for(const s in this.uniforms){const a=this.uniforms[s].value;a&&a.isTexture?t.uniforms[s]={type:"t",value:a.toJSON(e).uuid}:a&&a.isColor?t.uniforms[s]={type:"c",value:a.getHex()}:a&&a.isVector2?t.uniforms[s]={type:"v2",value:a.toArray()}:a&&a.isVector3?t.uniforms[s]={type:"v3",value:a.toArray()}:a&&a.isVector4?t.uniforms[s]={type:"v4",value:a.toArray()}:a&&a.isMatrix3?t.uniforms[s]={type:"m3",value:a.toArray()}:a&&a.isMatrix4?t.uniforms[s]={type:"m4",value:a.toArray()}:t.uniforms[s]={value:a}}Object.keys(this.defines).length>0&&(t.defines=this.defines),t.vertexShader=this.vertexShader,t.fragmentShader=this.fragmentShader,t.lights=this.lights,t.clipping=this.clipping;const n={};for(const s in this.extensions)this.extensions[s]===!0&&(n[s]=!0);return Object.keys(n).length>0&&(t.extensions=n),t}}class Hp extends gn{constructor(){super(),this.isCamera=!0,this.type="Camera",this.matrixWorldInverse=new Nt,this.projectionMatrix=new Nt,this.projectionMatrixInverse=new Nt,this.coordinateSystem=Zn,this._reversedDepth=!1}get reversedDepth(){return this._reversedDepth}copy(e,t){return super.copy(e,t),this.matrixWorldInverse.copy(e.matrixWorldInverse),this.projectionMatrix.copy(e.projectionMatrix),this.projectionMatrixInverse.copy(e.projectionMatrixInverse),this.coordinateSystem=e.coordinateSystem,this}getWorldDirection(e){return super.getWorldDirection(e).negate()}updateMatrixWorld(e){super.updateMatrixWorld(e),this.matrixWorldInverse.copy(this.matrixWorld).invert()}updateWorldMatrix(e,t){super.updateWorldMatrix(e,t),this.matrixWorldInverse.copy(this.matrixWorld).invert()}clone(){return new this.constructor().copy(this)}}const Yi=new F,Wp=new rt,qp=new rt;class Cn extends Hp{constructor(e=50,t=1,n=.1,s=2e3){super(),this.isPerspectiveCamera=!0,this.type="PerspectiveCamera",this.fov=e,this.zoom=1,this.near=n,this.far=s,this.focus=10,this.aspect=t,this.view=null,this.filmGauge=35,this.filmOffset=0,this.updateProjectionMatrix()}copy(e,t){return super.copy(e,t),this.fov=e.fov,this.zoom=e.zoom,this.near=e.near,this.far=e.far,this.focus=e.focus,this.aspect=e.aspect,this.view=e.view===null?null:Object.assign({},e.view),this.filmGauge=e.filmGauge,this.filmOffset=e.filmOffset,this}setFocalLength(e){const t=.5*this.getFilmHeight()/e;this.fov=nd*2*Math.atan(t),this.updateProjectionMatrix()}getFocalLength(){const e=Math.tan(td*.5*this.fov);return .5*this.getFilmHeight()/e}getEffectiveFOV(){return nd*2*Math.atan(Math.tan(td*.5*this.fov)/this.zoom)}getFilmWidth(){return this.filmGauge*Math.min(this.aspect,1)}getFilmHeight(){return this.filmGauge/Math.max(this.aspect,1)}getViewBounds(e,t,n){Yi.set(-1,-1,.5).applyMatrix4(this.projectionMatrixInverse),t.set(Yi.x,Yi.y).multiplyScalar(-e/Yi.z),Yi.set(1,1,.5).applyMatrix4(this.projectionMatrixInverse),n.set(Yi.x,Yi.y).multiplyScalar(-e/Yi.z)}getViewSize(e,t){return this.getViewBounds(e,Wp,qp),t.subVectors(qp,Wp)}setViewOffset(e,t,n,s,r,a){this.aspect=e/t,this.view===null&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=e,this.view.fullHeight=t,this.view.offsetX=n,this.view.offsetY=s,this.view.width=r,this.view.height=a,this.updateProjectionMatrix()}clearViewOffset(){this.view!==null&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){const e=this.near;let t=e*Math.tan(td*.5*this.fov)/this.zoom,n=2*t,s=this.aspect*n,r=-.5*s;const a=this.view;if(this.view!==null&&this.view.enabled){const c=a.fullWidth,l=a.fullHeight;r+=a.offsetX*s/c,t-=a.offsetY*n/l,s*=a.width/c,n*=a.height/l}const o=this.filmOffset;o!==0&&(r+=e*o/this.getFilmWidth()),this.projectionMatrix.makePerspective(r,r+s,t,t-n,e,this.far,this.coordinateSystem,this.reversedDepth),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(e){const t=super.toJSON(e);return t.object.fov=this.fov,t.object.zoom=this.zoom,t.object.near=this.near,t.object.far=this.far,t.object.focus=this.focus,t.object.aspect=this.aspect,this.view!==null&&(t.object.view=Object.assign({},this.view)),t.object.filmGauge=this.filmGauge,t.object.filmOffset=this.filmOffset,t}}const rr=-90,ar=1;class oy extends gn{constructor(e,t,n){super(),this.type="CubeCamera",this.renderTarget=n,this.coordinateSystem=null,this.activeMipmapLevel=0;const s=new Cn(rr,ar,e,t);s.layers=this.layers,this.add(s);const r=new Cn(rr,ar,e,t);r.layers=this.layers,this.add(r);const a=new Cn(rr,ar,e,t);a.layers=this.layers,this.add(a);const o=new Cn(rr,ar,e,t);o.layers=this.layers,this.add(o);const c=new Cn(rr,ar,e,t);c.layers=this.layers,this.add(c);const l=new Cn(rr,ar,e,t);l.layers=this.layers,this.add(l)}updateCoordinateSystem(){const e=this.coordinateSystem,t=this.children.concat(),[n,s,r,a,o,c]=t;for(const l of t)this.remove(l);if(e===Zn)n.up.set(0,1,0),n.lookAt(1,0,0),s.up.set(0,1,0),s.lookAt(-1,0,0),r.up.set(0,0,-1),r.lookAt(0,1,0),a.up.set(0,0,1),a.lookAt(0,-1,0),o.up.set(0,1,0),o.lookAt(0,0,1),c.up.set(0,1,0),c.lookAt(0,0,-1);else if(e===Wa)n.up.set(0,-1,0),n.lookAt(-1,0,0),s.up.set(0,-1,0),s.lookAt(1,0,0),r.up.set(0,0,1),r.lookAt(0,1,0),a.up.set(0,0,-1),a.lookAt(0,-1,0),o.up.set(0,-1,0),o.lookAt(0,0,1),c.up.set(0,-1,0),c.lookAt(0,0,-1);else throw new Error("THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: "+e);for(const l of t)this.add(l),l.updateMatrixWorld()}update(e,t){this.parent===null&&this.updateMatrixWorld();const{renderTarget:n,activeMipmapLevel:s}=this;this.coordinateSystem!==e.coordinateSystem&&(this.coordinateSystem=e.coordinateSystem,this.updateCoordinateSystem());const[r,a,o,c,l,d]=this.children,u=e.getRenderTarget(),h=e.getActiveCubeFace(),f=e.getActiveMipmapLevel(),g=e.xr.enabled;e.xr.enabled=!1;const v=n.texture.generateMipmaps;n.texture.generateMipmaps=!1,e.setRenderTarget(n,0,s),e.render(t,r),e.setRenderTarget(n,1,s),e.render(t,a),e.setRenderTarget(n,2,s),e.render(t,o),e.setRenderTarget(n,3,s),e.render(t,c),e.setRenderTarget(n,4,s),e.render(t,l),n.texture.generateMipmaps=v,e.setRenderTarget(n,5,s),e.render(t,d),e.setRenderTarget(u,h,f),e.xr.enabled=g,n.texture.needsPMREMUpdate=!0}}class jp extends Qt{constructor(e=[],t=ds,n,s,r,a,o,c,l,d){super(e,t,n,s,r,a,o,c,l,d),this.isCubeTexture=!0,this.flipY=!1}get images(){return this.image}set images(e){this.image=e}}class $p extends Qn{constructor(e=1,t={}){super(e,e,t),this.isWebGLCubeRenderTarget=!0;const n={width:e,height:e,depth:1},s=[n,n,n,n,n,n];this.texture=new jp(s),this._setTextureOptions(t),this.texture.isRenderTargetTexture=!0}fromEquirectangularTexture(e,t){this.texture.type=t.type,this.texture.colorSpace=t.colorSpace,this.texture.generateMipmaps=t.generateMipmaps,this.texture.minFilter=t.minFilter,this.texture.magFilter=t.magFilter;const n={uniforms:{tEquirect:{value:null}},vertexShader:`
92
+ }`;class Cn extends eo{constructor(e){super(),this.isShaderMaterial=!0,this.type="ShaderMaterial",this.defines={},this.uniforms={},this.uniformsGroups=[],this.vertexShader=ry,this.fragmentShader=ay,this.linewidth=1,this.wireframe=!1,this.wireframeLinewidth=1,this.fog=!1,this.lights=!1,this.clipping=!1,this.forceSinglePass=!0,this.extensions={clipCullDistance:!1,multiDraw:!1},this.defaultAttributeValues={color:[1,1,1],uv:[0,0],uv1:[0,0]},this.index0AttributeName=void 0,this.uniformsNeedUpdate=!1,this.glslVersion=null,e!==void 0&&this.setValues(e)}copy(e){return super.copy(e),this.fragmentShader=e.fragmentShader,this.vertexShader=e.vertexShader,this.uniforms=sr(e.uniforms),this.uniformsGroups=iy(e.uniformsGroups),this.defines=Object.assign({},e.defines),this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.fog=e.fog,this.lights=e.lights,this.clipping=e.clipping,this.extensions=Object.assign({},e.extensions),this.glslVersion=e.glslVersion,this.defaultAttributeValues=Object.assign({},e.defaultAttributeValues),this.index0AttributeName=e.index0AttributeName,this.uniformsNeedUpdate=e.uniformsNeedUpdate,this}toJSON(e){const t=super.toJSON(e);t.glslVersion=this.glslVersion,t.uniforms={};for(const s in this.uniforms){const a=this.uniforms[s].value;a&&a.isTexture?t.uniforms[s]={type:"t",value:a.toJSON(e).uuid}:a&&a.isColor?t.uniforms[s]={type:"c",value:a.getHex()}:a&&a.isVector2?t.uniforms[s]={type:"v2",value:a.toArray()}:a&&a.isVector3?t.uniforms[s]={type:"v3",value:a.toArray()}:a&&a.isVector4?t.uniforms[s]={type:"v4",value:a.toArray()}:a&&a.isMatrix3?t.uniforms[s]={type:"m3",value:a.toArray()}:a&&a.isMatrix4?t.uniforms[s]={type:"m4",value:a.toArray()}:t.uniforms[s]={value:a}}Object.keys(this.defines).length>0&&(t.defines=this.defines),t.vertexShader=this.vertexShader,t.fragmentShader=this.fragmentShader,t.lights=this.lights,t.clipping=this.clipping;const n={};for(const s in this.extensions)this.extensions[s]===!0&&(n[s]=!0);return Object.keys(n).length>0&&(t.extensions=n),t}}class Hp extends gn{constructor(){super(),this.isCamera=!0,this.type="Camera",this.matrixWorldInverse=new Nt,this.projectionMatrix=new Nt,this.projectionMatrixInverse=new Nt,this.coordinateSystem=Qn,this._reversedDepth=!1}get reversedDepth(){return this._reversedDepth}copy(e,t){return super.copy(e,t),this.matrixWorldInverse.copy(e.matrixWorldInverse),this.projectionMatrix.copy(e.projectionMatrix),this.projectionMatrixInverse.copy(e.projectionMatrixInverse),this.coordinateSystem=e.coordinateSystem,this}getWorldDirection(e){return super.getWorldDirection(e).negate()}updateMatrixWorld(e){super.updateMatrixWorld(e),this.matrixWorldInverse.copy(this.matrixWorld).invert()}updateWorldMatrix(e,t){super.updateWorldMatrix(e,t),this.matrixWorldInverse.copy(this.matrixWorld).invert()}clone(){return new this.constructor().copy(this)}}const Yi=new F,Wp=new rt,qp=new rt;class En extends Hp{constructor(e=50,t=1,n=.1,s=2e3){super(),this.isPerspectiveCamera=!0,this.type="PerspectiveCamera",this.fov=e,this.zoom=1,this.near=n,this.far=s,this.focus=10,this.aspect=t,this.view=null,this.filmGauge=35,this.filmOffset=0,this.updateProjectionMatrix()}copy(e,t){return super.copy(e,t),this.fov=e.fov,this.zoom=e.zoom,this.near=e.near,this.far=e.far,this.focus=e.focus,this.aspect=e.aspect,this.view=e.view===null?null:Object.assign({},e.view),this.filmGauge=e.filmGauge,this.filmOffset=e.filmOffset,this}setFocalLength(e){const t=.5*this.getFilmHeight()/e;this.fov=nd*2*Math.atan(t),this.updateProjectionMatrix()}getFocalLength(){const e=Math.tan(td*.5*this.fov);return .5*this.getFilmHeight()/e}getEffectiveFOV(){return nd*2*Math.atan(Math.tan(td*.5*this.fov)/this.zoom)}getFilmWidth(){return this.filmGauge*Math.min(this.aspect,1)}getFilmHeight(){return this.filmGauge/Math.max(this.aspect,1)}getViewBounds(e,t,n){Yi.set(-1,-1,.5).applyMatrix4(this.projectionMatrixInverse),t.set(Yi.x,Yi.y).multiplyScalar(-e/Yi.z),Yi.set(1,1,.5).applyMatrix4(this.projectionMatrixInverse),n.set(Yi.x,Yi.y).multiplyScalar(-e/Yi.z)}getViewSize(e,t){return this.getViewBounds(e,Wp,qp),t.subVectors(qp,Wp)}setViewOffset(e,t,n,s,r,a){this.aspect=e/t,this.view===null&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=e,this.view.fullHeight=t,this.view.offsetX=n,this.view.offsetY=s,this.view.width=r,this.view.height=a,this.updateProjectionMatrix()}clearViewOffset(){this.view!==null&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){const e=this.near;let t=e*Math.tan(td*.5*this.fov)/this.zoom,n=2*t,s=this.aspect*n,r=-.5*s;const a=this.view;if(this.view!==null&&this.view.enabled){const c=a.fullWidth,l=a.fullHeight;r+=a.offsetX*s/c,t-=a.offsetY*n/l,s*=a.width/c,n*=a.height/l}const o=this.filmOffset;o!==0&&(r+=e*o/this.getFilmWidth()),this.projectionMatrix.makePerspective(r,r+s,t,t-n,e,this.far,this.coordinateSystem,this.reversedDepth),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(e){const t=super.toJSON(e);return t.object.fov=this.fov,t.object.zoom=this.zoom,t.object.near=this.near,t.object.far=this.far,t.object.focus=this.focus,t.object.aspect=this.aspect,this.view!==null&&(t.object.view=Object.assign({},this.view)),t.object.filmGauge=this.filmGauge,t.object.filmOffset=this.filmOffset,t}}const rr=-90,ar=1;class oy extends gn{constructor(e,t,n){super(),this.type="CubeCamera",this.renderTarget=n,this.coordinateSystem=null,this.activeMipmapLevel=0;const s=new En(rr,ar,e,t);s.layers=this.layers,this.add(s);const r=new En(rr,ar,e,t);r.layers=this.layers,this.add(r);const a=new En(rr,ar,e,t);a.layers=this.layers,this.add(a);const o=new En(rr,ar,e,t);o.layers=this.layers,this.add(o);const c=new En(rr,ar,e,t);c.layers=this.layers,this.add(c);const l=new En(rr,ar,e,t);l.layers=this.layers,this.add(l)}updateCoordinateSystem(){const e=this.coordinateSystem,t=this.children.concat(),[n,s,r,a,o,c]=t;for(const l of t)this.remove(l);if(e===Qn)n.up.set(0,1,0),n.lookAt(1,0,0),s.up.set(0,1,0),s.lookAt(-1,0,0),r.up.set(0,0,-1),r.lookAt(0,1,0),a.up.set(0,0,1),a.lookAt(0,-1,0),o.up.set(0,1,0),o.lookAt(0,0,1),c.up.set(0,1,0),c.lookAt(0,0,-1);else if(e===Wa)n.up.set(0,-1,0),n.lookAt(-1,0,0),s.up.set(0,-1,0),s.lookAt(1,0,0),r.up.set(0,0,1),r.lookAt(0,1,0),a.up.set(0,0,-1),a.lookAt(0,-1,0),o.up.set(0,-1,0),o.lookAt(0,0,1),c.up.set(0,-1,0),c.lookAt(0,0,-1);else throw new Error("THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: "+e);for(const l of t)this.add(l),l.updateMatrixWorld()}update(e,t){this.parent===null&&this.updateMatrixWorld();const{renderTarget:n,activeMipmapLevel:s}=this;this.coordinateSystem!==e.coordinateSystem&&(this.coordinateSystem=e.coordinateSystem,this.updateCoordinateSystem());const[r,a,o,c,l,d]=this.children,u=e.getRenderTarget(),h=e.getActiveCubeFace(),f=e.getActiveMipmapLevel(),g=e.xr.enabled;e.xr.enabled=!1;const v=n.texture.generateMipmaps;n.texture.generateMipmaps=!1,e.setRenderTarget(n,0,s),e.render(t,r),e.setRenderTarget(n,1,s),e.render(t,a),e.setRenderTarget(n,2,s),e.render(t,o),e.setRenderTarget(n,3,s),e.render(t,c),e.setRenderTarget(n,4,s),e.render(t,l),n.texture.generateMipmaps=v,e.setRenderTarget(n,5,s),e.render(t,d),e.setRenderTarget(u,h,f),e.xr.enabled=g,n.texture.needsPMREMUpdate=!0}}class jp extends Qt{constructor(e=[],t=ds,n,s,r,a,o,c,l,d){super(e,t,n,s,r,a,o,c,l,d),this.isCubeTexture=!0,this.flipY=!1}get images(){return this.image}set images(e){this.image=e}}class $p extends ei{constructor(e=1,t={}){super(e,e,t),this.isWebGLCubeRenderTarget=!0;const n={width:e,height:e,depth:1},s=[n,n,n,n,n,n];this.texture=new jp(s),this._setTextureOptions(t),this.texture.isRenderTargetTexture=!0}fromEquirectangularTexture(e,t){this.texture.type=t.type,this.texture.colorSpace=t.colorSpace,this.texture.generateMipmaps=t.generateMipmaps,this.texture.minFilter=t.minFilter,this.texture.magFilter=t.magFilter;const n={uniforms:{tEquirect:{value:null}},vertexShader:`
93
93
 
94
94
  varying vec3 vWorldDirection;
95
95
 
@@ -124,7 +124,7 @@ a=extmap-allow-mixed`)!==-1){const r=s.sdp.split(`
124
124
  gl_FragColor = texture2D( tEquirect, sampleUV );
125
125
 
126
126
  }
127
- `},s=new Kr(5,5,5),r=new Tn({name:"CubemapFromEquirect",uniforms:sr(n.uniforms),vertexShader:n.vertexShader,fragmentShader:n.fragmentShader,side:Zt,blending:vi});r.uniforms.tEquirect.value=t;const a=new Vn(s,r),o=t.minFilter;return t.minFilter===us&&(t.minFilter=Kt),new oy(1,10,this).update(e,a),t.minFilter=o,a.geometry.dispose(),a.material.dispose(),this}clear(e,t=!0,n=!0,s=!0){const r=e.getRenderTarget();for(let a=0;a<6;a++)e.setRenderTarget(this,a),e.clear(t,n,s);e.setRenderTarget(r)}}class lo extends gn{constructor(){super(),this.isGroup=!0,this.type="Group"}}const cy={type:"move"};class Md{constructor(){this._targetRay=null,this._grip=null,this._hand=null}getHandSpace(){return this._hand===null&&(this._hand=new lo,this._hand.matrixAutoUpdate=!1,this._hand.visible=!1,this._hand.joints={},this._hand.inputState={pinching:!1}),this._hand}getTargetRaySpace(){return this._targetRay===null&&(this._targetRay=new lo,this._targetRay.matrixAutoUpdate=!1,this._targetRay.visible=!1,this._targetRay.hasLinearVelocity=!1,this._targetRay.linearVelocity=new F,this._targetRay.hasAngularVelocity=!1,this._targetRay.angularVelocity=new F),this._targetRay}getGripSpace(){return this._grip===null&&(this._grip=new lo,this._grip.matrixAutoUpdate=!1,this._grip.visible=!1,this._grip.hasLinearVelocity=!1,this._grip.linearVelocity=new F,this._grip.hasAngularVelocity=!1,this._grip.angularVelocity=new F),this._grip}dispatchEvent(e){return this._targetRay!==null&&this._targetRay.dispatchEvent(e),this._grip!==null&&this._grip.dispatchEvent(e),this._hand!==null&&this._hand.dispatchEvent(e),this}connect(e){if(e&&e.hand){const t=this._hand;if(t)for(const n of e.hand.values())this._getHandJoint(t,n)}return this.dispatchEvent({type:"connected",data:e}),this}disconnect(e){return this.dispatchEvent({type:"disconnected",data:e}),this._targetRay!==null&&(this._targetRay.visible=!1),this._grip!==null&&(this._grip.visible=!1),this._hand!==null&&(this._hand.visible=!1),this}update(e,t,n){let s=null,r=null,a=null;const o=this._targetRay,c=this._grip,l=this._hand;if(e&&t.session.visibilityState!=="visible-blurred"){if(l&&e.hand){a=!0;for(const v of e.hand.values()){const m=t.getJointPose(v,n),p=this._getHandJoint(l,v);m!==null&&(p.matrix.fromArray(m.transform.matrix),p.matrix.decompose(p.position,p.rotation,p.scale),p.matrixWorldNeedsUpdate=!0,p.jointRadius=m.radius),p.visible=m!==null}const d=l.joints["index-finger-tip"],u=l.joints["thumb-tip"],h=d.position.distanceTo(u.position),f=.02,g=.005;l.inputState.pinching&&h>f+g?(l.inputState.pinching=!1,this.dispatchEvent({type:"pinchend",handedness:e.handedness,target:this})):!l.inputState.pinching&&h<=f-g&&(l.inputState.pinching=!0,this.dispatchEvent({type:"pinchstart",handedness:e.handedness,target:this}))}else c!==null&&e.gripSpace&&(r=t.getPose(e.gripSpace,n),r!==null&&(c.matrix.fromArray(r.transform.matrix),c.matrix.decompose(c.position,c.rotation,c.scale),c.matrixWorldNeedsUpdate=!0,r.linearVelocity?(c.hasLinearVelocity=!0,c.linearVelocity.copy(r.linearVelocity)):c.hasLinearVelocity=!1,r.angularVelocity?(c.hasAngularVelocity=!0,c.angularVelocity.copy(r.angularVelocity)):c.hasAngularVelocity=!1));o!==null&&(s=t.getPose(e.targetRaySpace,n),s===null&&r!==null&&(s=r),s!==null&&(o.matrix.fromArray(s.transform.matrix),o.matrix.decompose(o.position,o.rotation,o.scale),o.matrixWorldNeedsUpdate=!0,s.linearVelocity?(o.hasLinearVelocity=!0,o.linearVelocity.copy(s.linearVelocity)):o.hasLinearVelocity=!1,s.angularVelocity?(o.hasAngularVelocity=!0,o.angularVelocity.copy(s.angularVelocity)):o.hasAngularVelocity=!1,this.dispatchEvent(cy)))}return o!==null&&(o.visible=s!==null),c!==null&&(c.visible=r!==null),l!==null&&(l.visible=a!==null),this}_getHandJoint(e,t){if(e.joints[t.jointName]===void 0){const n=new lo;n.matrixAutoUpdate=!1,n.visible=!1,e.joints[t.jointName]=n,e.add(n)}return e.joints[t.jointName]}}class ly extends gn{constructor(){super(),this.isScene=!0,this.type="Scene",this.background=null,this.environment=null,this.fog=null,this.backgroundBlurriness=0,this.backgroundIntensity=1,this.backgroundRotation=new Ci,this.environmentIntensity=1,this.environmentRotation=new Ci,this.overrideMaterial=null,typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}copy(e,t){return super.copy(e,t),e.background!==null&&(this.background=e.background.clone()),e.environment!==null&&(this.environment=e.environment.clone()),e.fog!==null&&(this.fog=e.fog.clone()),this.backgroundBlurriness=e.backgroundBlurriness,this.backgroundIntensity=e.backgroundIntensity,this.backgroundRotation.copy(e.backgroundRotation),this.environmentIntensity=e.environmentIntensity,this.environmentRotation.copy(e.environmentRotation),e.overrideMaterial!==null&&(this.overrideMaterial=e.overrideMaterial.clone()),this.matrixAutoUpdate=e.matrixAutoUpdate,this}toJSON(e){const t=super.toJSON(e);return this.fog!==null&&(t.object.fog=this.fog.toJSON()),this.backgroundBlurriness>0&&(t.object.backgroundBlurriness=this.backgroundBlurriness),this.backgroundIntensity!==1&&(t.object.backgroundIntensity=this.backgroundIntensity),t.object.backgroundRotation=this.backgroundRotation.toArray(),this.environmentIntensity!==1&&(t.object.environmentIntensity=this.environmentIntensity),t.object.environmentRotation=this.environmentRotation.toArray(),t}}class dy extends Qt{constructor(e=null,t=1,n=1,s,r,a,o,c,l=Xt,d=Xt,u,h){super(null,a,o,c,l,d,s,r,u,h),this.isDataTexture=!0,this.image={data:e,width:t,height:n},this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}}const wd=new F,uy=new F,hy=new ze;class gs{constructor(e=new F(1,0,0),t=0){this.isPlane=!0,this.normal=e,this.constant=t}set(e,t){return this.normal.copy(e),this.constant=t,this}setComponents(e,t,n,s){return this.normal.set(e,t,n),this.constant=s,this}setFromNormalAndCoplanarPoint(e,t){return this.normal.copy(e),this.constant=-t.dot(this.normal),this}setFromCoplanarPoints(e,t,n){const s=wd.subVectors(n,t).cross(uy.subVectors(e,t)).normalize();return this.setFromNormalAndCoplanarPoint(s,e),this}copy(e){return this.normal.copy(e.normal),this.constant=e.constant,this}normalize(){const e=1/this.normal.length();return this.normal.multiplyScalar(e),this.constant*=e,this}negate(){return this.constant*=-1,this.normal.negate(),this}distanceToPoint(e){return this.normal.dot(e)+this.constant}distanceToSphere(e){return this.distanceToPoint(e.center)-e.radius}projectPoint(e,t){return t.copy(e).addScaledVector(this.normal,-this.distanceToPoint(e))}intersectLine(e,t){const n=e.delta(wd),s=this.normal.dot(n);if(s===0)return this.distanceToPoint(e.start)===0?t.copy(e.start):null;const r=-(e.start.dot(this.normal)+this.constant)/s;return r<0||r>1?null:t.copy(e.start).addScaledVector(n,r)}intersectsLine(e){const t=this.distanceToPoint(e.start),n=this.distanceToPoint(e.end);return t<0&&n>0||n<0&&t>0}intersectsBox(e){return e.intersectsPlane(this)}intersectsSphere(e){return e.intersectsPlane(this)}coplanarPoint(e){return e.copy(this.normal).multiplyScalar(-this.constant)}applyMatrix4(e,t){const n=t||hy.getNormalMatrix(e),s=this.coplanarPoint(wd).applyMatrix4(e),r=this.normal.applyMatrix3(n).normalize();return this.constant=-s.dot(r),this}translate(e){return this.constant-=e.dot(this.normal),this}equals(e){return e.normal.equals(this.normal)&&e.constant===this.constant}clone(){return new this.constructor().copy(this)}}const vs=new ud,fy=new rt(.5,.5),uo=new F;class Xp{constructor(e=new gs,t=new gs,n=new gs,s=new gs,r=new gs,a=new gs){this.planes=[e,t,n,s,r,a]}set(e,t,n,s,r,a){const o=this.planes;return o[0].copy(e),o[1].copy(t),o[2].copy(n),o[3].copy(s),o[4].copy(r),o[5].copy(a),this}copy(e){const t=this.planes;for(let n=0;n<6;n++)t[n].copy(e.planes[n]);return this}setFromProjectionMatrix(e,t=Zn,n=!1){const s=this.planes,r=e.elements,a=r[0],o=r[1],c=r[2],l=r[3],d=r[4],u=r[5],h=r[6],f=r[7],g=r[8],v=r[9],m=r[10],p=r[11],x=r[12],C=r[13],b=r[14],S=r[15];if(s[0].setComponents(l-a,f-d,p-g,S-x).normalize(),s[1].setComponents(l+a,f+d,p+g,S+x).normalize(),s[2].setComponents(l+o,f+u,p+v,S+C).normalize(),s[3].setComponents(l-o,f-u,p-v,S-C).normalize(),n)s[4].setComponents(c,h,m,b).normalize(),s[5].setComponents(l-c,f-h,p-m,S-b).normalize();else if(s[4].setComponents(l-c,f-h,p-m,S-b).normalize(),t===Zn)s[5].setComponents(l+c,f+h,p+m,S+b).normalize();else if(t===Wa)s[5].setComponents(c,h,m,b).normalize();else throw new Error("THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: "+t);return this}intersectsObject(e){if(e.boundingSphere!==void 0)e.boundingSphere===null&&e.computeBoundingSphere(),vs.copy(e.boundingSphere).applyMatrix4(e.matrixWorld);else{const t=e.geometry;t.boundingSphere===null&&t.computeBoundingSphere(),vs.copy(t.boundingSphere).applyMatrix4(e.matrixWorld)}return this.intersectsSphere(vs)}intersectsSprite(e){vs.center.set(0,0,0);const t=fy.distanceTo(e.center);return vs.radius=.7071067811865476+t,vs.applyMatrix4(e.matrixWorld),this.intersectsSphere(vs)}intersectsSphere(e){const t=this.planes,n=e.center,s=-e.radius;for(let r=0;r<6;r++)if(t[r].distanceToPoint(n)<s)return!1;return!0}intersectsBox(e){const t=this.planes;for(let n=0;n<6;n++){const s=t[n];if(uo.x=s.normal.x>0?e.max.x:e.min.x,uo.y=s.normal.y>0?e.max.y:e.min.y,uo.z=s.normal.z>0?e.max.z:e.min.z,s.distanceToPoint(uo)<0)return!1}return!0}containsPoint(e){const t=this.planes;for(let n=0;n<6;n++)if(t[n].distanceToPoint(e)<0)return!1;return!0}clone(){return new this.constructor().copy(this)}}class Yr extends Qt{constructor(e,t,n=Yn,s,r,a,o=Xt,c=Xt,l,d=yi,u=1){if(d!==yi&&d!==hs)throw new Error("DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat");const h={width:e,height:t,depth:u};super(h,s,r,a,o,c,d,n,l),this.isDepthTexture=!0,this.flipY=!1,this.generateMipmaps=!1,this.compareFunction=null}copy(e){return super.copy(e),this.source=new ad(Object.assign({},e.image)),this.compareFunction=e.compareFunction,this}toJSON(e){const t=super.toJSON(e);return this.compareFunction!==null&&(t.compareFunction=this.compareFunction),t}}class py extends Yr{constructor(e,t=Yn,n=ds,s,r,a=Xt,o=Xt,c,l=yi){const d={width:e,height:e,depth:1},u=[d,d,d,d,d,d];super(e,e,t,n,s,r,a,o,c,l),this.image=u,this.isCubeDepthTexture=!0,this.isCubeTexture=!0}get images(){return this.image}set images(e){this.image=e}}class Kp extends Qt{constructor(e=null){super(),this.sourceTexture=e,this.isExternalTexture=!0}copy(e){return super.copy(e),this.sourceTexture=e.sourceTexture,this}}class Ad extends Bn{constructor(e=[],t=[],n=1,s=0){super(),this.type="PolyhedronGeometry",this.parameters={vertices:e,indices:t,radius:n,detail:s};const r=[],a=[];o(s),l(n),d(),this.setAttribute("position",new en(r,3)),this.setAttribute("normal",new en(r.slice(),3)),this.setAttribute("uv",new en(a,2)),s===0?this.computeVertexNormals():this.normalizeNormals();function o(x){const C=new F,b=new F,S=new F;for(let M=0;M<t.length;M+=3)f(t[M+0],C),f(t[M+1],b),f(t[M+2],S),c(C,b,S,x)}function c(x,C,b,S){const M=S+1,A=[];for(let k=0;k<=M;k++){A[k]=[];const y=x.clone().lerp(b,k/M),T=C.clone().lerp(b,k/M),R=M-k;for(let U=0;U<=R;U++)U===0&&k===M?A[k][U]=y:A[k][U]=y.clone().lerp(T,U/R)}for(let k=0;k<M;k++)for(let y=0;y<2*(M-k)-1;y++){const T=Math.floor(y/2);y%2===0?(h(A[k][T+1]),h(A[k+1][T]),h(A[k][T])):(h(A[k][T+1]),h(A[k+1][T+1]),h(A[k+1][T]))}}function l(x){const C=new F;for(let b=0;b<r.length;b+=3)C.x=r[b+0],C.y=r[b+1],C.z=r[b+2],C.normalize().multiplyScalar(x),r[b+0]=C.x,r[b+1]=C.y,r[b+2]=C.z}function d(){const x=new F;for(let C=0;C<r.length;C+=3){x.x=r[C+0],x.y=r[C+1],x.z=r[C+2];const b=m(x)/2/Math.PI+.5,S=p(x)/Math.PI+.5;a.push(b,1-S)}g(),u()}function u(){for(let x=0;x<a.length;x+=6){const C=a[x+0],b=a[x+2],S=a[x+4],M=Math.max(C,b,S),A=Math.min(C,b,S);M>.9&&A<.1&&(C<.2&&(a[x+0]+=1),b<.2&&(a[x+2]+=1),S<.2&&(a[x+4]+=1))}}function h(x){r.push(x.x,x.y,x.z)}function f(x,C){const b=x*3;C.x=e[b+0],C.y=e[b+1],C.z=e[b+2]}function g(){const x=new F,C=new F,b=new F,S=new F,M=new rt,A=new rt,k=new rt;for(let y=0,T=0;y<r.length;y+=9,T+=6){x.set(r[y+0],r[y+1],r[y+2]),C.set(r[y+3],r[y+4],r[y+5]),b.set(r[y+6],r[y+7],r[y+8]),M.set(a[T+0],a[T+1]),A.set(a[T+2],a[T+3]),k.set(a[T+4],a[T+5]),S.copy(x).add(C).add(b).divideScalar(3);const R=m(S);v(M,T+0,x,R),v(A,T+2,C,R),v(k,T+4,b,R)}}function v(x,C,b,S){S<0&&x.x===1&&(a[C]=x.x-1),b.x===0&&b.z===0&&(a[C]=S/2/Math.PI+.5)}function m(x){return Math.atan2(x.z,-x.x)}function p(x){return Math.atan2(-x.y,Math.sqrt(x.x*x.x+x.z*x.z))}}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new Ad(e.vertices,e.indices,e.radius,e.detail)}}class Rd extends Ad{constructor(e=1,t=0){const n=(1+Math.sqrt(5))/2,s=[-1,n,0,1,n,0,-1,-n,0,1,-n,0,0,-1,n,0,1,n,0,-1,-n,0,1,-n,n,0,-1,n,0,1,-n,0,-1,-n,0,1],r=[0,11,5,0,5,1,0,1,7,0,7,10,0,10,11,1,5,9,5,11,4,11,10,2,10,7,6,7,1,8,3,9,4,3,4,2,3,2,6,3,6,8,3,8,9,4,9,5,2,4,11,6,2,10,8,6,7,9,8,1];super(s,r,e,t),this.type="IcosahedronGeometry",this.parameters={radius:e,detail:t}}static fromJSON(e){return new Rd(e.radius,e.detail)}}class ho extends Bn{constructor(e=1,t=1,n=1,s=1){super(),this.type="PlaneGeometry",this.parameters={width:e,height:t,widthSegments:n,heightSegments:s};const r=e/2,a=t/2,o=Math.floor(n),c=Math.floor(s),l=o+1,d=c+1,u=e/o,h=t/c,f=[],g=[],v=[],m=[];for(let p=0;p<d;p++){const x=p*h-a;for(let C=0;C<l;C++){const b=C*u-r;g.push(b,-x,0),v.push(0,0,1),m.push(C/o),m.push(1-p/c)}}for(let p=0;p<c;p++)for(let x=0;x<o;x++){const C=x+l*p,b=x+l*(p+1),S=x+1+l*(p+1),M=x+1+l*p;f.push(C,b,M),f.push(b,S,M)}this.setIndex(f),this.setAttribute("position",new en(g,3)),this.setAttribute("normal",new en(v,3)),this.setAttribute("uv",new en(m,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new ho(e.width,e.height,e.widthSegments,e.heightSegments)}}class Pd extends Bn{constructor(e=1,t=32,n=16,s=0,r=Math.PI*2,a=0,o=Math.PI){super(),this.type="SphereGeometry",this.parameters={radius:e,widthSegments:t,heightSegments:n,phiStart:s,phiLength:r,thetaStart:a,thetaLength:o},t=Math.max(3,Math.floor(t)),n=Math.max(2,Math.floor(n));const c=Math.min(a+o,Math.PI);let l=0;const d=[],u=new F,h=new F,f=[],g=[],v=[],m=[];for(let p=0;p<=n;p++){const x=[],C=p/n;let b=0;p===0&&a===0?b=.5/t:p===n&&c===Math.PI&&(b=-.5/t);for(let S=0;S<=t;S++){const M=S/t;u.x=-e*Math.cos(s+M*r)*Math.sin(a+C*o),u.y=e*Math.cos(a+C*o),u.z=e*Math.sin(s+M*r)*Math.sin(a+C*o),g.push(u.x,u.y,u.z),h.copy(u).normalize(),v.push(h.x,h.y,h.z),m.push(M+b,1-C),x.push(l++)}d.push(x)}for(let p=0;p<n;p++)for(let x=0;x<t;x++){const C=d[p][x+1],b=d[p][x],S=d[p+1][x],M=d[p+1][x+1];(p!==0||a>0)&&f.push(C,b,M),(p!==n-1||c<Math.PI)&&f.push(b,S,M)}this.setIndex(f),this.setAttribute("position",new en(g,3)),this.setAttribute("normal",new en(v,3)),this.setAttribute("uv",new en(m,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new Pd(e.radius,e.widthSegments,e.heightSegments,e.phiStart,e.phiLength,e.thetaStart,e.thetaLength)}}class my extends Tn{constructor(e){super(e),this.isRawShaderMaterial=!0,this.type="RawShaderMaterial"}}class gy extends eo{constructor(e){super(),this.isMeshDepthMaterial=!0,this.type="MeshDepthMaterial",this.depthPacking=w_,this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.wireframe=!1,this.wireframeLinewidth=1,this.setValues(e)}copy(e){return super.copy(e),this.depthPacking=e.depthPacking,this.map=e.map,this.alphaMap=e.alphaMap,this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this}}class vy extends eo{constructor(e){super(),this.isMeshDistanceMaterial=!0,this.type="MeshDistanceMaterial",this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.setValues(e)}copy(e){return super.copy(e),this.map=e.map,this.alphaMap=e.alphaMap,this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this}}class Yp extends Hp{constructor(e=-1,t=1,n=1,s=-1,r=.1,a=2e3){super(),this.isOrthographicCamera=!0,this.type="OrthographicCamera",this.zoom=1,this.view=null,this.left=e,this.right=t,this.top=n,this.bottom=s,this.near=r,this.far=a,this.updateProjectionMatrix()}copy(e,t){return super.copy(e,t),this.left=e.left,this.right=e.right,this.top=e.top,this.bottom=e.bottom,this.near=e.near,this.far=e.far,this.zoom=e.zoom,this.view=e.view===null?null:Object.assign({},e.view),this}setViewOffset(e,t,n,s,r,a){this.view===null&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=e,this.view.fullHeight=t,this.view.offsetX=n,this.view.offsetY=s,this.view.width=r,this.view.height=a,this.updateProjectionMatrix()}clearViewOffset(){this.view!==null&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){const e=(this.right-this.left)/(2*this.zoom),t=(this.top-this.bottom)/(2*this.zoom),n=(this.right+this.left)/2,s=(this.top+this.bottom)/2;let r=n-e,a=n+e,o=s+t,c=s-t;if(this.view!==null&&this.view.enabled){const l=(this.right-this.left)/this.view.fullWidth/this.zoom,d=(this.top-this.bottom)/this.view.fullHeight/this.zoom;r+=l*this.view.offsetX,a=r+l*this.view.width,o-=d*this.view.offsetY,c=o-d*this.view.height}this.projectionMatrix.makeOrthographic(r,a,o,c,this.near,this.far,this.coordinateSystem,this.reversedDepth),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(e){const t=super.toJSON(e);return t.object.zoom=this.zoom,t.object.left=this.left,t.object.right=this.right,t.object.top=this.top,t.object.bottom=this.bottom,t.object.near=this.near,t.object.far=this.far,this.view!==null&&(t.object.view=Object.assign({},this.view)),t}}class by extends Cn{constructor(e=[]){super(),this.isArrayCamera=!0,this.isMultiViewCamera=!1,this.cameras=e}}class _y{constructor(e=!0){this.autoStart=e,this.startTime=0,this.oldTime=0,this.elapsedTime=0,this.running=!1}start(){this.startTime=performance.now(),this.oldTime=this.startTime,this.elapsedTime=0,this.running=!0}stop(){this.getElapsedTime(),this.running=!1,this.autoStart=!1}getElapsedTime(){return this.getDelta(),this.elapsedTime}getDelta(){let e=0;if(this.autoStart&&!this.running)return this.start(),0;if(this.running){const t=performance.now();e=(t-this.oldTime)/1e3,this.oldTime=t,this.elapsedTime+=e}return e}}function Jp(i,e,t,n){const s=yy(n);switch(t){case fp:return i*e;case mp:return i*e/s.components*s.byteLength;case bl:return i*e/s.components*s.byteLength;case Hs:return i*e*2/s.components*s.byteLength;case _l:return i*e*2/s.components*s.byteLength;case pp:return i*e*3/s.components*s.byteLength;case Ln:return i*e*4/s.components*s.byteLength;case yl:return i*e*4/s.components*s.byteLength;case Ba:case Va:return Math.floor((i+3)/4)*Math.floor((e+3)/4)*8;case za:case Ga:return Math.floor((i+3)/4)*Math.floor((e+3)/4)*16;case xl:case Cl:return Math.max(i,16)*Math.max(e,8)/4;case Sl:case Tl:return Math.max(i,8)*Math.max(e,8)/2;case El:case Ml:case Al:case Rl:return Math.floor((i+3)/4)*Math.floor((e+3)/4)*8;case wl:case Pl:case kl:return Math.floor((i+3)/4)*Math.floor((e+3)/4)*16;case Il:return Math.floor((i+3)/4)*Math.floor((e+3)/4)*16;case Dl:return Math.floor((i+4)/5)*Math.floor((e+3)/4)*16;case Ll:return Math.floor((i+4)/5)*Math.floor((e+4)/5)*16;case Nl:return Math.floor((i+5)/6)*Math.floor((e+4)/5)*16;case Ul:return Math.floor((i+5)/6)*Math.floor((e+5)/6)*16;case Ol:return Math.floor((i+7)/8)*Math.floor((e+4)/5)*16;case Fl:return Math.floor((i+7)/8)*Math.floor((e+5)/6)*16;case Bl:return Math.floor((i+7)/8)*Math.floor((e+7)/8)*16;case Vl:return Math.floor((i+9)/10)*Math.floor((e+4)/5)*16;case zl:return Math.floor((i+9)/10)*Math.floor((e+5)/6)*16;case Gl:return Math.floor((i+9)/10)*Math.floor((e+7)/8)*16;case Hl:return Math.floor((i+9)/10)*Math.floor((e+9)/10)*16;case Wl:return Math.floor((i+11)/12)*Math.floor((e+9)/10)*16;case ql:return Math.floor((i+11)/12)*Math.floor((e+11)/12)*16;case jl:case $l:case Xl:return Math.ceil(i/4)*Math.ceil(e/4)*16;case Kl:case Yl:return Math.ceil(i/4)*Math.ceil(e/4)*8;case Jl:case Zl:return Math.ceil(i/4)*Math.ceil(e/4)*16}throw new Error(`Unable to determine texture byte length for ${t} format.`)}function yy(i){switch(i){case yn:case lp:return{byteLength:1,components:1};case Fr:case dp:case _i:return{byteLength:2,components:1};case gl:case vl:return{byteLength:2,components:4};case Yn:case ml:case Jn:return{byteLength:4,components:1};case up:case hp:return{byteLength:4,components:3}}throw new Error(`Unknown texture type ${i}.`)}typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("register",{detail:{revision:Qc}})),typeof window<"u"&&(window.__THREE__?Oe("WARNING: Multiple instances of Three.js being imported."):window.__THREE__=Qc);/**
127
+ `},s=new Kr(5,5,5),r=new Cn({name:"CubemapFromEquirect",uniforms:sr(n.uniforms),vertexShader:n.vertexShader,fragmentShader:n.fragmentShader,side:Zt,blending:vi});r.uniforms.tEquirect.value=t;const a=new zn(s,r),o=t.minFilter;return t.minFilter===us&&(t.minFilter=Kt),new oy(1,10,this).update(e,a),t.minFilter=o,a.geometry.dispose(),a.material.dispose(),this}clear(e,t=!0,n=!0,s=!0){const r=e.getRenderTarget();for(let a=0;a<6;a++)e.setRenderTarget(this,a),e.clear(t,n,s);e.setRenderTarget(r)}}class lo extends gn{constructor(){super(),this.isGroup=!0,this.type="Group"}}const cy={type:"move"};class Md{constructor(){this._targetRay=null,this._grip=null,this._hand=null}getHandSpace(){return this._hand===null&&(this._hand=new lo,this._hand.matrixAutoUpdate=!1,this._hand.visible=!1,this._hand.joints={},this._hand.inputState={pinching:!1}),this._hand}getTargetRaySpace(){return this._targetRay===null&&(this._targetRay=new lo,this._targetRay.matrixAutoUpdate=!1,this._targetRay.visible=!1,this._targetRay.hasLinearVelocity=!1,this._targetRay.linearVelocity=new F,this._targetRay.hasAngularVelocity=!1,this._targetRay.angularVelocity=new F),this._targetRay}getGripSpace(){return this._grip===null&&(this._grip=new lo,this._grip.matrixAutoUpdate=!1,this._grip.visible=!1,this._grip.hasLinearVelocity=!1,this._grip.linearVelocity=new F,this._grip.hasAngularVelocity=!1,this._grip.angularVelocity=new F),this._grip}dispatchEvent(e){return this._targetRay!==null&&this._targetRay.dispatchEvent(e),this._grip!==null&&this._grip.dispatchEvent(e),this._hand!==null&&this._hand.dispatchEvent(e),this}connect(e){if(e&&e.hand){const t=this._hand;if(t)for(const n of e.hand.values())this._getHandJoint(t,n)}return this.dispatchEvent({type:"connected",data:e}),this}disconnect(e){return this.dispatchEvent({type:"disconnected",data:e}),this._targetRay!==null&&(this._targetRay.visible=!1),this._grip!==null&&(this._grip.visible=!1),this._hand!==null&&(this._hand.visible=!1),this}update(e,t,n){let s=null,r=null,a=null;const o=this._targetRay,c=this._grip,l=this._hand;if(e&&t.session.visibilityState!=="visible-blurred"){if(l&&e.hand){a=!0;for(const v of e.hand.values()){const m=t.getJointPose(v,n),p=this._getHandJoint(l,v);m!==null&&(p.matrix.fromArray(m.transform.matrix),p.matrix.decompose(p.position,p.rotation,p.scale),p.matrixWorldNeedsUpdate=!0,p.jointRadius=m.radius),p.visible=m!==null}const d=l.joints["index-finger-tip"],u=l.joints["thumb-tip"],h=d.position.distanceTo(u.position),f=.02,g=.005;l.inputState.pinching&&h>f+g?(l.inputState.pinching=!1,this.dispatchEvent({type:"pinchend",handedness:e.handedness,target:this})):!l.inputState.pinching&&h<=f-g&&(l.inputState.pinching=!0,this.dispatchEvent({type:"pinchstart",handedness:e.handedness,target:this}))}else c!==null&&e.gripSpace&&(r=t.getPose(e.gripSpace,n),r!==null&&(c.matrix.fromArray(r.transform.matrix),c.matrix.decompose(c.position,c.rotation,c.scale),c.matrixWorldNeedsUpdate=!0,r.linearVelocity?(c.hasLinearVelocity=!0,c.linearVelocity.copy(r.linearVelocity)):c.hasLinearVelocity=!1,r.angularVelocity?(c.hasAngularVelocity=!0,c.angularVelocity.copy(r.angularVelocity)):c.hasAngularVelocity=!1));o!==null&&(s=t.getPose(e.targetRaySpace,n),s===null&&r!==null&&(s=r),s!==null&&(o.matrix.fromArray(s.transform.matrix),o.matrix.decompose(o.position,o.rotation,o.scale),o.matrixWorldNeedsUpdate=!0,s.linearVelocity?(o.hasLinearVelocity=!0,o.linearVelocity.copy(s.linearVelocity)):o.hasLinearVelocity=!1,s.angularVelocity?(o.hasAngularVelocity=!0,o.angularVelocity.copy(s.angularVelocity)):o.hasAngularVelocity=!1,this.dispatchEvent(cy)))}return o!==null&&(o.visible=s!==null),c!==null&&(c.visible=r!==null),l!==null&&(l.visible=a!==null),this}_getHandJoint(e,t){if(e.joints[t.jointName]===void 0){const n=new lo;n.matrixAutoUpdate=!1,n.visible=!1,e.joints[t.jointName]=n,e.add(n)}return e.joints[t.jointName]}}class ly extends gn{constructor(){super(),this.isScene=!0,this.type="Scene",this.background=null,this.environment=null,this.fog=null,this.backgroundBlurriness=0,this.backgroundIntensity=1,this.backgroundRotation=new Ci,this.environmentIntensity=1,this.environmentRotation=new Ci,this.overrideMaterial=null,typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}copy(e,t){return super.copy(e,t),e.background!==null&&(this.background=e.background.clone()),e.environment!==null&&(this.environment=e.environment.clone()),e.fog!==null&&(this.fog=e.fog.clone()),this.backgroundBlurriness=e.backgroundBlurriness,this.backgroundIntensity=e.backgroundIntensity,this.backgroundRotation.copy(e.backgroundRotation),this.environmentIntensity=e.environmentIntensity,this.environmentRotation.copy(e.environmentRotation),e.overrideMaterial!==null&&(this.overrideMaterial=e.overrideMaterial.clone()),this.matrixAutoUpdate=e.matrixAutoUpdate,this}toJSON(e){const t=super.toJSON(e);return this.fog!==null&&(t.object.fog=this.fog.toJSON()),this.backgroundBlurriness>0&&(t.object.backgroundBlurriness=this.backgroundBlurriness),this.backgroundIntensity!==1&&(t.object.backgroundIntensity=this.backgroundIntensity),t.object.backgroundRotation=this.backgroundRotation.toArray(),this.environmentIntensity!==1&&(t.object.environmentIntensity=this.environmentIntensity),t.object.environmentRotation=this.environmentRotation.toArray(),t}}class dy extends Qt{constructor(e=null,t=1,n=1,s,r,a,o,c,l=Xt,d=Xt,u,h){super(null,a,o,c,l,d,s,r,u,h),this.isDataTexture=!0,this.image={data:e,width:t,height:n},this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}}const wd=new F,uy=new F,hy=new ze;class gs{constructor(e=new F(1,0,0),t=0){this.isPlane=!0,this.normal=e,this.constant=t}set(e,t){return this.normal.copy(e),this.constant=t,this}setComponents(e,t,n,s){return this.normal.set(e,t,n),this.constant=s,this}setFromNormalAndCoplanarPoint(e,t){return this.normal.copy(e),this.constant=-t.dot(this.normal),this}setFromCoplanarPoints(e,t,n){const s=wd.subVectors(n,t).cross(uy.subVectors(e,t)).normalize();return this.setFromNormalAndCoplanarPoint(s,e),this}copy(e){return this.normal.copy(e.normal),this.constant=e.constant,this}normalize(){const e=1/this.normal.length();return this.normal.multiplyScalar(e),this.constant*=e,this}negate(){return this.constant*=-1,this.normal.negate(),this}distanceToPoint(e){return this.normal.dot(e)+this.constant}distanceToSphere(e){return this.distanceToPoint(e.center)-e.radius}projectPoint(e,t){return t.copy(e).addScaledVector(this.normal,-this.distanceToPoint(e))}intersectLine(e,t){const n=e.delta(wd),s=this.normal.dot(n);if(s===0)return this.distanceToPoint(e.start)===0?t.copy(e.start):null;const r=-(e.start.dot(this.normal)+this.constant)/s;return r<0||r>1?null:t.copy(e.start).addScaledVector(n,r)}intersectsLine(e){const t=this.distanceToPoint(e.start),n=this.distanceToPoint(e.end);return t<0&&n>0||n<0&&t>0}intersectsBox(e){return e.intersectsPlane(this)}intersectsSphere(e){return e.intersectsPlane(this)}coplanarPoint(e){return e.copy(this.normal).multiplyScalar(-this.constant)}applyMatrix4(e,t){const n=t||hy.getNormalMatrix(e),s=this.coplanarPoint(wd).applyMatrix4(e),r=this.normal.applyMatrix3(n).normalize();return this.constant=-s.dot(r),this}translate(e){return this.constant-=e.dot(this.normal),this}equals(e){return e.normal.equals(this.normal)&&e.constant===this.constant}clone(){return new this.constructor().copy(this)}}const vs=new ud,fy=new rt(.5,.5),uo=new F;class Xp{constructor(e=new gs,t=new gs,n=new gs,s=new gs,r=new gs,a=new gs){this.planes=[e,t,n,s,r,a]}set(e,t,n,s,r,a){const o=this.planes;return o[0].copy(e),o[1].copy(t),o[2].copy(n),o[3].copy(s),o[4].copy(r),o[5].copy(a),this}copy(e){const t=this.planes;for(let n=0;n<6;n++)t[n].copy(e.planes[n]);return this}setFromProjectionMatrix(e,t=Qn,n=!1){const s=this.planes,r=e.elements,a=r[0],o=r[1],c=r[2],l=r[3],d=r[4],u=r[5],h=r[6],f=r[7],g=r[8],v=r[9],m=r[10],p=r[11],x=r[12],C=r[13],b=r[14],S=r[15];if(s[0].setComponents(l-a,f-d,p-g,S-x).normalize(),s[1].setComponents(l+a,f+d,p+g,S+x).normalize(),s[2].setComponents(l+o,f+u,p+v,S+C).normalize(),s[3].setComponents(l-o,f-u,p-v,S-C).normalize(),n)s[4].setComponents(c,h,m,b).normalize(),s[5].setComponents(l-c,f-h,p-m,S-b).normalize();else if(s[4].setComponents(l-c,f-h,p-m,S-b).normalize(),t===Qn)s[5].setComponents(l+c,f+h,p+m,S+b).normalize();else if(t===Wa)s[5].setComponents(c,h,m,b).normalize();else throw new Error("THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: "+t);return this}intersectsObject(e){if(e.boundingSphere!==void 0)e.boundingSphere===null&&e.computeBoundingSphere(),vs.copy(e.boundingSphere).applyMatrix4(e.matrixWorld);else{const t=e.geometry;t.boundingSphere===null&&t.computeBoundingSphere(),vs.copy(t.boundingSphere).applyMatrix4(e.matrixWorld)}return this.intersectsSphere(vs)}intersectsSprite(e){vs.center.set(0,0,0);const t=fy.distanceTo(e.center);return vs.radius=.7071067811865476+t,vs.applyMatrix4(e.matrixWorld),this.intersectsSphere(vs)}intersectsSphere(e){const t=this.planes,n=e.center,s=-e.radius;for(let r=0;r<6;r++)if(t[r].distanceToPoint(n)<s)return!1;return!0}intersectsBox(e){const t=this.planes;for(let n=0;n<6;n++){const s=t[n];if(uo.x=s.normal.x>0?e.max.x:e.min.x,uo.y=s.normal.y>0?e.max.y:e.min.y,uo.z=s.normal.z>0?e.max.z:e.min.z,s.distanceToPoint(uo)<0)return!1}return!0}containsPoint(e){const t=this.planes;for(let n=0;n<6;n++)if(t[n].distanceToPoint(e)<0)return!1;return!0}clone(){return new this.constructor().copy(this)}}class Yr extends Qt{constructor(e,t,n=Jn,s,r,a,o=Xt,c=Xt,l,d=yi,u=1){if(d!==yi&&d!==hs)throw new Error("DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat");const h={width:e,height:t,depth:u};super(h,s,r,a,o,c,d,n,l),this.isDepthTexture=!0,this.flipY=!1,this.generateMipmaps=!1,this.compareFunction=null}copy(e){return super.copy(e),this.source=new ad(Object.assign({},e.image)),this.compareFunction=e.compareFunction,this}toJSON(e){const t=super.toJSON(e);return this.compareFunction!==null&&(t.compareFunction=this.compareFunction),t}}class py extends Yr{constructor(e,t=Jn,n=ds,s,r,a=Xt,o=Xt,c,l=yi){const d={width:e,height:e,depth:1},u=[d,d,d,d,d,d];super(e,e,t,n,s,r,a,o,c,l),this.image=u,this.isCubeDepthTexture=!0,this.isCubeTexture=!0}get images(){return this.image}set images(e){this.image=e}}class Kp extends Qt{constructor(e=null){super(),this.sourceTexture=e,this.isExternalTexture=!0}copy(e){return super.copy(e),this.sourceTexture=e.sourceTexture,this}}class Ad extends Vn{constructor(e=[],t=[],n=1,s=0){super(),this.type="PolyhedronGeometry",this.parameters={vertices:e,indices:t,radius:n,detail:s};const r=[],a=[];o(s),l(n),d(),this.setAttribute("position",new en(r,3)),this.setAttribute("normal",new en(r.slice(),3)),this.setAttribute("uv",new en(a,2)),s===0?this.computeVertexNormals():this.normalizeNormals();function o(x){const C=new F,b=new F,S=new F;for(let M=0;M<t.length;M+=3)f(t[M+0],C),f(t[M+1],b),f(t[M+2],S),c(C,b,S,x)}function c(x,C,b,S){const M=S+1,A=[];for(let k=0;k<=M;k++){A[k]=[];const y=x.clone().lerp(b,k/M),T=C.clone().lerp(b,k/M),R=M-k;for(let U=0;U<=R;U++)U===0&&k===M?A[k][U]=y:A[k][U]=y.clone().lerp(T,U/R)}for(let k=0;k<M;k++)for(let y=0;y<2*(M-k)-1;y++){const T=Math.floor(y/2);y%2===0?(h(A[k][T+1]),h(A[k+1][T]),h(A[k][T])):(h(A[k][T+1]),h(A[k+1][T+1]),h(A[k+1][T]))}}function l(x){const C=new F;for(let b=0;b<r.length;b+=3)C.x=r[b+0],C.y=r[b+1],C.z=r[b+2],C.normalize().multiplyScalar(x),r[b+0]=C.x,r[b+1]=C.y,r[b+2]=C.z}function d(){const x=new F;for(let C=0;C<r.length;C+=3){x.x=r[C+0],x.y=r[C+1],x.z=r[C+2];const b=m(x)/2/Math.PI+.5,S=p(x)/Math.PI+.5;a.push(b,1-S)}g(),u()}function u(){for(let x=0;x<a.length;x+=6){const C=a[x+0],b=a[x+2],S=a[x+4],M=Math.max(C,b,S),A=Math.min(C,b,S);M>.9&&A<.1&&(C<.2&&(a[x+0]+=1),b<.2&&(a[x+2]+=1),S<.2&&(a[x+4]+=1))}}function h(x){r.push(x.x,x.y,x.z)}function f(x,C){const b=x*3;C.x=e[b+0],C.y=e[b+1],C.z=e[b+2]}function g(){const x=new F,C=new F,b=new F,S=new F,M=new rt,A=new rt,k=new rt;for(let y=0,T=0;y<r.length;y+=9,T+=6){x.set(r[y+0],r[y+1],r[y+2]),C.set(r[y+3],r[y+4],r[y+5]),b.set(r[y+6],r[y+7],r[y+8]),M.set(a[T+0],a[T+1]),A.set(a[T+2],a[T+3]),k.set(a[T+4],a[T+5]),S.copy(x).add(C).add(b).divideScalar(3);const R=m(S);v(M,T+0,x,R),v(A,T+2,C,R),v(k,T+4,b,R)}}function v(x,C,b,S){S<0&&x.x===1&&(a[C]=x.x-1),b.x===0&&b.z===0&&(a[C]=S/2/Math.PI+.5)}function m(x){return Math.atan2(x.z,-x.x)}function p(x){return Math.atan2(-x.y,Math.sqrt(x.x*x.x+x.z*x.z))}}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new Ad(e.vertices,e.indices,e.radius,e.detail)}}class Rd extends Ad{constructor(e=1,t=0){const n=(1+Math.sqrt(5))/2,s=[-1,n,0,1,n,0,-1,-n,0,1,-n,0,0,-1,n,0,1,n,0,-1,-n,0,1,-n,n,0,-1,n,0,1,-n,0,-1,-n,0,1],r=[0,11,5,0,5,1,0,1,7,0,7,10,0,10,11,1,5,9,5,11,4,11,10,2,10,7,6,7,1,8,3,9,4,3,4,2,3,2,6,3,6,8,3,8,9,4,9,5,2,4,11,6,2,10,8,6,7,9,8,1];super(s,r,e,t),this.type="IcosahedronGeometry",this.parameters={radius:e,detail:t}}static fromJSON(e){return new Rd(e.radius,e.detail)}}class ho extends Vn{constructor(e=1,t=1,n=1,s=1){super(),this.type="PlaneGeometry",this.parameters={width:e,height:t,widthSegments:n,heightSegments:s};const r=e/2,a=t/2,o=Math.floor(n),c=Math.floor(s),l=o+1,d=c+1,u=e/o,h=t/c,f=[],g=[],v=[],m=[];for(let p=0;p<d;p++){const x=p*h-a;for(let C=0;C<l;C++){const b=C*u-r;g.push(b,-x,0),v.push(0,0,1),m.push(C/o),m.push(1-p/c)}}for(let p=0;p<c;p++)for(let x=0;x<o;x++){const C=x+l*p,b=x+l*(p+1),S=x+1+l*(p+1),M=x+1+l*p;f.push(C,b,M),f.push(b,S,M)}this.setIndex(f),this.setAttribute("position",new en(g,3)),this.setAttribute("normal",new en(v,3)),this.setAttribute("uv",new en(m,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new ho(e.width,e.height,e.widthSegments,e.heightSegments)}}class Pd extends Vn{constructor(e=1,t=32,n=16,s=0,r=Math.PI*2,a=0,o=Math.PI){super(),this.type="SphereGeometry",this.parameters={radius:e,widthSegments:t,heightSegments:n,phiStart:s,phiLength:r,thetaStart:a,thetaLength:o},t=Math.max(3,Math.floor(t)),n=Math.max(2,Math.floor(n));const c=Math.min(a+o,Math.PI);let l=0;const d=[],u=new F,h=new F,f=[],g=[],v=[],m=[];for(let p=0;p<=n;p++){const x=[],C=p/n;let b=0;p===0&&a===0?b=.5/t:p===n&&c===Math.PI&&(b=-.5/t);for(let S=0;S<=t;S++){const M=S/t;u.x=-e*Math.cos(s+M*r)*Math.sin(a+C*o),u.y=e*Math.cos(a+C*o),u.z=e*Math.sin(s+M*r)*Math.sin(a+C*o),g.push(u.x,u.y,u.z),h.copy(u).normalize(),v.push(h.x,h.y,h.z),m.push(M+b,1-C),x.push(l++)}d.push(x)}for(let p=0;p<n;p++)for(let x=0;x<t;x++){const C=d[p][x+1],b=d[p][x],S=d[p+1][x],M=d[p+1][x+1];(p!==0||a>0)&&f.push(C,b,M),(p!==n-1||c<Math.PI)&&f.push(b,S,M)}this.setIndex(f),this.setAttribute("position",new en(g,3)),this.setAttribute("normal",new en(v,3)),this.setAttribute("uv",new en(m,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new Pd(e.radius,e.widthSegments,e.heightSegments,e.phiStart,e.phiLength,e.thetaStart,e.thetaLength)}}class my extends Cn{constructor(e){super(e),this.isRawShaderMaterial=!0,this.type="RawShaderMaterial"}}class gy extends eo{constructor(e){super(),this.isMeshDepthMaterial=!0,this.type="MeshDepthMaterial",this.depthPacking=w_,this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.wireframe=!1,this.wireframeLinewidth=1,this.setValues(e)}copy(e){return super.copy(e),this.depthPacking=e.depthPacking,this.map=e.map,this.alphaMap=e.alphaMap,this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this}}class vy extends eo{constructor(e){super(),this.isMeshDistanceMaterial=!0,this.type="MeshDistanceMaterial",this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.setValues(e)}copy(e){return super.copy(e),this.map=e.map,this.alphaMap=e.alphaMap,this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this}}class Yp extends Hp{constructor(e=-1,t=1,n=1,s=-1,r=.1,a=2e3){super(),this.isOrthographicCamera=!0,this.type="OrthographicCamera",this.zoom=1,this.view=null,this.left=e,this.right=t,this.top=n,this.bottom=s,this.near=r,this.far=a,this.updateProjectionMatrix()}copy(e,t){return super.copy(e,t),this.left=e.left,this.right=e.right,this.top=e.top,this.bottom=e.bottom,this.near=e.near,this.far=e.far,this.zoom=e.zoom,this.view=e.view===null?null:Object.assign({},e.view),this}setViewOffset(e,t,n,s,r,a){this.view===null&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=e,this.view.fullHeight=t,this.view.offsetX=n,this.view.offsetY=s,this.view.width=r,this.view.height=a,this.updateProjectionMatrix()}clearViewOffset(){this.view!==null&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){const e=(this.right-this.left)/(2*this.zoom),t=(this.top-this.bottom)/(2*this.zoom),n=(this.right+this.left)/2,s=(this.top+this.bottom)/2;let r=n-e,a=n+e,o=s+t,c=s-t;if(this.view!==null&&this.view.enabled){const l=(this.right-this.left)/this.view.fullWidth/this.zoom,d=(this.top-this.bottom)/this.view.fullHeight/this.zoom;r+=l*this.view.offsetX,a=r+l*this.view.width,o-=d*this.view.offsetY,c=o-d*this.view.height}this.projectionMatrix.makeOrthographic(r,a,o,c,this.near,this.far,this.coordinateSystem,this.reversedDepth),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(e){const t=super.toJSON(e);return t.object.zoom=this.zoom,t.object.left=this.left,t.object.right=this.right,t.object.top=this.top,t.object.bottom=this.bottom,t.object.near=this.near,t.object.far=this.far,this.view!==null&&(t.object.view=Object.assign({},this.view)),t}}class by extends En{constructor(e=[]){super(),this.isArrayCamera=!0,this.isMultiViewCamera=!1,this.cameras=e}}class _y{constructor(e=!0){this.autoStart=e,this.startTime=0,this.oldTime=0,this.elapsedTime=0,this.running=!1}start(){this.startTime=performance.now(),this.oldTime=this.startTime,this.elapsedTime=0,this.running=!0}stop(){this.getElapsedTime(),this.running=!1,this.autoStart=!1}getElapsedTime(){return this.getDelta(),this.elapsedTime}getDelta(){let e=0;if(this.autoStart&&!this.running)return this.start(),0;if(this.running){const t=performance.now();e=(t-this.oldTime)/1e3,this.oldTime=t,this.elapsedTime+=e}return e}}function Jp(i,e,t,n){const s=yy(n);switch(t){case fp:return i*e;case mp:return i*e/s.components*s.byteLength;case bl:return i*e/s.components*s.byteLength;case Hs:return i*e*2/s.components*s.byteLength;case _l:return i*e*2/s.components*s.byteLength;case pp:return i*e*3/s.components*s.byteLength;case Nn:return i*e*4/s.components*s.byteLength;case yl:return i*e*4/s.components*s.byteLength;case Ba:case Va:return Math.floor((i+3)/4)*Math.floor((e+3)/4)*8;case za:case Ga:return Math.floor((i+3)/4)*Math.floor((e+3)/4)*16;case xl:case Cl:return Math.max(i,16)*Math.max(e,8)/4;case Sl:case Tl:return Math.max(i,8)*Math.max(e,8)/2;case El:case Ml:case Al:case Rl:return Math.floor((i+3)/4)*Math.floor((e+3)/4)*8;case wl:case Pl:case kl:return Math.floor((i+3)/4)*Math.floor((e+3)/4)*16;case Il:return Math.floor((i+3)/4)*Math.floor((e+3)/4)*16;case Dl:return Math.floor((i+4)/5)*Math.floor((e+3)/4)*16;case Ll:return Math.floor((i+4)/5)*Math.floor((e+4)/5)*16;case Nl:return Math.floor((i+5)/6)*Math.floor((e+4)/5)*16;case Ul:return Math.floor((i+5)/6)*Math.floor((e+5)/6)*16;case Ol:return Math.floor((i+7)/8)*Math.floor((e+4)/5)*16;case Fl:return Math.floor((i+7)/8)*Math.floor((e+5)/6)*16;case Bl:return Math.floor((i+7)/8)*Math.floor((e+7)/8)*16;case Vl:return Math.floor((i+9)/10)*Math.floor((e+4)/5)*16;case zl:return Math.floor((i+9)/10)*Math.floor((e+5)/6)*16;case Gl:return Math.floor((i+9)/10)*Math.floor((e+7)/8)*16;case Hl:return Math.floor((i+9)/10)*Math.floor((e+9)/10)*16;case Wl:return Math.floor((i+11)/12)*Math.floor((e+9)/10)*16;case ql:return Math.floor((i+11)/12)*Math.floor((e+11)/12)*16;case jl:case $l:case Xl:return Math.ceil(i/4)*Math.ceil(e/4)*16;case Kl:case Yl:return Math.ceil(i/4)*Math.ceil(e/4)*8;case Jl:case Zl:return Math.ceil(i/4)*Math.ceil(e/4)*16}throw new Error(`Unable to determine texture byte length for ${t} format.`)}function yy(i){switch(i){case Sn:case lp:return{byteLength:1,components:1};case Fr:case dp:case _i:return{byteLength:2,components:1};case gl:case vl:return{byteLength:2,components:4};case Jn:case ml:case Zn:return{byteLength:4,components:1};case up:case hp:return{byteLength:4,components:3}}throw new Error(`Unknown texture type ${i}.`)}typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("register",{detail:{revision:Qc}})),typeof window<"u"&&(window.__THREE__?Oe("WARNING: Multiple instances of Three.js being imported."):window.__THREE__=Qc);/**
128
128
  * @license
129
129
  * Copyright 2010-2025 Three.js Authors
130
130
  * SPDX-License-Identifier: MIT
@@ -3693,7 +3693,7 @@ void main() {
3693
3693
  #include <tonemapping_fragment>
3694
3694
  #include <colorspace_fragment>
3695
3695
  #include <fog_fragment>
3696
- }`},ge={common:{diffuse:{value:new Ze(16777215)},opacity:{value:1},map:{value:null},mapTransform:{value:new ze},alphaMap:{value:null},alphaMapTransform:{value:new ze},alphaTest:{value:0}},specularmap:{specularMap:{value:null},specularMapTransform:{value:new ze}},envmap:{envMap:{value:null},envMapRotation:{value:new ze},flipEnvMap:{value:-1},reflectivity:{value:1},ior:{value:1.5},refractionRatio:{value:.98},dfgLUT:{value:null}},aomap:{aoMap:{value:null},aoMapIntensity:{value:1},aoMapTransform:{value:new ze}},lightmap:{lightMap:{value:null},lightMapIntensity:{value:1},lightMapTransform:{value:new ze}},bumpmap:{bumpMap:{value:null},bumpMapTransform:{value:new ze},bumpScale:{value:1}},normalmap:{normalMap:{value:null},normalMapTransform:{value:new ze},normalScale:{value:new rt(1,1)}},displacementmap:{displacementMap:{value:null},displacementMapTransform:{value:new ze},displacementScale:{value:1},displacementBias:{value:0}},emissivemap:{emissiveMap:{value:null},emissiveMapTransform:{value:new ze}},metalnessmap:{metalnessMap:{value:null},metalnessMapTransform:{value:new ze}},roughnessmap:{roughnessMap:{value:null},roughnessMapTransform:{value:new ze}},gradientmap:{gradientMap:{value:null}},fog:{fogDensity:{value:25e-5},fogNear:{value:1},fogFar:{value:2e3},fogColor:{value:new Ze(16777215)}},lights:{ambientLightColor:{value:[]},lightProbe:{value:[]},directionalLights:{value:[],properties:{direction:{},color:{}}},directionalLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},directionalShadowMap:{value:[]},directionalShadowMatrix:{value:[]},spotLights:{value:[],properties:{color:{},position:{},direction:{},distance:{},coneCos:{},penumbraCos:{},decay:{}}},spotLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},spotLightMap:{value:[]},spotShadowMap:{value:[]},spotLightMatrix:{value:[]},pointLights:{value:[],properties:{color:{},position:{},decay:{},distance:{}}},pointLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{},shadowCameraNear:{},shadowCameraFar:{}}},pointShadowMap:{value:[]},pointShadowMatrix:{value:[]},hemisphereLights:{value:[],properties:{direction:{},skyColor:{},groundColor:{}}},rectAreaLights:{value:[],properties:{color:{},position:{},width:{},height:{}}},ltc_1:{value:null},ltc_2:{value:null}},points:{diffuse:{value:new Ze(16777215)},opacity:{value:1},size:{value:1},scale:{value:1},map:{value:null},alphaMap:{value:null},alphaMapTransform:{value:new ze},alphaTest:{value:0},uvTransform:{value:new ze}},sprite:{diffuse:{value:new Ze(16777215)},opacity:{value:1},center:{value:new rt(.5,.5)},rotation:{value:0},map:{value:null},mapTransform:{value:new ze},alphaMap:{value:null},alphaMapTransform:{value:new ze},alphaTest:{value:0}}},ti={basic:{uniforms:tn([ge.common,ge.specularmap,ge.envmap,ge.aomap,ge.lightmap,ge.fog]),vertexShader:He.meshbasic_vert,fragmentShader:He.meshbasic_frag},lambert:{uniforms:tn([ge.common,ge.specularmap,ge.envmap,ge.aomap,ge.lightmap,ge.emissivemap,ge.bumpmap,ge.normalmap,ge.displacementmap,ge.fog,ge.lights,{emissive:{value:new Ze(0)}}]),vertexShader:He.meshlambert_vert,fragmentShader:He.meshlambert_frag},phong:{uniforms:tn([ge.common,ge.specularmap,ge.envmap,ge.aomap,ge.lightmap,ge.emissivemap,ge.bumpmap,ge.normalmap,ge.displacementmap,ge.fog,ge.lights,{emissive:{value:new Ze(0)},specular:{value:new Ze(1118481)},shininess:{value:30}}]),vertexShader:He.meshphong_vert,fragmentShader:He.meshphong_frag},standard:{uniforms:tn([ge.common,ge.envmap,ge.aomap,ge.lightmap,ge.emissivemap,ge.bumpmap,ge.normalmap,ge.displacementmap,ge.roughnessmap,ge.metalnessmap,ge.fog,ge.lights,{emissive:{value:new Ze(0)},roughness:{value:1},metalness:{value:0},envMapIntensity:{value:1}}]),vertexShader:He.meshphysical_vert,fragmentShader:He.meshphysical_frag},toon:{uniforms:tn([ge.common,ge.aomap,ge.lightmap,ge.emissivemap,ge.bumpmap,ge.normalmap,ge.displacementmap,ge.gradientmap,ge.fog,ge.lights,{emissive:{value:new Ze(0)}}]),vertexShader:He.meshtoon_vert,fragmentShader:He.meshtoon_frag},matcap:{uniforms:tn([ge.common,ge.bumpmap,ge.normalmap,ge.displacementmap,ge.fog,{matcap:{value:null}}]),vertexShader:He.meshmatcap_vert,fragmentShader:He.meshmatcap_frag},points:{uniforms:tn([ge.points,ge.fog]),vertexShader:He.points_vert,fragmentShader:He.points_frag},dashed:{uniforms:tn([ge.common,ge.fog,{scale:{value:1},dashSize:{value:1},totalSize:{value:2}}]),vertexShader:He.linedashed_vert,fragmentShader:He.linedashed_frag},depth:{uniforms:tn([ge.common,ge.displacementmap]),vertexShader:He.depth_vert,fragmentShader:He.depth_frag},normal:{uniforms:tn([ge.common,ge.bumpmap,ge.normalmap,ge.displacementmap,{opacity:{value:1}}]),vertexShader:He.meshnormal_vert,fragmentShader:He.meshnormal_frag},sprite:{uniforms:tn([ge.sprite,ge.fog]),vertexShader:He.sprite_vert,fragmentShader:He.sprite_frag},background:{uniforms:{uvTransform:{value:new ze},t2D:{value:null},backgroundIntensity:{value:1}},vertexShader:He.background_vert,fragmentShader:He.background_frag},backgroundCube:{uniforms:{envMap:{value:null},flipEnvMap:{value:-1},backgroundBlurriness:{value:0},backgroundIntensity:{value:1},backgroundRotation:{value:new ze}},vertexShader:He.backgroundCube_vert,fragmentShader:He.backgroundCube_frag},cube:{uniforms:{tCube:{value:null},tFlip:{value:-1},opacity:{value:1}},vertexShader:He.cube_vert,fragmentShader:He.cube_frag},equirect:{uniforms:{tEquirect:{value:null}},vertexShader:He.equirect_vert,fragmentShader:He.equirect_frag},distance:{uniforms:tn([ge.common,ge.displacementmap,{referencePosition:{value:new F},nearDistance:{value:1},farDistance:{value:1e3}}]),vertexShader:He.distance_vert,fragmentShader:He.distance_frag},shadow:{uniforms:tn([ge.lights,ge.fog,{color:{value:new Ze(0)},opacity:{value:1}}]),vertexShader:He.shadow_vert,fragmentShader:He.shadow_frag}};ti.physical={uniforms:tn([ti.standard.uniforms,{clearcoat:{value:0},clearcoatMap:{value:null},clearcoatMapTransform:{value:new ze},clearcoatNormalMap:{value:null},clearcoatNormalMapTransform:{value:new ze},clearcoatNormalScale:{value:new rt(1,1)},clearcoatRoughness:{value:0},clearcoatRoughnessMap:{value:null},clearcoatRoughnessMapTransform:{value:new ze},dispersion:{value:0},iridescence:{value:0},iridescenceMap:{value:null},iridescenceMapTransform:{value:new ze},iridescenceIOR:{value:1.3},iridescenceThicknessMinimum:{value:100},iridescenceThicknessMaximum:{value:400},iridescenceThicknessMap:{value:null},iridescenceThicknessMapTransform:{value:new ze},sheen:{value:0},sheenColor:{value:new Ze(0)},sheenColorMap:{value:null},sheenColorMapTransform:{value:new ze},sheenRoughness:{value:1},sheenRoughnessMap:{value:null},sheenRoughnessMapTransform:{value:new ze},transmission:{value:0},transmissionMap:{value:null},transmissionMapTransform:{value:new ze},transmissionSamplerSize:{value:new rt},transmissionSamplerMap:{value:null},thickness:{value:0},thicknessMap:{value:null},thicknessMapTransform:{value:new ze},attenuationDistance:{value:0},attenuationColor:{value:new Ze(0)},specularColor:{value:new Ze(1,1,1)},specularColorMap:{value:null},specularColorMapTransform:{value:new ze},specularIntensity:{value:1},specularIntensityMap:{value:null},specularIntensityMapTransform:{value:new ze},anisotropyVector:{value:new rt},anisotropyMap:{value:null},anisotropyMapTransform:{value:new ze}}]),vertexShader:He.meshphysical_vert,fragmentShader:He.meshphysical_frag};const fo={r:0,b:0,g:0},bs=new Ci,Sx=new Nt;function xx(i,e,t,n,s,r,a){const o=new Ze(0);let c=r===!0?0:1,l,d,u=null,h=0,f=null;function g(C){let b=C.isScene===!0?C.background:null;return b&&b.isTexture&&(b=(C.backgroundBlurriness>0?t:e).get(b)),b}function v(C){let b=!1;const S=g(C);S===null?p(o,c):S&&S.isColor&&(p(S,1),b=!0);const M=i.xr.getEnvironmentBlendMode();M==="additive"?n.buffers.color.setClear(0,0,0,1,a):M==="alpha-blend"&&n.buffers.color.setClear(0,0,0,0,a),(i.autoClear||b)&&(n.buffers.depth.setTest(!0),n.buffers.depth.setMask(!0),n.buffers.color.setMask(!0),i.clear(i.autoClearColor,i.autoClearDepth,i.autoClearStencil))}function m(C,b){const S=g(b);S&&(S.isCubeTexture||S.mapping===Oa)?(d===void 0&&(d=new Vn(new Kr(1,1,1),new Tn({name:"BackgroundCubeMaterial",uniforms:sr(ti.backgroundCube.uniforms),vertexShader:ti.backgroundCube.vertexShader,fragmentShader:ti.backgroundCube.fragmentShader,side:Zt,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),d.geometry.deleteAttribute("normal"),d.geometry.deleteAttribute("uv"),d.onBeforeRender=function(M,A,k){this.matrixWorld.copyPosition(k.matrixWorld)},Object.defineProperty(d.material,"envMap",{get:function(){return this.uniforms.envMap.value}}),s.update(d)),bs.copy(b.backgroundRotation),bs.x*=-1,bs.y*=-1,bs.z*=-1,S.isCubeTexture&&S.isRenderTargetTexture===!1&&(bs.y*=-1,bs.z*=-1),d.material.uniforms.envMap.value=S,d.material.uniforms.flipEnvMap.value=S.isCubeTexture&&S.isRenderTargetTexture===!1?-1:1,d.material.uniforms.backgroundBlurriness.value=b.backgroundBlurriness,d.material.uniforms.backgroundIntensity.value=b.backgroundIntensity,d.material.uniforms.backgroundRotation.value.setFromMatrix4(Sx.makeRotationFromEuler(bs)),d.material.toneMapped=Qe.getTransfer(S.colorSpace)!==ot,(u!==S||h!==S.version||f!==i.toneMapping)&&(d.material.needsUpdate=!0,u=S,h=S.version,f=i.toneMapping),d.layers.enableAll(),C.unshift(d,d.geometry,d.material,0,0,null)):S&&S.isTexture&&(l===void 0&&(l=new Vn(new ho(2,2),new Tn({name:"BackgroundMaterial",uniforms:sr(ti.background.uniforms),vertexShader:ti.background.vertexShader,fragmentShader:ti.background.fragmentShader,side:mi,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),l.geometry.deleteAttribute("normal"),Object.defineProperty(l.material,"map",{get:function(){return this.uniforms.t2D.value}}),s.update(l)),l.material.uniforms.t2D.value=S,l.material.uniforms.backgroundIntensity.value=b.backgroundIntensity,l.material.toneMapped=Qe.getTransfer(S.colorSpace)!==ot,S.matrixAutoUpdate===!0&&S.updateMatrix(),l.material.uniforms.uvTransform.value.copy(S.matrix),(u!==S||h!==S.version||f!==i.toneMapping)&&(l.material.needsUpdate=!0,u=S,h=S.version,f=i.toneMapping),l.layers.enableAll(),C.unshift(l,l.geometry,l.material,0,0,null))}function p(C,b){C.getRGB(fo,Gp(i)),n.buffers.color.setClear(fo.r,fo.g,fo.b,b,a)}function x(){d!==void 0&&(d.geometry.dispose(),d.material.dispose(),d=void 0),l!==void 0&&(l.geometry.dispose(),l.material.dispose(),l=void 0)}return{getClearColor:function(){return o},setClearColor:function(C,b=1){o.set(C),c=b,p(o,c)},getClearAlpha:function(){return c},setClearAlpha:function(C){c=C,p(o,c)},render:v,addToRenderList:m,dispose:x}}function Tx(i,e){const t=i.getParameter(i.MAX_VERTEX_ATTRIBS),n={},s=h(null);let r=s,a=!1;function o(T,R,U,B,q){let K=!1;const H=u(B,U,R);r!==H&&(r=H,l(r.object)),K=f(T,B,U,q),K&&g(T,B,U,q),q!==null&&e.update(q,i.ELEMENT_ARRAY_BUFFER),(K||a)&&(a=!1,b(T,R,U,B),q!==null&&i.bindBuffer(i.ELEMENT_ARRAY_BUFFER,e.get(q).buffer))}function c(){return i.createVertexArray()}function l(T){return i.bindVertexArray(T)}function d(T){return i.deleteVertexArray(T)}function u(T,R,U){const B=U.wireframe===!0;let q=n[T.id];q===void 0&&(q={},n[T.id]=q);let K=q[R.id];K===void 0&&(K={},q[R.id]=K);let H=K[B];return H===void 0&&(H=h(c()),K[B]=H),H}function h(T){const R=[],U=[],B=[];for(let q=0;q<t;q++)R[q]=0,U[q]=0,B[q]=0;return{geometry:null,program:null,wireframe:!1,newAttributes:R,enabledAttributes:U,attributeDivisors:B,object:T,attributes:{},index:null}}function f(T,R,U,B){const q=r.attributes,K=R.attributes;let H=0;const W=U.getAttributes();for(const te in W)if(W[te].location>=0){const de=q[te];let _e=K[te];if(_e===void 0&&(te==="instanceMatrix"&&T.instanceMatrix&&(_e=T.instanceMatrix),te==="instanceColor"&&T.instanceColor&&(_e=T.instanceColor)),de===void 0||de.attribute!==_e||_e&&de.data!==_e.data)return!0;H++}return r.attributesNum!==H||r.index!==B}function g(T,R,U,B){const q={},K=R.attributes;let H=0;const W=U.getAttributes();for(const te in W)if(W[te].location>=0){let de=K[te];de===void 0&&(te==="instanceMatrix"&&T.instanceMatrix&&(de=T.instanceMatrix),te==="instanceColor"&&T.instanceColor&&(de=T.instanceColor));const _e={};_e.attribute=de,de&&de.data&&(_e.data=de.data),q[te]=_e,H++}r.attributes=q,r.attributesNum=H,r.index=B}function v(){const T=r.newAttributes;for(let R=0,U=T.length;R<U;R++)T[R]=0}function m(T){p(T,0)}function p(T,R){const U=r.newAttributes,B=r.enabledAttributes,q=r.attributeDivisors;U[T]=1,B[T]===0&&(i.enableVertexAttribArray(T),B[T]=1),q[T]!==R&&(i.vertexAttribDivisor(T,R),q[T]=R)}function x(){const T=r.newAttributes,R=r.enabledAttributes;for(let U=0,B=R.length;U<B;U++)R[U]!==T[U]&&(i.disableVertexAttribArray(U),R[U]=0)}function C(T,R,U,B,q,K,H){H===!0?i.vertexAttribIPointer(T,R,U,q,K):i.vertexAttribPointer(T,R,U,B,q,K)}function b(T,R,U,B){v();const q=B.attributes,K=U.getAttributes(),H=R.defaultAttributeValues;for(const W in K){const te=K[W];if(te.location>=0){let ve=q[W];if(ve===void 0&&(W==="instanceMatrix"&&T.instanceMatrix&&(ve=T.instanceMatrix),W==="instanceColor"&&T.instanceColor&&(ve=T.instanceColor)),ve!==void 0){const de=ve.normalized,_e=ve.itemSize,Ve=e.get(ve);if(Ve===void 0)continue;const Be=Ve.buffer,Ct=Ve.type,ht=Ve.bytesPerElement,X=Ct===i.INT||Ct===i.UNSIGNED_INT||ve.gpuType===ml;if(ve.isInterleavedBufferAttribute){const ie=ve.data,Ce=ie.stride,Ge=ve.offset;if(ie.isInstancedInterleavedBuffer){for(let we=0;we<te.locationSize;we++)p(te.location+we,ie.meshPerAttribute);T.isInstancedMesh!==!0&&B._maxInstanceCount===void 0&&(B._maxInstanceCount=ie.meshPerAttribute*ie.count)}else for(let we=0;we<te.locationSize;we++)m(te.location+we);i.bindBuffer(i.ARRAY_BUFFER,Be);for(let we=0;we<te.locationSize;we++)C(te.location+we,_e/te.locationSize,Ct,de,Ce*ht,(Ge+_e/te.locationSize*we)*ht,X)}else{if(ve.isInstancedBufferAttribute){for(let ie=0;ie<te.locationSize;ie++)p(te.location+ie,ve.meshPerAttribute);T.isInstancedMesh!==!0&&B._maxInstanceCount===void 0&&(B._maxInstanceCount=ve.meshPerAttribute*ve.count)}else for(let ie=0;ie<te.locationSize;ie++)m(te.location+ie);i.bindBuffer(i.ARRAY_BUFFER,Be);for(let ie=0;ie<te.locationSize;ie++)C(te.location+ie,_e/te.locationSize,Ct,de,_e*ht,_e/te.locationSize*ie*ht,X)}}else if(H!==void 0){const de=H[W];if(de!==void 0)switch(de.length){case 2:i.vertexAttrib2fv(te.location,de);break;case 3:i.vertexAttrib3fv(te.location,de);break;case 4:i.vertexAttrib4fv(te.location,de);break;default:i.vertexAttrib1fv(te.location,de)}}}}x()}function S(){k();for(const T in n){const R=n[T];for(const U in R){const B=R[U];for(const q in B)d(B[q].object),delete B[q];delete R[U]}delete n[T]}}function M(T){if(n[T.id]===void 0)return;const R=n[T.id];for(const U in R){const B=R[U];for(const q in B)d(B[q].object),delete B[q];delete R[U]}delete n[T.id]}function A(T){for(const R in n){const U=n[R];if(U[T.id]===void 0)continue;const B=U[T.id];for(const q in B)d(B[q].object),delete B[q];delete U[T.id]}}function k(){y(),a=!0,r!==s&&(r=s,l(r.object))}function y(){s.geometry=null,s.program=null,s.wireframe=!1}return{setup:o,reset:k,resetDefaultState:y,dispose:S,releaseStatesOfGeometry:M,releaseStatesOfProgram:A,initAttributes:v,enableAttribute:m,disableUnusedAttributes:x}}function Cx(i,e,t){let n;function s(l){n=l}function r(l,d){i.drawArrays(n,l,d),t.update(d,n,1)}function a(l,d,u){u!==0&&(i.drawArraysInstanced(n,l,d,u),t.update(d,n,u))}function o(l,d,u){if(u===0)return;e.get("WEBGL_multi_draw").multiDrawArraysWEBGL(n,l,0,d,0,u);let f=0;for(let g=0;g<u;g++)f+=d[g];t.update(f,n,1)}function c(l,d,u,h){if(u===0)return;const f=e.get("WEBGL_multi_draw");if(f===null)for(let g=0;g<l.length;g++)a(l[g],d[g],h[g]);else{f.multiDrawArraysInstancedWEBGL(n,l,0,d,0,h,0,u);let g=0;for(let v=0;v<u;v++)g+=d[v]*h[v];t.update(g,n,1)}}this.setMode=s,this.render=r,this.renderInstances=a,this.renderMultiDraw=o,this.renderMultiDrawInstances=c}function Ex(i,e,t,n){let s;function r(){if(s!==void 0)return s;if(e.has("EXT_texture_filter_anisotropic")===!0){const A=e.get("EXT_texture_filter_anisotropic");s=i.getParameter(A.MAX_TEXTURE_MAX_ANISOTROPY_EXT)}else s=0;return s}function a(A){return!(A!==Ln&&n.convert(A)!==i.getParameter(i.IMPLEMENTATION_COLOR_READ_FORMAT))}function o(A){const k=A===_i&&(e.has("EXT_color_buffer_half_float")||e.has("EXT_color_buffer_float"));return!(A!==yn&&n.convert(A)!==i.getParameter(i.IMPLEMENTATION_COLOR_READ_TYPE)&&A!==Jn&&!k)}function c(A){if(A==="highp"){if(i.getShaderPrecisionFormat(i.VERTEX_SHADER,i.HIGH_FLOAT).precision>0&&i.getShaderPrecisionFormat(i.FRAGMENT_SHADER,i.HIGH_FLOAT).precision>0)return"highp";A="mediump"}return A==="mediump"&&i.getShaderPrecisionFormat(i.VERTEX_SHADER,i.MEDIUM_FLOAT).precision>0&&i.getShaderPrecisionFormat(i.FRAGMENT_SHADER,i.MEDIUM_FLOAT).precision>0?"mediump":"lowp"}let l=t.precision!==void 0?t.precision:"highp";const d=c(l);d!==l&&(Oe("WebGLRenderer:",l,"not supported, using",d,"instead."),l=d);const u=t.logarithmicDepthBuffer===!0,h=t.reversedDepthBuffer===!0&&e.has("EXT_clip_control"),f=i.getParameter(i.MAX_TEXTURE_IMAGE_UNITS),g=i.getParameter(i.MAX_VERTEX_TEXTURE_IMAGE_UNITS),v=i.getParameter(i.MAX_TEXTURE_SIZE),m=i.getParameter(i.MAX_CUBE_MAP_TEXTURE_SIZE),p=i.getParameter(i.MAX_VERTEX_ATTRIBS),x=i.getParameter(i.MAX_VERTEX_UNIFORM_VECTORS),C=i.getParameter(i.MAX_VARYING_VECTORS),b=i.getParameter(i.MAX_FRAGMENT_UNIFORM_VECTORS),S=i.getParameter(i.MAX_SAMPLES),M=i.getParameter(i.SAMPLES);return{isWebGL2:!0,getMaxAnisotropy:r,getMaxPrecision:c,textureFormatReadable:a,textureTypeReadable:o,precision:l,logarithmicDepthBuffer:u,reversedDepthBuffer:h,maxTextures:f,maxVertexTextures:g,maxTextureSize:v,maxCubemapSize:m,maxAttributes:p,maxVertexUniforms:x,maxVaryings:C,maxFragmentUniforms:b,maxSamples:S,samples:M}}function Mx(i){const e=this;let t=null,n=0,s=!1,r=!1;const a=new gs,o=new ze,c={value:null,needsUpdate:!1};this.uniform=c,this.numPlanes=0,this.numIntersection=0,this.init=function(u,h){const f=u.length!==0||h||n!==0||s;return s=h,n=u.length,f},this.beginShadows=function(){r=!0,d(null)},this.endShadows=function(){r=!1},this.setGlobalState=function(u,h){t=d(u,h,0)},this.setState=function(u,h,f){const g=u.clippingPlanes,v=u.clipIntersection,m=u.clipShadows,p=i.get(u);if(!s||g===null||g.length===0||r&&!m)r?d(null):l();else{const x=r?0:n,C=x*4;let b=p.clippingState||null;c.value=b,b=d(g,h,C,f);for(let S=0;S!==C;++S)b[S]=t[S];p.clippingState=b,this.numIntersection=v?this.numPlanes:0,this.numPlanes+=x}};function l(){c.value!==t&&(c.value=t,c.needsUpdate=n>0),e.numPlanes=n,e.numIntersection=0}function d(u,h,f,g){const v=u!==null?u.length:0;let m=null;if(v!==0){if(m=c.value,g!==!0||m===null){const p=f+v*4,x=h.matrixWorldInverse;o.getNormalMatrix(x),(m===null||m.length<p)&&(m=new Float32Array(p));for(let C=0,b=f;C!==v;++C,b+=4)a.copy(u[C]).applyMatrix4(x,o),a.normal.toArray(m,b),m[b+3]=a.constant}c.value=m,c.needsUpdate=!0}return e.numPlanes=v,e.numIntersection=0,m}}function wx(i){let e=new WeakMap;function t(a,o){return o===dl?a.mapping=ds:o===ul&&(a.mapping=Gs),a}function n(a){if(a&&a.isTexture){const o=a.mapping;if(o===dl||o===ul)if(e.has(a)){const c=e.get(a).texture;return t(c,a.mapping)}else{const c=a.image;if(c&&c.height>0){const l=new $p(c.height);return l.fromEquirectangularTexture(i,a),e.set(a,l),a.addEventListener("dispose",s),t(l.texture,a.mapping)}else return null}}return a}function s(a){const o=a.target;o.removeEventListener("dispose",s);const c=e.get(o);c!==void 0&&(e.delete(o),c.dispose())}function r(){e=new WeakMap}return{get:n,dispose:r}}const Ji=4,Qp=[.125,.215,.35,.446,.526,.582],_s=20,Ax=256,Jr=new Yp,em=new Ze;let kd=null,Id=0,Dd=0,Ld=!1;const Rx=new F;class tm{constructor(e){this._renderer=e,this._pingPongRenderTarget=null,this._lodMax=0,this._cubeSize=0,this._sizeLods=[],this._sigmas=[],this._lodMeshes=[],this._backgroundBox=null,this._cubemapMaterial=null,this._equirectMaterial=null,this._blurMaterial=null,this._ggxMaterial=null}fromScene(e,t=0,n=.1,s=100,r={}){const{size:a=256,position:o=Rx}=r;kd=this._renderer.getRenderTarget(),Id=this._renderer.getActiveCubeFace(),Dd=this._renderer.getActiveMipmapLevel(),Ld=this._renderer.xr.enabled,this._renderer.xr.enabled=!1,this._setSize(a);const c=this._allocateTargets();return c.depthBuffer=!0,this._sceneToCubeUV(e,n,s,c,o),t>0&&this._blur(c,0,0,t),this._applyPMREM(c),this._cleanup(c),c}fromEquirectangular(e,t=null){return this._fromTexture(e,t)}fromCubemap(e,t=null){return this._fromTexture(e,t)}compileCubemapShader(){this._cubemapMaterial===null&&(this._cubemapMaterial=sm(),this._compileMaterial(this._cubemapMaterial))}compileEquirectangularShader(){this._equirectMaterial===null&&(this._equirectMaterial=im(),this._compileMaterial(this._equirectMaterial))}dispose(){this._dispose(),this._cubemapMaterial!==null&&this._cubemapMaterial.dispose(),this._equirectMaterial!==null&&this._equirectMaterial.dispose(),this._backgroundBox!==null&&(this._backgroundBox.geometry.dispose(),this._backgroundBox.material.dispose())}_setSize(e){this._lodMax=Math.floor(Math.log2(e)),this._cubeSize=Math.pow(2,this._lodMax)}_dispose(){this._blurMaterial!==null&&this._blurMaterial.dispose(),this._ggxMaterial!==null&&this._ggxMaterial.dispose(),this._pingPongRenderTarget!==null&&this._pingPongRenderTarget.dispose();for(let e=0;e<this._lodMeshes.length;e++)this._lodMeshes[e].geometry.dispose()}_cleanup(e){this._renderer.setRenderTarget(kd,Id,Dd),this._renderer.xr.enabled=Ld,e.scissorTest=!1,or(e,0,0,e.width,e.height)}_fromTexture(e,t){e.mapping===ds||e.mapping===Gs?this._setSize(e.image.length===0?16:e.image[0].width||e.image[0].image.width):this._setSize(e.image.width/4),kd=this._renderer.getRenderTarget(),Id=this._renderer.getActiveCubeFace(),Dd=this._renderer.getActiveMipmapLevel(),Ld=this._renderer.xr.enabled,this._renderer.xr.enabled=!1;const n=t||this._allocateTargets();return this._textureToCubeUV(e,n),this._applyPMREM(n),this._cleanup(n),n}_allocateTargets(){const e=3*Math.max(this._cubeSize,112),t=4*this._cubeSize,n={magFilter:Kt,minFilter:Kt,generateMipmaps:!1,type:_i,format:Ln,colorSpace:Ws,depthBuffer:!1},s=nm(e,t,n);if(this._pingPongRenderTarget===null||this._pingPongRenderTarget.width!==e||this._pingPongRenderTarget.height!==t){this._pingPongRenderTarget!==null&&this._dispose(),this._pingPongRenderTarget=nm(e,t,n);const{_lodMax:r}=this;({lodMeshes:this._lodMeshes,sizeLods:this._sizeLods,sigmas:this._sigmas}=Px(r)),this._blurMaterial=Ix(r,e,t),this._ggxMaterial=kx(r,e,t)}return s}_compileMaterial(e){const t=new Vn(new Bn,e);this._renderer.compile(t,Jr)}_sceneToCubeUV(e,t,n,s,r){const c=new Cn(90,1,t,n),l=[1,-1,1,1,1,1],d=[1,1,1,-1,-1,-1],u=this._renderer,h=u.autoClear,f=u.toneMapping;u.getClearColor(em),u.toneMapping=Kn,u.autoClear=!1,u.state.buffers.depth.getReversed()&&(u.setRenderTarget(s),u.clearDepth(),u.setRenderTarget(null)),this._backgroundBox===null&&(this._backgroundBox=new Vn(new Kr,new Up({name:"PMREM.Background",side:Zt,depthWrite:!1,depthTest:!1})));const v=this._backgroundBox,m=v.material;let p=!1;const x=e.background;x?x.isColor&&(m.color.copy(x),e.background=null,p=!0):(m.color.copy(em),p=!0);for(let C=0;C<6;C++){const b=C%3;b===0?(c.up.set(0,l[C],0),c.position.set(r.x,r.y,r.z),c.lookAt(r.x+d[C],r.y,r.z)):b===1?(c.up.set(0,0,l[C]),c.position.set(r.x,r.y,r.z),c.lookAt(r.x,r.y+d[C],r.z)):(c.up.set(0,l[C],0),c.position.set(r.x,r.y,r.z),c.lookAt(r.x,r.y,r.z+d[C]));const S=this._cubeSize;or(s,b*S,C>2?S:0,S,S),u.setRenderTarget(s),p&&u.render(v,c),u.render(e,c)}u.toneMapping=f,u.autoClear=h,e.background=x}_textureToCubeUV(e,t){const n=this._renderer,s=e.mapping===ds||e.mapping===Gs;s?(this._cubemapMaterial===null&&(this._cubemapMaterial=sm()),this._cubemapMaterial.uniforms.flipEnvMap.value=e.isRenderTargetTexture===!1?-1:1):this._equirectMaterial===null&&(this._equirectMaterial=im());const r=s?this._cubemapMaterial:this._equirectMaterial,a=this._lodMeshes[0];a.material=r;const o=r.uniforms;o.envMap.value=e;const c=this._cubeSize;or(t,0,0,3*c,2*c),n.setRenderTarget(t),n.render(a,Jr)}_applyPMREM(e){const t=this._renderer,n=t.autoClear;t.autoClear=!1;const s=this._lodMeshes.length;for(let r=1;r<s;r++)this._applyGGXFilter(e,r-1,r);t.autoClear=n}_applyGGXFilter(e,t,n){const s=this._renderer,r=this._pingPongRenderTarget,a=this._ggxMaterial,o=this._lodMeshes[n];o.material=a;const c=a.uniforms,l=n/(this._lodMeshes.length-1),d=t/(this._lodMeshes.length-1),u=Math.sqrt(l*l-d*d),h=0+l*1.25,f=u*h,{_lodMax:g}=this,v=this._sizeLods[n],m=3*v*(n>g-Ji?n-g+Ji:0),p=4*(this._cubeSize-v);c.envMap.value=e.texture,c.roughness.value=f,c.mipInt.value=g-t,or(r,m,p,3*v,2*v),s.setRenderTarget(r),s.render(o,Jr),c.envMap.value=r.texture,c.roughness.value=0,c.mipInt.value=g-n,or(e,m,p,3*v,2*v),s.setRenderTarget(e),s.render(o,Jr)}_blur(e,t,n,s,r){const a=this._pingPongRenderTarget;this._halfBlur(e,a,t,n,s,"latitudinal",r),this._halfBlur(a,e,n,n,s,"longitudinal",r)}_halfBlur(e,t,n,s,r,a,o){const c=this._renderer,l=this._blurMaterial;a!=="latitudinal"&&a!=="longitudinal"&&tt("blur direction must be either latitudinal or longitudinal!");const d=3,u=this._lodMeshes[s];u.material=l;const h=l.uniforms,f=this._sizeLods[n]-1,g=isFinite(r)?Math.PI/(2*f):2*Math.PI/(2*_s-1),v=r/g,m=isFinite(r)?1+Math.floor(d*v):_s;m>_s&&Oe(`sigmaRadians, ${r}, is too large and will clip, as it requested ${m} samples when the maximum is set to ${_s}`);const p=[];let x=0;for(let A=0;A<_s;++A){const k=A/v,y=Math.exp(-k*k/2);p.push(y),A===0?x+=y:A<m&&(x+=2*y)}for(let A=0;A<p.length;A++)p[A]=p[A]/x;h.envMap.value=e.texture,h.samples.value=m,h.weights.value=p,h.latitudinal.value=a==="latitudinal",o&&(h.poleAxis.value=o);const{_lodMax:C}=this;h.dTheta.value=g,h.mipInt.value=C-n;const b=this._sizeLods[s],S=3*b*(s>C-Ji?s-C+Ji:0),M=4*(this._cubeSize-b);or(t,S,M,3*b,2*b),c.setRenderTarget(t),c.render(u,Jr)}}function Px(i){const e=[],t=[],n=[];let s=i;const r=i-Ji+1+Qp.length;for(let a=0;a<r;a++){const o=Math.pow(2,s);e.push(o);let c=1/o;a>i-Ji?c=Qp[a-i+Ji-1]:a===0&&(c=0),t.push(c);const l=1/(o-2),d=-l,u=1+l,h=[d,d,u,d,u,u,d,d,u,u,d,u],f=6,g=6,v=3,m=2,p=1,x=new Float32Array(v*g*f),C=new Float32Array(m*g*f),b=new Float32Array(p*g*f);for(let M=0;M<f;M++){const A=M%3*2/3-1,k=M>2?0:-1,y=[A,k,0,A+2/3,k,0,A+2/3,k+1,0,A,k,0,A+2/3,k+1,0,A,k+1,0];x.set(y,v*g*M),C.set(h,m*g*M);const T=[M,M,M,M,M,M];b.set(T,p*g*M)}const S=new Bn;S.setAttribute("position",new ei(x,v)),S.setAttribute("uv",new ei(C,m)),S.setAttribute("faceIndex",new ei(b,p)),n.push(new Vn(S,null)),s>Ji&&s--}return{lodMeshes:n,sizeLods:e,sigmas:t}}function nm(i,e,t){const n=new Qn(i,e,t);return n.texture.mapping=Oa,n.texture.name="PMREM.cubeUv",n.scissorTest=!0,n}function or(i,e,t,n,s){i.viewport.set(e,t,n,s),i.scissor.set(e,t,n,s)}function kx(i,e,t){return new Tn({name:"PMREMGGXConvolution",defines:{GGX_SAMPLES:Ax,CUBEUV_TEXEL_WIDTH:1/e,CUBEUV_TEXEL_HEIGHT:1/t,CUBEUV_MAX_MIP:`${i}.0`},uniforms:{envMap:{value:null},roughness:{value:0},mipInt:{value:0}},vertexShader:po(),fragmentShader:`
3696
+ }`},ge={common:{diffuse:{value:new Ze(16777215)},opacity:{value:1},map:{value:null},mapTransform:{value:new ze},alphaMap:{value:null},alphaMapTransform:{value:new ze},alphaTest:{value:0}},specularmap:{specularMap:{value:null},specularMapTransform:{value:new ze}},envmap:{envMap:{value:null},envMapRotation:{value:new ze},flipEnvMap:{value:-1},reflectivity:{value:1},ior:{value:1.5},refractionRatio:{value:.98},dfgLUT:{value:null}},aomap:{aoMap:{value:null},aoMapIntensity:{value:1},aoMapTransform:{value:new ze}},lightmap:{lightMap:{value:null},lightMapIntensity:{value:1},lightMapTransform:{value:new ze}},bumpmap:{bumpMap:{value:null},bumpMapTransform:{value:new ze},bumpScale:{value:1}},normalmap:{normalMap:{value:null},normalMapTransform:{value:new ze},normalScale:{value:new rt(1,1)}},displacementmap:{displacementMap:{value:null},displacementMapTransform:{value:new ze},displacementScale:{value:1},displacementBias:{value:0}},emissivemap:{emissiveMap:{value:null},emissiveMapTransform:{value:new ze}},metalnessmap:{metalnessMap:{value:null},metalnessMapTransform:{value:new ze}},roughnessmap:{roughnessMap:{value:null},roughnessMapTransform:{value:new ze}},gradientmap:{gradientMap:{value:null}},fog:{fogDensity:{value:25e-5},fogNear:{value:1},fogFar:{value:2e3},fogColor:{value:new Ze(16777215)}},lights:{ambientLightColor:{value:[]},lightProbe:{value:[]},directionalLights:{value:[],properties:{direction:{},color:{}}},directionalLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},directionalShadowMap:{value:[]},directionalShadowMatrix:{value:[]},spotLights:{value:[],properties:{color:{},position:{},direction:{},distance:{},coneCos:{},penumbraCos:{},decay:{}}},spotLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},spotLightMap:{value:[]},spotShadowMap:{value:[]},spotLightMatrix:{value:[]},pointLights:{value:[],properties:{color:{},position:{},decay:{},distance:{}}},pointLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{},shadowCameraNear:{},shadowCameraFar:{}}},pointShadowMap:{value:[]},pointShadowMatrix:{value:[]},hemisphereLights:{value:[],properties:{direction:{},skyColor:{},groundColor:{}}},rectAreaLights:{value:[],properties:{color:{},position:{},width:{},height:{}}},ltc_1:{value:null},ltc_2:{value:null}},points:{diffuse:{value:new Ze(16777215)},opacity:{value:1},size:{value:1},scale:{value:1},map:{value:null},alphaMap:{value:null},alphaMapTransform:{value:new ze},alphaTest:{value:0},uvTransform:{value:new ze}},sprite:{diffuse:{value:new Ze(16777215)},opacity:{value:1},center:{value:new rt(.5,.5)},rotation:{value:0},map:{value:null},mapTransform:{value:new ze},alphaMap:{value:null},alphaMapTransform:{value:new ze},alphaTest:{value:0}}},ni={basic:{uniforms:tn([ge.common,ge.specularmap,ge.envmap,ge.aomap,ge.lightmap,ge.fog]),vertexShader:He.meshbasic_vert,fragmentShader:He.meshbasic_frag},lambert:{uniforms:tn([ge.common,ge.specularmap,ge.envmap,ge.aomap,ge.lightmap,ge.emissivemap,ge.bumpmap,ge.normalmap,ge.displacementmap,ge.fog,ge.lights,{emissive:{value:new Ze(0)}}]),vertexShader:He.meshlambert_vert,fragmentShader:He.meshlambert_frag},phong:{uniforms:tn([ge.common,ge.specularmap,ge.envmap,ge.aomap,ge.lightmap,ge.emissivemap,ge.bumpmap,ge.normalmap,ge.displacementmap,ge.fog,ge.lights,{emissive:{value:new Ze(0)},specular:{value:new Ze(1118481)},shininess:{value:30}}]),vertexShader:He.meshphong_vert,fragmentShader:He.meshphong_frag},standard:{uniforms:tn([ge.common,ge.envmap,ge.aomap,ge.lightmap,ge.emissivemap,ge.bumpmap,ge.normalmap,ge.displacementmap,ge.roughnessmap,ge.metalnessmap,ge.fog,ge.lights,{emissive:{value:new Ze(0)},roughness:{value:1},metalness:{value:0},envMapIntensity:{value:1}}]),vertexShader:He.meshphysical_vert,fragmentShader:He.meshphysical_frag},toon:{uniforms:tn([ge.common,ge.aomap,ge.lightmap,ge.emissivemap,ge.bumpmap,ge.normalmap,ge.displacementmap,ge.gradientmap,ge.fog,ge.lights,{emissive:{value:new Ze(0)}}]),vertexShader:He.meshtoon_vert,fragmentShader:He.meshtoon_frag},matcap:{uniforms:tn([ge.common,ge.bumpmap,ge.normalmap,ge.displacementmap,ge.fog,{matcap:{value:null}}]),vertexShader:He.meshmatcap_vert,fragmentShader:He.meshmatcap_frag},points:{uniforms:tn([ge.points,ge.fog]),vertexShader:He.points_vert,fragmentShader:He.points_frag},dashed:{uniforms:tn([ge.common,ge.fog,{scale:{value:1},dashSize:{value:1},totalSize:{value:2}}]),vertexShader:He.linedashed_vert,fragmentShader:He.linedashed_frag},depth:{uniforms:tn([ge.common,ge.displacementmap]),vertexShader:He.depth_vert,fragmentShader:He.depth_frag},normal:{uniforms:tn([ge.common,ge.bumpmap,ge.normalmap,ge.displacementmap,{opacity:{value:1}}]),vertexShader:He.meshnormal_vert,fragmentShader:He.meshnormal_frag},sprite:{uniforms:tn([ge.sprite,ge.fog]),vertexShader:He.sprite_vert,fragmentShader:He.sprite_frag},background:{uniforms:{uvTransform:{value:new ze},t2D:{value:null},backgroundIntensity:{value:1}},vertexShader:He.background_vert,fragmentShader:He.background_frag},backgroundCube:{uniforms:{envMap:{value:null},flipEnvMap:{value:-1},backgroundBlurriness:{value:0},backgroundIntensity:{value:1},backgroundRotation:{value:new ze}},vertexShader:He.backgroundCube_vert,fragmentShader:He.backgroundCube_frag},cube:{uniforms:{tCube:{value:null},tFlip:{value:-1},opacity:{value:1}},vertexShader:He.cube_vert,fragmentShader:He.cube_frag},equirect:{uniforms:{tEquirect:{value:null}},vertexShader:He.equirect_vert,fragmentShader:He.equirect_frag},distance:{uniforms:tn([ge.common,ge.displacementmap,{referencePosition:{value:new F},nearDistance:{value:1},farDistance:{value:1e3}}]),vertexShader:He.distance_vert,fragmentShader:He.distance_frag},shadow:{uniforms:tn([ge.lights,ge.fog,{color:{value:new Ze(0)},opacity:{value:1}}]),vertexShader:He.shadow_vert,fragmentShader:He.shadow_frag}};ni.physical={uniforms:tn([ni.standard.uniforms,{clearcoat:{value:0},clearcoatMap:{value:null},clearcoatMapTransform:{value:new ze},clearcoatNormalMap:{value:null},clearcoatNormalMapTransform:{value:new ze},clearcoatNormalScale:{value:new rt(1,1)},clearcoatRoughness:{value:0},clearcoatRoughnessMap:{value:null},clearcoatRoughnessMapTransform:{value:new ze},dispersion:{value:0},iridescence:{value:0},iridescenceMap:{value:null},iridescenceMapTransform:{value:new ze},iridescenceIOR:{value:1.3},iridescenceThicknessMinimum:{value:100},iridescenceThicknessMaximum:{value:400},iridescenceThicknessMap:{value:null},iridescenceThicknessMapTransform:{value:new ze},sheen:{value:0},sheenColor:{value:new Ze(0)},sheenColorMap:{value:null},sheenColorMapTransform:{value:new ze},sheenRoughness:{value:1},sheenRoughnessMap:{value:null},sheenRoughnessMapTransform:{value:new ze},transmission:{value:0},transmissionMap:{value:null},transmissionMapTransform:{value:new ze},transmissionSamplerSize:{value:new rt},transmissionSamplerMap:{value:null},thickness:{value:0},thicknessMap:{value:null},thicknessMapTransform:{value:new ze},attenuationDistance:{value:0},attenuationColor:{value:new Ze(0)},specularColor:{value:new Ze(1,1,1)},specularColorMap:{value:null},specularColorMapTransform:{value:new ze},specularIntensity:{value:1},specularIntensityMap:{value:null},specularIntensityMapTransform:{value:new ze},anisotropyVector:{value:new rt},anisotropyMap:{value:null},anisotropyMapTransform:{value:new ze}}]),vertexShader:He.meshphysical_vert,fragmentShader:He.meshphysical_frag};const fo={r:0,b:0,g:0},bs=new Ci,Sx=new Nt;function xx(i,e,t,n,s,r,a){const o=new Ze(0);let c=r===!0?0:1,l,d,u=null,h=0,f=null;function g(C){let b=C.isScene===!0?C.background:null;return b&&b.isTexture&&(b=(C.backgroundBlurriness>0?t:e).get(b)),b}function v(C){let b=!1;const S=g(C);S===null?p(o,c):S&&S.isColor&&(p(S,1),b=!0);const M=i.xr.getEnvironmentBlendMode();M==="additive"?n.buffers.color.setClear(0,0,0,1,a):M==="alpha-blend"&&n.buffers.color.setClear(0,0,0,0,a),(i.autoClear||b)&&(n.buffers.depth.setTest(!0),n.buffers.depth.setMask(!0),n.buffers.color.setMask(!0),i.clear(i.autoClearColor,i.autoClearDepth,i.autoClearStencil))}function m(C,b){const S=g(b);S&&(S.isCubeTexture||S.mapping===Oa)?(d===void 0&&(d=new zn(new Kr(1,1,1),new Cn({name:"BackgroundCubeMaterial",uniforms:sr(ni.backgroundCube.uniforms),vertexShader:ni.backgroundCube.vertexShader,fragmentShader:ni.backgroundCube.fragmentShader,side:Zt,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),d.geometry.deleteAttribute("normal"),d.geometry.deleteAttribute("uv"),d.onBeforeRender=function(M,A,k){this.matrixWorld.copyPosition(k.matrixWorld)},Object.defineProperty(d.material,"envMap",{get:function(){return this.uniforms.envMap.value}}),s.update(d)),bs.copy(b.backgroundRotation),bs.x*=-1,bs.y*=-1,bs.z*=-1,S.isCubeTexture&&S.isRenderTargetTexture===!1&&(bs.y*=-1,bs.z*=-1),d.material.uniforms.envMap.value=S,d.material.uniforms.flipEnvMap.value=S.isCubeTexture&&S.isRenderTargetTexture===!1?-1:1,d.material.uniforms.backgroundBlurriness.value=b.backgroundBlurriness,d.material.uniforms.backgroundIntensity.value=b.backgroundIntensity,d.material.uniforms.backgroundRotation.value.setFromMatrix4(Sx.makeRotationFromEuler(bs)),d.material.toneMapped=Qe.getTransfer(S.colorSpace)!==ot,(u!==S||h!==S.version||f!==i.toneMapping)&&(d.material.needsUpdate=!0,u=S,h=S.version,f=i.toneMapping),d.layers.enableAll(),C.unshift(d,d.geometry,d.material,0,0,null)):S&&S.isTexture&&(l===void 0&&(l=new zn(new ho(2,2),new Cn({name:"BackgroundMaterial",uniforms:sr(ni.background.uniforms),vertexShader:ni.background.vertexShader,fragmentShader:ni.background.fragmentShader,side:mi,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),l.geometry.deleteAttribute("normal"),Object.defineProperty(l.material,"map",{get:function(){return this.uniforms.t2D.value}}),s.update(l)),l.material.uniforms.t2D.value=S,l.material.uniforms.backgroundIntensity.value=b.backgroundIntensity,l.material.toneMapped=Qe.getTransfer(S.colorSpace)!==ot,S.matrixAutoUpdate===!0&&S.updateMatrix(),l.material.uniforms.uvTransform.value.copy(S.matrix),(u!==S||h!==S.version||f!==i.toneMapping)&&(l.material.needsUpdate=!0,u=S,h=S.version,f=i.toneMapping),l.layers.enableAll(),C.unshift(l,l.geometry,l.material,0,0,null))}function p(C,b){C.getRGB(fo,Gp(i)),n.buffers.color.setClear(fo.r,fo.g,fo.b,b,a)}function x(){d!==void 0&&(d.geometry.dispose(),d.material.dispose(),d=void 0),l!==void 0&&(l.geometry.dispose(),l.material.dispose(),l=void 0)}return{getClearColor:function(){return o},setClearColor:function(C,b=1){o.set(C),c=b,p(o,c)},getClearAlpha:function(){return c},setClearAlpha:function(C){c=C,p(o,c)},render:v,addToRenderList:m,dispose:x}}function Tx(i,e){const t=i.getParameter(i.MAX_VERTEX_ATTRIBS),n={},s=h(null);let r=s,a=!1;function o(T,R,U,B,q){let K=!1;const H=u(B,U,R);r!==H&&(r=H,l(r.object)),K=f(T,B,U,q),K&&g(T,B,U,q),q!==null&&e.update(q,i.ELEMENT_ARRAY_BUFFER),(K||a)&&(a=!1,b(T,R,U,B),q!==null&&i.bindBuffer(i.ELEMENT_ARRAY_BUFFER,e.get(q).buffer))}function c(){return i.createVertexArray()}function l(T){return i.bindVertexArray(T)}function d(T){return i.deleteVertexArray(T)}function u(T,R,U){const B=U.wireframe===!0;let q=n[T.id];q===void 0&&(q={},n[T.id]=q);let K=q[R.id];K===void 0&&(K={},q[R.id]=K);let H=K[B];return H===void 0&&(H=h(c()),K[B]=H),H}function h(T){const R=[],U=[],B=[];for(let q=0;q<t;q++)R[q]=0,U[q]=0,B[q]=0;return{geometry:null,program:null,wireframe:!1,newAttributes:R,enabledAttributes:U,attributeDivisors:B,object:T,attributes:{},index:null}}function f(T,R,U,B){const q=r.attributes,K=R.attributes;let H=0;const W=U.getAttributes();for(const te in W)if(W[te].location>=0){const de=q[te];let _e=K[te];if(_e===void 0&&(te==="instanceMatrix"&&T.instanceMatrix&&(_e=T.instanceMatrix),te==="instanceColor"&&T.instanceColor&&(_e=T.instanceColor)),de===void 0||de.attribute!==_e||_e&&de.data!==_e.data)return!0;H++}return r.attributesNum!==H||r.index!==B}function g(T,R,U,B){const q={},K=R.attributes;let H=0;const W=U.getAttributes();for(const te in W)if(W[te].location>=0){let de=K[te];de===void 0&&(te==="instanceMatrix"&&T.instanceMatrix&&(de=T.instanceMatrix),te==="instanceColor"&&T.instanceColor&&(de=T.instanceColor));const _e={};_e.attribute=de,de&&de.data&&(_e.data=de.data),q[te]=_e,H++}r.attributes=q,r.attributesNum=H,r.index=B}function v(){const T=r.newAttributes;for(let R=0,U=T.length;R<U;R++)T[R]=0}function m(T){p(T,0)}function p(T,R){const U=r.newAttributes,B=r.enabledAttributes,q=r.attributeDivisors;U[T]=1,B[T]===0&&(i.enableVertexAttribArray(T),B[T]=1),q[T]!==R&&(i.vertexAttribDivisor(T,R),q[T]=R)}function x(){const T=r.newAttributes,R=r.enabledAttributes;for(let U=0,B=R.length;U<B;U++)R[U]!==T[U]&&(i.disableVertexAttribArray(U),R[U]=0)}function C(T,R,U,B,q,K,H){H===!0?i.vertexAttribIPointer(T,R,U,q,K):i.vertexAttribPointer(T,R,U,B,q,K)}function b(T,R,U,B){v();const q=B.attributes,K=U.getAttributes(),H=R.defaultAttributeValues;for(const W in K){const te=K[W];if(te.location>=0){let ve=q[W];if(ve===void 0&&(W==="instanceMatrix"&&T.instanceMatrix&&(ve=T.instanceMatrix),W==="instanceColor"&&T.instanceColor&&(ve=T.instanceColor)),ve!==void 0){const de=ve.normalized,_e=ve.itemSize,Ve=e.get(ve);if(Ve===void 0)continue;const Be=Ve.buffer,Ct=Ve.type,mt=Ve.bytesPerElement,X=Ct===i.INT||Ct===i.UNSIGNED_INT||ve.gpuType===ml;if(ve.isInterleavedBufferAttribute){const ie=ve.data,Ce=ie.stride,Ge=ve.offset;if(ie.isInstancedInterleavedBuffer){for(let we=0;we<te.locationSize;we++)p(te.location+we,ie.meshPerAttribute);T.isInstancedMesh!==!0&&B._maxInstanceCount===void 0&&(B._maxInstanceCount=ie.meshPerAttribute*ie.count)}else for(let we=0;we<te.locationSize;we++)m(te.location+we);i.bindBuffer(i.ARRAY_BUFFER,Be);for(let we=0;we<te.locationSize;we++)C(te.location+we,_e/te.locationSize,Ct,de,Ce*mt,(Ge+_e/te.locationSize*we)*mt,X)}else{if(ve.isInstancedBufferAttribute){for(let ie=0;ie<te.locationSize;ie++)p(te.location+ie,ve.meshPerAttribute);T.isInstancedMesh!==!0&&B._maxInstanceCount===void 0&&(B._maxInstanceCount=ve.meshPerAttribute*ve.count)}else for(let ie=0;ie<te.locationSize;ie++)m(te.location+ie);i.bindBuffer(i.ARRAY_BUFFER,Be);for(let ie=0;ie<te.locationSize;ie++)C(te.location+ie,_e/te.locationSize,Ct,de,_e*mt,_e/te.locationSize*ie*mt,X)}}else if(H!==void 0){const de=H[W];if(de!==void 0)switch(de.length){case 2:i.vertexAttrib2fv(te.location,de);break;case 3:i.vertexAttrib3fv(te.location,de);break;case 4:i.vertexAttrib4fv(te.location,de);break;default:i.vertexAttrib1fv(te.location,de)}}}}x()}function S(){k();for(const T in n){const R=n[T];for(const U in R){const B=R[U];for(const q in B)d(B[q].object),delete B[q];delete R[U]}delete n[T]}}function M(T){if(n[T.id]===void 0)return;const R=n[T.id];for(const U in R){const B=R[U];for(const q in B)d(B[q].object),delete B[q];delete R[U]}delete n[T.id]}function A(T){for(const R in n){const U=n[R];if(U[T.id]===void 0)continue;const B=U[T.id];for(const q in B)d(B[q].object),delete B[q];delete U[T.id]}}function k(){y(),a=!0,r!==s&&(r=s,l(r.object))}function y(){s.geometry=null,s.program=null,s.wireframe=!1}return{setup:o,reset:k,resetDefaultState:y,dispose:S,releaseStatesOfGeometry:M,releaseStatesOfProgram:A,initAttributes:v,enableAttribute:m,disableUnusedAttributes:x}}function Cx(i,e,t){let n;function s(l){n=l}function r(l,d){i.drawArrays(n,l,d),t.update(d,n,1)}function a(l,d,u){u!==0&&(i.drawArraysInstanced(n,l,d,u),t.update(d,n,u))}function o(l,d,u){if(u===0)return;e.get("WEBGL_multi_draw").multiDrawArraysWEBGL(n,l,0,d,0,u);let f=0;for(let g=0;g<u;g++)f+=d[g];t.update(f,n,1)}function c(l,d,u,h){if(u===0)return;const f=e.get("WEBGL_multi_draw");if(f===null)for(let g=0;g<l.length;g++)a(l[g],d[g],h[g]);else{f.multiDrawArraysInstancedWEBGL(n,l,0,d,0,h,0,u);let g=0;for(let v=0;v<u;v++)g+=d[v]*h[v];t.update(g,n,1)}}this.setMode=s,this.render=r,this.renderInstances=a,this.renderMultiDraw=o,this.renderMultiDrawInstances=c}function Ex(i,e,t,n){let s;function r(){if(s!==void 0)return s;if(e.has("EXT_texture_filter_anisotropic")===!0){const A=e.get("EXT_texture_filter_anisotropic");s=i.getParameter(A.MAX_TEXTURE_MAX_ANISOTROPY_EXT)}else s=0;return s}function a(A){return!(A!==Nn&&n.convert(A)!==i.getParameter(i.IMPLEMENTATION_COLOR_READ_FORMAT))}function o(A){const k=A===_i&&(e.has("EXT_color_buffer_half_float")||e.has("EXT_color_buffer_float"));return!(A!==Sn&&n.convert(A)!==i.getParameter(i.IMPLEMENTATION_COLOR_READ_TYPE)&&A!==Zn&&!k)}function c(A){if(A==="highp"){if(i.getShaderPrecisionFormat(i.VERTEX_SHADER,i.HIGH_FLOAT).precision>0&&i.getShaderPrecisionFormat(i.FRAGMENT_SHADER,i.HIGH_FLOAT).precision>0)return"highp";A="mediump"}return A==="mediump"&&i.getShaderPrecisionFormat(i.VERTEX_SHADER,i.MEDIUM_FLOAT).precision>0&&i.getShaderPrecisionFormat(i.FRAGMENT_SHADER,i.MEDIUM_FLOAT).precision>0?"mediump":"lowp"}let l=t.precision!==void 0?t.precision:"highp";const d=c(l);d!==l&&(Oe("WebGLRenderer:",l,"not supported, using",d,"instead."),l=d);const u=t.logarithmicDepthBuffer===!0,h=t.reversedDepthBuffer===!0&&e.has("EXT_clip_control"),f=i.getParameter(i.MAX_TEXTURE_IMAGE_UNITS),g=i.getParameter(i.MAX_VERTEX_TEXTURE_IMAGE_UNITS),v=i.getParameter(i.MAX_TEXTURE_SIZE),m=i.getParameter(i.MAX_CUBE_MAP_TEXTURE_SIZE),p=i.getParameter(i.MAX_VERTEX_ATTRIBS),x=i.getParameter(i.MAX_VERTEX_UNIFORM_VECTORS),C=i.getParameter(i.MAX_VARYING_VECTORS),b=i.getParameter(i.MAX_FRAGMENT_UNIFORM_VECTORS),S=i.getParameter(i.MAX_SAMPLES),M=i.getParameter(i.SAMPLES);return{isWebGL2:!0,getMaxAnisotropy:r,getMaxPrecision:c,textureFormatReadable:a,textureTypeReadable:o,precision:l,logarithmicDepthBuffer:u,reversedDepthBuffer:h,maxTextures:f,maxVertexTextures:g,maxTextureSize:v,maxCubemapSize:m,maxAttributes:p,maxVertexUniforms:x,maxVaryings:C,maxFragmentUniforms:b,maxSamples:S,samples:M}}function Mx(i){const e=this;let t=null,n=0,s=!1,r=!1;const a=new gs,o=new ze,c={value:null,needsUpdate:!1};this.uniform=c,this.numPlanes=0,this.numIntersection=0,this.init=function(u,h){const f=u.length!==0||h||n!==0||s;return s=h,n=u.length,f},this.beginShadows=function(){r=!0,d(null)},this.endShadows=function(){r=!1},this.setGlobalState=function(u,h){t=d(u,h,0)},this.setState=function(u,h,f){const g=u.clippingPlanes,v=u.clipIntersection,m=u.clipShadows,p=i.get(u);if(!s||g===null||g.length===0||r&&!m)r?d(null):l();else{const x=r?0:n,C=x*4;let b=p.clippingState||null;c.value=b,b=d(g,h,C,f);for(let S=0;S!==C;++S)b[S]=t[S];p.clippingState=b,this.numIntersection=v?this.numPlanes:0,this.numPlanes+=x}};function l(){c.value!==t&&(c.value=t,c.needsUpdate=n>0),e.numPlanes=n,e.numIntersection=0}function d(u,h,f,g){const v=u!==null?u.length:0;let m=null;if(v!==0){if(m=c.value,g!==!0||m===null){const p=f+v*4,x=h.matrixWorldInverse;o.getNormalMatrix(x),(m===null||m.length<p)&&(m=new Float32Array(p));for(let C=0,b=f;C!==v;++C,b+=4)a.copy(u[C]).applyMatrix4(x,o),a.normal.toArray(m,b),m[b+3]=a.constant}c.value=m,c.needsUpdate=!0}return e.numPlanes=v,e.numIntersection=0,m}}function wx(i){let e=new WeakMap;function t(a,o){return o===dl?a.mapping=ds:o===ul&&(a.mapping=Gs),a}function n(a){if(a&&a.isTexture){const o=a.mapping;if(o===dl||o===ul)if(e.has(a)){const c=e.get(a).texture;return t(c,a.mapping)}else{const c=a.image;if(c&&c.height>0){const l=new $p(c.height);return l.fromEquirectangularTexture(i,a),e.set(a,l),a.addEventListener("dispose",s),t(l.texture,a.mapping)}else return null}}return a}function s(a){const o=a.target;o.removeEventListener("dispose",s);const c=e.get(o);c!==void 0&&(e.delete(o),c.dispose())}function r(){e=new WeakMap}return{get:n,dispose:r}}const Ji=4,Qp=[.125,.215,.35,.446,.526,.582],_s=20,Ax=256,Jr=new Yp,em=new Ze;let kd=null,Id=0,Dd=0,Ld=!1;const Rx=new F;class tm{constructor(e){this._renderer=e,this._pingPongRenderTarget=null,this._lodMax=0,this._cubeSize=0,this._sizeLods=[],this._sigmas=[],this._lodMeshes=[],this._backgroundBox=null,this._cubemapMaterial=null,this._equirectMaterial=null,this._blurMaterial=null,this._ggxMaterial=null}fromScene(e,t=0,n=.1,s=100,r={}){const{size:a=256,position:o=Rx}=r;kd=this._renderer.getRenderTarget(),Id=this._renderer.getActiveCubeFace(),Dd=this._renderer.getActiveMipmapLevel(),Ld=this._renderer.xr.enabled,this._renderer.xr.enabled=!1,this._setSize(a);const c=this._allocateTargets();return c.depthBuffer=!0,this._sceneToCubeUV(e,n,s,c,o),t>0&&this._blur(c,0,0,t),this._applyPMREM(c),this._cleanup(c),c}fromEquirectangular(e,t=null){return this._fromTexture(e,t)}fromCubemap(e,t=null){return this._fromTexture(e,t)}compileCubemapShader(){this._cubemapMaterial===null&&(this._cubemapMaterial=sm(),this._compileMaterial(this._cubemapMaterial))}compileEquirectangularShader(){this._equirectMaterial===null&&(this._equirectMaterial=im(),this._compileMaterial(this._equirectMaterial))}dispose(){this._dispose(),this._cubemapMaterial!==null&&this._cubemapMaterial.dispose(),this._equirectMaterial!==null&&this._equirectMaterial.dispose(),this._backgroundBox!==null&&(this._backgroundBox.geometry.dispose(),this._backgroundBox.material.dispose())}_setSize(e){this._lodMax=Math.floor(Math.log2(e)),this._cubeSize=Math.pow(2,this._lodMax)}_dispose(){this._blurMaterial!==null&&this._blurMaterial.dispose(),this._ggxMaterial!==null&&this._ggxMaterial.dispose(),this._pingPongRenderTarget!==null&&this._pingPongRenderTarget.dispose();for(let e=0;e<this._lodMeshes.length;e++)this._lodMeshes[e].geometry.dispose()}_cleanup(e){this._renderer.setRenderTarget(kd,Id,Dd),this._renderer.xr.enabled=Ld,e.scissorTest=!1,or(e,0,0,e.width,e.height)}_fromTexture(e,t){e.mapping===ds||e.mapping===Gs?this._setSize(e.image.length===0?16:e.image[0].width||e.image[0].image.width):this._setSize(e.image.width/4),kd=this._renderer.getRenderTarget(),Id=this._renderer.getActiveCubeFace(),Dd=this._renderer.getActiveMipmapLevel(),Ld=this._renderer.xr.enabled,this._renderer.xr.enabled=!1;const n=t||this._allocateTargets();return this._textureToCubeUV(e,n),this._applyPMREM(n),this._cleanup(n),n}_allocateTargets(){const e=3*Math.max(this._cubeSize,112),t=4*this._cubeSize,n={magFilter:Kt,minFilter:Kt,generateMipmaps:!1,type:_i,format:Nn,colorSpace:Ws,depthBuffer:!1},s=nm(e,t,n);if(this._pingPongRenderTarget===null||this._pingPongRenderTarget.width!==e||this._pingPongRenderTarget.height!==t){this._pingPongRenderTarget!==null&&this._dispose(),this._pingPongRenderTarget=nm(e,t,n);const{_lodMax:r}=this;({lodMeshes:this._lodMeshes,sizeLods:this._sizeLods,sigmas:this._sigmas}=Px(r)),this._blurMaterial=Ix(r,e,t),this._ggxMaterial=kx(r,e,t)}return s}_compileMaterial(e){const t=new zn(new Vn,e);this._renderer.compile(t,Jr)}_sceneToCubeUV(e,t,n,s,r){const c=new En(90,1,t,n),l=[1,-1,1,1,1,1],d=[1,1,1,-1,-1,-1],u=this._renderer,h=u.autoClear,f=u.toneMapping;u.getClearColor(em),u.toneMapping=Yn,u.autoClear=!1,u.state.buffers.depth.getReversed()&&(u.setRenderTarget(s),u.clearDepth(),u.setRenderTarget(null)),this._backgroundBox===null&&(this._backgroundBox=new zn(new Kr,new Up({name:"PMREM.Background",side:Zt,depthWrite:!1,depthTest:!1})));const v=this._backgroundBox,m=v.material;let p=!1;const x=e.background;x?x.isColor&&(m.color.copy(x),e.background=null,p=!0):(m.color.copy(em),p=!0);for(let C=0;C<6;C++){const b=C%3;b===0?(c.up.set(0,l[C],0),c.position.set(r.x,r.y,r.z),c.lookAt(r.x+d[C],r.y,r.z)):b===1?(c.up.set(0,0,l[C]),c.position.set(r.x,r.y,r.z),c.lookAt(r.x,r.y+d[C],r.z)):(c.up.set(0,l[C],0),c.position.set(r.x,r.y,r.z),c.lookAt(r.x,r.y,r.z+d[C]));const S=this._cubeSize;or(s,b*S,C>2?S:0,S,S),u.setRenderTarget(s),p&&u.render(v,c),u.render(e,c)}u.toneMapping=f,u.autoClear=h,e.background=x}_textureToCubeUV(e,t){const n=this._renderer,s=e.mapping===ds||e.mapping===Gs;s?(this._cubemapMaterial===null&&(this._cubemapMaterial=sm()),this._cubemapMaterial.uniforms.flipEnvMap.value=e.isRenderTargetTexture===!1?-1:1):this._equirectMaterial===null&&(this._equirectMaterial=im());const r=s?this._cubemapMaterial:this._equirectMaterial,a=this._lodMeshes[0];a.material=r;const o=r.uniforms;o.envMap.value=e;const c=this._cubeSize;or(t,0,0,3*c,2*c),n.setRenderTarget(t),n.render(a,Jr)}_applyPMREM(e){const t=this._renderer,n=t.autoClear;t.autoClear=!1;const s=this._lodMeshes.length;for(let r=1;r<s;r++)this._applyGGXFilter(e,r-1,r);t.autoClear=n}_applyGGXFilter(e,t,n){const s=this._renderer,r=this._pingPongRenderTarget,a=this._ggxMaterial,o=this._lodMeshes[n];o.material=a;const c=a.uniforms,l=n/(this._lodMeshes.length-1),d=t/(this._lodMeshes.length-1),u=Math.sqrt(l*l-d*d),h=0+l*1.25,f=u*h,{_lodMax:g}=this,v=this._sizeLods[n],m=3*v*(n>g-Ji?n-g+Ji:0),p=4*(this._cubeSize-v);c.envMap.value=e.texture,c.roughness.value=f,c.mipInt.value=g-t,or(r,m,p,3*v,2*v),s.setRenderTarget(r),s.render(o,Jr),c.envMap.value=r.texture,c.roughness.value=0,c.mipInt.value=g-n,or(e,m,p,3*v,2*v),s.setRenderTarget(e),s.render(o,Jr)}_blur(e,t,n,s,r){const a=this._pingPongRenderTarget;this._halfBlur(e,a,t,n,s,"latitudinal",r),this._halfBlur(a,e,n,n,s,"longitudinal",r)}_halfBlur(e,t,n,s,r,a,o){const c=this._renderer,l=this._blurMaterial;a!=="latitudinal"&&a!=="longitudinal"&&tt("blur direction must be either latitudinal or longitudinal!");const d=3,u=this._lodMeshes[s];u.material=l;const h=l.uniforms,f=this._sizeLods[n]-1,g=isFinite(r)?Math.PI/(2*f):2*Math.PI/(2*_s-1),v=r/g,m=isFinite(r)?1+Math.floor(d*v):_s;m>_s&&Oe(`sigmaRadians, ${r}, is too large and will clip, as it requested ${m} samples when the maximum is set to ${_s}`);const p=[];let x=0;for(let A=0;A<_s;++A){const k=A/v,y=Math.exp(-k*k/2);p.push(y),A===0?x+=y:A<m&&(x+=2*y)}for(let A=0;A<p.length;A++)p[A]=p[A]/x;h.envMap.value=e.texture,h.samples.value=m,h.weights.value=p,h.latitudinal.value=a==="latitudinal",o&&(h.poleAxis.value=o);const{_lodMax:C}=this;h.dTheta.value=g,h.mipInt.value=C-n;const b=this._sizeLods[s],S=3*b*(s>C-Ji?s-C+Ji:0),M=4*(this._cubeSize-b);or(t,S,M,3*b,2*b),c.setRenderTarget(t),c.render(u,Jr)}}function Px(i){const e=[],t=[],n=[];let s=i;const r=i-Ji+1+Qp.length;for(let a=0;a<r;a++){const o=Math.pow(2,s);e.push(o);let c=1/o;a>i-Ji?c=Qp[a-i+Ji-1]:a===0&&(c=0),t.push(c);const l=1/(o-2),d=-l,u=1+l,h=[d,d,u,d,u,u,d,d,u,u,d,u],f=6,g=6,v=3,m=2,p=1,x=new Float32Array(v*g*f),C=new Float32Array(m*g*f),b=new Float32Array(p*g*f);for(let M=0;M<f;M++){const A=M%3*2/3-1,k=M>2?0:-1,y=[A,k,0,A+2/3,k,0,A+2/3,k+1,0,A,k,0,A+2/3,k+1,0,A,k+1,0];x.set(y,v*g*M),C.set(h,m*g*M);const T=[M,M,M,M,M,M];b.set(T,p*g*M)}const S=new Vn;S.setAttribute("position",new ti(x,v)),S.setAttribute("uv",new ti(C,m)),S.setAttribute("faceIndex",new ti(b,p)),n.push(new zn(S,null)),s>Ji&&s--}return{lodMeshes:n,sizeLods:e,sigmas:t}}function nm(i,e,t){const n=new ei(i,e,t);return n.texture.mapping=Oa,n.texture.name="PMREM.cubeUv",n.scissorTest=!0,n}function or(i,e,t,n,s){i.viewport.set(e,t,n,s),i.scissor.set(e,t,n,s)}function kx(i,e,t){return new Cn({name:"PMREMGGXConvolution",defines:{GGX_SAMPLES:Ax,CUBEUV_TEXEL_WIDTH:1/e,CUBEUV_TEXEL_HEIGHT:1/t,CUBEUV_MAX_MIP:`${i}.0`},uniforms:{envMap:{value:null},roughness:{value:0},mipInt:{value:0}},vertexShader:po(),fragmentShader:`
3697
3697
 
3698
3698
  precision highp float;
3699
3699
  precision highp int;
@@ -3801,7 +3801,7 @@ void main() {
3801
3801
 
3802
3802
  gl_FragColor = vec4(prefilteredColor, 1.0);
3803
3803
  }
3804
- `,blending:vi,depthTest:!1,depthWrite:!1})}function Ix(i,e,t){const n=new Float32Array(_s),s=new F(0,1,0);return new Tn({name:"SphericalGaussianBlur",defines:{n:_s,CUBEUV_TEXEL_WIDTH:1/e,CUBEUV_TEXEL_HEIGHT:1/t,CUBEUV_MAX_MIP:`${i}.0`},uniforms:{envMap:{value:null},samples:{value:1},weights:{value:n},latitudinal:{value:!1},dTheta:{value:0},mipInt:{value:0},poleAxis:{value:s}},vertexShader:po(),fragmentShader:`
3804
+ `,blending:vi,depthTest:!1,depthWrite:!1})}function Ix(i,e,t){const n=new Float32Array(_s),s=new F(0,1,0);return new Cn({name:"SphericalGaussianBlur",defines:{n:_s,CUBEUV_TEXEL_WIDTH:1/e,CUBEUV_TEXEL_HEIGHT:1/t,CUBEUV_MAX_MIP:`${i}.0`},uniforms:{envMap:{value:null},samples:{value:1},weights:{value:n},latitudinal:{value:!1},dTheta:{value:0},mipInt:{value:0},poleAxis:{value:s}},vertexShader:po(),fragmentShader:`
3805
3805
 
3806
3806
  precision mediump float;
3807
3807
  precision mediump int;
@@ -3861,7 +3861,7 @@ void main() {
3861
3861
  }
3862
3862
 
3863
3863
  }
3864
- `,blending:vi,depthTest:!1,depthWrite:!1})}function im(){return new Tn({name:"EquirectangularToCubeUV",uniforms:{envMap:{value:null}},vertexShader:po(),fragmentShader:`
3864
+ `,blending:vi,depthTest:!1,depthWrite:!1})}function im(){return new Cn({name:"EquirectangularToCubeUV",uniforms:{envMap:{value:null}},vertexShader:po(),fragmentShader:`
3865
3865
 
3866
3866
  precision mediump float;
3867
3867
  precision mediump int;
@@ -3880,7 +3880,7 @@ void main() {
3880
3880
  gl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 );
3881
3881
 
3882
3882
  }
3883
- `,blending:vi,depthTest:!1,depthWrite:!1})}function sm(){return new Tn({name:"CubemapToCubeUV",uniforms:{envMap:{value:null},flipEnvMap:{value:-1}},vertexShader:po(),fragmentShader:`
3883
+ `,blending:vi,depthTest:!1,depthWrite:!1})}function sm(){return new Cn({name:"CubemapToCubeUV",uniforms:{envMap:{value:null},flipEnvMap:{value:-1}},vertexShader:po(),fragmentShader:`
3884
3884
 
3885
3885
  precision mediump float;
3886
3886
  precision mediump int;
@@ -3951,7 +3951,7 @@ void main() {
3951
3951
  gl_Position = vec4( position, 1.0 );
3952
3952
 
3953
3953
  }
3954
- `}function Dx(i){let e=new WeakMap,t=null;function n(o){if(o&&o.isTexture){const c=o.mapping,l=c===dl||c===ul,d=c===ds||c===Gs;if(l||d){let u=e.get(o);const h=u!==void 0?u.texture.pmremVersion:0;if(o.isRenderTargetTexture&&o.pmremVersion!==h)return t===null&&(t=new tm(i)),u=l?t.fromEquirectangular(o,u):t.fromCubemap(o,u),u.texture.pmremVersion=o.pmremVersion,e.set(o,u),u.texture;if(u!==void 0)return u.texture;{const f=o.image;return l&&f&&f.height>0||d&&f&&s(f)?(t===null&&(t=new tm(i)),u=l?t.fromEquirectangular(o):t.fromCubemap(o),u.texture.pmremVersion=o.pmremVersion,e.set(o,u),o.addEventListener("dispose",r),u.texture):null}}}return o}function s(o){let c=0;const l=6;for(let d=0;d<l;d++)o[d]!==void 0&&c++;return c===l}function r(o){const c=o.target;c.removeEventListener("dispose",r);const l=e.get(c);l!==void 0&&(e.delete(c),l.dispose())}function a(){e=new WeakMap,t!==null&&(t.dispose(),t=null)}return{get:n,dispose:a}}function Lx(i){const e={};function t(n){if(e[n]!==void 0)return e[n];const s=i.getExtension(n);return e[n]=s,s}return{has:function(n){return t(n)!==null},init:function(){t("EXT_color_buffer_float"),t("WEBGL_clip_cull_distance"),t("OES_texture_float_linear"),t("EXT_color_buffer_half_float"),t("WEBGL_multisampled_render_to_texture"),t("WEBGL_render_shared_exponent")},get:function(n){const s=t(n);return s===null&&Vr("WebGLRenderer: "+n+" extension not supported."),s}}}function Nx(i,e,t,n){const s={},r=new WeakMap;function a(u){const h=u.target;h.index!==null&&e.remove(h.index);for(const g in h.attributes)e.remove(h.attributes[g]);h.removeEventListener("dispose",a),delete s[h.id];const f=r.get(h);f&&(e.remove(f),r.delete(h)),n.releaseStatesOfGeometry(h),h.isInstancedBufferGeometry===!0&&delete h._maxInstanceCount,t.memory.geometries--}function o(u,h){return s[h.id]===!0||(h.addEventListener("dispose",a),s[h.id]=!0,t.memory.geometries++),h}function c(u){const h=u.attributes;for(const f in h)e.update(h[f],i.ARRAY_BUFFER)}function l(u){const h=[],f=u.index,g=u.attributes.position;let v=0;if(f!==null){const x=f.array;v=f.version;for(let C=0,b=x.length;C<b;C+=3){const S=x[C+0],M=x[C+1],A=x[C+2];h.push(S,M,M,A,A,S)}}else if(g!==void 0){const x=g.array;v=g.version;for(let C=0,b=x.length/3-1;C<b;C+=3){const S=C+0,M=C+1,A=C+2;h.push(S,M,M,A,A,S)}}else return;const m=new(_p(h)?Fp:Op)(h,1);m.version=v;const p=r.get(u);p&&e.remove(p),r.set(u,m)}function d(u){const h=r.get(u);if(h){const f=u.index;f!==null&&h.version<f.version&&l(u)}else l(u);return r.get(u)}return{get:o,update:c,getWireframeAttribute:d}}function Ux(i,e,t){let n;function s(h){n=h}let r,a;function o(h){r=h.type,a=h.bytesPerElement}function c(h,f){i.drawElements(n,f,r,h*a),t.update(f,n,1)}function l(h,f,g){g!==0&&(i.drawElementsInstanced(n,f,r,h*a,g),t.update(f,n,g))}function d(h,f,g){if(g===0)return;e.get("WEBGL_multi_draw").multiDrawElementsWEBGL(n,f,0,r,h,0,g);let m=0;for(let p=0;p<g;p++)m+=f[p];t.update(m,n,1)}function u(h,f,g,v){if(g===0)return;const m=e.get("WEBGL_multi_draw");if(m===null)for(let p=0;p<h.length;p++)l(h[p]/a,f[p],v[p]);else{m.multiDrawElementsInstancedWEBGL(n,f,0,r,h,0,v,0,g);let p=0;for(let x=0;x<g;x++)p+=f[x]*v[x];t.update(p,n,1)}}this.setMode=s,this.setIndex=o,this.render=c,this.renderInstances=l,this.renderMultiDraw=d,this.renderMultiDrawInstances=u}function Ox(i){const e={geometries:0,textures:0},t={frame:0,calls:0,triangles:0,points:0,lines:0};function n(r,a,o){switch(t.calls++,a){case i.TRIANGLES:t.triangles+=o*(r/3);break;case i.LINES:t.lines+=o*(r/2);break;case i.LINE_STRIP:t.lines+=o*(r-1);break;case i.LINE_LOOP:t.lines+=o*r;break;case i.POINTS:t.points+=o*r;break;default:tt("WebGLInfo: Unknown draw mode:",a);break}}function s(){t.calls=0,t.triangles=0,t.points=0,t.lines=0}return{memory:e,render:t,programs:null,autoReset:!0,reset:s,update:n}}function Fx(i,e,t){const n=new WeakMap,s=new It;function r(a,o,c){const l=a.morphTargetInfluences,d=o.morphAttributes.position||o.morphAttributes.normal||o.morphAttributes.color,u=d!==void 0?d.length:0;let h=n.get(o);if(h===void 0||h.count!==u){let y=function(){A.dispose(),n.delete(o),o.removeEventListener("dispose",y)};h!==void 0&&h.texture.dispose();const f=o.morphAttributes.position!==void 0,g=o.morphAttributes.normal!==void 0,v=o.morphAttributes.color!==void 0,m=o.morphAttributes.position||[],p=o.morphAttributes.normal||[],x=o.morphAttributes.color||[];let C=0;f===!0&&(C=1),g===!0&&(C=2),v===!0&&(C=3);let b=o.attributes.position.count*C,S=1;b>e.maxTextureSize&&(S=Math.ceil(b/e.maxTextureSize),b=e.maxTextureSize);const M=new Float32Array(b*S*4*u),A=new Ep(M,b,S,u);A.type=Jn,A.needsUpdate=!0;const k=C*4;for(let T=0;T<u;T++){const R=m[T],U=p[T],B=x[T],q=b*S*4*T;for(let K=0;K<R.count;K++){const H=K*k;f===!0&&(s.fromBufferAttribute(R,K),M[q+H+0]=s.x,M[q+H+1]=s.y,M[q+H+2]=s.z,M[q+H+3]=0),g===!0&&(s.fromBufferAttribute(U,K),M[q+H+4]=s.x,M[q+H+5]=s.y,M[q+H+6]=s.z,M[q+H+7]=0),v===!0&&(s.fromBufferAttribute(B,K),M[q+H+8]=s.x,M[q+H+9]=s.y,M[q+H+10]=s.z,M[q+H+11]=B.itemSize===4?s.w:1)}}h={count:u,texture:A,size:new rt(b,S)},n.set(o,h),o.addEventListener("dispose",y)}if(a.isInstancedMesh===!0&&a.morphTexture!==null)c.getUniforms().setValue(i,"morphTexture",a.morphTexture,t);else{let f=0;for(let v=0;v<l.length;v++)f+=l[v];const g=o.morphTargetsRelative?1:1-f;c.getUniforms().setValue(i,"morphTargetBaseInfluence",g),c.getUniforms().setValue(i,"morphTargetInfluences",l)}c.getUniforms().setValue(i,"morphTargetsTexture",h.texture,t),c.getUniforms().setValue(i,"morphTargetsTextureSize",h.size)}return{update:r}}function Bx(i,e,t,n){let s=new WeakMap;function r(c){const l=n.render.frame,d=c.geometry,u=e.get(c,d);if(s.get(u)!==l&&(e.update(u),s.set(u,l)),c.isInstancedMesh&&(c.hasEventListener("dispose",o)===!1&&c.addEventListener("dispose",o),s.get(c)!==l&&(t.update(c.instanceMatrix,i.ARRAY_BUFFER),c.instanceColor!==null&&t.update(c.instanceColor,i.ARRAY_BUFFER),s.set(c,l))),c.isSkinnedMesh){const h=c.skeleton;s.get(h)!==l&&(h.update(),s.set(h,l))}return u}function a(){s=new WeakMap}function o(c){const l=c.target;l.removeEventListener("dispose",o),t.remove(l.instanceMatrix),l.instanceColor!==null&&t.remove(l.instanceColor)}return{update:r,dispose:a}}const Vx={[tp]:"LINEAR_TONE_MAPPING",[np]:"REINHARD_TONE_MAPPING",[ip]:"CINEON_TONE_MAPPING",[sp]:"ACES_FILMIC_TONE_MAPPING",[ap]:"AGX_TONE_MAPPING",[op]:"NEUTRAL_TONE_MAPPING",[rp]:"CUSTOM_TONE_MAPPING"};function zx(i,e,t,n,s){const r=new Qn(e,t,{type:i,depthBuffer:n,stencilBuffer:s}),a=new Qn(e,t,{type:_i,depthBuffer:!1,stencilBuffer:!1}),o=new Bn;o.setAttribute("position",new en([-1,3,0,-1,-1,0,3,-1,0],3)),o.setAttribute("uv",new en([0,2,0,0,2,0],2));const c=new my({uniforms:{tDiffuse:{value:null}},vertexShader:`
3954
+ `}function Dx(i){let e=new WeakMap,t=null;function n(o){if(o&&o.isTexture){const c=o.mapping,l=c===dl||c===ul,d=c===ds||c===Gs;if(l||d){let u=e.get(o);const h=u!==void 0?u.texture.pmremVersion:0;if(o.isRenderTargetTexture&&o.pmremVersion!==h)return t===null&&(t=new tm(i)),u=l?t.fromEquirectangular(o,u):t.fromCubemap(o,u),u.texture.pmremVersion=o.pmremVersion,e.set(o,u),u.texture;if(u!==void 0)return u.texture;{const f=o.image;return l&&f&&f.height>0||d&&f&&s(f)?(t===null&&(t=new tm(i)),u=l?t.fromEquirectangular(o):t.fromCubemap(o),u.texture.pmremVersion=o.pmremVersion,e.set(o,u),o.addEventListener("dispose",r),u.texture):null}}}return o}function s(o){let c=0;const l=6;for(let d=0;d<l;d++)o[d]!==void 0&&c++;return c===l}function r(o){const c=o.target;c.removeEventListener("dispose",r);const l=e.get(c);l!==void 0&&(e.delete(c),l.dispose())}function a(){e=new WeakMap,t!==null&&(t.dispose(),t=null)}return{get:n,dispose:a}}function Lx(i){const e={};function t(n){if(e[n]!==void 0)return e[n];const s=i.getExtension(n);return e[n]=s,s}return{has:function(n){return t(n)!==null},init:function(){t("EXT_color_buffer_float"),t("WEBGL_clip_cull_distance"),t("OES_texture_float_linear"),t("EXT_color_buffer_half_float"),t("WEBGL_multisampled_render_to_texture"),t("WEBGL_render_shared_exponent")},get:function(n){const s=t(n);return s===null&&Vr("WebGLRenderer: "+n+" extension not supported."),s}}}function Nx(i,e,t,n){const s={},r=new WeakMap;function a(u){const h=u.target;h.index!==null&&e.remove(h.index);for(const g in h.attributes)e.remove(h.attributes[g]);h.removeEventListener("dispose",a),delete s[h.id];const f=r.get(h);f&&(e.remove(f),r.delete(h)),n.releaseStatesOfGeometry(h),h.isInstancedBufferGeometry===!0&&delete h._maxInstanceCount,t.memory.geometries--}function o(u,h){return s[h.id]===!0||(h.addEventListener("dispose",a),s[h.id]=!0,t.memory.geometries++),h}function c(u){const h=u.attributes;for(const f in h)e.update(h[f],i.ARRAY_BUFFER)}function l(u){const h=[],f=u.index,g=u.attributes.position;let v=0;if(f!==null){const x=f.array;v=f.version;for(let C=0,b=x.length;C<b;C+=3){const S=x[C+0],M=x[C+1],A=x[C+2];h.push(S,M,M,A,A,S)}}else if(g!==void 0){const x=g.array;v=g.version;for(let C=0,b=x.length/3-1;C<b;C+=3){const S=C+0,M=C+1,A=C+2;h.push(S,M,M,A,A,S)}}else return;const m=new(_p(h)?Fp:Op)(h,1);m.version=v;const p=r.get(u);p&&e.remove(p),r.set(u,m)}function d(u){const h=r.get(u);if(h){const f=u.index;f!==null&&h.version<f.version&&l(u)}else l(u);return r.get(u)}return{get:o,update:c,getWireframeAttribute:d}}function Ux(i,e,t){let n;function s(h){n=h}let r,a;function o(h){r=h.type,a=h.bytesPerElement}function c(h,f){i.drawElements(n,f,r,h*a),t.update(f,n,1)}function l(h,f,g){g!==0&&(i.drawElementsInstanced(n,f,r,h*a,g),t.update(f,n,g))}function d(h,f,g){if(g===0)return;e.get("WEBGL_multi_draw").multiDrawElementsWEBGL(n,f,0,r,h,0,g);let m=0;for(let p=0;p<g;p++)m+=f[p];t.update(m,n,1)}function u(h,f,g,v){if(g===0)return;const m=e.get("WEBGL_multi_draw");if(m===null)for(let p=0;p<h.length;p++)l(h[p]/a,f[p],v[p]);else{m.multiDrawElementsInstancedWEBGL(n,f,0,r,h,0,v,0,g);let p=0;for(let x=0;x<g;x++)p+=f[x]*v[x];t.update(p,n,1)}}this.setMode=s,this.setIndex=o,this.render=c,this.renderInstances=l,this.renderMultiDraw=d,this.renderMultiDrawInstances=u}function Ox(i){const e={geometries:0,textures:0},t={frame:0,calls:0,triangles:0,points:0,lines:0};function n(r,a,o){switch(t.calls++,a){case i.TRIANGLES:t.triangles+=o*(r/3);break;case i.LINES:t.lines+=o*(r/2);break;case i.LINE_STRIP:t.lines+=o*(r-1);break;case i.LINE_LOOP:t.lines+=o*r;break;case i.POINTS:t.points+=o*r;break;default:tt("WebGLInfo: Unknown draw mode:",a);break}}function s(){t.calls=0,t.triangles=0,t.points=0,t.lines=0}return{memory:e,render:t,programs:null,autoReset:!0,reset:s,update:n}}function Fx(i,e,t){const n=new WeakMap,s=new It;function r(a,o,c){const l=a.morphTargetInfluences,d=o.morphAttributes.position||o.morphAttributes.normal||o.morphAttributes.color,u=d!==void 0?d.length:0;let h=n.get(o);if(h===void 0||h.count!==u){let y=function(){A.dispose(),n.delete(o),o.removeEventListener("dispose",y)};h!==void 0&&h.texture.dispose();const f=o.morphAttributes.position!==void 0,g=o.morphAttributes.normal!==void 0,v=o.morphAttributes.color!==void 0,m=o.morphAttributes.position||[],p=o.morphAttributes.normal||[],x=o.morphAttributes.color||[];let C=0;f===!0&&(C=1),g===!0&&(C=2),v===!0&&(C=3);let b=o.attributes.position.count*C,S=1;b>e.maxTextureSize&&(S=Math.ceil(b/e.maxTextureSize),b=e.maxTextureSize);const M=new Float32Array(b*S*4*u),A=new Ep(M,b,S,u);A.type=Zn,A.needsUpdate=!0;const k=C*4;for(let T=0;T<u;T++){const R=m[T],U=p[T],B=x[T],q=b*S*4*T;for(let K=0;K<R.count;K++){const H=K*k;f===!0&&(s.fromBufferAttribute(R,K),M[q+H+0]=s.x,M[q+H+1]=s.y,M[q+H+2]=s.z,M[q+H+3]=0),g===!0&&(s.fromBufferAttribute(U,K),M[q+H+4]=s.x,M[q+H+5]=s.y,M[q+H+6]=s.z,M[q+H+7]=0),v===!0&&(s.fromBufferAttribute(B,K),M[q+H+8]=s.x,M[q+H+9]=s.y,M[q+H+10]=s.z,M[q+H+11]=B.itemSize===4?s.w:1)}}h={count:u,texture:A,size:new rt(b,S)},n.set(o,h),o.addEventListener("dispose",y)}if(a.isInstancedMesh===!0&&a.morphTexture!==null)c.getUniforms().setValue(i,"morphTexture",a.morphTexture,t);else{let f=0;for(let v=0;v<l.length;v++)f+=l[v];const g=o.morphTargetsRelative?1:1-f;c.getUniforms().setValue(i,"morphTargetBaseInfluence",g),c.getUniforms().setValue(i,"morphTargetInfluences",l)}c.getUniforms().setValue(i,"morphTargetsTexture",h.texture,t),c.getUniforms().setValue(i,"morphTargetsTextureSize",h.size)}return{update:r}}function Bx(i,e,t,n){let s=new WeakMap;function r(c){const l=n.render.frame,d=c.geometry,u=e.get(c,d);if(s.get(u)!==l&&(e.update(u),s.set(u,l)),c.isInstancedMesh&&(c.hasEventListener("dispose",o)===!1&&c.addEventListener("dispose",o),s.get(c)!==l&&(t.update(c.instanceMatrix,i.ARRAY_BUFFER),c.instanceColor!==null&&t.update(c.instanceColor,i.ARRAY_BUFFER),s.set(c,l))),c.isSkinnedMesh){const h=c.skeleton;s.get(h)!==l&&(h.update(),s.set(h,l))}return u}function a(){s=new WeakMap}function o(c){const l=c.target;l.removeEventListener("dispose",o),t.remove(l.instanceMatrix),l.instanceColor!==null&&t.remove(l.instanceColor)}return{update:r,dispose:a}}const Vx={[tp]:"LINEAR_TONE_MAPPING",[np]:"REINHARD_TONE_MAPPING",[ip]:"CINEON_TONE_MAPPING",[sp]:"ACES_FILMIC_TONE_MAPPING",[ap]:"AGX_TONE_MAPPING",[op]:"NEUTRAL_TONE_MAPPING",[rp]:"CUSTOM_TONE_MAPPING"};function zx(i,e,t,n,s){const r=new ei(e,t,{type:i,depthBuffer:n,stencilBuffer:s}),a=new ei(e,t,{type:_i,depthBuffer:!1,stencilBuffer:!1}),o=new Vn;o.setAttribute("position",new en([-1,3,0,-1,-1,0,3,-1,0],3)),o.setAttribute("uv",new en([0,2,0,0,2,0],2));const c=new my({uniforms:{tDiffuse:{value:null}},vertexShader:`
3955
3955
  precision highp float;
3956
3956
 
3957
3957
  uniform mat4 modelViewMatrix;
@@ -3997,7 +3997,7 @@ void main() {
3997
3997
  #ifdef SRGB_TRANSFER
3998
3998
  gl_FragColor = sRGBTransferOETF( gl_FragColor );
3999
3999
  #endif
4000
- }`,depthTest:!1,depthWrite:!1}),l=new Vn(o,c),d=new Yp(-1,1,1,-1,0,1);let u=null,h=null,f=!1,g,v=null,m=[],p=!1;this.setSize=function(x,C){r.setSize(x,C),a.setSize(x,C);for(let b=0;b<m.length;b++){const S=m[b];S.setSize&&S.setSize(x,C)}},this.setEffects=function(x){m=x,p=m.length>0&&m[0].isRenderPass===!0;const C=r.width,b=r.height;for(let S=0;S<m.length;S++){const M=m[S];M.setSize&&M.setSize(C,b)}},this.begin=function(x,C){if(f||x.toneMapping===Kn&&m.length===0)return!1;if(v=C,C!==null){const b=C.width,S=C.height;(r.width!==b||r.height!==S)&&this.setSize(b,S)}return p===!1&&x.setRenderTarget(r),g=x.toneMapping,x.toneMapping=Kn,!0},this.hasRenderPass=function(){return p},this.end=function(x,C){x.toneMapping=g,f=!0;let b=r,S=a;for(let M=0;M<m.length;M++){const A=m[M];if(A.enabled!==!1&&(A.render(x,S,b,C),A.needsSwap!==!1)){const k=b;b=S,S=k}}if(u!==x.outputColorSpace||h!==x.toneMapping){u=x.outputColorSpace,h=x.toneMapping,c.defines={},Qe.getTransfer(u)===ot&&(c.defines.SRGB_TRANSFER="");const M=Vx[h];M&&(c.defines[M]=""),c.needsUpdate=!0}c.uniforms.tDiffuse.value=b.texture,x.setRenderTarget(v),x.render(l,d),v=null,f=!1},this.isCompositing=function(){return f},this.dispose=function(){r.dispose(),a.dispose(),o.dispose(),c.dispose()}}const rm=new Qt,Nd=new Yr(1,1),am=new Ep,om=new W_,cm=new jp,lm=[],dm=[],um=new Float32Array(16),hm=new Float32Array(9),fm=new Float32Array(4);function cr(i,e,t){const n=i[0];if(n<=0||n>0)return i;const s=e*t;let r=lm[s];if(r===void 0&&(r=new Float32Array(s),lm[s]=r),e!==0){n.toArray(r,0);for(let a=1,o=0;a!==e;++a)o+=t,i[a].toArray(r,o)}return r}function Vt(i,e){if(i.length!==e.length)return!1;for(let t=0,n=i.length;t<n;t++)if(i[t]!==e[t])return!1;return!0}function zt(i,e){for(let t=0,n=e.length;t<n;t++)i[t]=e[t]}function mo(i,e){let t=dm[e];t===void 0&&(t=new Int32Array(e),dm[e]=t);for(let n=0;n!==e;++n)t[n]=i.allocateTextureUnit();return t}function Gx(i,e){const t=this.cache;t[0]!==e&&(i.uniform1f(this.addr,e),t[0]=e)}function Hx(i,e){const t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y)&&(i.uniform2f(this.addr,e.x,e.y),t[0]=e.x,t[1]=e.y);else{if(Vt(t,e))return;i.uniform2fv(this.addr,e),zt(t,e)}}function Wx(i,e){const t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y||t[2]!==e.z)&&(i.uniform3f(this.addr,e.x,e.y,e.z),t[0]=e.x,t[1]=e.y,t[2]=e.z);else if(e.r!==void 0)(t[0]!==e.r||t[1]!==e.g||t[2]!==e.b)&&(i.uniform3f(this.addr,e.r,e.g,e.b),t[0]=e.r,t[1]=e.g,t[2]=e.b);else{if(Vt(t,e))return;i.uniform3fv(this.addr,e),zt(t,e)}}function qx(i,e){const t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y||t[2]!==e.z||t[3]!==e.w)&&(i.uniform4f(this.addr,e.x,e.y,e.z,e.w),t[0]=e.x,t[1]=e.y,t[2]=e.z,t[3]=e.w);else{if(Vt(t,e))return;i.uniform4fv(this.addr,e),zt(t,e)}}function jx(i,e){const t=this.cache,n=e.elements;if(n===void 0){if(Vt(t,e))return;i.uniformMatrix2fv(this.addr,!1,e),zt(t,e)}else{if(Vt(t,n))return;fm.set(n),i.uniformMatrix2fv(this.addr,!1,fm),zt(t,n)}}function $x(i,e){const t=this.cache,n=e.elements;if(n===void 0){if(Vt(t,e))return;i.uniformMatrix3fv(this.addr,!1,e),zt(t,e)}else{if(Vt(t,n))return;hm.set(n),i.uniformMatrix3fv(this.addr,!1,hm),zt(t,n)}}function Xx(i,e){const t=this.cache,n=e.elements;if(n===void 0){if(Vt(t,e))return;i.uniformMatrix4fv(this.addr,!1,e),zt(t,e)}else{if(Vt(t,n))return;um.set(n),i.uniformMatrix4fv(this.addr,!1,um),zt(t,n)}}function Kx(i,e){const t=this.cache;t[0]!==e&&(i.uniform1i(this.addr,e),t[0]=e)}function Yx(i,e){const t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y)&&(i.uniform2i(this.addr,e.x,e.y),t[0]=e.x,t[1]=e.y);else{if(Vt(t,e))return;i.uniform2iv(this.addr,e),zt(t,e)}}function Jx(i,e){const t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y||t[2]!==e.z)&&(i.uniform3i(this.addr,e.x,e.y,e.z),t[0]=e.x,t[1]=e.y,t[2]=e.z);else{if(Vt(t,e))return;i.uniform3iv(this.addr,e),zt(t,e)}}function Zx(i,e){const t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y||t[2]!==e.z||t[3]!==e.w)&&(i.uniform4i(this.addr,e.x,e.y,e.z,e.w),t[0]=e.x,t[1]=e.y,t[2]=e.z,t[3]=e.w);else{if(Vt(t,e))return;i.uniform4iv(this.addr,e),zt(t,e)}}function Qx(i,e){const t=this.cache;t[0]!==e&&(i.uniform1ui(this.addr,e),t[0]=e)}function eT(i,e){const t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y)&&(i.uniform2ui(this.addr,e.x,e.y),t[0]=e.x,t[1]=e.y);else{if(Vt(t,e))return;i.uniform2uiv(this.addr,e),zt(t,e)}}function tT(i,e){const t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y||t[2]!==e.z)&&(i.uniform3ui(this.addr,e.x,e.y,e.z),t[0]=e.x,t[1]=e.y,t[2]=e.z);else{if(Vt(t,e))return;i.uniform3uiv(this.addr,e),zt(t,e)}}function nT(i,e){const t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y||t[2]!==e.z||t[3]!==e.w)&&(i.uniform4ui(this.addr,e.x,e.y,e.z,e.w),t[0]=e.x,t[1]=e.y,t[2]=e.z,t[3]=e.w);else{if(Vt(t,e))return;i.uniform4uiv(this.addr,e),zt(t,e)}}function iT(i,e,t){const n=this.cache,s=t.allocateTextureUnit();n[0]!==s&&(i.uniform1i(this.addr,s),n[0]=s);let r;this.type===i.SAMPLER_2D_SHADOW?(Nd.compareFunction=t.isReversedDepthBuffer()?ed:Ql,r=Nd):r=rm,t.setTexture2D(e||r,s)}function sT(i,e,t){const n=this.cache,s=t.allocateTextureUnit();n[0]!==s&&(i.uniform1i(this.addr,s),n[0]=s),t.setTexture3D(e||om,s)}function rT(i,e,t){const n=this.cache,s=t.allocateTextureUnit();n[0]!==s&&(i.uniform1i(this.addr,s),n[0]=s),t.setTextureCube(e||cm,s)}function aT(i,e,t){const n=this.cache,s=t.allocateTextureUnit();n[0]!==s&&(i.uniform1i(this.addr,s),n[0]=s),t.setTexture2DArray(e||am,s)}function oT(i){switch(i){case 5126:return Gx;case 35664:return Hx;case 35665:return Wx;case 35666:return qx;case 35674:return jx;case 35675:return $x;case 35676:return Xx;case 5124:case 35670:return Kx;case 35667:case 35671:return Yx;case 35668:case 35672:return Jx;case 35669:case 35673:return Zx;case 5125:return Qx;case 36294:return eT;case 36295:return tT;case 36296:return nT;case 35678:case 36198:case 36298:case 36306:case 35682:return iT;case 35679:case 36299:case 36307:return sT;case 35680:case 36300:case 36308:case 36293:return rT;case 36289:case 36303:case 36311:case 36292:return aT}}function cT(i,e){i.uniform1fv(this.addr,e)}function lT(i,e){const t=cr(e,this.size,2);i.uniform2fv(this.addr,t)}function dT(i,e){const t=cr(e,this.size,3);i.uniform3fv(this.addr,t)}function uT(i,e){const t=cr(e,this.size,4);i.uniform4fv(this.addr,t)}function hT(i,e){const t=cr(e,this.size,4);i.uniformMatrix2fv(this.addr,!1,t)}function fT(i,e){const t=cr(e,this.size,9);i.uniformMatrix3fv(this.addr,!1,t)}function pT(i,e){const t=cr(e,this.size,16);i.uniformMatrix4fv(this.addr,!1,t)}function mT(i,e){i.uniform1iv(this.addr,e)}function gT(i,e){i.uniform2iv(this.addr,e)}function vT(i,e){i.uniform3iv(this.addr,e)}function bT(i,e){i.uniform4iv(this.addr,e)}function _T(i,e){i.uniform1uiv(this.addr,e)}function yT(i,e){i.uniform2uiv(this.addr,e)}function ST(i,e){i.uniform3uiv(this.addr,e)}function xT(i,e){i.uniform4uiv(this.addr,e)}function TT(i,e,t){const n=this.cache,s=e.length,r=mo(t,s);Vt(n,r)||(i.uniform1iv(this.addr,r),zt(n,r));let a;this.type===i.SAMPLER_2D_SHADOW?a=Nd:a=rm;for(let o=0;o!==s;++o)t.setTexture2D(e[o]||a,r[o])}function CT(i,e,t){const n=this.cache,s=e.length,r=mo(t,s);Vt(n,r)||(i.uniform1iv(this.addr,r),zt(n,r));for(let a=0;a!==s;++a)t.setTexture3D(e[a]||om,r[a])}function ET(i,e,t){const n=this.cache,s=e.length,r=mo(t,s);Vt(n,r)||(i.uniform1iv(this.addr,r),zt(n,r));for(let a=0;a!==s;++a)t.setTextureCube(e[a]||cm,r[a])}function MT(i,e,t){const n=this.cache,s=e.length,r=mo(t,s);Vt(n,r)||(i.uniform1iv(this.addr,r),zt(n,r));for(let a=0;a!==s;++a)t.setTexture2DArray(e[a]||am,r[a])}function wT(i){switch(i){case 5126:return cT;case 35664:return lT;case 35665:return dT;case 35666:return uT;case 35674:return hT;case 35675:return fT;case 35676:return pT;case 5124:case 35670:return mT;case 35667:case 35671:return gT;case 35668:case 35672:return vT;case 35669:case 35673:return bT;case 5125:return _T;case 36294:return yT;case 36295:return ST;case 36296:return xT;case 35678:case 36198:case 36298:case 36306:case 35682:return TT;case 35679:case 36299:case 36307:return CT;case 35680:case 36300:case 36308:case 36293:return ET;case 36289:case 36303:case 36311:case 36292:return MT}}class AT{constructor(e,t,n){this.id=e,this.addr=n,this.cache=[],this.type=t.type,this.setValue=oT(t.type)}}class RT{constructor(e,t,n){this.id=e,this.addr=n,this.cache=[],this.type=t.type,this.size=t.size,this.setValue=wT(t.type)}}class PT{constructor(e){this.id=e,this.seq=[],this.map={}}setValue(e,t,n){const s=this.seq;for(let r=0,a=s.length;r!==a;++r){const o=s[r];o.setValue(e,t[o.id],n)}}}const Ud=/(\w+)(\])?(\[|\.)?/g;function pm(i,e){i.seq.push(e),i.map[e.id]=e}function kT(i,e,t){const n=i.name,s=n.length;for(Ud.lastIndex=0;;){const r=Ud.exec(n),a=Ud.lastIndex;let o=r[1];const c=r[2]==="]",l=r[3];if(c&&(o=o|0),l===void 0||l==="["&&a+2===s){pm(t,l===void 0?new AT(o,i,e):new RT(o,i,e));break}else{let u=t.map[o];u===void 0&&(u=new PT(o),pm(t,u)),t=u}}}class go{constructor(e,t){this.seq=[],this.map={};const n=e.getProgramParameter(t,e.ACTIVE_UNIFORMS);for(let a=0;a<n;++a){const o=e.getActiveUniform(t,a),c=e.getUniformLocation(t,o.name);kT(o,c,this)}const s=[],r=[];for(const a of this.seq)a.type===e.SAMPLER_2D_SHADOW||a.type===e.SAMPLER_CUBE_SHADOW||a.type===e.SAMPLER_2D_ARRAY_SHADOW?s.push(a):r.push(a);s.length>0&&(this.seq=s.concat(r))}setValue(e,t,n,s){const r=this.map[t];r!==void 0&&r.setValue(e,n,s)}setOptional(e,t,n){const s=t[n];s!==void 0&&this.setValue(e,n,s)}static upload(e,t,n,s){for(let r=0,a=t.length;r!==a;++r){const o=t[r],c=n[o.id];c.needsUpdate!==!1&&o.setValue(e,c.value,s)}}static seqWithValue(e,t){const n=[];for(let s=0,r=e.length;s!==r;++s){const a=e[s];a.id in t&&n.push(a)}return n}}function mm(i,e,t){const n=i.createShader(e);return i.shaderSource(n,t),i.compileShader(n),n}const IT=37297;let DT=0;function LT(i,e){const t=i.split(`
4000
+ }`,depthTest:!1,depthWrite:!1}),l=new zn(o,c),d=new Yp(-1,1,1,-1,0,1);let u=null,h=null,f=!1,g,v=null,m=[],p=!1;this.setSize=function(x,C){r.setSize(x,C),a.setSize(x,C);for(let b=0;b<m.length;b++){const S=m[b];S.setSize&&S.setSize(x,C)}},this.setEffects=function(x){m=x,p=m.length>0&&m[0].isRenderPass===!0;const C=r.width,b=r.height;for(let S=0;S<m.length;S++){const M=m[S];M.setSize&&M.setSize(C,b)}},this.begin=function(x,C){if(f||x.toneMapping===Yn&&m.length===0)return!1;if(v=C,C!==null){const b=C.width,S=C.height;(r.width!==b||r.height!==S)&&this.setSize(b,S)}return p===!1&&x.setRenderTarget(r),g=x.toneMapping,x.toneMapping=Yn,!0},this.hasRenderPass=function(){return p},this.end=function(x,C){x.toneMapping=g,f=!0;let b=r,S=a;for(let M=0;M<m.length;M++){const A=m[M];if(A.enabled!==!1&&(A.render(x,S,b,C),A.needsSwap!==!1)){const k=b;b=S,S=k}}if(u!==x.outputColorSpace||h!==x.toneMapping){u=x.outputColorSpace,h=x.toneMapping,c.defines={},Qe.getTransfer(u)===ot&&(c.defines.SRGB_TRANSFER="");const M=Vx[h];M&&(c.defines[M]=""),c.needsUpdate=!0}c.uniforms.tDiffuse.value=b.texture,x.setRenderTarget(v),x.render(l,d),v=null,f=!1},this.isCompositing=function(){return f},this.dispose=function(){r.dispose(),a.dispose(),o.dispose(),c.dispose()}}const rm=new Qt,Nd=new Yr(1,1),am=new Ep,om=new W_,cm=new jp,lm=[],dm=[],um=new Float32Array(16),hm=new Float32Array(9),fm=new Float32Array(4);function cr(i,e,t){const n=i[0];if(n<=0||n>0)return i;const s=e*t;let r=lm[s];if(r===void 0&&(r=new Float32Array(s),lm[s]=r),e!==0){n.toArray(r,0);for(let a=1,o=0;a!==e;++a)o+=t,i[a].toArray(r,o)}return r}function Vt(i,e){if(i.length!==e.length)return!1;for(let t=0,n=i.length;t<n;t++)if(i[t]!==e[t])return!1;return!0}function zt(i,e){for(let t=0,n=e.length;t<n;t++)i[t]=e[t]}function mo(i,e){let t=dm[e];t===void 0&&(t=new Int32Array(e),dm[e]=t);for(let n=0;n!==e;++n)t[n]=i.allocateTextureUnit();return t}function Gx(i,e){const t=this.cache;t[0]!==e&&(i.uniform1f(this.addr,e),t[0]=e)}function Hx(i,e){const t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y)&&(i.uniform2f(this.addr,e.x,e.y),t[0]=e.x,t[1]=e.y);else{if(Vt(t,e))return;i.uniform2fv(this.addr,e),zt(t,e)}}function Wx(i,e){const t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y||t[2]!==e.z)&&(i.uniform3f(this.addr,e.x,e.y,e.z),t[0]=e.x,t[1]=e.y,t[2]=e.z);else if(e.r!==void 0)(t[0]!==e.r||t[1]!==e.g||t[2]!==e.b)&&(i.uniform3f(this.addr,e.r,e.g,e.b),t[0]=e.r,t[1]=e.g,t[2]=e.b);else{if(Vt(t,e))return;i.uniform3fv(this.addr,e),zt(t,e)}}function qx(i,e){const t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y||t[2]!==e.z||t[3]!==e.w)&&(i.uniform4f(this.addr,e.x,e.y,e.z,e.w),t[0]=e.x,t[1]=e.y,t[2]=e.z,t[3]=e.w);else{if(Vt(t,e))return;i.uniform4fv(this.addr,e),zt(t,e)}}function jx(i,e){const t=this.cache,n=e.elements;if(n===void 0){if(Vt(t,e))return;i.uniformMatrix2fv(this.addr,!1,e),zt(t,e)}else{if(Vt(t,n))return;fm.set(n),i.uniformMatrix2fv(this.addr,!1,fm),zt(t,n)}}function $x(i,e){const t=this.cache,n=e.elements;if(n===void 0){if(Vt(t,e))return;i.uniformMatrix3fv(this.addr,!1,e),zt(t,e)}else{if(Vt(t,n))return;hm.set(n),i.uniformMatrix3fv(this.addr,!1,hm),zt(t,n)}}function Xx(i,e){const t=this.cache,n=e.elements;if(n===void 0){if(Vt(t,e))return;i.uniformMatrix4fv(this.addr,!1,e),zt(t,e)}else{if(Vt(t,n))return;um.set(n),i.uniformMatrix4fv(this.addr,!1,um),zt(t,n)}}function Kx(i,e){const t=this.cache;t[0]!==e&&(i.uniform1i(this.addr,e),t[0]=e)}function Yx(i,e){const t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y)&&(i.uniform2i(this.addr,e.x,e.y),t[0]=e.x,t[1]=e.y);else{if(Vt(t,e))return;i.uniform2iv(this.addr,e),zt(t,e)}}function Jx(i,e){const t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y||t[2]!==e.z)&&(i.uniform3i(this.addr,e.x,e.y,e.z),t[0]=e.x,t[1]=e.y,t[2]=e.z);else{if(Vt(t,e))return;i.uniform3iv(this.addr,e),zt(t,e)}}function Zx(i,e){const t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y||t[2]!==e.z||t[3]!==e.w)&&(i.uniform4i(this.addr,e.x,e.y,e.z,e.w),t[0]=e.x,t[1]=e.y,t[2]=e.z,t[3]=e.w);else{if(Vt(t,e))return;i.uniform4iv(this.addr,e),zt(t,e)}}function Qx(i,e){const t=this.cache;t[0]!==e&&(i.uniform1ui(this.addr,e),t[0]=e)}function eT(i,e){const t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y)&&(i.uniform2ui(this.addr,e.x,e.y),t[0]=e.x,t[1]=e.y);else{if(Vt(t,e))return;i.uniform2uiv(this.addr,e),zt(t,e)}}function tT(i,e){const t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y||t[2]!==e.z)&&(i.uniform3ui(this.addr,e.x,e.y,e.z),t[0]=e.x,t[1]=e.y,t[2]=e.z);else{if(Vt(t,e))return;i.uniform3uiv(this.addr,e),zt(t,e)}}function nT(i,e){const t=this.cache;if(e.x!==void 0)(t[0]!==e.x||t[1]!==e.y||t[2]!==e.z||t[3]!==e.w)&&(i.uniform4ui(this.addr,e.x,e.y,e.z,e.w),t[0]=e.x,t[1]=e.y,t[2]=e.z,t[3]=e.w);else{if(Vt(t,e))return;i.uniform4uiv(this.addr,e),zt(t,e)}}function iT(i,e,t){const n=this.cache,s=t.allocateTextureUnit();n[0]!==s&&(i.uniform1i(this.addr,s),n[0]=s);let r;this.type===i.SAMPLER_2D_SHADOW?(Nd.compareFunction=t.isReversedDepthBuffer()?ed:Ql,r=Nd):r=rm,t.setTexture2D(e||r,s)}function sT(i,e,t){const n=this.cache,s=t.allocateTextureUnit();n[0]!==s&&(i.uniform1i(this.addr,s),n[0]=s),t.setTexture3D(e||om,s)}function rT(i,e,t){const n=this.cache,s=t.allocateTextureUnit();n[0]!==s&&(i.uniform1i(this.addr,s),n[0]=s),t.setTextureCube(e||cm,s)}function aT(i,e,t){const n=this.cache,s=t.allocateTextureUnit();n[0]!==s&&(i.uniform1i(this.addr,s),n[0]=s),t.setTexture2DArray(e||am,s)}function oT(i){switch(i){case 5126:return Gx;case 35664:return Hx;case 35665:return Wx;case 35666:return qx;case 35674:return jx;case 35675:return $x;case 35676:return Xx;case 5124:case 35670:return Kx;case 35667:case 35671:return Yx;case 35668:case 35672:return Jx;case 35669:case 35673:return Zx;case 5125:return Qx;case 36294:return eT;case 36295:return tT;case 36296:return nT;case 35678:case 36198:case 36298:case 36306:case 35682:return iT;case 35679:case 36299:case 36307:return sT;case 35680:case 36300:case 36308:case 36293:return rT;case 36289:case 36303:case 36311:case 36292:return aT}}function cT(i,e){i.uniform1fv(this.addr,e)}function lT(i,e){const t=cr(e,this.size,2);i.uniform2fv(this.addr,t)}function dT(i,e){const t=cr(e,this.size,3);i.uniform3fv(this.addr,t)}function uT(i,e){const t=cr(e,this.size,4);i.uniform4fv(this.addr,t)}function hT(i,e){const t=cr(e,this.size,4);i.uniformMatrix2fv(this.addr,!1,t)}function fT(i,e){const t=cr(e,this.size,9);i.uniformMatrix3fv(this.addr,!1,t)}function pT(i,e){const t=cr(e,this.size,16);i.uniformMatrix4fv(this.addr,!1,t)}function mT(i,e){i.uniform1iv(this.addr,e)}function gT(i,e){i.uniform2iv(this.addr,e)}function vT(i,e){i.uniform3iv(this.addr,e)}function bT(i,e){i.uniform4iv(this.addr,e)}function _T(i,e){i.uniform1uiv(this.addr,e)}function yT(i,e){i.uniform2uiv(this.addr,e)}function ST(i,e){i.uniform3uiv(this.addr,e)}function xT(i,e){i.uniform4uiv(this.addr,e)}function TT(i,e,t){const n=this.cache,s=e.length,r=mo(t,s);Vt(n,r)||(i.uniform1iv(this.addr,r),zt(n,r));let a;this.type===i.SAMPLER_2D_SHADOW?a=Nd:a=rm;for(let o=0;o!==s;++o)t.setTexture2D(e[o]||a,r[o])}function CT(i,e,t){const n=this.cache,s=e.length,r=mo(t,s);Vt(n,r)||(i.uniform1iv(this.addr,r),zt(n,r));for(let a=0;a!==s;++a)t.setTexture3D(e[a]||om,r[a])}function ET(i,e,t){const n=this.cache,s=e.length,r=mo(t,s);Vt(n,r)||(i.uniform1iv(this.addr,r),zt(n,r));for(let a=0;a!==s;++a)t.setTextureCube(e[a]||cm,r[a])}function MT(i,e,t){const n=this.cache,s=e.length,r=mo(t,s);Vt(n,r)||(i.uniform1iv(this.addr,r),zt(n,r));for(let a=0;a!==s;++a)t.setTexture2DArray(e[a]||am,r[a])}function wT(i){switch(i){case 5126:return cT;case 35664:return lT;case 35665:return dT;case 35666:return uT;case 35674:return hT;case 35675:return fT;case 35676:return pT;case 5124:case 35670:return mT;case 35667:case 35671:return gT;case 35668:case 35672:return vT;case 35669:case 35673:return bT;case 5125:return _T;case 36294:return yT;case 36295:return ST;case 36296:return xT;case 35678:case 36198:case 36298:case 36306:case 35682:return TT;case 35679:case 36299:case 36307:return CT;case 35680:case 36300:case 36308:case 36293:return ET;case 36289:case 36303:case 36311:case 36292:return MT}}class AT{constructor(e,t,n){this.id=e,this.addr=n,this.cache=[],this.type=t.type,this.setValue=oT(t.type)}}class RT{constructor(e,t,n){this.id=e,this.addr=n,this.cache=[],this.type=t.type,this.size=t.size,this.setValue=wT(t.type)}}class PT{constructor(e){this.id=e,this.seq=[],this.map={}}setValue(e,t,n){const s=this.seq;for(let r=0,a=s.length;r!==a;++r){const o=s[r];o.setValue(e,t[o.id],n)}}}const Ud=/(\w+)(\])?(\[|\.)?/g;function pm(i,e){i.seq.push(e),i.map[e.id]=e}function kT(i,e,t){const n=i.name,s=n.length;for(Ud.lastIndex=0;;){const r=Ud.exec(n),a=Ud.lastIndex;let o=r[1];const c=r[2]==="]",l=r[3];if(c&&(o=o|0),l===void 0||l==="["&&a+2===s){pm(t,l===void 0?new AT(o,i,e):new RT(o,i,e));break}else{let u=t.map[o];u===void 0&&(u=new PT(o),pm(t,u)),t=u}}}class go{constructor(e,t){this.seq=[],this.map={};const n=e.getProgramParameter(t,e.ACTIVE_UNIFORMS);for(let a=0;a<n;++a){const o=e.getActiveUniform(t,a),c=e.getUniformLocation(t,o.name);kT(o,c,this)}const s=[],r=[];for(const a of this.seq)a.type===e.SAMPLER_2D_SHADOW||a.type===e.SAMPLER_CUBE_SHADOW||a.type===e.SAMPLER_2D_ARRAY_SHADOW?s.push(a):r.push(a);s.length>0&&(this.seq=s.concat(r))}setValue(e,t,n,s){const r=this.map[t];r!==void 0&&r.setValue(e,n,s)}setOptional(e,t,n){const s=t[n];s!==void 0&&this.setValue(e,n,s)}static upload(e,t,n,s){for(let r=0,a=t.length;r!==a;++r){const o=t[r],c=n[o.id];c.needsUpdate!==!1&&o.setValue(e,c.value,s)}}static seqWithValue(e,t){const n=[];for(let s=0,r=e.length;s!==r;++s){const a=e[s];a.id in t&&n.push(a)}return n}}function mm(i,e,t){const n=i.createShader(e);return i.shaderSource(n,t),i.compileShader(n),n}const IT=37297;let DT=0;function LT(i,e){const t=i.split(`
4001
4001
  `),n=[],s=Math.max(e-6,0),r=Math.min(e+6,t.length);for(let a=s;a<r;a++){const o=a+1;n.push(`${o===e?">":" "} ${o}: ${t[a]}`)}return n.join(`
4002
4002
  `)}const gm=new ze;function NT(i){Qe._getMatrix(gm,Qe.workingColorSpace,i);const e=`mat3( ${gm.elements.map(t=>t.toFixed(4))} )`;switch(Qe.getTransfer(i)){case Ha:return[e,"LinearTransferOETF"];case ot:return[e,"sRGBTransferOETF"];default:return Oe("WebGLProgram: Unsupported color space: ",i),[e,"LinearTransferOETF"]}}function vm(i,e,t){const n=i.getShaderParameter(e,i.COMPILE_STATUS),r=(i.getShaderInfoLog(e)||"").trim();if(n&&r==="")return"";const a=/ERROR: 0:(\d+)/.exec(r);if(a){const o=parseInt(a[1]);return t.toUpperCase()+`
4003
4003
 
@@ -4034,7 +4034,7 @@ void main() {
4034
4034
  `),p.length>0&&(p+=`
4035
4035
  `)):(m=[Sm(t),"#define SHADER_TYPE "+t.shaderType,"#define SHADER_NAME "+t.shaderName,g,t.extensionClipCullDistance?"#define USE_CLIP_DISTANCE":"",t.batching?"#define USE_BATCHING":"",t.batchingColor?"#define USE_BATCHING_COLOR":"",t.instancing?"#define USE_INSTANCING":"",t.instancingColor?"#define USE_INSTANCING_COLOR":"",t.instancingMorph?"#define USE_INSTANCING_MORPH":"",t.useFog&&t.fog?"#define USE_FOG":"",t.useFog&&t.fogExp2?"#define FOG_EXP2":"",t.map?"#define USE_MAP":"",t.envMap?"#define USE_ENVMAP":"",t.envMap?"#define "+d:"",t.lightMap?"#define USE_LIGHTMAP":"",t.aoMap?"#define USE_AOMAP":"",t.bumpMap?"#define USE_BUMPMAP":"",t.normalMap?"#define USE_NORMALMAP":"",t.normalMapObjectSpace?"#define USE_NORMALMAP_OBJECTSPACE":"",t.normalMapTangentSpace?"#define USE_NORMALMAP_TANGENTSPACE":"",t.displacementMap?"#define USE_DISPLACEMENTMAP":"",t.emissiveMap?"#define USE_EMISSIVEMAP":"",t.anisotropy?"#define USE_ANISOTROPY":"",t.anisotropyMap?"#define USE_ANISOTROPYMAP":"",t.clearcoatMap?"#define USE_CLEARCOATMAP":"",t.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",t.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",t.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",t.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",t.specularMap?"#define USE_SPECULARMAP":"",t.specularColorMap?"#define USE_SPECULAR_COLORMAP":"",t.specularIntensityMap?"#define USE_SPECULAR_INTENSITYMAP":"",t.roughnessMap?"#define USE_ROUGHNESSMAP":"",t.metalnessMap?"#define USE_METALNESSMAP":"",t.alphaMap?"#define USE_ALPHAMAP":"",t.alphaHash?"#define USE_ALPHAHASH":"",t.transmission?"#define USE_TRANSMISSION":"",t.transmissionMap?"#define USE_TRANSMISSIONMAP":"",t.thicknessMap?"#define USE_THICKNESSMAP":"",t.sheenColorMap?"#define USE_SHEEN_COLORMAP":"",t.sheenRoughnessMap?"#define USE_SHEEN_ROUGHNESSMAP":"",t.mapUv?"#define MAP_UV "+t.mapUv:"",t.alphaMapUv?"#define ALPHAMAP_UV "+t.alphaMapUv:"",t.lightMapUv?"#define LIGHTMAP_UV "+t.lightMapUv:"",t.aoMapUv?"#define AOMAP_UV "+t.aoMapUv:"",t.emissiveMapUv?"#define EMISSIVEMAP_UV "+t.emissiveMapUv:"",t.bumpMapUv?"#define BUMPMAP_UV "+t.bumpMapUv:"",t.normalMapUv?"#define NORMALMAP_UV "+t.normalMapUv:"",t.displacementMapUv?"#define DISPLACEMENTMAP_UV "+t.displacementMapUv:"",t.metalnessMapUv?"#define METALNESSMAP_UV "+t.metalnessMapUv:"",t.roughnessMapUv?"#define ROUGHNESSMAP_UV "+t.roughnessMapUv:"",t.anisotropyMapUv?"#define ANISOTROPYMAP_UV "+t.anisotropyMapUv:"",t.clearcoatMapUv?"#define CLEARCOATMAP_UV "+t.clearcoatMapUv:"",t.clearcoatNormalMapUv?"#define CLEARCOAT_NORMALMAP_UV "+t.clearcoatNormalMapUv:"",t.clearcoatRoughnessMapUv?"#define CLEARCOAT_ROUGHNESSMAP_UV "+t.clearcoatRoughnessMapUv:"",t.iridescenceMapUv?"#define IRIDESCENCEMAP_UV "+t.iridescenceMapUv:"",t.iridescenceThicknessMapUv?"#define IRIDESCENCE_THICKNESSMAP_UV "+t.iridescenceThicknessMapUv:"",t.sheenColorMapUv?"#define SHEEN_COLORMAP_UV "+t.sheenColorMapUv:"",t.sheenRoughnessMapUv?"#define SHEEN_ROUGHNESSMAP_UV "+t.sheenRoughnessMapUv:"",t.specularMapUv?"#define SPECULARMAP_UV "+t.specularMapUv:"",t.specularColorMapUv?"#define SPECULAR_COLORMAP_UV "+t.specularColorMapUv:"",t.specularIntensityMapUv?"#define SPECULAR_INTENSITYMAP_UV "+t.specularIntensityMapUv:"",t.transmissionMapUv?"#define TRANSMISSIONMAP_UV "+t.transmissionMapUv:"",t.thicknessMapUv?"#define THICKNESSMAP_UV "+t.thicknessMapUv:"",t.vertexTangents&&t.flatShading===!1?"#define USE_TANGENT":"",t.vertexColors?"#define USE_COLOR":"",t.vertexAlphas?"#define USE_COLOR_ALPHA":"",t.vertexUv1s?"#define USE_UV1":"",t.vertexUv2s?"#define USE_UV2":"",t.vertexUv3s?"#define USE_UV3":"",t.pointsUvs?"#define USE_POINTS_UV":"",t.flatShading?"#define FLAT_SHADED":"",t.skinning?"#define USE_SKINNING":"",t.morphTargets?"#define USE_MORPHTARGETS":"",t.morphNormals&&t.flatShading===!1?"#define USE_MORPHNORMALS":"",t.morphColors?"#define USE_MORPHCOLORS":"",t.morphTargetsCount>0?"#define MORPHTARGETS_TEXTURE_STRIDE "+t.morphTextureStride:"",t.morphTargetsCount>0?"#define MORPHTARGETS_COUNT "+t.morphTargetsCount:"",t.doubleSided?"#define DOUBLE_SIDED":"",t.flipSided?"#define FLIP_SIDED":"",t.shadowMapEnabled?"#define USE_SHADOWMAP":"",t.shadowMapEnabled?"#define "+c:"",t.sizeAttenuation?"#define USE_SIZEATTENUATION":"",t.numLightProbes>0?"#define USE_LIGHT_PROBES":"",t.logarithmicDepthBuffer?"#define USE_LOGARITHMIC_DEPTH_BUFFER":"",t.reversedDepthBuffer?"#define USE_REVERSED_DEPTH_BUFFER":"","uniform mat4 modelMatrix;","uniform mat4 modelViewMatrix;","uniform mat4 projectionMatrix;","uniform mat4 viewMatrix;","uniform mat3 normalMatrix;","uniform vec3 cameraPosition;","uniform bool isOrthographic;","#ifdef USE_INSTANCING"," attribute mat4 instanceMatrix;","#endif","#ifdef USE_INSTANCING_COLOR"," attribute vec3 instanceColor;","#endif","#ifdef USE_INSTANCING_MORPH"," uniform sampler2D morphTexture;","#endif","attribute vec3 position;","attribute vec3 normal;","attribute vec2 uv;","#ifdef USE_UV1"," attribute vec2 uv1;","#endif","#ifdef USE_UV2"," attribute vec2 uv2;","#endif","#ifdef USE_UV3"," attribute vec2 uv3;","#endif","#ifdef USE_TANGENT"," attribute vec4 tangent;","#endif","#if defined( USE_COLOR_ALPHA )"," attribute vec4 color;","#elif defined( USE_COLOR )"," attribute vec3 color;","#endif","#ifdef USE_SKINNING"," attribute vec4 skinIndex;"," attribute vec4 skinWeight;","#endif",`
4036
4036
  `].filter(Zr).join(`
4037
- `),p=[Sm(t),"#define SHADER_TYPE "+t.shaderType,"#define SHADER_NAME "+t.shaderName,g,t.useFog&&t.fog?"#define USE_FOG":"",t.useFog&&t.fogExp2?"#define FOG_EXP2":"",t.alphaToCoverage?"#define ALPHA_TO_COVERAGE":"",t.map?"#define USE_MAP":"",t.matcap?"#define USE_MATCAP":"",t.envMap?"#define USE_ENVMAP":"",t.envMap?"#define "+l:"",t.envMap?"#define "+d:"",t.envMap?"#define "+u:"",h?"#define CUBEUV_TEXEL_WIDTH "+h.texelWidth:"",h?"#define CUBEUV_TEXEL_HEIGHT "+h.texelHeight:"",h?"#define CUBEUV_MAX_MIP "+h.maxMip+".0":"",t.lightMap?"#define USE_LIGHTMAP":"",t.aoMap?"#define USE_AOMAP":"",t.bumpMap?"#define USE_BUMPMAP":"",t.normalMap?"#define USE_NORMALMAP":"",t.normalMapObjectSpace?"#define USE_NORMALMAP_OBJECTSPACE":"",t.normalMapTangentSpace?"#define USE_NORMALMAP_TANGENTSPACE":"",t.emissiveMap?"#define USE_EMISSIVEMAP":"",t.anisotropy?"#define USE_ANISOTROPY":"",t.anisotropyMap?"#define USE_ANISOTROPYMAP":"",t.clearcoat?"#define USE_CLEARCOAT":"",t.clearcoatMap?"#define USE_CLEARCOATMAP":"",t.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",t.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",t.dispersion?"#define USE_DISPERSION":"",t.iridescence?"#define USE_IRIDESCENCE":"",t.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",t.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",t.specularMap?"#define USE_SPECULARMAP":"",t.specularColorMap?"#define USE_SPECULAR_COLORMAP":"",t.specularIntensityMap?"#define USE_SPECULAR_INTENSITYMAP":"",t.roughnessMap?"#define USE_ROUGHNESSMAP":"",t.metalnessMap?"#define USE_METALNESSMAP":"",t.alphaMap?"#define USE_ALPHAMAP":"",t.alphaTest?"#define USE_ALPHATEST":"",t.alphaHash?"#define USE_ALPHAHASH":"",t.sheen?"#define USE_SHEEN":"",t.sheenColorMap?"#define USE_SHEEN_COLORMAP":"",t.sheenRoughnessMap?"#define USE_SHEEN_ROUGHNESSMAP":"",t.transmission?"#define USE_TRANSMISSION":"",t.transmissionMap?"#define USE_TRANSMISSIONMAP":"",t.thicknessMap?"#define USE_THICKNESSMAP":"",t.vertexTangents&&t.flatShading===!1?"#define USE_TANGENT":"",t.vertexColors||t.instancingColor||t.batchingColor?"#define USE_COLOR":"",t.vertexAlphas?"#define USE_COLOR_ALPHA":"",t.vertexUv1s?"#define USE_UV1":"",t.vertexUv2s?"#define USE_UV2":"",t.vertexUv3s?"#define USE_UV3":"",t.pointsUvs?"#define USE_POINTS_UV":"",t.gradientMap?"#define USE_GRADIENTMAP":"",t.flatShading?"#define FLAT_SHADED":"",t.doubleSided?"#define DOUBLE_SIDED":"",t.flipSided?"#define FLIP_SIDED":"",t.shadowMapEnabled?"#define USE_SHADOWMAP":"",t.shadowMapEnabled?"#define "+c:"",t.premultipliedAlpha?"#define PREMULTIPLIED_ALPHA":"",t.numLightProbes>0?"#define USE_LIGHT_PROBES":"",t.decodeVideoTexture?"#define DECODE_VIDEO_TEXTURE":"",t.decodeVideoTextureEmissive?"#define DECODE_VIDEO_TEXTURE_EMISSIVE":"",t.logarithmicDepthBuffer?"#define USE_LOGARITHMIC_DEPTH_BUFFER":"",t.reversedDepthBuffer?"#define USE_REVERSED_DEPTH_BUFFER":"","uniform mat4 viewMatrix;","uniform vec3 cameraPosition;","uniform bool isOrthographic;",t.toneMapping!==Kn?"#define TONE_MAPPING":"",t.toneMapping!==Kn?He.tonemapping_pars_fragment:"",t.toneMapping!==Kn?FT("toneMapping",t.toneMapping):"",t.dithering?"#define DITHERING":"",t.opaque?"#define OPAQUE":"",He.colorspace_pars_fragment,UT("linearToOutputTexel",t.outputColorSpace),BT(),t.useDepthPacking?"#define DEPTH_PACKING "+t.depthPacking:"",`
4037
+ `),p=[Sm(t),"#define SHADER_TYPE "+t.shaderType,"#define SHADER_NAME "+t.shaderName,g,t.useFog&&t.fog?"#define USE_FOG":"",t.useFog&&t.fogExp2?"#define FOG_EXP2":"",t.alphaToCoverage?"#define ALPHA_TO_COVERAGE":"",t.map?"#define USE_MAP":"",t.matcap?"#define USE_MATCAP":"",t.envMap?"#define USE_ENVMAP":"",t.envMap?"#define "+l:"",t.envMap?"#define "+d:"",t.envMap?"#define "+u:"",h?"#define CUBEUV_TEXEL_WIDTH "+h.texelWidth:"",h?"#define CUBEUV_TEXEL_HEIGHT "+h.texelHeight:"",h?"#define CUBEUV_MAX_MIP "+h.maxMip+".0":"",t.lightMap?"#define USE_LIGHTMAP":"",t.aoMap?"#define USE_AOMAP":"",t.bumpMap?"#define USE_BUMPMAP":"",t.normalMap?"#define USE_NORMALMAP":"",t.normalMapObjectSpace?"#define USE_NORMALMAP_OBJECTSPACE":"",t.normalMapTangentSpace?"#define USE_NORMALMAP_TANGENTSPACE":"",t.emissiveMap?"#define USE_EMISSIVEMAP":"",t.anisotropy?"#define USE_ANISOTROPY":"",t.anisotropyMap?"#define USE_ANISOTROPYMAP":"",t.clearcoat?"#define USE_CLEARCOAT":"",t.clearcoatMap?"#define USE_CLEARCOATMAP":"",t.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",t.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",t.dispersion?"#define USE_DISPERSION":"",t.iridescence?"#define USE_IRIDESCENCE":"",t.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",t.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",t.specularMap?"#define USE_SPECULARMAP":"",t.specularColorMap?"#define USE_SPECULAR_COLORMAP":"",t.specularIntensityMap?"#define USE_SPECULAR_INTENSITYMAP":"",t.roughnessMap?"#define USE_ROUGHNESSMAP":"",t.metalnessMap?"#define USE_METALNESSMAP":"",t.alphaMap?"#define USE_ALPHAMAP":"",t.alphaTest?"#define USE_ALPHATEST":"",t.alphaHash?"#define USE_ALPHAHASH":"",t.sheen?"#define USE_SHEEN":"",t.sheenColorMap?"#define USE_SHEEN_COLORMAP":"",t.sheenRoughnessMap?"#define USE_SHEEN_ROUGHNESSMAP":"",t.transmission?"#define USE_TRANSMISSION":"",t.transmissionMap?"#define USE_TRANSMISSIONMAP":"",t.thicknessMap?"#define USE_THICKNESSMAP":"",t.vertexTangents&&t.flatShading===!1?"#define USE_TANGENT":"",t.vertexColors||t.instancingColor||t.batchingColor?"#define USE_COLOR":"",t.vertexAlphas?"#define USE_COLOR_ALPHA":"",t.vertexUv1s?"#define USE_UV1":"",t.vertexUv2s?"#define USE_UV2":"",t.vertexUv3s?"#define USE_UV3":"",t.pointsUvs?"#define USE_POINTS_UV":"",t.gradientMap?"#define USE_GRADIENTMAP":"",t.flatShading?"#define FLAT_SHADED":"",t.doubleSided?"#define DOUBLE_SIDED":"",t.flipSided?"#define FLIP_SIDED":"",t.shadowMapEnabled?"#define USE_SHADOWMAP":"",t.shadowMapEnabled?"#define "+c:"",t.premultipliedAlpha?"#define PREMULTIPLIED_ALPHA":"",t.numLightProbes>0?"#define USE_LIGHT_PROBES":"",t.decodeVideoTexture?"#define DECODE_VIDEO_TEXTURE":"",t.decodeVideoTextureEmissive?"#define DECODE_VIDEO_TEXTURE_EMISSIVE":"",t.logarithmicDepthBuffer?"#define USE_LOGARITHMIC_DEPTH_BUFFER":"",t.reversedDepthBuffer?"#define USE_REVERSED_DEPTH_BUFFER":"","uniform mat4 viewMatrix;","uniform vec3 cameraPosition;","uniform bool isOrthographic;",t.toneMapping!==Yn?"#define TONE_MAPPING":"",t.toneMapping!==Yn?He.tonemapping_pars_fragment:"",t.toneMapping!==Yn?FT("toneMapping",t.toneMapping):"",t.dithering?"#define DITHERING":"",t.opaque?"#define OPAQUE":"",He.colorspace_pars_fragment,UT("linearToOutputTexel",t.outputColorSpace),BT(),t.useDepthPacking?"#define DEPTH_PACKING "+t.depthPacking:"",`
4038
4038
  `].filter(Zr).join(`
4039
4039
  `)),a=Od(a),a=bm(a,t),a=_m(a,t),o=Od(o),o=bm(o,t),o=_m(o,t),a=ym(a),o=ym(o),t.isRawShaderMaterial!==!0&&(x=`#version 300 es
4040
4040
  `,m=[f,"#define attribute in","#define varying out","#define texture2D texture"].join(`
@@ -4048,7 +4048,7 @@ Material Type: `+R.type+`
4048
4048
 
4049
4049
  Program Info Log: `+K+`
4050
4050
  `+de+`
4051
- `+_e)}else K!==""?Oe("WebGLProgram: Program Info Log:",K):(H===""||W==="")&&(ve=!1);ve&&(R.diagnostics={runnable:te,programLog:K,vertexShader:{log:H,prefix:m},fragmentShader:{log:W,prefix:p}})}s.deleteShader(S),s.deleteShader(M),k=new go(s,v),y=GT(s,v)}let k;this.getUniforms=function(){return k===void 0&&A(this),k};let y;this.getAttributes=function(){return y===void 0&&A(this),y};let T=t.rendererExtensionParallelShaderCompile===!1;return this.isReady=function(){return T===!1&&(T=s.getProgramParameter(v,IT)),T},this.destroy=function(){n.releaseStatesOfProgram(this),s.deleteProgram(v),this.program=void 0},this.type=t.shaderType,this.name=t.shaderName,this.id=DT++,this.cacheKey=e,this.usedTimes=1,this.program=v,this.vertexShader=S,this.fragmentShader=M,this}let sC=0;class rC{constructor(){this.shaderCache=new Map,this.materialCache=new Map}update(e){const t=e.vertexShader,n=e.fragmentShader,s=this._getShaderStage(t),r=this._getShaderStage(n),a=this._getShaderCacheForMaterial(e);return a.has(s)===!1&&(a.add(s),s.usedTimes++),a.has(r)===!1&&(a.add(r),r.usedTimes++),this}remove(e){const t=this.materialCache.get(e);for(const n of t)n.usedTimes--,n.usedTimes===0&&this.shaderCache.delete(n.code);return this.materialCache.delete(e),this}getVertexShaderID(e){return this._getShaderStage(e.vertexShader).id}getFragmentShaderID(e){return this._getShaderStage(e.fragmentShader).id}dispose(){this.shaderCache.clear(),this.materialCache.clear()}_getShaderCacheForMaterial(e){const t=this.materialCache;let n=t.get(e);return n===void 0&&(n=new Set,t.set(e,n)),n}_getShaderStage(e){const t=this.shaderCache;let n=t.get(e);return n===void 0&&(n=new aC(e),t.set(e,n)),n}}class aC{constructor(e){this.id=sC++,this.code=e,this.usedTimes=0}}function oC(i,e,t,n,s,r,a){const o=new Ap,c=new rC,l=new Set,d=[],u=new Map,h=s.logarithmicDepthBuffer;let f=s.precision;const g={MeshDepthMaterial:"depth",MeshDistanceMaterial:"distance",MeshNormalMaterial:"normal",MeshBasicMaterial:"basic",MeshLambertMaterial:"lambert",MeshPhongMaterial:"phong",MeshToonMaterial:"toon",MeshStandardMaterial:"physical",MeshPhysicalMaterial:"physical",MeshMatcapMaterial:"matcap",LineBasicMaterial:"basic",LineDashedMaterial:"dashed",PointsMaterial:"points",ShadowMaterial:"shadow",SpriteMaterial:"sprite"};function v(y){return l.add(y),y===0?"uv":`uv${y}`}function m(y,T,R,U,B){const q=U.fog,K=B.geometry,H=y.isMeshStandardMaterial?U.environment:null,W=(y.isMeshStandardMaterial?t:e).get(y.envMap||H),te=W&&W.mapping===Oa?W.image.height:null,ve=g[y.type];y.precision!==null&&(f=s.getMaxPrecision(y.precision),f!==y.precision&&Oe("WebGLProgram.getParameters:",y.precision,"not supported, using",f,"instead."));const de=K.morphAttributes.position||K.morphAttributes.normal||K.morphAttributes.color,_e=de!==void 0?de.length:0;let Ve=0;K.morphAttributes.position!==void 0&&(Ve=1),K.morphAttributes.normal!==void 0&&(Ve=2),K.morphAttributes.color!==void 0&&(Ve=3);let Be,Ct,ht,X;if(ve){const lt=ti[ve];Be=lt.vertexShader,Ct=lt.fragmentShader}else Be=y.vertexShader,Ct=y.fragmentShader,c.update(y),ht=c.getVertexShaderID(y),X=c.getFragmentShaderID(y);const ie=i.getRenderTarget(),Ce=i.state.buffers.depth.getReversed(),Ge=B.isInstancedMesh===!0,we=B.isBatchedMesh===!0,nt=!!y.map,jt=!!y.matcap,et=!!W,ct=!!y.aoMap,bt=!!y.lightMap,qe=!!y.bumpMap,Ot=!!y.normalMap,I=!!y.displacementMap,Ft=!!y.emissiveMap,at=!!y.metalnessMap,yt=!!y.roughnessMap,Re=y.anisotropy>0,w=y.clearcoat>0,_=y.dispersion>0,L=y.iridescence>0,$=y.sheen>0,ee=y.transmission>0,j=Re&&!!y.anisotropyMap,ke=w&&!!y.clearcoatMap,he=w&&!!y.clearcoatNormalMap,Ae=w&&!!y.clearcoatRoughnessMap,Ue=L&&!!y.iridescenceMap,re=L&&!!y.iridescenceThicknessMap,pe=$&&!!y.sheenColorMap,Me=$&&!!y.sheenRoughnessMap,Pe=!!y.specularMap,fe=!!y.specularColorMap,je=!!y.specularIntensityMap,D=ee&&!!y.transmissionMap,ye=ee&&!!y.thicknessMap,oe=!!y.gradientMap,xe=!!y.alphaMap,se=y.alphaTest>0,Q=!!y.alphaHash,ue=!!y.extensions;let Fe=Kn;y.toneMapped&&(ie===null||ie.isXRRenderTarget===!0)&&(Fe=i.toneMapping);const St={shaderID:ve,shaderType:y.type,shaderName:y.name,vertexShader:Be,fragmentShader:Ct,defines:y.defines,customVertexShaderID:ht,customFragmentShaderID:X,isRawShaderMaterial:y.isRawShaderMaterial===!0,glslVersion:y.glslVersion,precision:f,batching:we,batchingColor:we&&B._colorsTexture!==null,instancing:Ge,instancingColor:Ge&&B.instanceColor!==null,instancingMorph:Ge&&B.morphTexture!==null,outputColorSpace:ie===null?i.outputColorSpace:ie.isXRRenderTarget===!0?ie.texture.colorSpace:Ws,alphaToCoverage:!!y.alphaToCoverage,map:nt,matcap:jt,envMap:et,envMapMode:et&&W.mapping,envMapCubeUVHeight:te,aoMap:ct,lightMap:bt,bumpMap:qe,normalMap:Ot,displacementMap:I,emissiveMap:Ft,normalMapObjectSpace:Ot&&y.normalMapType===R_,normalMapTangentSpace:Ot&&y.normalMapType===A_,metalnessMap:at,roughnessMap:yt,anisotropy:Re,anisotropyMap:j,clearcoat:w,clearcoatMap:ke,clearcoatNormalMap:he,clearcoatRoughnessMap:Ae,dispersion:_,iridescence:L,iridescenceMap:Ue,iridescenceThicknessMap:re,sheen:$,sheenColorMap:pe,sheenRoughnessMap:Me,specularMap:Pe,specularColorMap:fe,specularIntensityMap:je,transmission:ee,transmissionMap:D,thicknessMap:ye,gradientMap:oe,opaque:y.transparent===!1&&y.blending===Vs&&y.alphaToCoverage===!1,alphaMap:xe,alphaTest:se,alphaHash:Q,combine:y.combine,mapUv:nt&&v(y.map.channel),aoMapUv:ct&&v(y.aoMap.channel),lightMapUv:bt&&v(y.lightMap.channel),bumpMapUv:qe&&v(y.bumpMap.channel),normalMapUv:Ot&&v(y.normalMap.channel),displacementMapUv:I&&v(y.displacementMap.channel),emissiveMapUv:Ft&&v(y.emissiveMap.channel),metalnessMapUv:at&&v(y.metalnessMap.channel),roughnessMapUv:yt&&v(y.roughnessMap.channel),anisotropyMapUv:j&&v(y.anisotropyMap.channel),clearcoatMapUv:ke&&v(y.clearcoatMap.channel),clearcoatNormalMapUv:he&&v(y.clearcoatNormalMap.channel),clearcoatRoughnessMapUv:Ae&&v(y.clearcoatRoughnessMap.channel),iridescenceMapUv:Ue&&v(y.iridescenceMap.channel),iridescenceThicknessMapUv:re&&v(y.iridescenceThicknessMap.channel),sheenColorMapUv:pe&&v(y.sheenColorMap.channel),sheenRoughnessMapUv:Me&&v(y.sheenRoughnessMap.channel),specularMapUv:Pe&&v(y.specularMap.channel),specularColorMapUv:fe&&v(y.specularColorMap.channel),specularIntensityMapUv:je&&v(y.specularIntensityMap.channel),transmissionMapUv:D&&v(y.transmissionMap.channel),thicknessMapUv:ye&&v(y.thicknessMap.channel),alphaMapUv:xe&&v(y.alphaMap.channel),vertexTangents:!!K.attributes.tangent&&(Ot||Re),vertexColors:y.vertexColors,vertexAlphas:y.vertexColors===!0&&!!K.attributes.color&&K.attributes.color.itemSize===4,pointsUvs:B.isPoints===!0&&!!K.attributes.uv&&(nt||xe),fog:!!q,useFog:y.fog===!0,fogExp2:!!q&&q.isFogExp2,flatShading:y.flatShading===!0&&y.wireframe===!1,sizeAttenuation:y.sizeAttenuation===!0,logarithmicDepthBuffer:h,reversedDepthBuffer:Ce,skinning:B.isSkinnedMesh===!0,morphTargets:K.morphAttributes.position!==void 0,morphNormals:K.morphAttributes.normal!==void 0,morphColors:K.morphAttributes.color!==void 0,morphTargetsCount:_e,morphTextureStride:Ve,numDirLights:T.directional.length,numPointLights:T.point.length,numSpotLights:T.spot.length,numSpotLightMaps:T.spotLightMap.length,numRectAreaLights:T.rectArea.length,numHemiLights:T.hemi.length,numDirLightShadows:T.directionalShadowMap.length,numPointLightShadows:T.pointShadowMap.length,numSpotLightShadows:T.spotShadowMap.length,numSpotLightShadowsWithMaps:T.numSpotLightShadowsWithMaps,numLightProbes:T.numLightProbes,numClippingPlanes:a.numPlanes,numClipIntersection:a.numIntersection,dithering:y.dithering,shadowMapEnabled:i.shadowMap.enabled&&R.length>0,shadowMapType:i.shadowMap.type,toneMapping:Fe,decodeVideoTexture:nt&&y.map.isVideoTexture===!0&&Qe.getTransfer(y.map.colorSpace)===ot,decodeVideoTextureEmissive:Ft&&y.emissiveMap.isVideoTexture===!0&&Qe.getTransfer(y.emissiveMap.colorSpace)===ot,premultipliedAlpha:y.premultipliedAlpha,doubleSided:y.side===gi,flipSided:y.side===Zt,useDepthPacking:y.depthPacking>=0,depthPacking:y.depthPacking||0,index0AttributeName:y.index0AttributeName,extensionClipCullDistance:ue&&y.extensions.clipCullDistance===!0&&n.has("WEBGL_clip_cull_distance"),extensionMultiDraw:(ue&&y.extensions.multiDraw===!0||we)&&n.has("WEBGL_multi_draw"),rendererExtensionParallelShaderCompile:n.has("KHR_parallel_shader_compile"),customProgramCacheKey:y.customProgramCacheKey()};return St.vertexUv1s=l.has(1),St.vertexUv2s=l.has(2),St.vertexUv3s=l.has(3),l.clear(),St}function p(y){const T=[];if(y.shaderID?T.push(y.shaderID):(T.push(y.customVertexShaderID),T.push(y.customFragmentShaderID)),y.defines!==void 0)for(const R in y.defines)T.push(R),T.push(y.defines[R]);return y.isRawShaderMaterial===!1&&(x(T,y),C(T,y),T.push(i.outputColorSpace)),T.push(y.customProgramCacheKey),T.join()}function x(y,T){y.push(T.precision),y.push(T.outputColorSpace),y.push(T.envMapMode),y.push(T.envMapCubeUVHeight),y.push(T.mapUv),y.push(T.alphaMapUv),y.push(T.lightMapUv),y.push(T.aoMapUv),y.push(T.bumpMapUv),y.push(T.normalMapUv),y.push(T.displacementMapUv),y.push(T.emissiveMapUv),y.push(T.metalnessMapUv),y.push(T.roughnessMapUv),y.push(T.anisotropyMapUv),y.push(T.clearcoatMapUv),y.push(T.clearcoatNormalMapUv),y.push(T.clearcoatRoughnessMapUv),y.push(T.iridescenceMapUv),y.push(T.iridescenceThicknessMapUv),y.push(T.sheenColorMapUv),y.push(T.sheenRoughnessMapUv),y.push(T.specularMapUv),y.push(T.specularColorMapUv),y.push(T.specularIntensityMapUv),y.push(T.transmissionMapUv),y.push(T.thicknessMapUv),y.push(T.combine),y.push(T.fogExp2),y.push(T.sizeAttenuation),y.push(T.morphTargetsCount),y.push(T.morphAttributeCount),y.push(T.numDirLights),y.push(T.numPointLights),y.push(T.numSpotLights),y.push(T.numSpotLightMaps),y.push(T.numHemiLights),y.push(T.numRectAreaLights),y.push(T.numDirLightShadows),y.push(T.numPointLightShadows),y.push(T.numSpotLightShadows),y.push(T.numSpotLightShadowsWithMaps),y.push(T.numLightProbes),y.push(T.shadowMapType),y.push(T.toneMapping),y.push(T.numClippingPlanes),y.push(T.numClipIntersection),y.push(T.depthPacking)}function C(y,T){o.disableAll(),T.instancing&&o.enable(0),T.instancingColor&&o.enable(1),T.instancingMorph&&o.enable(2),T.matcap&&o.enable(3),T.envMap&&o.enable(4),T.normalMapObjectSpace&&o.enable(5),T.normalMapTangentSpace&&o.enable(6),T.clearcoat&&o.enable(7),T.iridescence&&o.enable(8),T.alphaTest&&o.enable(9),T.vertexColors&&o.enable(10),T.vertexAlphas&&o.enable(11),T.vertexUv1s&&o.enable(12),T.vertexUv2s&&o.enable(13),T.vertexUv3s&&o.enable(14),T.vertexTangents&&o.enable(15),T.anisotropy&&o.enable(16),T.alphaHash&&o.enable(17),T.batching&&o.enable(18),T.dispersion&&o.enable(19),T.batchingColor&&o.enable(20),T.gradientMap&&o.enable(21),y.push(o.mask),o.disableAll(),T.fog&&o.enable(0),T.useFog&&o.enable(1),T.flatShading&&o.enable(2),T.logarithmicDepthBuffer&&o.enable(3),T.reversedDepthBuffer&&o.enable(4),T.skinning&&o.enable(5),T.morphTargets&&o.enable(6),T.morphNormals&&o.enable(7),T.morphColors&&o.enable(8),T.premultipliedAlpha&&o.enable(9),T.shadowMapEnabled&&o.enable(10),T.doubleSided&&o.enable(11),T.flipSided&&o.enable(12),T.useDepthPacking&&o.enable(13),T.dithering&&o.enable(14),T.transmission&&o.enable(15),T.sheen&&o.enable(16),T.opaque&&o.enable(17),T.pointsUvs&&o.enable(18),T.decodeVideoTexture&&o.enable(19),T.decodeVideoTextureEmissive&&o.enable(20),T.alphaToCoverage&&o.enable(21),y.push(o.mask)}function b(y){const T=g[y.type];let R;if(T){const U=ti[T];R=sy.clone(U.uniforms)}else R=y.uniforms;return R}function S(y,T){let R=u.get(T);return R!==void 0?++R.usedTimes:(R=new iC(i,T,y,r),d.push(R),u.set(T,R)),R}function M(y){if(--y.usedTimes===0){const T=d.indexOf(y);d[T]=d[d.length-1],d.pop(),u.delete(y.cacheKey),y.destroy()}}function A(y){c.remove(y)}function k(){c.dispose()}return{getParameters:m,getProgramCacheKey:p,getUniforms:b,acquireProgram:S,releaseProgram:M,releaseShaderCache:A,programs:d,dispose:k}}function cC(){let i=new WeakMap;function e(a){return i.has(a)}function t(a){let o=i.get(a);return o===void 0&&(o={},i.set(a,o)),o}function n(a){i.delete(a)}function s(a,o,c){i.get(a)[o]=c}function r(){i=new WeakMap}return{has:e,get:t,remove:n,update:s,dispose:r}}function lC(i,e){return i.groupOrder!==e.groupOrder?i.groupOrder-e.groupOrder:i.renderOrder!==e.renderOrder?i.renderOrder-e.renderOrder:i.material.id!==e.material.id?i.material.id-e.material.id:i.z!==e.z?i.z-e.z:i.id-e.id}function xm(i,e){return i.groupOrder!==e.groupOrder?i.groupOrder-e.groupOrder:i.renderOrder!==e.renderOrder?i.renderOrder-e.renderOrder:i.z!==e.z?e.z-i.z:i.id-e.id}function Tm(){const i=[];let e=0;const t=[],n=[],s=[];function r(){e=0,t.length=0,n.length=0,s.length=0}function a(u,h,f,g,v,m){let p=i[e];return p===void 0?(p={id:u.id,object:u,geometry:h,material:f,groupOrder:g,renderOrder:u.renderOrder,z:v,group:m},i[e]=p):(p.id=u.id,p.object=u,p.geometry=h,p.material=f,p.groupOrder=g,p.renderOrder=u.renderOrder,p.z=v,p.group=m),e++,p}function o(u,h,f,g,v,m){const p=a(u,h,f,g,v,m);f.transmission>0?n.push(p):f.transparent===!0?s.push(p):t.push(p)}function c(u,h,f,g,v,m){const p=a(u,h,f,g,v,m);f.transmission>0?n.unshift(p):f.transparent===!0?s.unshift(p):t.unshift(p)}function l(u,h){t.length>1&&t.sort(u||lC),n.length>1&&n.sort(h||xm),s.length>1&&s.sort(h||xm)}function d(){for(let u=e,h=i.length;u<h;u++){const f=i[u];if(f.id===null)break;f.id=null,f.object=null,f.geometry=null,f.material=null,f.group=null}}return{opaque:t,transmissive:n,transparent:s,init:r,push:o,unshift:c,finish:d,sort:l}}function dC(){let i=new WeakMap;function e(n,s){const r=i.get(n);let a;return r===void 0?(a=new Tm,i.set(n,[a])):s>=r.length?(a=new Tm,r.push(a)):a=r[s],a}function t(){i=new WeakMap}return{get:e,dispose:t}}function uC(){const i={};return{get:function(e){if(i[e.id]!==void 0)return i[e.id];let t;switch(e.type){case"DirectionalLight":t={direction:new F,color:new Ze};break;case"SpotLight":t={position:new F,direction:new F,color:new Ze,distance:0,coneCos:0,penumbraCos:0,decay:0};break;case"PointLight":t={position:new F,color:new Ze,distance:0,decay:0};break;case"HemisphereLight":t={direction:new F,skyColor:new Ze,groundColor:new Ze};break;case"RectAreaLight":t={color:new Ze,position:new F,halfWidth:new F,halfHeight:new F};break}return i[e.id]=t,t}}}function hC(){const i={};return{get:function(e){if(i[e.id]!==void 0)return i[e.id];let t;switch(e.type){case"DirectionalLight":t={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new rt};break;case"SpotLight":t={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new rt};break;case"PointLight":t={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new rt,shadowCameraNear:1,shadowCameraFar:1e3};break}return i[e.id]=t,t}}}let fC=0;function pC(i,e){return(e.castShadow?2:0)-(i.castShadow?2:0)+(e.map?1:0)-(i.map?1:0)}function mC(i){const e=new uC,t=hC(),n={version:0,hash:{directionalLength:-1,pointLength:-1,spotLength:-1,rectAreaLength:-1,hemiLength:-1,numDirectionalShadows:-1,numPointShadows:-1,numSpotShadows:-1,numSpotMaps:-1,numLightProbes:-1},ambient:[0,0,0],probe:[],directional:[],directionalShadow:[],directionalShadowMap:[],directionalShadowMatrix:[],spot:[],spotLightMap:[],spotShadow:[],spotShadowMap:[],spotLightMatrix:[],rectArea:[],rectAreaLTC1:null,rectAreaLTC2:null,point:[],pointShadow:[],pointShadowMap:[],pointShadowMatrix:[],hemi:[],numSpotLightShadowsWithMaps:0,numLightProbes:0};for(let l=0;l<9;l++)n.probe.push(new F);const s=new F,r=new Nt,a=new Nt;function o(l){let d=0,u=0,h=0;for(let y=0;y<9;y++)n.probe[y].set(0,0,0);let f=0,g=0,v=0,m=0,p=0,x=0,C=0,b=0,S=0,M=0,A=0;l.sort(pC);for(let y=0,T=l.length;y<T;y++){const R=l[y],U=R.color,B=R.intensity,q=R.distance;let K=null;if(R.shadow&&R.shadow.map&&(R.shadow.map.texture.format===Hs?K=R.shadow.map.texture:K=R.shadow.map.depthTexture||R.shadow.map.texture),R.isAmbientLight)d+=U.r*B,u+=U.g*B,h+=U.b*B;else if(R.isLightProbe){for(let H=0;H<9;H++)n.probe[H].addScaledVector(R.sh.coefficients[H],B);A++}else if(R.isDirectionalLight){const H=e.get(R);if(H.color.copy(R.color).multiplyScalar(R.intensity),R.castShadow){const W=R.shadow,te=t.get(R);te.shadowIntensity=W.intensity,te.shadowBias=W.bias,te.shadowNormalBias=W.normalBias,te.shadowRadius=W.radius,te.shadowMapSize=W.mapSize,n.directionalShadow[f]=te,n.directionalShadowMap[f]=K,n.directionalShadowMatrix[f]=R.shadow.matrix,x++}n.directional[f]=H,f++}else if(R.isSpotLight){const H=e.get(R);H.position.setFromMatrixPosition(R.matrixWorld),H.color.copy(U).multiplyScalar(B),H.distance=q,H.coneCos=Math.cos(R.angle),H.penumbraCos=Math.cos(R.angle*(1-R.penumbra)),H.decay=R.decay,n.spot[v]=H;const W=R.shadow;if(R.map&&(n.spotLightMap[S]=R.map,S++,W.updateMatrices(R),R.castShadow&&M++),n.spotLightMatrix[v]=W.matrix,R.castShadow){const te=t.get(R);te.shadowIntensity=W.intensity,te.shadowBias=W.bias,te.shadowNormalBias=W.normalBias,te.shadowRadius=W.radius,te.shadowMapSize=W.mapSize,n.spotShadow[v]=te,n.spotShadowMap[v]=K,b++}v++}else if(R.isRectAreaLight){const H=e.get(R);H.color.copy(U).multiplyScalar(B),H.halfWidth.set(R.width*.5,0,0),H.halfHeight.set(0,R.height*.5,0),n.rectArea[m]=H,m++}else if(R.isPointLight){const H=e.get(R);if(H.color.copy(R.color).multiplyScalar(R.intensity),H.distance=R.distance,H.decay=R.decay,R.castShadow){const W=R.shadow,te=t.get(R);te.shadowIntensity=W.intensity,te.shadowBias=W.bias,te.shadowNormalBias=W.normalBias,te.shadowRadius=W.radius,te.shadowMapSize=W.mapSize,te.shadowCameraNear=W.camera.near,te.shadowCameraFar=W.camera.far,n.pointShadow[g]=te,n.pointShadowMap[g]=K,n.pointShadowMatrix[g]=R.shadow.matrix,C++}n.point[g]=H,g++}else if(R.isHemisphereLight){const H=e.get(R);H.skyColor.copy(R.color).multiplyScalar(B),H.groundColor.copy(R.groundColor).multiplyScalar(B),n.hemi[p]=H,p++}}m>0&&(i.has("OES_texture_float_linear")===!0?(n.rectAreaLTC1=ge.LTC_FLOAT_1,n.rectAreaLTC2=ge.LTC_FLOAT_2):(n.rectAreaLTC1=ge.LTC_HALF_1,n.rectAreaLTC2=ge.LTC_HALF_2)),n.ambient[0]=d,n.ambient[1]=u,n.ambient[2]=h;const k=n.hash;(k.directionalLength!==f||k.pointLength!==g||k.spotLength!==v||k.rectAreaLength!==m||k.hemiLength!==p||k.numDirectionalShadows!==x||k.numPointShadows!==C||k.numSpotShadows!==b||k.numSpotMaps!==S||k.numLightProbes!==A)&&(n.directional.length=f,n.spot.length=v,n.rectArea.length=m,n.point.length=g,n.hemi.length=p,n.directionalShadow.length=x,n.directionalShadowMap.length=x,n.pointShadow.length=C,n.pointShadowMap.length=C,n.spotShadow.length=b,n.spotShadowMap.length=b,n.directionalShadowMatrix.length=x,n.pointShadowMatrix.length=C,n.spotLightMatrix.length=b+S-M,n.spotLightMap.length=S,n.numSpotLightShadowsWithMaps=M,n.numLightProbes=A,k.directionalLength=f,k.pointLength=g,k.spotLength=v,k.rectAreaLength=m,k.hemiLength=p,k.numDirectionalShadows=x,k.numPointShadows=C,k.numSpotShadows=b,k.numSpotMaps=S,k.numLightProbes=A,n.version=fC++)}function c(l,d){let u=0,h=0,f=0,g=0,v=0;const m=d.matrixWorldInverse;for(let p=0,x=l.length;p<x;p++){const C=l[p];if(C.isDirectionalLight){const b=n.directional[u];b.direction.setFromMatrixPosition(C.matrixWorld),s.setFromMatrixPosition(C.target.matrixWorld),b.direction.sub(s),b.direction.transformDirection(m),u++}else if(C.isSpotLight){const b=n.spot[f];b.position.setFromMatrixPosition(C.matrixWorld),b.position.applyMatrix4(m),b.direction.setFromMatrixPosition(C.matrixWorld),s.setFromMatrixPosition(C.target.matrixWorld),b.direction.sub(s),b.direction.transformDirection(m),f++}else if(C.isRectAreaLight){const b=n.rectArea[g];b.position.setFromMatrixPosition(C.matrixWorld),b.position.applyMatrix4(m),a.identity(),r.copy(C.matrixWorld),r.premultiply(m),a.extractRotation(r),b.halfWidth.set(C.width*.5,0,0),b.halfHeight.set(0,C.height*.5,0),b.halfWidth.applyMatrix4(a),b.halfHeight.applyMatrix4(a),g++}else if(C.isPointLight){const b=n.point[h];b.position.setFromMatrixPosition(C.matrixWorld),b.position.applyMatrix4(m),h++}else if(C.isHemisphereLight){const b=n.hemi[v];b.direction.setFromMatrixPosition(C.matrixWorld),b.direction.transformDirection(m),v++}}}return{setup:o,setupView:c,state:n}}function Cm(i){const e=new mC(i),t=[],n=[];function s(d){l.camera=d,t.length=0,n.length=0}function r(d){t.push(d)}function a(d){n.push(d)}function o(){e.setup(t)}function c(d){e.setupView(t,d)}const l={lightsArray:t,shadowsArray:n,camera:null,lights:e,transmissionRenderTarget:{}};return{init:s,state:l,setupLights:o,setupLightsView:c,pushLight:r,pushShadow:a}}function gC(i){let e=new WeakMap;function t(s,r=0){const a=e.get(s);let o;return a===void 0?(o=new Cm(i),e.set(s,[o])):r>=a.length?(o=new Cm(i),a.push(o)):o=a[r],o}function n(){e=new WeakMap}return{get:t,dispose:n}}const vC=`void main() {
4051
+ `+_e)}else K!==""?Oe("WebGLProgram: Program Info Log:",K):(H===""||W==="")&&(ve=!1);ve&&(R.diagnostics={runnable:te,programLog:K,vertexShader:{log:H,prefix:m},fragmentShader:{log:W,prefix:p}})}s.deleteShader(S),s.deleteShader(M),k=new go(s,v),y=GT(s,v)}let k;this.getUniforms=function(){return k===void 0&&A(this),k};let y;this.getAttributes=function(){return y===void 0&&A(this),y};let T=t.rendererExtensionParallelShaderCompile===!1;return this.isReady=function(){return T===!1&&(T=s.getProgramParameter(v,IT)),T},this.destroy=function(){n.releaseStatesOfProgram(this),s.deleteProgram(v),this.program=void 0},this.type=t.shaderType,this.name=t.shaderName,this.id=DT++,this.cacheKey=e,this.usedTimes=1,this.program=v,this.vertexShader=S,this.fragmentShader=M,this}let sC=0;class rC{constructor(){this.shaderCache=new Map,this.materialCache=new Map}update(e){const t=e.vertexShader,n=e.fragmentShader,s=this._getShaderStage(t),r=this._getShaderStage(n),a=this._getShaderCacheForMaterial(e);return a.has(s)===!1&&(a.add(s),s.usedTimes++),a.has(r)===!1&&(a.add(r),r.usedTimes++),this}remove(e){const t=this.materialCache.get(e);for(const n of t)n.usedTimes--,n.usedTimes===0&&this.shaderCache.delete(n.code);return this.materialCache.delete(e),this}getVertexShaderID(e){return this._getShaderStage(e.vertexShader).id}getFragmentShaderID(e){return this._getShaderStage(e.fragmentShader).id}dispose(){this.shaderCache.clear(),this.materialCache.clear()}_getShaderCacheForMaterial(e){const t=this.materialCache;let n=t.get(e);return n===void 0&&(n=new Set,t.set(e,n)),n}_getShaderStage(e){const t=this.shaderCache;let n=t.get(e);return n===void 0&&(n=new aC(e),t.set(e,n)),n}}class aC{constructor(e){this.id=sC++,this.code=e,this.usedTimes=0}}function oC(i,e,t,n,s,r,a){const o=new Ap,c=new rC,l=new Set,d=[],u=new Map,h=s.logarithmicDepthBuffer;let f=s.precision;const g={MeshDepthMaterial:"depth",MeshDistanceMaterial:"distance",MeshNormalMaterial:"normal",MeshBasicMaterial:"basic",MeshLambertMaterial:"lambert",MeshPhongMaterial:"phong",MeshToonMaterial:"toon",MeshStandardMaterial:"physical",MeshPhysicalMaterial:"physical",MeshMatcapMaterial:"matcap",LineBasicMaterial:"basic",LineDashedMaterial:"dashed",PointsMaterial:"points",ShadowMaterial:"shadow",SpriteMaterial:"sprite"};function v(y){return l.add(y),y===0?"uv":`uv${y}`}function m(y,T,R,U,B){const q=U.fog,K=B.geometry,H=y.isMeshStandardMaterial?U.environment:null,W=(y.isMeshStandardMaterial?t:e).get(y.envMap||H),te=W&&W.mapping===Oa?W.image.height:null,ve=g[y.type];y.precision!==null&&(f=s.getMaxPrecision(y.precision),f!==y.precision&&Oe("WebGLProgram.getParameters:",y.precision,"not supported, using",f,"instead."));const de=K.morphAttributes.position||K.morphAttributes.normal||K.morphAttributes.color,_e=de!==void 0?de.length:0;let Ve=0;K.morphAttributes.position!==void 0&&(Ve=1),K.morphAttributes.normal!==void 0&&(Ve=2),K.morphAttributes.color!==void 0&&(Ve=3);let Be,Ct,mt,X;if(ve){const lt=ni[ve];Be=lt.vertexShader,Ct=lt.fragmentShader}else Be=y.vertexShader,Ct=y.fragmentShader,c.update(y),mt=c.getVertexShaderID(y),X=c.getFragmentShaderID(y);const ie=i.getRenderTarget(),Ce=i.state.buffers.depth.getReversed(),Ge=B.isInstancedMesh===!0,we=B.isBatchedMesh===!0,nt=!!y.map,jt=!!y.matcap,et=!!W,ct=!!y.aoMap,bt=!!y.lightMap,qe=!!y.bumpMap,Ot=!!y.normalMap,I=!!y.displacementMap,Ft=!!y.emissiveMap,at=!!y.metalnessMap,yt=!!y.roughnessMap,Re=y.anisotropy>0,w=y.clearcoat>0,_=y.dispersion>0,L=y.iridescence>0,$=y.sheen>0,ee=y.transmission>0,j=Re&&!!y.anisotropyMap,ke=w&&!!y.clearcoatMap,he=w&&!!y.clearcoatNormalMap,Ae=w&&!!y.clearcoatRoughnessMap,Ue=L&&!!y.iridescenceMap,re=L&&!!y.iridescenceThicknessMap,pe=$&&!!y.sheenColorMap,Me=$&&!!y.sheenRoughnessMap,Pe=!!y.specularMap,fe=!!y.specularColorMap,je=!!y.specularIntensityMap,D=ee&&!!y.transmissionMap,ye=ee&&!!y.thicknessMap,oe=!!y.gradientMap,xe=!!y.alphaMap,se=y.alphaTest>0,Q=!!y.alphaHash,ue=!!y.extensions;let Fe=Yn;y.toneMapped&&(ie===null||ie.isXRRenderTarget===!0)&&(Fe=i.toneMapping);const St={shaderID:ve,shaderType:y.type,shaderName:y.name,vertexShader:Be,fragmentShader:Ct,defines:y.defines,customVertexShaderID:mt,customFragmentShaderID:X,isRawShaderMaterial:y.isRawShaderMaterial===!0,glslVersion:y.glslVersion,precision:f,batching:we,batchingColor:we&&B._colorsTexture!==null,instancing:Ge,instancingColor:Ge&&B.instanceColor!==null,instancingMorph:Ge&&B.morphTexture!==null,outputColorSpace:ie===null?i.outputColorSpace:ie.isXRRenderTarget===!0?ie.texture.colorSpace:Ws,alphaToCoverage:!!y.alphaToCoverage,map:nt,matcap:jt,envMap:et,envMapMode:et&&W.mapping,envMapCubeUVHeight:te,aoMap:ct,lightMap:bt,bumpMap:qe,normalMap:Ot,displacementMap:I,emissiveMap:Ft,normalMapObjectSpace:Ot&&y.normalMapType===R_,normalMapTangentSpace:Ot&&y.normalMapType===A_,metalnessMap:at,roughnessMap:yt,anisotropy:Re,anisotropyMap:j,clearcoat:w,clearcoatMap:ke,clearcoatNormalMap:he,clearcoatRoughnessMap:Ae,dispersion:_,iridescence:L,iridescenceMap:Ue,iridescenceThicknessMap:re,sheen:$,sheenColorMap:pe,sheenRoughnessMap:Me,specularMap:Pe,specularColorMap:fe,specularIntensityMap:je,transmission:ee,transmissionMap:D,thicknessMap:ye,gradientMap:oe,opaque:y.transparent===!1&&y.blending===Vs&&y.alphaToCoverage===!1,alphaMap:xe,alphaTest:se,alphaHash:Q,combine:y.combine,mapUv:nt&&v(y.map.channel),aoMapUv:ct&&v(y.aoMap.channel),lightMapUv:bt&&v(y.lightMap.channel),bumpMapUv:qe&&v(y.bumpMap.channel),normalMapUv:Ot&&v(y.normalMap.channel),displacementMapUv:I&&v(y.displacementMap.channel),emissiveMapUv:Ft&&v(y.emissiveMap.channel),metalnessMapUv:at&&v(y.metalnessMap.channel),roughnessMapUv:yt&&v(y.roughnessMap.channel),anisotropyMapUv:j&&v(y.anisotropyMap.channel),clearcoatMapUv:ke&&v(y.clearcoatMap.channel),clearcoatNormalMapUv:he&&v(y.clearcoatNormalMap.channel),clearcoatRoughnessMapUv:Ae&&v(y.clearcoatRoughnessMap.channel),iridescenceMapUv:Ue&&v(y.iridescenceMap.channel),iridescenceThicknessMapUv:re&&v(y.iridescenceThicknessMap.channel),sheenColorMapUv:pe&&v(y.sheenColorMap.channel),sheenRoughnessMapUv:Me&&v(y.sheenRoughnessMap.channel),specularMapUv:Pe&&v(y.specularMap.channel),specularColorMapUv:fe&&v(y.specularColorMap.channel),specularIntensityMapUv:je&&v(y.specularIntensityMap.channel),transmissionMapUv:D&&v(y.transmissionMap.channel),thicknessMapUv:ye&&v(y.thicknessMap.channel),alphaMapUv:xe&&v(y.alphaMap.channel),vertexTangents:!!K.attributes.tangent&&(Ot||Re),vertexColors:y.vertexColors,vertexAlphas:y.vertexColors===!0&&!!K.attributes.color&&K.attributes.color.itemSize===4,pointsUvs:B.isPoints===!0&&!!K.attributes.uv&&(nt||xe),fog:!!q,useFog:y.fog===!0,fogExp2:!!q&&q.isFogExp2,flatShading:y.flatShading===!0&&y.wireframe===!1,sizeAttenuation:y.sizeAttenuation===!0,logarithmicDepthBuffer:h,reversedDepthBuffer:Ce,skinning:B.isSkinnedMesh===!0,morphTargets:K.morphAttributes.position!==void 0,morphNormals:K.morphAttributes.normal!==void 0,morphColors:K.morphAttributes.color!==void 0,morphTargetsCount:_e,morphTextureStride:Ve,numDirLights:T.directional.length,numPointLights:T.point.length,numSpotLights:T.spot.length,numSpotLightMaps:T.spotLightMap.length,numRectAreaLights:T.rectArea.length,numHemiLights:T.hemi.length,numDirLightShadows:T.directionalShadowMap.length,numPointLightShadows:T.pointShadowMap.length,numSpotLightShadows:T.spotShadowMap.length,numSpotLightShadowsWithMaps:T.numSpotLightShadowsWithMaps,numLightProbes:T.numLightProbes,numClippingPlanes:a.numPlanes,numClipIntersection:a.numIntersection,dithering:y.dithering,shadowMapEnabled:i.shadowMap.enabled&&R.length>0,shadowMapType:i.shadowMap.type,toneMapping:Fe,decodeVideoTexture:nt&&y.map.isVideoTexture===!0&&Qe.getTransfer(y.map.colorSpace)===ot,decodeVideoTextureEmissive:Ft&&y.emissiveMap.isVideoTexture===!0&&Qe.getTransfer(y.emissiveMap.colorSpace)===ot,premultipliedAlpha:y.premultipliedAlpha,doubleSided:y.side===gi,flipSided:y.side===Zt,useDepthPacking:y.depthPacking>=0,depthPacking:y.depthPacking||0,index0AttributeName:y.index0AttributeName,extensionClipCullDistance:ue&&y.extensions.clipCullDistance===!0&&n.has("WEBGL_clip_cull_distance"),extensionMultiDraw:(ue&&y.extensions.multiDraw===!0||we)&&n.has("WEBGL_multi_draw"),rendererExtensionParallelShaderCompile:n.has("KHR_parallel_shader_compile"),customProgramCacheKey:y.customProgramCacheKey()};return St.vertexUv1s=l.has(1),St.vertexUv2s=l.has(2),St.vertexUv3s=l.has(3),l.clear(),St}function p(y){const T=[];if(y.shaderID?T.push(y.shaderID):(T.push(y.customVertexShaderID),T.push(y.customFragmentShaderID)),y.defines!==void 0)for(const R in y.defines)T.push(R),T.push(y.defines[R]);return y.isRawShaderMaterial===!1&&(x(T,y),C(T,y),T.push(i.outputColorSpace)),T.push(y.customProgramCacheKey),T.join()}function x(y,T){y.push(T.precision),y.push(T.outputColorSpace),y.push(T.envMapMode),y.push(T.envMapCubeUVHeight),y.push(T.mapUv),y.push(T.alphaMapUv),y.push(T.lightMapUv),y.push(T.aoMapUv),y.push(T.bumpMapUv),y.push(T.normalMapUv),y.push(T.displacementMapUv),y.push(T.emissiveMapUv),y.push(T.metalnessMapUv),y.push(T.roughnessMapUv),y.push(T.anisotropyMapUv),y.push(T.clearcoatMapUv),y.push(T.clearcoatNormalMapUv),y.push(T.clearcoatRoughnessMapUv),y.push(T.iridescenceMapUv),y.push(T.iridescenceThicknessMapUv),y.push(T.sheenColorMapUv),y.push(T.sheenRoughnessMapUv),y.push(T.specularMapUv),y.push(T.specularColorMapUv),y.push(T.specularIntensityMapUv),y.push(T.transmissionMapUv),y.push(T.thicknessMapUv),y.push(T.combine),y.push(T.fogExp2),y.push(T.sizeAttenuation),y.push(T.morphTargetsCount),y.push(T.morphAttributeCount),y.push(T.numDirLights),y.push(T.numPointLights),y.push(T.numSpotLights),y.push(T.numSpotLightMaps),y.push(T.numHemiLights),y.push(T.numRectAreaLights),y.push(T.numDirLightShadows),y.push(T.numPointLightShadows),y.push(T.numSpotLightShadows),y.push(T.numSpotLightShadowsWithMaps),y.push(T.numLightProbes),y.push(T.shadowMapType),y.push(T.toneMapping),y.push(T.numClippingPlanes),y.push(T.numClipIntersection),y.push(T.depthPacking)}function C(y,T){o.disableAll(),T.instancing&&o.enable(0),T.instancingColor&&o.enable(1),T.instancingMorph&&o.enable(2),T.matcap&&o.enable(3),T.envMap&&o.enable(4),T.normalMapObjectSpace&&o.enable(5),T.normalMapTangentSpace&&o.enable(6),T.clearcoat&&o.enable(7),T.iridescence&&o.enable(8),T.alphaTest&&o.enable(9),T.vertexColors&&o.enable(10),T.vertexAlphas&&o.enable(11),T.vertexUv1s&&o.enable(12),T.vertexUv2s&&o.enable(13),T.vertexUv3s&&o.enable(14),T.vertexTangents&&o.enable(15),T.anisotropy&&o.enable(16),T.alphaHash&&o.enable(17),T.batching&&o.enable(18),T.dispersion&&o.enable(19),T.batchingColor&&o.enable(20),T.gradientMap&&o.enable(21),y.push(o.mask),o.disableAll(),T.fog&&o.enable(0),T.useFog&&o.enable(1),T.flatShading&&o.enable(2),T.logarithmicDepthBuffer&&o.enable(3),T.reversedDepthBuffer&&o.enable(4),T.skinning&&o.enable(5),T.morphTargets&&o.enable(6),T.morphNormals&&o.enable(7),T.morphColors&&o.enable(8),T.premultipliedAlpha&&o.enable(9),T.shadowMapEnabled&&o.enable(10),T.doubleSided&&o.enable(11),T.flipSided&&o.enable(12),T.useDepthPacking&&o.enable(13),T.dithering&&o.enable(14),T.transmission&&o.enable(15),T.sheen&&o.enable(16),T.opaque&&o.enable(17),T.pointsUvs&&o.enable(18),T.decodeVideoTexture&&o.enable(19),T.decodeVideoTextureEmissive&&o.enable(20),T.alphaToCoverage&&o.enable(21),y.push(o.mask)}function b(y){const T=g[y.type];let R;if(T){const U=ni[T];R=sy.clone(U.uniforms)}else R=y.uniforms;return R}function S(y,T){let R=u.get(T);return R!==void 0?++R.usedTimes:(R=new iC(i,T,y,r),d.push(R),u.set(T,R)),R}function M(y){if(--y.usedTimes===0){const T=d.indexOf(y);d[T]=d[d.length-1],d.pop(),u.delete(y.cacheKey),y.destroy()}}function A(y){c.remove(y)}function k(){c.dispose()}return{getParameters:m,getProgramCacheKey:p,getUniforms:b,acquireProgram:S,releaseProgram:M,releaseShaderCache:A,programs:d,dispose:k}}function cC(){let i=new WeakMap;function e(a){return i.has(a)}function t(a){let o=i.get(a);return o===void 0&&(o={},i.set(a,o)),o}function n(a){i.delete(a)}function s(a,o,c){i.get(a)[o]=c}function r(){i=new WeakMap}return{has:e,get:t,remove:n,update:s,dispose:r}}function lC(i,e){return i.groupOrder!==e.groupOrder?i.groupOrder-e.groupOrder:i.renderOrder!==e.renderOrder?i.renderOrder-e.renderOrder:i.material.id!==e.material.id?i.material.id-e.material.id:i.z!==e.z?i.z-e.z:i.id-e.id}function xm(i,e){return i.groupOrder!==e.groupOrder?i.groupOrder-e.groupOrder:i.renderOrder!==e.renderOrder?i.renderOrder-e.renderOrder:i.z!==e.z?e.z-i.z:i.id-e.id}function Tm(){const i=[];let e=0;const t=[],n=[],s=[];function r(){e=0,t.length=0,n.length=0,s.length=0}function a(u,h,f,g,v,m){let p=i[e];return p===void 0?(p={id:u.id,object:u,geometry:h,material:f,groupOrder:g,renderOrder:u.renderOrder,z:v,group:m},i[e]=p):(p.id=u.id,p.object=u,p.geometry=h,p.material=f,p.groupOrder=g,p.renderOrder=u.renderOrder,p.z=v,p.group=m),e++,p}function o(u,h,f,g,v,m){const p=a(u,h,f,g,v,m);f.transmission>0?n.push(p):f.transparent===!0?s.push(p):t.push(p)}function c(u,h,f,g,v,m){const p=a(u,h,f,g,v,m);f.transmission>0?n.unshift(p):f.transparent===!0?s.unshift(p):t.unshift(p)}function l(u,h){t.length>1&&t.sort(u||lC),n.length>1&&n.sort(h||xm),s.length>1&&s.sort(h||xm)}function d(){for(let u=e,h=i.length;u<h;u++){const f=i[u];if(f.id===null)break;f.id=null,f.object=null,f.geometry=null,f.material=null,f.group=null}}return{opaque:t,transmissive:n,transparent:s,init:r,push:o,unshift:c,finish:d,sort:l}}function dC(){let i=new WeakMap;function e(n,s){const r=i.get(n);let a;return r===void 0?(a=new Tm,i.set(n,[a])):s>=r.length?(a=new Tm,r.push(a)):a=r[s],a}function t(){i=new WeakMap}return{get:e,dispose:t}}function uC(){const i={};return{get:function(e){if(i[e.id]!==void 0)return i[e.id];let t;switch(e.type){case"DirectionalLight":t={direction:new F,color:new Ze};break;case"SpotLight":t={position:new F,direction:new F,color:new Ze,distance:0,coneCos:0,penumbraCos:0,decay:0};break;case"PointLight":t={position:new F,color:new Ze,distance:0,decay:0};break;case"HemisphereLight":t={direction:new F,skyColor:new Ze,groundColor:new Ze};break;case"RectAreaLight":t={color:new Ze,position:new F,halfWidth:new F,halfHeight:new F};break}return i[e.id]=t,t}}}function hC(){const i={};return{get:function(e){if(i[e.id]!==void 0)return i[e.id];let t;switch(e.type){case"DirectionalLight":t={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new rt};break;case"SpotLight":t={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new rt};break;case"PointLight":t={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new rt,shadowCameraNear:1,shadowCameraFar:1e3};break}return i[e.id]=t,t}}}let fC=0;function pC(i,e){return(e.castShadow?2:0)-(i.castShadow?2:0)+(e.map?1:0)-(i.map?1:0)}function mC(i){const e=new uC,t=hC(),n={version:0,hash:{directionalLength:-1,pointLength:-1,spotLength:-1,rectAreaLength:-1,hemiLength:-1,numDirectionalShadows:-1,numPointShadows:-1,numSpotShadows:-1,numSpotMaps:-1,numLightProbes:-1},ambient:[0,0,0],probe:[],directional:[],directionalShadow:[],directionalShadowMap:[],directionalShadowMatrix:[],spot:[],spotLightMap:[],spotShadow:[],spotShadowMap:[],spotLightMatrix:[],rectArea:[],rectAreaLTC1:null,rectAreaLTC2:null,point:[],pointShadow:[],pointShadowMap:[],pointShadowMatrix:[],hemi:[],numSpotLightShadowsWithMaps:0,numLightProbes:0};for(let l=0;l<9;l++)n.probe.push(new F);const s=new F,r=new Nt,a=new Nt;function o(l){let d=0,u=0,h=0;for(let y=0;y<9;y++)n.probe[y].set(0,0,0);let f=0,g=0,v=0,m=0,p=0,x=0,C=0,b=0,S=0,M=0,A=0;l.sort(pC);for(let y=0,T=l.length;y<T;y++){const R=l[y],U=R.color,B=R.intensity,q=R.distance;let K=null;if(R.shadow&&R.shadow.map&&(R.shadow.map.texture.format===Hs?K=R.shadow.map.texture:K=R.shadow.map.depthTexture||R.shadow.map.texture),R.isAmbientLight)d+=U.r*B,u+=U.g*B,h+=U.b*B;else if(R.isLightProbe){for(let H=0;H<9;H++)n.probe[H].addScaledVector(R.sh.coefficients[H],B);A++}else if(R.isDirectionalLight){const H=e.get(R);if(H.color.copy(R.color).multiplyScalar(R.intensity),R.castShadow){const W=R.shadow,te=t.get(R);te.shadowIntensity=W.intensity,te.shadowBias=W.bias,te.shadowNormalBias=W.normalBias,te.shadowRadius=W.radius,te.shadowMapSize=W.mapSize,n.directionalShadow[f]=te,n.directionalShadowMap[f]=K,n.directionalShadowMatrix[f]=R.shadow.matrix,x++}n.directional[f]=H,f++}else if(R.isSpotLight){const H=e.get(R);H.position.setFromMatrixPosition(R.matrixWorld),H.color.copy(U).multiplyScalar(B),H.distance=q,H.coneCos=Math.cos(R.angle),H.penumbraCos=Math.cos(R.angle*(1-R.penumbra)),H.decay=R.decay,n.spot[v]=H;const W=R.shadow;if(R.map&&(n.spotLightMap[S]=R.map,S++,W.updateMatrices(R),R.castShadow&&M++),n.spotLightMatrix[v]=W.matrix,R.castShadow){const te=t.get(R);te.shadowIntensity=W.intensity,te.shadowBias=W.bias,te.shadowNormalBias=W.normalBias,te.shadowRadius=W.radius,te.shadowMapSize=W.mapSize,n.spotShadow[v]=te,n.spotShadowMap[v]=K,b++}v++}else if(R.isRectAreaLight){const H=e.get(R);H.color.copy(U).multiplyScalar(B),H.halfWidth.set(R.width*.5,0,0),H.halfHeight.set(0,R.height*.5,0),n.rectArea[m]=H,m++}else if(R.isPointLight){const H=e.get(R);if(H.color.copy(R.color).multiplyScalar(R.intensity),H.distance=R.distance,H.decay=R.decay,R.castShadow){const W=R.shadow,te=t.get(R);te.shadowIntensity=W.intensity,te.shadowBias=W.bias,te.shadowNormalBias=W.normalBias,te.shadowRadius=W.radius,te.shadowMapSize=W.mapSize,te.shadowCameraNear=W.camera.near,te.shadowCameraFar=W.camera.far,n.pointShadow[g]=te,n.pointShadowMap[g]=K,n.pointShadowMatrix[g]=R.shadow.matrix,C++}n.point[g]=H,g++}else if(R.isHemisphereLight){const H=e.get(R);H.skyColor.copy(R.color).multiplyScalar(B),H.groundColor.copy(R.groundColor).multiplyScalar(B),n.hemi[p]=H,p++}}m>0&&(i.has("OES_texture_float_linear")===!0?(n.rectAreaLTC1=ge.LTC_FLOAT_1,n.rectAreaLTC2=ge.LTC_FLOAT_2):(n.rectAreaLTC1=ge.LTC_HALF_1,n.rectAreaLTC2=ge.LTC_HALF_2)),n.ambient[0]=d,n.ambient[1]=u,n.ambient[2]=h;const k=n.hash;(k.directionalLength!==f||k.pointLength!==g||k.spotLength!==v||k.rectAreaLength!==m||k.hemiLength!==p||k.numDirectionalShadows!==x||k.numPointShadows!==C||k.numSpotShadows!==b||k.numSpotMaps!==S||k.numLightProbes!==A)&&(n.directional.length=f,n.spot.length=v,n.rectArea.length=m,n.point.length=g,n.hemi.length=p,n.directionalShadow.length=x,n.directionalShadowMap.length=x,n.pointShadow.length=C,n.pointShadowMap.length=C,n.spotShadow.length=b,n.spotShadowMap.length=b,n.directionalShadowMatrix.length=x,n.pointShadowMatrix.length=C,n.spotLightMatrix.length=b+S-M,n.spotLightMap.length=S,n.numSpotLightShadowsWithMaps=M,n.numLightProbes=A,k.directionalLength=f,k.pointLength=g,k.spotLength=v,k.rectAreaLength=m,k.hemiLength=p,k.numDirectionalShadows=x,k.numPointShadows=C,k.numSpotShadows=b,k.numSpotMaps=S,k.numLightProbes=A,n.version=fC++)}function c(l,d){let u=0,h=0,f=0,g=0,v=0;const m=d.matrixWorldInverse;for(let p=0,x=l.length;p<x;p++){const C=l[p];if(C.isDirectionalLight){const b=n.directional[u];b.direction.setFromMatrixPosition(C.matrixWorld),s.setFromMatrixPosition(C.target.matrixWorld),b.direction.sub(s),b.direction.transformDirection(m),u++}else if(C.isSpotLight){const b=n.spot[f];b.position.setFromMatrixPosition(C.matrixWorld),b.position.applyMatrix4(m),b.direction.setFromMatrixPosition(C.matrixWorld),s.setFromMatrixPosition(C.target.matrixWorld),b.direction.sub(s),b.direction.transformDirection(m),f++}else if(C.isRectAreaLight){const b=n.rectArea[g];b.position.setFromMatrixPosition(C.matrixWorld),b.position.applyMatrix4(m),a.identity(),r.copy(C.matrixWorld),r.premultiply(m),a.extractRotation(r),b.halfWidth.set(C.width*.5,0,0),b.halfHeight.set(0,C.height*.5,0),b.halfWidth.applyMatrix4(a),b.halfHeight.applyMatrix4(a),g++}else if(C.isPointLight){const b=n.point[h];b.position.setFromMatrixPosition(C.matrixWorld),b.position.applyMatrix4(m),h++}else if(C.isHemisphereLight){const b=n.hemi[v];b.direction.setFromMatrixPosition(C.matrixWorld),b.direction.transformDirection(m),v++}}}return{setup:o,setupView:c,state:n}}function Cm(i){const e=new mC(i),t=[],n=[];function s(d){l.camera=d,t.length=0,n.length=0}function r(d){t.push(d)}function a(d){n.push(d)}function o(){e.setup(t)}function c(d){e.setupView(t,d)}const l={lightsArray:t,shadowsArray:n,camera:null,lights:e,transmissionRenderTarget:{}};return{init:s,state:l,setupLights:o,setupLightsView:c,pushLight:r,pushShadow:a}}function gC(i){let e=new WeakMap;function t(s,r=0){const a=e.get(s);let o;return a===void 0?(o=new Cm(i),e.set(s,[o])):r>=a.length?(o=new Cm(i),a.push(o)):o=a[r],o}function n(){e=new WeakMap}return{get:t,dispose:n}}const vC=`void main() {
4052
4052
  gl_Position = vec4( position, 1.0 );
4053
4053
  }`,bC=`uniform sampler2D shadow_pass;
4054
4054
  uniform vec2 resolution;
@@ -4075,7 +4075,7 @@ void main() {
4075
4075
  squared_mean = squared_mean / samples;
4076
4076
  float std_dev = sqrt( max( 0.0, squared_mean - mean * mean ) );
4077
4077
  gl_FragColor = vec4( mean, std_dev, 0.0, 1.0 );
4078
- }`,_C=[new F(1,0,0),new F(-1,0,0),new F(0,1,0),new F(0,-1,0),new F(0,0,1),new F(0,0,-1)],yC=[new F(0,-1,0),new F(0,-1,0),new F(0,0,1),new F(0,0,-1),new F(0,-1,0),new F(0,-1,0)],Em=new Nt,Qr=new F,Fd=new F;function SC(i,e,t){let n=new Xp;const s=new rt,r=new rt,a=new It,o=new gy,c=new vy,l={},d=t.maxTextureSize,u={[mi]:Zt,[Zt]:mi,[gi]:gi},h=new Tn({defines:{VSM_SAMPLES:8},uniforms:{shadow_pass:{value:null},resolution:{value:new rt},radius:{value:4}},vertexShader:vC,fragmentShader:bC}),f=h.clone();f.defines.HORIZONTAL_PASS=1;const g=new Bn;g.setAttribute("position",new ei(new Float32Array([-1,-1,.5,3,-1,.5,-1,3,.5]),3));const v=new Vn(g,h),m=this;this.enabled=!1,this.autoUpdate=!0,this.needsUpdate=!1,this.type=Ua;let p=this.type;this.render=function(M,A,k){if(m.enabled===!1||m.autoUpdate===!1&&m.needsUpdate===!1||M.length===0)return;M.type===r_&&(Oe("WebGLShadowMap: PCFSoftShadowMap has been deprecated. Using PCFShadowMap instead."),M.type=Ua);const y=i.getRenderTarget(),T=i.getActiveCubeFace(),R=i.getActiveMipmapLevel(),U=i.state;U.setBlending(vi),U.buffers.depth.getReversed()===!0?U.buffers.color.setClear(0,0,0,0):U.buffers.color.setClear(1,1,1,1),U.buffers.depth.setTest(!0),U.setScissorTest(!1);const B=p!==this.type;B&&A.traverse(function(q){q.material&&(Array.isArray(q.material)?q.material.forEach(K=>K.needsUpdate=!0):q.material.needsUpdate=!0)});for(let q=0,K=M.length;q<K;q++){const H=M[q],W=H.shadow;if(W===void 0){Oe("WebGLShadowMap:",H,"has no shadow.");continue}if(W.autoUpdate===!1&&W.needsUpdate===!1)continue;s.copy(W.mapSize);const te=W.getFrameExtents();if(s.multiply(te),r.copy(W.mapSize),(s.x>d||s.y>d)&&(s.x>d&&(r.x=Math.floor(d/te.x),s.x=r.x*te.x,W.mapSize.x=r.x),s.y>d&&(r.y=Math.floor(d/te.y),s.y=r.y*te.y,W.mapSize.y=r.y)),W.map===null||B===!0){if(W.map!==null&&(W.map.depthTexture!==null&&(W.map.depthTexture.dispose(),W.map.depthTexture=null),W.map.dispose()),this.type===Or){if(H.isPointLight){Oe("WebGLShadowMap: VSM shadow maps are not supported for PointLights. Use PCF or BasicShadowMap instead.");continue}W.map=new Qn(s.x,s.y,{format:Hs,type:_i,minFilter:Kt,magFilter:Kt,generateMipmaps:!1}),W.map.texture.name=H.name+".shadowMap",W.map.depthTexture=new Yr(s.x,s.y,Jn),W.map.depthTexture.name=H.name+".shadowMapDepth",W.map.depthTexture.format=yi,W.map.depthTexture.compareFunction=null,W.map.depthTexture.minFilter=Xt,W.map.depthTexture.magFilter=Xt}else{H.isPointLight?(W.map=new $p(s.x),W.map.depthTexture=new py(s.x,Yn)):(W.map=new Qn(s.x,s.y),W.map.depthTexture=new Yr(s.x,s.y,Yn)),W.map.depthTexture.name=H.name+".shadowMap",W.map.depthTexture.format=yi;const de=i.state.buffers.depth.getReversed();this.type===Ua?(W.map.depthTexture.compareFunction=de?ed:Ql,W.map.depthTexture.minFilter=Kt,W.map.depthTexture.magFilter=Kt):(W.map.depthTexture.compareFunction=null,W.map.depthTexture.minFilter=Xt,W.map.depthTexture.magFilter=Xt)}W.camera.updateProjectionMatrix()}const ve=W.map.isWebGLCubeRenderTarget?6:1;for(let de=0;de<ve;de++){if(W.map.isWebGLCubeRenderTarget)i.setRenderTarget(W.map,de),i.clear();else{de===0&&(i.setRenderTarget(W.map),i.clear());const _e=W.getViewport(de);a.set(r.x*_e.x,r.y*_e.y,r.x*_e.z,r.y*_e.w),U.viewport(a)}if(H.isPointLight){const _e=W.camera,Ve=W.matrix,Be=H.distance||_e.far;Be!==_e.far&&(_e.far=Be,_e.updateProjectionMatrix()),Qr.setFromMatrixPosition(H.matrixWorld),_e.position.copy(Qr),Fd.copy(_e.position),Fd.add(_C[de]),_e.up.copy(yC[de]),_e.lookAt(Fd),_e.updateMatrixWorld(),Ve.makeTranslation(-Qr.x,-Qr.y,-Qr.z),Em.multiplyMatrices(_e.projectionMatrix,_e.matrixWorldInverse),W._frustum.setFromProjectionMatrix(Em,_e.coordinateSystem,_e.reversedDepth)}else W.updateMatrices(H);n=W.getFrustum(),b(A,k,W.camera,H,this.type)}W.isPointLightShadow!==!0&&this.type===Or&&x(W,k),W.needsUpdate=!1}p=this.type,m.needsUpdate=!1,i.setRenderTarget(y,T,R)};function x(M,A){const k=e.update(v);h.defines.VSM_SAMPLES!==M.blurSamples&&(h.defines.VSM_SAMPLES=M.blurSamples,f.defines.VSM_SAMPLES=M.blurSamples,h.needsUpdate=!0,f.needsUpdate=!0),M.mapPass===null&&(M.mapPass=new Qn(s.x,s.y,{format:Hs,type:_i})),h.uniforms.shadow_pass.value=M.map.depthTexture,h.uniforms.resolution.value=M.mapSize,h.uniforms.radius.value=M.radius,i.setRenderTarget(M.mapPass),i.clear(),i.renderBufferDirect(A,null,k,h,v,null),f.uniforms.shadow_pass.value=M.mapPass.texture,f.uniforms.resolution.value=M.mapSize,f.uniforms.radius.value=M.radius,i.setRenderTarget(M.map),i.clear(),i.renderBufferDirect(A,null,k,f,v,null)}function C(M,A,k,y){let T=null;const R=k.isPointLight===!0?M.customDistanceMaterial:M.customDepthMaterial;if(R!==void 0)T=R;else if(T=k.isPointLight===!0?c:o,i.localClippingEnabled&&A.clipShadows===!0&&Array.isArray(A.clippingPlanes)&&A.clippingPlanes.length!==0||A.displacementMap&&A.displacementScale!==0||A.alphaMap&&A.alphaTest>0||A.map&&A.alphaTest>0||A.alphaToCoverage===!0){const U=T.uuid,B=A.uuid;let q=l[U];q===void 0&&(q={},l[U]=q);let K=q[B];K===void 0&&(K=T.clone(),q[B]=K,A.addEventListener("dispose",S)),T=K}if(T.visible=A.visible,T.wireframe=A.wireframe,y===Or?T.side=A.shadowSide!==null?A.shadowSide:A.side:T.side=A.shadowSide!==null?A.shadowSide:u[A.side],T.alphaMap=A.alphaMap,T.alphaTest=A.alphaToCoverage===!0?.5:A.alphaTest,T.map=A.map,T.clipShadows=A.clipShadows,T.clippingPlanes=A.clippingPlanes,T.clipIntersection=A.clipIntersection,T.displacementMap=A.displacementMap,T.displacementScale=A.displacementScale,T.displacementBias=A.displacementBias,T.wireframeLinewidth=A.wireframeLinewidth,T.linewidth=A.linewidth,k.isPointLight===!0&&T.isMeshDistanceMaterial===!0){const U=i.properties.get(T);U.light=k}return T}function b(M,A,k,y,T){if(M.visible===!1)return;if(M.layers.test(A.layers)&&(M.isMesh||M.isLine||M.isPoints)&&(M.castShadow||M.receiveShadow&&T===Or)&&(!M.frustumCulled||n.intersectsObject(M))){M.modelViewMatrix.multiplyMatrices(k.matrixWorldInverse,M.matrixWorld);const B=e.update(M),q=M.material;if(Array.isArray(q)){const K=B.groups;for(let H=0,W=K.length;H<W;H++){const te=K[H],ve=q[te.materialIndex];if(ve&&ve.visible){const de=C(M,ve,y,T);M.onBeforeShadow(i,M,A,k,B,de,te),i.renderBufferDirect(k,null,B,de,M,te),M.onAfterShadow(i,M,A,k,B,de,te)}}}else if(q.visible){const K=C(M,q,y,T);M.onBeforeShadow(i,M,A,k,B,K,null),i.renderBufferDirect(k,null,B,K,M,null),M.onAfterShadow(i,M,A,k,B,K,null)}}const U=M.children;for(let B=0,q=U.length;B<q;B++)b(U[B],A,k,y,T)}function S(M){M.target.removeEventListener("dispose",S);for(const k in l){const y=l[k],T=M.target.uuid;T in y&&(y[T].dispose(),delete y[T])}}}const xC={[il]:sl,[rl]:cl,[al]:ll,[zs]:ol,[sl]:il,[cl]:rl,[ll]:al,[ol]:zs};function TC(i,e){function t(){let D=!1;const ye=new It;let oe=null;const xe=new It(0,0,0,0);return{setMask:function(se){oe!==se&&!D&&(i.colorMask(se,se,se,se),oe=se)},setLocked:function(se){D=se},setClear:function(se,Q,ue,Fe,St){St===!0&&(se*=Fe,Q*=Fe,ue*=Fe),ye.set(se,Q,ue,Fe),xe.equals(ye)===!1&&(i.clearColor(se,Q,ue,Fe),xe.copy(ye))},reset:function(){D=!1,oe=null,xe.set(-1,0,0,0)}}}function n(){let D=!1,ye=!1,oe=null,xe=null,se=null;return{setReversed:function(Q){if(ye!==Q){const ue=e.get("EXT_clip_control");Q?ue.clipControlEXT(ue.LOWER_LEFT_EXT,ue.ZERO_TO_ONE_EXT):ue.clipControlEXT(ue.LOWER_LEFT_EXT,ue.NEGATIVE_ONE_TO_ONE_EXT),ye=Q;const Fe=se;se=null,this.setClear(Fe)}},getReversed:function(){return ye},setTest:function(Q){Q?ie(i.DEPTH_TEST):Ce(i.DEPTH_TEST)},setMask:function(Q){oe!==Q&&!D&&(i.depthMask(Q),oe=Q)},setFunc:function(Q){if(ye&&(Q=xC[Q]),xe!==Q){switch(Q){case il:i.depthFunc(i.NEVER);break;case sl:i.depthFunc(i.ALWAYS);break;case rl:i.depthFunc(i.LESS);break;case zs:i.depthFunc(i.LEQUAL);break;case al:i.depthFunc(i.EQUAL);break;case ol:i.depthFunc(i.GEQUAL);break;case cl:i.depthFunc(i.GREATER);break;case ll:i.depthFunc(i.NOTEQUAL);break;default:i.depthFunc(i.LEQUAL)}xe=Q}},setLocked:function(Q){D=Q},setClear:function(Q){se!==Q&&(ye&&(Q=1-Q),i.clearDepth(Q),se=Q)},reset:function(){D=!1,oe=null,xe=null,se=null,ye=!1}}}function s(){let D=!1,ye=null,oe=null,xe=null,se=null,Q=null,ue=null,Fe=null,St=null;return{setTest:function(lt){D||(lt?ie(i.STENCIL_TEST):Ce(i.STENCIL_TEST))},setMask:function(lt){ye!==lt&&!D&&(i.stencilMask(lt),ye=lt)},setFunc:function(lt,ri,Ai){(oe!==lt||xe!==ri||se!==Ai)&&(i.stencilFunc(lt,ri,Ai),oe=lt,xe=ri,se=Ai)},setOp:function(lt,ri,Ai){(Q!==lt||ue!==ri||Fe!==Ai)&&(i.stencilOp(lt,ri,Ai),Q=lt,ue=ri,Fe=Ai)},setLocked:function(lt){D=lt},setClear:function(lt){St!==lt&&(i.clearStencil(lt),St=lt)},reset:function(){D=!1,ye=null,oe=null,xe=null,se=null,Q=null,ue=null,Fe=null,St=null}}}const r=new t,a=new n,o=new s,c=new WeakMap,l=new WeakMap;let d={},u={},h=new WeakMap,f=[],g=null,v=!1,m=null,p=null,x=null,C=null,b=null,S=null,M=null,A=new Ze(0,0,0),k=0,y=!1,T=null,R=null,U=null,B=null,q=null;const K=i.getParameter(i.MAX_COMBINED_TEXTURE_IMAGE_UNITS);let H=!1,W=0;const te=i.getParameter(i.VERSION);te.indexOf("WebGL")!==-1?(W=parseFloat(/^WebGL (\d)/.exec(te)[1]),H=W>=1):te.indexOf("OpenGL ES")!==-1&&(W=parseFloat(/^OpenGL ES (\d)/.exec(te)[1]),H=W>=2);let ve=null,de={};const _e=i.getParameter(i.SCISSOR_BOX),Ve=i.getParameter(i.VIEWPORT),Be=new It().fromArray(_e),Ct=new It().fromArray(Ve);function ht(D,ye,oe,xe){const se=new Uint8Array(4),Q=i.createTexture();i.bindTexture(D,Q),i.texParameteri(D,i.TEXTURE_MIN_FILTER,i.NEAREST),i.texParameteri(D,i.TEXTURE_MAG_FILTER,i.NEAREST);for(let ue=0;ue<oe;ue++)D===i.TEXTURE_3D||D===i.TEXTURE_2D_ARRAY?i.texImage3D(ye,0,i.RGBA,1,1,xe,0,i.RGBA,i.UNSIGNED_BYTE,se):i.texImage2D(ye+ue,0,i.RGBA,1,1,0,i.RGBA,i.UNSIGNED_BYTE,se);return Q}const X={};X[i.TEXTURE_2D]=ht(i.TEXTURE_2D,i.TEXTURE_2D,1),X[i.TEXTURE_CUBE_MAP]=ht(i.TEXTURE_CUBE_MAP,i.TEXTURE_CUBE_MAP_POSITIVE_X,6),X[i.TEXTURE_2D_ARRAY]=ht(i.TEXTURE_2D_ARRAY,i.TEXTURE_2D_ARRAY,1,1),X[i.TEXTURE_3D]=ht(i.TEXTURE_3D,i.TEXTURE_3D,1,1),r.setClear(0,0,0,1),a.setClear(1),o.setClear(0),ie(i.DEPTH_TEST),a.setFunc(zs),qe(!1),Ot(Jf),ie(i.CULL_FACE),ct(vi);function ie(D){d[D]!==!0&&(i.enable(D),d[D]=!0)}function Ce(D){d[D]!==!1&&(i.disable(D),d[D]=!1)}function Ge(D,ye){return u[D]!==ye?(i.bindFramebuffer(D,ye),u[D]=ye,D===i.DRAW_FRAMEBUFFER&&(u[i.FRAMEBUFFER]=ye),D===i.FRAMEBUFFER&&(u[i.DRAW_FRAMEBUFFER]=ye),!0):!1}function we(D,ye){let oe=f,xe=!1;if(D){oe=h.get(ye),oe===void 0&&(oe=[],h.set(ye,oe));const se=D.textures;if(oe.length!==se.length||oe[0]!==i.COLOR_ATTACHMENT0){for(let Q=0,ue=se.length;Q<ue;Q++)oe[Q]=i.COLOR_ATTACHMENT0+Q;oe.length=se.length,xe=!0}}else oe[0]!==i.BACK&&(oe[0]=i.BACK,xe=!0);xe&&i.drawBuffers(oe)}function nt(D){return g!==D?(i.useProgram(D),g=D,!0):!1}const jt={[ls]:i.FUNC_ADD,[o_]:i.FUNC_SUBTRACT,[c_]:i.FUNC_REVERSE_SUBTRACT};jt[l_]=i.MIN,jt[d_]=i.MAX;const et={[u_]:i.ZERO,[h_]:i.ONE,[f_]:i.SRC_COLOR,[tl]:i.SRC_ALPHA,[__]:i.SRC_ALPHA_SATURATE,[v_]:i.DST_COLOR,[m_]:i.DST_ALPHA,[p_]:i.ONE_MINUS_SRC_COLOR,[nl]:i.ONE_MINUS_SRC_ALPHA,[b_]:i.ONE_MINUS_DST_COLOR,[g_]:i.ONE_MINUS_DST_ALPHA,[y_]:i.CONSTANT_COLOR,[S_]:i.ONE_MINUS_CONSTANT_COLOR,[x_]:i.CONSTANT_ALPHA,[T_]:i.ONE_MINUS_CONSTANT_ALPHA};function ct(D,ye,oe,xe,se,Q,ue,Fe,St,lt){if(D===vi){v===!0&&(Ce(i.BLEND),v=!1);return}if(v===!1&&(ie(i.BLEND),v=!0),D!==a_){if(D!==m||lt!==y){if((p!==ls||b!==ls)&&(i.blendEquation(i.FUNC_ADD),p=ls,b=ls),lt)switch(D){case Vs:i.blendFuncSeparate(i.ONE,i.ONE_MINUS_SRC_ALPHA,i.ONE,i.ONE_MINUS_SRC_ALPHA);break;case el:i.blendFunc(i.ONE,i.ONE);break;case Zf:i.blendFuncSeparate(i.ZERO,i.ONE_MINUS_SRC_COLOR,i.ZERO,i.ONE);break;case Qf:i.blendFuncSeparate(i.DST_COLOR,i.ONE_MINUS_SRC_ALPHA,i.ZERO,i.ONE);break;default:tt("WebGLState: Invalid blending: ",D);break}else switch(D){case Vs:i.blendFuncSeparate(i.SRC_ALPHA,i.ONE_MINUS_SRC_ALPHA,i.ONE,i.ONE_MINUS_SRC_ALPHA);break;case el:i.blendFuncSeparate(i.SRC_ALPHA,i.ONE,i.ONE,i.ONE);break;case Zf:tt("WebGLState: SubtractiveBlending requires material.premultipliedAlpha = true");break;case Qf:tt("WebGLState: MultiplyBlending requires material.premultipliedAlpha = true");break;default:tt("WebGLState: Invalid blending: ",D);break}x=null,C=null,S=null,M=null,A.set(0,0,0),k=0,m=D,y=lt}return}se=se||ye,Q=Q||oe,ue=ue||xe,(ye!==p||se!==b)&&(i.blendEquationSeparate(jt[ye],jt[se]),p=ye,b=se),(oe!==x||xe!==C||Q!==S||ue!==M)&&(i.blendFuncSeparate(et[oe],et[xe],et[Q],et[ue]),x=oe,C=xe,S=Q,M=ue),(Fe.equals(A)===!1||St!==k)&&(i.blendColor(Fe.r,Fe.g,Fe.b,St),A.copy(Fe),k=St),m=D,y=!1}function bt(D,ye){D.side===gi?Ce(i.CULL_FACE):ie(i.CULL_FACE);let oe=D.side===Zt;ye&&(oe=!oe),qe(oe),D.blending===Vs&&D.transparent===!1?ct(vi):ct(D.blending,D.blendEquation,D.blendSrc,D.blendDst,D.blendEquationAlpha,D.blendSrcAlpha,D.blendDstAlpha,D.blendColor,D.blendAlpha,D.premultipliedAlpha),a.setFunc(D.depthFunc),a.setTest(D.depthTest),a.setMask(D.depthWrite),r.setMask(D.colorWrite);const xe=D.stencilWrite;o.setTest(xe),xe&&(o.setMask(D.stencilWriteMask),o.setFunc(D.stencilFunc,D.stencilRef,D.stencilFuncMask),o.setOp(D.stencilFail,D.stencilZFail,D.stencilZPass)),Ft(D.polygonOffset,D.polygonOffsetFactor,D.polygonOffsetUnits),D.alphaToCoverage===!0?ie(i.SAMPLE_ALPHA_TO_COVERAGE):Ce(i.SAMPLE_ALPHA_TO_COVERAGE)}function qe(D){T!==D&&(D?i.frontFace(i.CW):i.frontFace(i.CCW),T=D)}function Ot(D){D!==i_?(ie(i.CULL_FACE),D!==R&&(D===Jf?i.cullFace(i.BACK):D===s_?i.cullFace(i.FRONT):i.cullFace(i.FRONT_AND_BACK))):Ce(i.CULL_FACE),R=D}function I(D){D!==U&&(H&&i.lineWidth(D),U=D)}function Ft(D,ye,oe){D?(ie(i.POLYGON_OFFSET_FILL),(B!==ye||q!==oe)&&(i.polygonOffset(ye,oe),B=ye,q=oe)):Ce(i.POLYGON_OFFSET_FILL)}function at(D){D?ie(i.SCISSOR_TEST):Ce(i.SCISSOR_TEST)}function yt(D){D===void 0&&(D=i.TEXTURE0+K-1),ve!==D&&(i.activeTexture(D),ve=D)}function Re(D,ye,oe){oe===void 0&&(ve===null?oe=i.TEXTURE0+K-1:oe=ve);let xe=de[oe];xe===void 0&&(xe={type:void 0,texture:void 0},de[oe]=xe),(xe.type!==D||xe.texture!==ye)&&(ve!==oe&&(i.activeTexture(oe),ve=oe),i.bindTexture(D,ye||X[D]),xe.type=D,xe.texture=ye)}function w(){const D=de[ve];D!==void 0&&D.type!==void 0&&(i.bindTexture(D.type,null),D.type=void 0,D.texture=void 0)}function _(){try{i.compressedTexImage2D(...arguments)}catch(D){tt("WebGLState:",D)}}function L(){try{i.compressedTexImage3D(...arguments)}catch(D){tt("WebGLState:",D)}}function $(){try{i.texSubImage2D(...arguments)}catch(D){tt("WebGLState:",D)}}function ee(){try{i.texSubImage3D(...arguments)}catch(D){tt("WebGLState:",D)}}function j(){try{i.compressedTexSubImage2D(...arguments)}catch(D){tt("WebGLState:",D)}}function ke(){try{i.compressedTexSubImage3D(...arguments)}catch(D){tt("WebGLState:",D)}}function he(){try{i.texStorage2D(...arguments)}catch(D){tt("WebGLState:",D)}}function Ae(){try{i.texStorage3D(...arguments)}catch(D){tt("WebGLState:",D)}}function Ue(){try{i.texImage2D(...arguments)}catch(D){tt("WebGLState:",D)}}function re(){try{i.texImage3D(...arguments)}catch(D){tt("WebGLState:",D)}}function pe(D){Be.equals(D)===!1&&(i.scissor(D.x,D.y,D.z,D.w),Be.copy(D))}function Me(D){Ct.equals(D)===!1&&(i.viewport(D.x,D.y,D.z,D.w),Ct.copy(D))}function Pe(D,ye){let oe=l.get(ye);oe===void 0&&(oe=new WeakMap,l.set(ye,oe));let xe=oe.get(D);xe===void 0&&(xe=i.getUniformBlockIndex(ye,D.name),oe.set(D,xe))}function fe(D,ye){const xe=l.get(ye).get(D);c.get(ye)!==xe&&(i.uniformBlockBinding(ye,xe,D.__bindingPointIndex),c.set(ye,xe))}function je(){i.disable(i.BLEND),i.disable(i.CULL_FACE),i.disable(i.DEPTH_TEST),i.disable(i.POLYGON_OFFSET_FILL),i.disable(i.SCISSOR_TEST),i.disable(i.STENCIL_TEST),i.disable(i.SAMPLE_ALPHA_TO_COVERAGE),i.blendEquation(i.FUNC_ADD),i.blendFunc(i.ONE,i.ZERO),i.blendFuncSeparate(i.ONE,i.ZERO,i.ONE,i.ZERO),i.blendColor(0,0,0,0),i.colorMask(!0,!0,!0,!0),i.clearColor(0,0,0,0),i.depthMask(!0),i.depthFunc(i.LESS),a.setReversed(!1),i.clearDepth(1),i.stencilMask(4294967295),i.stencilFunc(i.ALWAYS,0,4294967295),i.stencilOp(i.KEEP,i.KEEP,i.KEEP),i.clearStencil(0),i.cullFace(i.BACK),i.frontFace(i.CCW),i.polygonOffset(0,0),i.activeTexture(i.TEXTURE0),i.bindFramebuffer(i.FRAMEBUFFER,null),i.bindFramebuffer(i.DRAW_FRAMEBUFFER,null),i.bindFramebuffer(i.READ_FRAMEBUFFER,null),i.useProgram(null),i.lineWidth(1),i.scissor(0,0,i.canvas.width,i.canvas.height),i.viewport(0,0,i.canvas.width,i.canvas.height),d={},ve=null,de={},u={},h=new WeakMap,f=[],g=null,v=!1,m=null,p=null,x=null,C=null,b=null,S=null,M=null,A=new Ze(0,0,0),k=0,y=!1,T=null,R=null,U=null,B=null,q=null,Be.set(0,0,i.canvas.width,i.canvas.height),Ct.set(0,0,i.canvas.width,i.canvas.height),r.reset(),a.reset(),o.reset()}return{buffers:{color:r,depth:a,stencil:o},enable:ie,disable:Ce,bindFramebuffer:Ge,drawBuffers:we,useProgram:nt,setBlending:ct,setMaterial:bt,setFlipSided:qe,setCullFace:Ot,setLineWidth:I,setPolygonOffset:Ft,setScissorTest:at,activeTexture:yt,bindTexture:Re,unbindTexture:w,compressedTexImage2D:_,compressedTexImage3D:L,texImage2D:Ue,texImage3D:re,updateUBOMapping:Pe,uniformBlockBinding:fe,texStorage2D:he,texStorage3D:Ae,texSubImage2D:$,texSubImage3D:ee,compressedTexSubImage2D:j,compressedTexSubImage3D:ke,scissor:pe,viewport:Me,reset:je}}function CC(i,e,t,n,s,r,a){const o=e.has("WEBGL_multisampled_render_to_texture")?e.get("WEBGL_multisampled_render_to_texture"):null,c=typeof navigator>"u"?!1:/OculusBrowser/g.test(navigator.userAgent),l=new rt,d=new WeakMap;let u;const h=new WeakMap;let f=!1;try{f=typeof OffscreenCanvas<"u"&&new OffscreenCanvas(1,1).getContext("2d")!==null}catch{}function g(w,_){return f?new OffscreenCanvas(w,_):qa("canvas")}function v(w,_,L){let $=1;const ee=Re(w);if((ee.width>L||ee.height>L)&&($=L/Math.max(ee.width,ee.height)),$<1)if(typeof HTMLImageElement<"u"&&w instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&w instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&w instanceof ImageBitmap||typeof VideoFrame<"u"&&w instanceof VideoFrame){const j=Math.floor($*ee.width),ke=Math.floor($*ee.height);u===void 0&&(u=g(j,ke));const he=_?g(j,ke):u;return he.width=j,he.height=ke,he.getContext("2d").drawImage(w,0,0,j,ke),Oe("WebGLRenderer: Texture has been resized from ("+ee.width+"x"+ee.height+") to ("+j+"x"+ke+")."),he}else return"data"in w&&Oe("WebGLRenderer: Image in DataTexture is too big ("+ee.width+"x"+ee.height+")."),w;return w}function m(w){return w.generateMipmaps}function p(w){i.generateMipmap(w)}function x(w){return w.isWebGLCubeRenderTarget?i.TEXTURE_CUBE_MAP:w.isWebGL3DRenderTarget?i.TEXTURE_3D:w.isWebGLArrayRenderTarget||w.isCompressedArrayTexture?i.TEXTURE_2D_ARRAY:i.TEXTURE_2D}function C(w,_,L,$,ee=!1){if(w!==null){if(i[w]!==void 0)return i[w];Oe("WebGLRenderer: Attempt to use non-existing WebGL internal format '"+w+"'")}let j=_;if(_===i.RED&&(L===i.FLOAT&&(j=i.R32F),L===i.HALF_FLOAT&&(j=i.R16F),L===i.UNSIGNED_BYTE&&(j=i.R8)),_===i.RED_INTEGER&&(L===i.UNSIGNED_BYTE&&(j=i.R8UI),L===i.UNSIGNED_SHORT&&(j=i.R16UI),L===i.UNSIGNED_INT&&(j=i.R32UI),L===i.BYTE&&(j=i.R8I),L===i.SHORT&&(j=i.R16I),L===i.INT&&(j=i.R32I)),_===i.RG&&(L===i.FLOAT&&(j=i.RG32F),L===i.HALF_FLOAT&&(j=i.RG16F),L===i.UNSIGNED_BYTE&&(j=i.RG8)),_===i.RG_INTEGER&&(L===i.UNSIGNED_BYTE&&(j=i.RG8UI),L===i.UNSIGNED_SHORT&&(j=i.RG16UI),L===i.UNSIGNED_INT&&(j=i.RG32UI),L===i.BYTE&&(j=i.RG8I),L===i.SHORT&&(j=i.RG16I),L===i.INT&&(j=i.RG32I)),_===i.RGB_INTEGER&&(L===i.UNSIGNED_BYTE&&(j=i.RGB8UI),L===i.UNSIGNED_SHORT&&(j=i.RGB16UI),L===i.UNSIGNED_INT&&(j=i.RGB32UI),L===i.BYTE&&(j=i.RGB8I),L===i.SHORT&&(j=i.RGB16I),L===i.INT&&(j=i.RGB32I)),_===i.RGBA_INTEGER&&(L===i.UNSIGNED_BYTE&&(j=i.RGBA8UI),L===i.UNSIGNED_SHORT&&(j=i.RGBA16UI),L===i.UNSIGNED_INT&&(j=i.RGBA32UI),L===i.BYTE&&(j=i.RGBA8I),L===i.SHORT&&(j=i.RGBA16I),L===i.INT&&(j=i.RGBA32I)),_===i.RGB&&(L===i.UNSIGNED_INT_5_9_9_9_REV&&(j=i.RGB9_E5),L===i.UNSIGNED_INT_10F_11F_11F_REV&&(j=i.R11F_G11F_B10F)),_===i.RGBA){const ke=ee?Ha:Qe.getTransfer($);L===i.FLOAT&&(j=i.RGBA32F),L===i.HALF_FLOAT&&(j=i.RGBA16F),L===i.UNSIGNED_BYTE&&(j=ke===ot?i.SRGB8_ALPHA8:i.RGBA8),L===i.UNSIGNED_SHORT_4_4_4_4&&(j=i.RGBA4),L===i.UNSIGNED_SHORT_5_5_5_1&&(j=i.RGB5_A1)}return(j===i.R16F||j===i.R32F||j===i.RG16F||j===i.RG32F||j===i.RGBA16F||j===i.RGBA32F)&&e.get("EXT_color_buffer_float"),j}function b(w,_){let L;return w?_===null||_===Yn||_===Br?L=i.DEPTH24_STENCIL8:_===Jn?L=i.DEPTH32F_STENCIL8:_===Fr&&(L=i.DEPTH24_STENCIL8,Oe("DepthTexture: 16 bit depth attachment is not supported with stencil. Using 24-bit attachment.")):_===null||_===Yn||_===Br?L=i.DEPTH_COMPONENT24:_===Jn?L=i.DEPTH_COMPONENT32F:_===Fr&&(L=i.DEPTH_COMPONENT16),L}function S(w,_){return m(w)===!0||w.isFramebufferTexture&&w.minFilter!==Xt&&w.minFilter!==Kt?Math.log2(Math.max(_.width,_.height))+1:w.mipmaps!==void 0&&w.mipmaps.length>0?w.mipmaps.length:w.isCompressedTexture&&Array.isArray(w.image)?_.mipmaps.length:1}function M(w){const _=w.target;_.removeEventListener("dispose",M),k(_),_.isVideoTexture&&d.delete(_)}function A(w){const _=w.target;_.removeEventListener("dispose",A),T(_)}function k(w){const _=n.get(w);if(_.__webglInit===void 0)return;const L=w.source,$=h.get(L);if($){const ee=$[_.__cacheKey];ee.usedTimes--,ee.usedTimes===0&&y(w),Object.keys($).length===0&&h.delete(L)}n.remove(w)}function y(w){const _=n.get(w);i.deleteTexture(_.__webglTexture);const L=w.source,$=h.get(L);delete $[_.__cacheKey],a.memory.textures--}function T(w){const _=n.get(w);if(w.depthTexture&&(w.depthTexture.dispose(),n.remove(w.depthTexture)),w.isWebGLCubeRenderTarget)for(let $=0;$<6;$++){if(Array.isArray(_.__webglFramebuffer[$]))for(let ee=0;ee<_.__webglFramebuffer[$].length;ee++)i.deleteFramebuffer(_.__webglFramebuffer[$][ee]);else i.deleteFramebuffer(_.__webglFramebuffer[$]);_.__webglDepthbuffer&&i.deleteRenderbuffer(_.__webglDepthbuffer[$])}else{if(Array.isArray(_.__webglFramebuffer))for(let $=0;$<_.__webglFramebuffer.length;$++)i.deleteFramebuffer(_.__webglFramebuffer[$]);else i.deleteFramebuffer(_.__webglFramebuffer);if(_.__webglDepthbuffer&&i.deleteRenderbuffer(_.__webglDepthbuffer),_.__webglMultisampledFramebuffer&&i.deleteFramebuffer(_.__webglMultisampledFramebuffer),_.__webglColorRenderbuffer)for(let $=0;$<_.__webglColorRenderbuffer.length;$++)_.__webglColorRenderbuffer[$]&&i.deleteRenderbuffer(_.__webglColorRenderbuffer[$]);_.__webglDepthRenderbuffer&&i.deleteRenderbuffer(_.__webglDepthRenderbuffer)}const L=w.textures;for(let $=0,ee=L.length;$<ee;$++){const j=n.get(L[$]);j.__webglTexture&&(i.deleteTexture(j.__webglTexture),a.memory.textures--),n.remove(L[$])}n.remove(w)}let R=0;function U(){R=0}function B(){const w=R;return w>=s.maxTextures&&Oe("WebGLTextures: Trying to use "+w+" texture units while this GPU supports only "+s.maxTextures),R+=1,w}function q(w){const _=[];return _.push(w.wrapS),_.push(w.wrapT),_.push(w.wrapR||0),_.push(w.magFilter),_.push(w.minFilter),_.push(w.anisotropy),_.push(w.internalFormat),_.push(w.format),_.push(w.type),_.push(w.generateMipmaps),_.push(w.premultiplyAlpha),_.push(w.flipY),_.push(w.unpackAlignment),_.push(w.colorSpace),_.join()}function K(w,_){const L=n.get(w);if(w.isVideoTexture&&at(w),w.isRenderTargetTexture===!1&&w.isExternalTexture!==!0&&w.version>0&&L.__version!==w.version){const $=w.image;if($===null)Oe("WebGLRenderer: Texture marked for update but no image data found.");else if($.complete===!1)Oe("WebGLRenderer: Texture marked for update but image is incomplete");else{X(L,w,_);return}}else w.isExternalTexture&&(L.__webglTexture=w.sourceTexture?w.sourceTexture:null);t.bindTexture(i.TEXTURE_2D,L.__webglTexture,i.TEXTURE0+_)}function H(w,_){const L=n.get(w);if(w.isRenderTargetTexture===!1&&w.version>0&&L.__version!==w.version){X(L,w,_);return}else w.isExternalTexture&&(L.__webglTexture=w.sourceTexture?w.sourceTexture:null);t.bindTexture(i.TEXTURE_2D_ARRAY,L.__webglTexture,i.TEXTURE0+_)}function W(w,_){const L=n.get(w);if(w.isRenderTargetTexture===!1&&w.version>0&&L.__version!==w.version){X(L,w,_);return}t.bindTexture(i.TEXTURE_3D,L.__webglTexture,i.TEXTURE0+_)}function te(w,_){const L=n.get(w);if(w.isCubeDepthTexture!==!0&&w.version>0&&L.__version!==w.version){ie(L,w,_);return}t.bindTexture(i.TEXTURE_CUBE_MAP,L.__webglTexture,i.TEXTURE0+_)}const ve={[hl]:i.REPEAT,[bi]:i.CLAMP_TO_EDGE,[fl]:i.MIRRORED_REPEAT},de={[Xt]:i.NEAREST,[M_]:i.NEAREST_MIPMAP_NEAREST,[Fa]:i.NEAREST_MIPMAP_LINEAR,[Kt]:i.LINEAR,[pl]:i.LINEAR_MIPMAP_NEAREST,[us]:i.LINEAR_MIPMAP_LINEAR},_e={[P_]:i.NEVER,[N_]:i.ALWAYS,[k_]:i.LESS,[Ql]:i.LEQUAL,[I_]:i.EQUAL,[ed]:i.GEQUAL,[D_]:i.GREATER,[L_]:i.NOTEQUAL};function Ve(w,_){if(_.type===Jn&&e.has("OES_texture_float_linear")===!1&&(_.magFilter===Kt||_.magFilter===pl||_.magFilter===Fa||_.magFilter===us||_.minFilter===Kt||_.minFilter===pl||_.minFilter===Fa||_.minFilter===us)&&Oe("WebGLRenderer: Unable to use linear filtering with floating point textures. OES_texture_float_linear not supported on this device."),i.texParameteri(w,i.TEXTURE_WRAP_S,ve[_.wrapS]),i.texParameteri(w,i.TEXTURE_WRAP_T,ve[_.wrapT]),(w===i.TEXTURE_3D||w===i.TEXTURE_2D_ARRAY)&&i.texParameteri(w,i.TEXTURE_WRAP_R,ve[_.wrapR]),i.texParameteri(w,i.TEXTURE_MAG_FILTER,de[_.magFilter]),i.texParameteri(w,i.TEXTURE_MIN_FILTER,de[_.minFilter]),_.compareFunction&&(i.texParameteri(w,i.TEXTURE_COMPARE_MODE,i.COMPARE_REF_TO_TEXTURE),i.texParameteri(w,i.TEXTURE_COMPARE_FUNC,_e[_.compareFunction])),e.has("EXT_texture_filter_anisotropic")===!0){if(_.magFilter===Xt||_.minFilter!==Fa&&_.minFilter!==us||_.type===Jn&&e.has("OES_texture_float_linear")===!1)return;if(_.anisotropy>1||n.get(_).__currentAnisotropy){const L=e.get("EXT_texture_filter_anisotropic");i.texParameterf(w,L.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(_.anisotropy,s.getMaxAnisotropy())),n.get(_).__currentAnisotropy=_.anisotropy}}}function Be(w,_){let L=!1;w.__webglInit===void 0&&(w.__webglInit=!0,_.addEventListener("dispose",M));const $=_.source;let ee=h.get($);ee===void 0&&(ee={},h.set($,ee));const j=q(_);if(j!==w.__cacheKey){ee[j]===void 0&&(ee[j]={texture:i.createTexture(),usedTimes:0},a.memory.textures++,L=!0),ee[j].usedTimes++;const ke=ee[w.__cacheKey];ke!==void 0&&(ee[w.__cacheKey].usedTimes--,ke.usedTimes===0&&y(_)),w.__cacheKey=j,w.__webglTexture=ee[j].texture}return L}function Ct(w,_,L){return Math.floor(Math.floor(w/L)/_)}function ht(w,_,L,$){const j=w.updateRanges;if(j.length===0)t.texSubImage2D(i.TEXTURE_2D,0,0,0,_.width,_.height,L,$,_.data);else{j.sort((re,pe)=>re.start-pe.start);let ke=0;for(let re=1;re<j.length;re++){const pe=j[ke],Me=j[re],Pe=pe.start+pe.count,fe=Ct(Me.start,_.width,4),je=Ct(pe.start,_.width,4);Me.start<=Pe+1&&fe===je&&Ct(Me.start+Me.count-1,_.width,4)===fe?pe.count=Math.max(pe.count,Me.start+Me.count-pe.start):(++ke,j[ke]=Me)}j.length=ke+1;const he=i.getParameter(i.UNPACK_ROW_LENGTH),Ae=i.getParameter(i.UNPACK_SKIP_PIXELS),Ue=i.getParameter(i.UNPACK_SKIP_ROWS);i.pixelStorei(i.UNPACK_ROW_LENGTH,_.width);for(let re=0,pe=j.length;re<pe;re++){const Me=j[re],Pe=Math.floor(Me.start/4),fe=Math.ceil(Me.count/4),je=Pe%_.width,D=Math.floor(Pe/_.width),ye=fe,oe=1;i.pixelStorei(i.UNPACK_SKIP_PIXELS,je),i.pixelStorei(i.UNPACK_SKIP_ROWS,D),t.texSubImage2D(i.TEXTURE_2D,0,je,D,ye,oe,L,$,_.data)}w.clearUpdateRanges(),i.pixelStorei(i.UNPACK_ROW_LENGTH,he),i.pixelStorei(i.UNPACK_SKIP_PIXELS,Ae),i.pixelStorei(i.UNPACK_SKIP_ROWS,Ue)}}function X(w,_,L){let $=i.TEXTURE_2D;(_.isDataArrayTexture||_.isCompressedArrayTexture)&&($=i.TEXTURE_2D_ARRAY),_.isData3DTexture&&($=i.TEXTURE_3D);const ee=Be(w,_),j=_.source;t.bindTexture($,w.__webglTexture,i.TEXTURE0+L);const ke=n.get(j);if(j.version!==ke.__version||ee===!0){t.activeTexture(i.TEXTURE0+L);const he=Qe.getPrimaries(Qe.workingColorSpace),Ae=_.colorSpace===Wi?null:Qe.getPrimaries(_.colorSpace),Ue=_.colorSpace===Wi||he===Ae?i.NONE:i.BROWSER_DEFAULT_WEBGL;i.pixelStorei(i.UNPACK_FLIP_Y_WEBGL,_.flipY),i.pixelStorei(i.UNPACK_PREMULTIPLY_ALPHA_WEBGL,_.premultiplyAlpha),i.pixelStorei(i.UNPACK_ALIGNMENT,_.unpackAlignment),i.pixelStorei(i.UNPACK_COLORSPACE_CONVERSION_WEBGL,Ue);let re=v(_.image,!1,s.maxTextureSize);re=yt(_,re);const pe=r.convert(_.format,_.colorSpace),Me=r.convert(_.type);let Pe=C(_.internalFormat,pe,Me,_.colorSpace,_.isVideoTexture);Ve($,_);let fe;const je=_.mipmaps,D=_.isVideoTexture!==!0,ye=ke.__version===void 0||ee===!0,oe=j.dataReady,xe=S(_,re);if(_.isDepthTexture)Pe=b(_.format===hs,_.type),ye&&(D?t.texStorage2D(i.TEXTURE_2D,1,Pe,re.width,re.height):t.texImage2D(i.TEXTURE_2D,0,Pe,re.width,re.height,0,pe,Me,null));else if(_.isDataTexture)if(je.length>0){D&&ye&&t.texStorage2D(i.TEXTURE_2D,xe,Pe,je[0].width,je[0].height);for(let se=0,Q=je.length;se<Q;se++)fe=je[se],D?oe&&t.texSubImage2D(i.TEXTURE_2D,se,0,0,fe.width,fe.height,pe,Me,fe.data):t.texImage2D(i.TEXTURE_2D,se,Pe,fe.width,fe.height,0,pe,Me,fe.data);_.generateMipmaps=!1}else D?(ye&&t.texStorage2D(i.TEXTURE_2D,xe,Pe,re.width,re.height),oe&&ht(_,re,pe,Me)):t.texImage2D(i.TEXTURE_2D,0,Pe,re.width,re.height,0,pe,Me,re.data);else if(_.isCompressedTexture)if(_.isCompressedArrayTexture){D&&ye&&t.texStorage3D(i.TEXTURE_2D_ARRAY,xe,Pe,je[0].width,je[0].height,re.depth);for(let se=0,Q=je.length;se<Q;se++)if(fe=je[se],_.format!==Ln)if(pe!==null)if(D){if(oe)if(_.layerUpdates.size>0){const ue=Jp(fe.width,fe.height,_.format,_.type);for(const Fe of _.layerUpdates){const St=fe.data.subarray(Fe*ue/fe.data.BYTES_PER_ELEMENT,(Fe+1)*ue/fe.data.BYTES_PER_ELEMENT);t.compressedTexSubImage3D(i.TEXTURE_2D_ARRAY,se,0,0,Fe,fe.width,fe.height,1,pe,St)}_.clearLayerUpdates()}else t.compressedTexSubImage3D(i.TEXTURE_2D_ARRAY,se,0,0,0,fe.width,fe.height,re.depth,pe,fe.data)}else t.compressedTexImage3D(i.TEXTURE_2D_ARRAY,se,Pe,fe.width,fe.height,re.depth,0,fe.data,0,0);else Oe("WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()");else D?oe&&t.texSubImage3D(i.TEXTURE_2D_ARRAY,se,0,0,0,fe.width,fe.height,re.depth,pe,Me,fe.data):t.texImage3D(i.TEXTURE_2D_ARRAY,se,Pe,fe.width,fe.height,re.depth,0,pe,Me,fe.data)}else{D&&ye&&t.texStorage2D(i.TEXTURE_2D,xe,Pe,je[0].width,je[0].height);for(let se=0,Q=je.length;se<Q;se++)fe=je[se],_.format!==Ln?pe!==null?D?oe&&t.compressedTexSubImage2D(i.TEXTURE_2D,se,0,0,fe.width,fe.height,pe,fe.data):t.compressedTexImage2D(i.TEXTURE_2D,se,Pe,fe.width,fe.height,0,fe.data):Oe("WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()"):D?oe&&t.texSubImage2D(i.TEXTURE_2D,se,0,0,fe.width,fe.height,pe,Me,fe.data):t.texImage2D(i.TEXTURE_2D,se,Pe,fe.width,fe.height,0,pe,Me,fe.data)}else if(_.isDataArrayTexture)if(D){if(ye&&t.texStorage3D(i.TEXTURE_2D_ARRAY,xe,Pe,re.width,re.height,re.depth),oe)if(_.layerUpdates.size>0){const se=Jp(re.width,re.height,_.format,_.type);for(const Q of _.layerUpdates){const ue=re.data.subarray(Q*se/re.data.BYTES_PER_ELEMENT,(Q+1)*se/re.data.BYTES_PER_ELEMENT);t.texSubImage3D(i.TEXTURE_2D_ARRAY,0,0,0,Q,re.width,re.height,1,pe,Me,ue)}_.clearLayerUpdates()}else t.texSubImage3D(i.TEXTURE_2D_ARRAY,0,0,0,0,re.width,re.height,re.depth,pe,Me,re.data)}else t.texImage3D(i.TEXTURE_2D_ARRAY,0,Pe,re.width,re.height,re.depth,0,pe,Me,re.data);else if(_.isData3DTexture)D?(ye&&t.texStorage3D(i.TEXTURE_3D,xe,Pe,re.width,re.height,re.depth),oe&&t.texSubImage3D(i.TEXTURE_3D,0,0,0,0,re.width,re.height,re.depth,pe,Me,re.data)):t.texImage3D(i.TEXTURE_3D,0,Pe,re.width,re.height,re.depth,0,pe,Me,re.data);else if(_.isFramebufferTexture){if(ye)if(D)t.texStorage2D(i.TEXTURE_2D,xe,Pe,re.width,re.height);else{let se=re.width,Q=re.height;for(let ue=0;ue<xe;ue++)t.texImage2D(i.TEXTURE_2D,ue,Pe,se,Q,0,pe,Me,null),se>>=1,Q>>=1}}else if(je.length>0){if(D&&ye){const se=Re(je[0]);t.texStorage2D(i.TEXTURE_2D,xe,Pe,se.width,se.height)}for(let se=0,Q=je.length;se<Q;se++)fe=je[se],D?oe&&t.texSubImage2D(i.TEXTURE_2D,se,0,0,pe,Me,fe):t.texImage2D(i.TEXTURE_2D,se,Pe,pe,Me,fe);_.generateMipmaps=!1}else if(D){if(ye){const se=Re(re);t.texStorage2D(i.TEXTURE_2D,xe,Pe,se.width,se.height)}oe&&t.texSubImage2D(i.TEXTURE_2D,0,0,0,pe,Me,re)}else t.texImage2D(i.TEXTURE_2D,0,Pe,pe,Me,re);m(_)&&p($),ke.__version=j.version,_.onUpdate&&_.onUpdate(_)}w.__version=_.version}function ie(w,_,L){if(_.image.length!==6)return;const $=Be(w,_),ee=_.source;t.bindTexture(i.TEXTURE_CUBE_MAP,w.__webglTexture,i.TEXTURE0+L);const j=n.get(ee);if(ee.version!==j.__version||$===!0){t.activeTexture(i.TEXTURE0+L);const ke=Qe.getPrimaries(Qe.workingColorSpace),he=_.colorSpace===Wi?null:Qe.getPrimaries(_.colorSpace),Ae=_.colorSpace===Wi||ke===he?i.NONE:i.BROWSER_DEFAULT_WEBGL;i.pixelStorei(i.UNPACK_FLIP_Y_WEBGL,_.flipY),i.pixelStorei(i.UNPACK_PREMULTIPLY_ALPHA_WEBGL,_.premultiplyAlpha),i.pixelStorei(i.UNPACK_ALIGNMENT,_.unpackAlignment),i.pixelStorei(i.UNPACK_COLORSPACE_CONVERSION_WEBGL,Ae);const Ue=_.isCompressedTexture||_.image[0].isCompressedTexture,re=_.image[0]&&_.image[0].isDataTexture,pe=[];for(let Q=0;Q<6;Q++)!Ue&&!re?pe[Q]=v(_.image[Q],!0,s.maxCubemapSize):pe[Q]=re?_.image[Q].image:_.image[Q],pe[Q]=yt(_,pe[Q]);const Me=pe[0],Pe=r.convert(_.format,_.colorSpace),fe=r.convert(_.type),je=C(_.internalFormat,Pe,fe,_.colorSpace),D=_.isVideoTexture!==!0,ye=j.__version===void 0||$===!0,oe=ee.dataReady;let xe=S(_,Me);Ve(i.TEXTURE_CUBE_MAP,_);let se;if(Ue){D&&ye&&t.texStorage2D(i.TEXTURE_CUBE_MAP,xe,je,Me.width,Me.height);for(let Q=0;Q<6;Q++){se=pe[Q].mipmaps;for(let ue=0;ue<se.length;ue++){const Fe=se[ue];_.format!==Ln?Pe!==null?D?oe&&t.compressedTexSubImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+Q,ue,0,0,Fe.width,Fe.height,Pe,Fe.data):t.compressedTexImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+Q,ue,je,Fe.width,Fe.height,0,Fe.data):Oe("WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()"):D?oe&&t.texSubImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+Q,ue,0,0,Fe.width,Fe.height,Pe,fe,Fe.data):t.texImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+Q,ue,je,Fe.width,Fe.height,0,Pe,fe,Fe.data)}}}else{if(se=_.mipmaps,D&&ye){se.length>0&&xe++;const Q=Re(pe[0]);t.texStorage2D(i.TEXTURE_CUBE_MAP,xe,je,Q.width,Q.height)}for(let Q=0;Q<6;Q++)if(re){D?oe&&t.texSubImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+Q,0,0,0,pe[Q].width,pe[Q].height,Pe,fe,pe[Q].data):t.texImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+Q,0,je,pe[Q].width,pe[Q].height,0,Pe,fe,pe[Q].data);for(let ue=0;ue<se.length;ue++){const St=se[ue].image[Q].image;D?oe&&t.texSubImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+Q,ue+1,0,0,St.width,St.height,Pe,fe,St.data):t.texImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+Q,ue+1,je,St.width,St.height,0,Pe,fe,St.data)}}else{D?oe&&t.texSubImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+Q,0,0,0,Pe,fe,pe[Q]):t.texImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+Q,0,je,Pe,fe,pe[Q]);for(let ue=0;ue<se.length;ue++){const Fe=se[ue];D?oe&&t.texSubImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+Q,ue+1,0,0,Pe,fe,Fe.image[Q]):t.texImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+Q,ue+1,je,Pe,fe,Fe.image[Q])}}}m(_)&&p(i.TEXTURE_CUBE_MAP),j.__version=ee.version,_.onUpdate&&_.onUpdate(_)}w.__version=_.version}function Ce(w,_,L,$,ee,j){const ke=r.convert(L.format,L.colorSpace),he=r.convert(L.type),Ae=C(L.internalFormat,ke,he,L.colorSpace),Ue=n.get(_),re=n.get(L);if(re.__renderTarget=_,!Ue.__hasExternalTextures){const pe=Math.max(1,_.width>>j),Me=Math.max(1,_.height>>j);ee===i.TEXTURE_3D||ee===i.TEXTURE_2D_ARRAY?t.texImage3D(ee,j,Ae,pe,Me,_.depth,0,ke,he,null):t.texImage2D(ee,j,Ae,pe,Me,0,ke,he,null)}t.bindFramebuffer(i.FRAMEBUFFER,w),Ft(_)?o.framebufferTexture2DMultisampleEXT(i.FRAMEBUFFER,$,ee,re.__webglTexture,0,I(_)):(ee===i.TEXTURE_2D||ee>=i.TEXTURE_CUBE_MAP_POSITIVE_X&&ee<=i.TEXTURE_CUBE_MAP_NEGATIVE_Z)&&i.framebufferTexture2D(i.FRAMEBUFFER,$,ee,re.__webglTexture,j),t.bindFramebuffer(i.FRAMEBUFFER,null)}function Ge(w,_,L){if(i.bindRenderbuffer(i.RENDERBUFFER,w),_.depthBuffer){const $=_.depthTexture,ee=$&&$.isDepthTexture?$.type:null,j=b(_.stencilBuffer,ee),ke=_.stencilBuffer?i.DEPTH_STENCIL_ATTACHMENT:i.DEPTH_ATTACHMENT;Ft(_)?o.renderbufferStorageMultisampleEXT(i.RENDERBUFFER,I(_),j,_.width,_.height):L?i.renderbufferStorageMultisample(i.RENDERBUFFER,I(_),j,_.width,_.height):i.renderbufferStorage(i.RENDERBUFFER,j,_.width,_.height),i.framebufferRenderbuffer(i.FRAMEBUFFER,ke,i.RENDERBUFFER,w)}else{const $=_.textures;for(let ee=0;ee<$.length;ee++){const j=$[ee],ke=r.convert(j.format,j.colorSpace),he=r.convert(j.type),Ae=C(j.internalFormat,ke,he,j.colorSpace);Ft(_)?o.renderbufferStorageMultisampleEXT(i.RENDERBUFFER,I(_),Ae,_.width,_.height):L?i.renderbufferStorageMultisample(i.RENDERBUFFER,I(_),Ae,_.width,_.height):i.renderbufferStorage(i.RENDERBUFFER,Ae,_.width,_.height)}}i.bindRenderbuffer(i.RENDERBUFFER,null)}function we(w,_,L){const $=_.isWebGLCubeRenderTarget===!0;if(t.bindFramebuffer(i.FRAMEBUFFER,w),!(_.depthTexture&&_.depthTexture.isDepthTexture))throw new Error("renderTarget.depthTexture must be an instance of THREE.DepthTexture");const ee=n.get(_.depthTexture);if(ee.__renderTarget=_,(!ee.__webglTexture||_.depthTexture.image.width!==_.width||_.depthTexture.image.height!==_.height)&&(_.depthTexture.image.width=_.width,_.depthTexture.image.height=_.height,_.depthTexture.needsUpdate=!0),$){if(ee.__webglInit===void 0&&(ee.__webglInit=!0,_.depthTexture.addEventListener("dispose",M)),ee.__webglTexture===void 0){ee.__webglTexture=i.createTexture(),t.bindTexture(i.TEXTURE_CUBE_MAP,ee.__webglTexture),Ve(i.TEXTURE_CUBE_MAP,_.depthTexture);const Ue=r.convert(_.depthTexture.format),re=r.convert(_.depthTexture.type);let pe;_.depthTexture.format===yi?pe=i.DEPTH_COMPONENT24:_.depthTexture.format===hs&&(pe=i.DEPTH24_STENCIL8);for(let Me=0;Me<6;Me++)i.texImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+Me,0,pe,_.width,_.height,0,Ue,re,null)}}else K(_.depthTexture,0);const j=ee.__webglTexture,ke=I(_),he=$?i.TEXTURE_CUBE_MAP_POSITIVE_X+L:i.TEXTURE_2D,Ae=_.depthTexture.format===hs?i.DEPTH_STENCIL_ATTACHMENT:i.DEPTH_ATTACHMENT;if(_.depthTexture.format===yi)Ft(_)?o.framebufferTexture2DMultisampleEXT(i.FRAMEBUFFER,Ae,he,j,0,ke):i.framebufferTexture2D(i.FRAMEBUFFER,Ae,he,j,0);else if(_.depthTexture.format===hs)Ft(_)?o.framebufferTexture2DMultisampleEXT(i.FRAMEBUFFER,Ae,he,j,0,ke):i.framebufferTexture2D(i.FRAMEBUFFER,Ae,he,j,0);else throw new Error("Unknown depthTexture format")}function nt(w){const _=n.get(w),L=w.isWebGLCubeRenderTarget===!0;if(_.__boundDepthTexture!==w.depthTexture){const $=w.depthTexture;if(_.__depthDisposeCallback&&_.__depthDisposeCallback(),$){const ee=()=>{delete _.__boundDepthTexture,delete _.__depthDisposeCallback,$.removeEventListener("dispose",ee)};$.addEventListener("dispose",ee),_.__depthDisposeCallback=ee}_.__boundDepthTexture=$}if(w.depthTexture&&!_.__autoAllocateDepthBuffer)if(L)for(let $=0;$<6;$++)we(_.__webglFramebuffer[$],w,$);else{const $=w.texture.mipmaps;$&&$.length>0?we(_.__webglFramebuffer[0],w,0):we(_.__webglFramebuffer,w,0)}else if(L){_.__webglDepthbuffer=[];for(let $=0;$<6;$++)if(t.bindFramebuffer(i.FRAMEBUFFER,_.__webglFramebuffer[$]),_.__webglDepthbuffer[$]===void 0)_.__webglDepthbuffer[$]=i.createRenderbuffer(),Ge(_.__webglDepthbuffer[$],w,!1);else{const ee=w.stencilBuffer?i.DEPTH_STENCIL_ATTACHMENT:i.DEPTH_ATTACHMENT,j=_.__webglDepthbuffer[$];i.bindRenderbuffer(i.RENDERBUFFER,j),i.framebufferRenderbuffer(i.FRAMEBUFFER,ee,i.RENDERBUFFER,j)}}else{const $=w.texture.mipmaps;if($&&$.length>0?t.bindFramebuffer(i.FRAMEBUFFER,_.__webglFramebuffer[0]):t.bindFramebuffer(i.FRAMEBUFFER,_.__webglFramebuffer),_.__webglDepthbuffer===void 0)_.__webglDepthbuffer=i.createRenderbuffer(),Ge(_.__webglDepthbuffer,w,!1);else{const ee=w.stencilBuffer?i.DEPTH_STENCIL_ATTACHMENT:i.DEPTH_ATTACHMENT,j=_.__webglDepthbuffer;i.bindRenderbuffer(i.RENDERBUFFER,j),i.framebufferRenderbuffer(i.FRAMEBUFFER,ee,i.RENDERBUFFER,j)}}t.bindFramebuffer(i.FRAMEBUFFER,null)}function jt(w,_,L){const $=n.get(w);_!==void 0&&Ce($.__webglFramebuffer,w,w.texture,i.COLOR_ATTACHMENT0,i.TEXTURE_2D,0),L!==void 0&&nt(w)}function et(w){const _=w.texture,L=n.get(w),$=n.get(_);w.addEventListener("dispose",A);const ee=w.textures,j=w.isWebGLCubeRenderTarget===!0,ke=ee.length>1;if(ke||($.__webglTexture===void 0&&($.__webglTexture=i.createTexture()),$.__version=_.version,a.memory.textures++),j){L.__webglFramebuffer=[];for(let he=0;he<6;he++)if(_.mipmaps&&_.mipmaps.length>0){L.__webglFramebuffer[he]=[];for(let Ae=0;Ae<_.mipmaps.length;Ae++)L.__webglFramebuffer[he][Ae]=i.createFramebuffer()}else L.__webglFramebuffer[he]=i.createFramebuffer()}else{if(_.mipmaps&&_.mipmaps.length>0){L.__webglFramebuffer=[];for(let he=0;he<_.mipmaps.length;he++)L.__webglFramebuffer[he]=i.createFramebuffer()}else L.__webglFramebuffer=i.createFramebuffer();if(ke)for(let he=0,Ae=ee.length;he<Ae;he++){const Ue=n.get(ee[he]);Ue.__webglTexture===void 0&&(Ue.__webglTexture=i.createTexture(),a.memory.textures++)}if(w.samples>0&&Ft(w)===!1){L.__webglMultisampledFramebuffer=i.createFramebuffer(),L.__webglColorRenderbuffer=[],t.bindFramebuffer(i.FRAMEBUFFER,L.__webglMultisampledFramebuffer);for(let he=0;he<ee.length;he++){const Ae=ee[he];L.__webglColorRenderbuffer[he]=i.createRenderbuffer(),i.bindRenderbuffer(i.RENDERBUFFER,L.__webglColorRenderbuffer[he]);const Ue=r.convert(Ae.format,Ae.colorSpace),re=r.convert(Ae.type),pe=C(Ae.internalFormat,Ue,re,Ae.colorSpace,w.isXRRenderTarget===!0),Me=I(w);i.renderbufferStorageMultisample(i.RENDERBUFFER,Me,pe,w.width,w.height),i.framebufferRenderbuffer(i.FRAMEBUFFER,i.COLOR_ATTACHMENT0+he,i.RENDERBUFFER,L.__webglColorRenderbuffer[he])}i.bindRenderbuffer(i.RENDERBUFFER,null),w.depthBuffer&&(L.__webglDepthRenderbuffer=i.createRenderbuffer(),Ge(L.__webglDepthRenderbuffer,w,!0)),t.bindFramebuffer(i.FRAMEBUFFER,null)}}if(j){t.bindTexture(i.TEXTURE_CUBE_MAP,$.__webglTexture),Ve(i.TEXTURE_CUBE_MAP,_);for(let he=0;he<6;he++)if(_.mipmaps&&_.mipmaps.length>0)for(let Ae=0;Ae<_.mipmaps.length;Ae++)Ce(L.__webglFramebuffer[he][Ae],w,_,i.COLOR_ATTACHMENT0,i.TEXTURE_CUBE_MAP_POSITIVE_X+he,Ae);else Ce(L.__webglFramebuffer[he],w,_,i.COLOR_ATTACHMENT0,i.TEXTURE_CUBE_MAP_POSITIVE_X+he,0);m(_)&&p(i.TEXTURE_CUBE_MAP),t.unbindTexture()}else if(ke){for(let he=0,Ae=ee.length;he<Ae;he++){const Ue=ee[he],re=n.get(Ue);let pe=i.TEXTURE_2D;(w.isWebGL3DRenderTarget||w.isWebGLArrayRenderTarget)&&(pe=w.isWebGL3DRenderTarget?i.TEXTURE_3D:i.TEXTURE_2D_ARRAY),t.bindTexture(pe,re.__webglTexture),Ve(pe,Ue),Ce(L.__webglFramebuffer,w,Ue,i.COLOR_ATTACHMENT0+he,pe,0),m(Ue)&&p(pe)}t.unbindTexture()}else{let he=i.TEXTURE_2D;if((w.isWebGL3DRenderTarget||w.isWebGLArrayRenderTarget)&&(he=w.isWebGL3DRenderTarget?i.TEXTURE_3D:i.TEXTURE_2D_ARRAY),t.bindTexture(he,$.__webglTexture),Ve(he,_),_.mipmaps&&_.mipmaps.length>0)for(let Ae=0;Ae<_.mipmaps.length;Ae++)Ce(L.__webglFramebuffer[Ae],w,_,i.COLOR_ATTACHMENT0,he,Ae);else Ce(L.__webglFramebuffer,w,_,i.COLOR_ATTACHMENT0,he,0);m(_)&&p(he),t.unbindTexture()}w.depthBuffer&&nt(w)}function ct(w){const _=w.textures;for(let L=0,$=_.length;L<$;L++){const ee=_[L];if(m(ee)){const j=x(w),ke=n.get(ee).__webglTexture;t.bindTexture(j,ke),p(j),t.unbindTexture()}}}const bt=[],qe=[];function Ot(w){if(w.samples>0){if(Ft(w)===!1){const _=w.textures,L=w.width,$=w.height;let ee=i.COLOR_BUFFER_BIT;const j=w.stencilBuffer?i.DEPTH_STENCIL_ATTACHMENT:i.DEPTH_ATTACHMENT,ke=n.get(w),he=_.length>1;if(he)for(let Ue=0;Ue<_.length;Ue++)t.bindFramebuffer(i.FRAMEBUFFER,ke.__webglMultisampledFramebuffer),i.framebufferRenderbuffer(i.FRAMEBUFFER,i.COLOR_ATTACHMENT0+Ue,i.RENDERBUFFER,null),t.bindFramebuffer(i.FRAMEBUFFER,ke.__webglFramebuffer),i.framebufferTexture2D(i.DRAW_FRAMEBUFFER,i.COLOR_ATTACHMENT0+Ue,i.TEXTURE_2D,null,0);t.bindFramebuffer(i.READ_FRAMEBUFFER,ke.__webglMultisampledFramebuffer);const Ae=w.texture.mipmaps;Ae&&Ae.length>0?t.bindFramebuffer(i.DRAW_FRAMEBUFFER,ke.__webglFramebuffer[0]):t.bindFramebuffer(i.DRAW_FRAMEBUFFER,ke.__webglFramebuffer);for(let Ue=0;Ue<_.length;Ue++){if(w.resolveDepthBuffer&&(w.depthBuffer&&(ee|=i.DEPTH_BUFFER_BIT),w.stencilBuffer&&w.resolveStencilBuffer&&(ee|=i.STENCIL_BUFFER_BIT)),he){i.framebufferRenderbuffer(i.READ_FRAMEBUFFER,i.COLOR_ATTACHMENT0,i.RENDERBUFFER,ke.__webglColorRenderbuffer[Ue]);const re=n.get(_[Ue]).__webglTexture;i.framebufferTexture2D(i.DRAW_FRAMEBUFFER,i.COLOR_ATTACHMENT0,i.TEXTURE_2D,re,0)}i.blitFramebuffer(0,0,L,$,0,0,L,$,ee,i.NEAREST),c===!0&&(bt.length=0,qe.length=0,bt.push(i.COLOR_ATTACHMENT0+Ue),w.depthBuffer&&w.resolveDepthBuffer===!1&&(bt.push(j),qe.push(j),i.invalidateFramebuffer(i.DRAW_FRAMEBUFFER,qe)),i.invalidateFramebuffer(i.READ_FRAMEBUFFER,bt))}if(t.bindFramebuffer(i.READ_FRAMEBUFFER,null),t.bindFramebuffer(i.DRAW_FRAMEBUFFER,null),he)for(let Ue=0;Ue<_.length;Ue++){t.bindFramebuffer(i.FRAMEBUFFER,ke.__webglMultisampledFramebuffer),i.framebufferRenderbuffer(i.FRAMEBUFFER,i.COLOR_ATTACHMENT0+Ue,i.RENDERBUFFER,ke.__webglColorRenderbuffer[Ue]);const re=n.get(_[Ue]).__webglTexture;t.bindFramebuffer(i.FRAMEBUFFER,ke.__webglFramebuffer),i.framebufferTexture2D(i.DRAW_FRAMEBUFFER,i.COLOR_ATTACHMENT0+Ue,i.TEXTURE_2D,re,0)}t.bindFramebuffer(i.DRAW_FRAMEBUFFER,ke.__webglMultisampledFramebuffer)}else if(w.depthBuffer&&w.resolveDepthBuffer===!1&&c){const _=w.stencilBuffer?i.DEPTH_STENCIL_ATTACHMENT:i.DEPTH_ATTACHMENT;i.invalidateFramebuffer(i.DRAW_FRAMEBUFFER,[_])}}}function I(w){return Math.min(s.maxSamples,w.samples)}function Ft(w){const _=n.get(w);return w.samples>0&&e.has("WEBGL_multisampled_render_to_texture")===!0&&_.__useRenderToTexture!==!1}function at(w){const _=a.render.frame;d.get(w)!==_&&(d.set(w,_),w.update())}function yt(w,_){const L=w.colorSpace,$=w.format,ee=w.type;return w.isCompressedTexture===!0||w.isVideoTexture===!0||L!==Ws&&L!==Wi&&(Qe.getTransfer(L)===ot?($!==Ln||ee!==yn)&&Oe("WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType."):tt("WebGLTextures: Unsupported texture color space:",L)),_}function Re(w){return typeof HTMLImageElement<"u"&&w instanceof HTMLImageElement?(l.width=w.naturalWidth||w.width,l.height=w.naturalHeight||w.height):typeof VideoFrame<"u"&&w instanceof VideoFrame?(l.width=w.displayWidth,l.height=w.displayHeight):(l.width=w.width,l.height=w.height),l}this.allocateTextureUnit=B,this.resetTextureUnits=U,this.setTexture2D=K,this.setTexture2DArray=H,this.setTexture3D=W,this.setTextureCube=te,this.rebindTextures=jt,this.setupRenderTarget=et,this.updateRenderTargetMipmap=ct,this.updateMultisampleRenderTarget=Ot,this.setupDepthRenderbuffer=nt,this.setupFrameBufferTexture=Ce,this.useMultisampledRTT=Ft,this.isReversedDepthBuffer=function(){return t.buffers.depth.getReversed()}}function EC(i,e){function t(n,s=Wi){let r;const a=Qe.getTransfer(s);if(n===yn)return i.UNSIGNED_BYTE;if(n===gl)return i.UNSIGNED_SHORT_4_4_4_4;if(n===vl)return i.UNSIGNED_SHORT_5_5_5_1;if(n===up)return i.UNSIGNED_INT_5_9_9_9_REV;if(n===hp)return i.UNSIGNED_INT_10F_11F_11F_REV;if(n===lp)return i.BYTE;if(n===dp)return i.SHORT;if(n===Fr)return i.UNSIGNED_SHORT;if(n===ml)return i.INT;if(n===Yn)return i.UNSIGNED_INT;if(n===Jn)return i.FLOAT;if(n===_i)return i.HALF_FLOAT;if(n===fp)return i.ALPHA;if(n===pp)return i.RGB;if(n===Ln)return i.RGBA;if(n===yi)return i.DEPTH_COMPONENT;if(n===hs)return i.DEPTH_STENCIL;if(n===mp)return i.RED;if(n===bl)return i.RED_INTEGER;if(n===Hs)return i.RG;if(n===_l)return i.RG_INTEGER;if(n===yl)return i.RGBA_INTEGER;if(n===Ba||n===Va||n===za||n===Ga)if(a===ot)if(r=e.get("WEBGL_compressed_texture_s3tc_srgb"),r!==null){if(n===Ba)return r.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(n===Va)return r.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(n===za)return r.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(n===Ga)return r.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else return null;else if(r=e.get("WEBGL_compressed_texture_s3tc"),r!==null){if(n===Ba)return r.COMPRESSED_RGB_S3TC_DXT1_EXT;if(n===Va)return r.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(n===za)return r.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(n===Ga)return r.COMPRESSED_RGBA_S3TC_DXT5_EXT}else return null;if(n===Sl||n===xl||n===Tl||n===Cl)if(r=e.get("WEBGL_compressed_texture_pvrtc"),r!==null){if(n===Sl)return r.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(n===xl)return r.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(n===Tl)return r.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(n===Cl)return r.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}else return null;if(n===El||n===Ml||n===wl||n===Al||n===Rl||n===Pl||n===kl)if(r=e.get("WEBGL_compressed_texture_etc"),r!==null){if(n===El||n===Ml)return a===ot?r.COMPRESSED_SRGB8_ETC2:r.COMPRESSED_RGB8_ETC2;if(n===wl)return a===ot?r.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:r.COMPRESSED_RGBA8_ETC2_EAC;if(n===Al)return r.COMPRESSED_R11_EAC;if(n===Rl)return r.COMPRESSED_SIGNED_R11_EAC;if(n===Pl)return r.COMPRESSED_RG11_EAC;if(n===kl)return r.COMPRESSED_SIGNED_RG11_EAC}else return null;if(n===Il||n===Dl||n===Ll||n===Nl||n===Ul||n===Ol||n===Fl||n===Bl||n===Vl||n===zl||n===Gl||n===Hl||n===Wl||n===ql)if(r=e.get("WEBGL_compressed_texture_astc"),r!==null){if(n===Il)return a===ot?r.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:r.COMPRESSED_RGBA_ASTC_4x4_KHR;if(n===Dl)return a===ot?r.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:r.COMPRESSED_RGBA_ASTC_5x4_KHR;if(n===Ll)return a===ot?r.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:r.COMPRESSED_RGBA_ASTC_5x5_KHR;if(n===Nl)return a===ot?r.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:r.COMPRESSED_RGBA_ASTC_6x5_KHR;if(n===Ul)return a===ot?r.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:r.COMPRESSED_RGBA_ASTC_6x6_KHR;if(n===Ol)return a===ot?r.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:r.COMPRESSED_RGBA_ASTC_8x5_KHR;if(n===Fl)return a===ot?r.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:r.COMPRESSED_RGBA_ASTC_8x6_KHR;if(n===Bl)return a===ot?r.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:r.COMPRESSED_RGBA_ASTC_8x8_KHR;if(n===Vl)return a===ot?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:r.COMPRESSED_RGBA_ASTC_10x5_KHR;if(n===zl)return a===ot?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:r.COMPRESSED_RGBA_ASTC_10x6_KHR;if(n===Gl)return a===ot?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:r.COMPRESSED_RGBA_ASTC_10x8_KHR;if(n===Hl)return a===ot?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:r.COMPRESSED_RGBA_ASTC_10x10_KHR;if(n===Wl)return a===ot?r.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:r.COMPRESSED_RGBA_ASTC_12x10_KHR;if(n===ql)return a===ot?r.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:r.COMPRESSED_RGBA_ASTC_12x12_KHR}else return null;if(n===jl||n===$l||n===Xl)if(r=e.get("EXT_texture_compression_bptc"),r!==null){if(n===jl)return a===ot?r.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:r.COMPRESSED_RGBA_BPTC_UNORM_EXT;if(n===$l)return r.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;if(n===Xl)return r.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT}else return null;if(n===Kl||n===Yl||n===Jl||n===Zl)if(r=e.get("EXT_texture_compression_rgtc"),r!==null){if(n===Kl)return r.COMPRESSED_RED_RGTC1_EXT;if(n===Yl)return r.COMPRESSED_SIGNED_RED_RGTC1_EXT;if(n===Jl)return r.COMPRESSED_RED_GREEN_RGTC2_EXT;if(n===Zl)return r.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}else return null;return n===Br?i.UNSIGNED_INT_24_8:i[n]!==void 0?i[n]:null}return{convert:t}}const MC=`
4078
+ }`,_C=[new F(1,0,0),new F(-1,0,0),new F(0,1,0),new F(0,-1,0),new F(0,0,1),new F(0,0,-1)],yC=[new F(0,-1,0),new F(0,-1,0),new F(0,0,1),new F(0,0,-1),new F(0,-1,0),new F(0,-1,0)],Em=new Nt,Qr=new F,Fd=new F;function SC(i,e,t){let n=new Xp;const s=new rt,r=new rt,a=new It,o=new gy,c=new vy,l={},d=t.maxTextureSize,u={[mi]:Zt,[Zt]:mi,[gi]:gi},h=new Cn({defines:{VSM_SAMPLES:8},uniforms:{shadow_pass:{value:null},resolution:{value:new rt},radius:{value:4}},vertexShader:vC,fragmentShader:bC}),f=h.clone();f.defines.HORIZONTAL_PASS=1;const g=new Vn;g.setAttribute("position",new ti(new Float32Array([-1,-1,.5,3,-1,.5,-1,3,.5]),3));const v=new zn(g,h),m=this;this.enabled=!1,this.autoUpdate=!0,this.needsUpdate=!1,this.type=Ua;let p=this.type;this.render=function(M,A,k){if(m.enabled===!1||m.autoUpdate===!1&&m.needsUpdate===!1||M.length===0)return;M.type===r_&&(Oe("WebGLShadowMap: PCFSoftShadowMap has been deprecated. Using PCFShadowMap instead."),M.type=Ua);const y=i.getRenderTarget(),T=i.getActiveCubeFace(),R=i.getActiveMipmapLevel(),U=i.state;U.setBlending(vi),U.buffers.depth.getReversed()===!0?U.buffers.color.setClear(0,0,0,0):U.buffers.color.setClear(1,1,1,1),U.buffers.depth.setTest(!0),U.setScissorTest(!1);const B=p!==this.type;B&&A.traverse(function(q){q.material&&(Array.isArray(q.material)?q.material.forEach(K=>K.needsUpdate=!0):q.material.needsUpdate=!0)});for(let q=0,K=M.length;q<K;q++){const H=M[q],W=H.shadow;if(W===void 0){Oe("WebGLShadowMap:",H,"has no shadow.");continue}if(W.autoUpdate===!1&&W.needsUpdate===!1)continue;s.copy(W.mapSize);const te=W.getFrameExtents();if(s.multiply(te),r.copy(W.mapSize),(s.x>d||s.y>d)&&(s.x>d&&(r.x=Math.floor(d/te.x),s.x=r.x*te.x,W.mapSize.x=r.x),s.y>d&&(r.y=Math.floor(d/te.y),s.y=r.y*te.y,W.mapSize.y=r.y)),W.map===null||B===!0){if(W.map!==null&&(W.map.depthTexture!==null&&(W.map.depthTexture.dispose(),W.map.depthTexture=null),W.map.dispose()),this.type===Or){if(H.isPointLight){Oe("WebGLShadowMap: VSM shadow maps are not supported for PointLights. Use PCF or BasicShadowMap instead.");continue}W.map=new ei(s.x,s.y,{format:Hs,type:_i,minFilter:Kt,magFilter:Kt,generateMipmaps:!1}),W.map.texture.name=H.name+".shadowMap",W.map.depthTexture=new Yr(s.x,s.y,Zn),W.map.depthTexture.name=H.name+".shadowMapDepth",W.map.depthTexture.format=yi,W.map.depthTexture.compareFunction=null,W.map.depthTexture.minFilter=Xt,W.map.depthTexture.magFilter=Xt}else{H.isPointLight?(W.map=new $p(s.x),W.map.depthTexture=new py(s.x,Jn)):(W.map=new ei(s.x,s.y),W.map.depthTexture=new Yr(s.x,s.y,Jn)),W.map.depthTexture.name=H.name+".shadowMap",W.map.depthTexture.format=yi;const de=i.state.buffers.depth.getReversed();this.type===Ua?(W.map.depthTexture.compareFunction=de?ed:Ql,W.map.depthTexture.minFilter=Kt,W.map.depthTexture.magFilter=Kt):(W.map.depthTexture.compareFunction=null,W.map.depthTexture.minFilter=Xt,W.map.depthTexture.magFilter=Xt)}W.camera.updateProjectionMatrix()}const ve=W.map.isWebGLCubeRenderTarget?6:1;for(let de=0;de<ve;de++){if(W.map.isWebGLCubeRenderTarget)i.setRenderTarget(W.map,de),i.clear();else{de===0&&(i.setRenderTarget(W.map),i.clear());const _e=W.getViewport(de);a.set(r.x*_e.x,r.y*_e.y,r.x*_e.z,r.y*_e.w),U.viewport(a)}if(H.isPointLight){const _e=W.camera,Ve=W.matrix,Be=H.distance||_e.far;Be!==_e.far&&(_e.far=Be,_e.updateProjectionMatrix()),Qr.setFromMatrixPosition(H.matrixWorld),_e.position.copy(Qr),Fd.copy(_e.position),Fd.add(_C[de]),_e.up.copy(yC[de]),_e.lookAt(Fd),_e.updateMatrixWorld(),Ve.makeTranslation(-Qr.x,-Qr.y,-Qr.z),Em.multiplyMatrices(_e.projectionMatrix,_e.matrixWorldInverse),W._frustum.setFromProjectionMatrix(Em,_e.coordinateSystem,_e.reversedDepth)}else W.updateMatrices(H);n=W.getFrustum(),b(A,k,W.camera,H,this.type)}W.isPointLightShadow!==!0&&this.type===Or&&x(W,k),W.needsUpdate=!1}p=this.type,m.needsUpdate=!1,i.setRenderTarget(y,T,R)};function x(M,A){const k=e.update(v);h.defines.VSM_SAMPLES!==M.blurSamples&&(h.defines.VSM_SAMPLES=M.blurSamples,f.defines.VSM_SAMPLES=M.blurSamples,h.needsUpdate=!0,f.needsUpdate=!0),M.mapPass===null&&(M.mapPass=new ei(s.x,s.y,{format:Hs,type:_i})),h.uniforms.shadow_pass.value=M.map.depthTexture,h.uniforms.resolution.value=M.mapSize,h.uniforms.radius.value=M.radius,i.setRenderTarget(M.mapPass),i.clear(),i.renderBufferDirect(A,null,k,h,v,null),f.uniforms.shadow_pass.value=M.mapPass.texture,f.uniforms.resolution.value=M.mapSize,f.uniforms.radius.value=M.radius,i.setRenderTarget(M.map),i.clear(),i.renderBufferDirect(A,null,k,f,v,null)}function C(M,A,k,y){let T=null;const R=k.isPointLight===!0?M.customDistanceMaterial:M.customDepthMaterial;if(R!==void 0)T=R;else if(T=k.isPointLight===!0?c:o,i.localClippingEnabled&&A.clipShadows===!0&&Array.isArray(A.clippingPlanes)&&A.clippingPlanes.length!==0||A.displacementMap&&A.displacementScale!==0||A.alphaMap&&A.alphaTest>0||A.map&&A.alphaTest>0||A.alphaToCoverage===!0){const U=T.uuid,B=A.uuid;let q=l[U];q===void 0&&(q={},l[U]=q);let K=q[B];K===void 0&&(K=T.clone(),q[B]=K,A.addEventListener("dispose",S)),T=K}if(T.visible=A.visible,T.wireframe=A.wireframe,y===Or?T.side=A.shadowSide!==null?A.shadowSide:A.side:T.side=A.shadowSide!==null?A.shadowSide:u[A.side],T.alphaMap=A.alphaMap,T.alphaTest=A.alphaToCoverage===!0?.5:A.alphaTest,T.map=A.map,T.clipShadows=A.clipShadows,T.clippingPlanes=A.clippingPlanes,T.clipIntersection=A.clipIntersection,T.displacementMap=A.displacementMap,T.displacementScale=A.displacementScale,T.displacementBias=A.displacementBias,T.wireframeLinewidth=A.wireframeLinewidth,T.linewidth=A.linewidth,k.isPointLight===!0&&T.isMeshDistanceMaterial===!0){const U=i.properties.get(T);U.light=k}return T}function b(M,A,k,y,T){if(M.visible===!1)return;if(M.layers.test(A.layers)&&(M.isMesh||M.isLine||M.isPoints)&&(M.castShadow||M.receiveShadow&&T===Or)&&(!M.frustumCulled||n.intersectsObject(M))){M.modelViewMatrix.multiplyMatrices(k.matrixWorldInverse,M.matrixWorld);const B=e.update(M),q=M.material;if(Array.isArray(q)){const K=B.groups;for(let H=0,W=K.length;H<W;H++){const te=K[H],ve=q[te.materialIndex];if(ve&&ve.visible){const de=C(M,ve,y,T);M.onBeforeShadow(i,M,A,k,B,de,te),i.renderBufferDirect(k,null,B,de,M,te),M.onAfterShadow(i,M,A,k,B,de,te)}}}else if(q.visible){const K=C(M,q,y,T);M.onBeforeShadow(i,M,A,k,B,K,null),i.renderBufferDirect(k,null,B,K,M,null),M.onAfterShadow(i,M,A,k,B,K,null)}}const U=M.children;for(let B=0,q=U.length;B<q;B++)b(U[B],A,k,y,T)}function S(M){M.target.removeEventListener("dispose",S);for(const k in l){const y=l[k],T=M.target.uuid;T in y&&(y[T].dispose(),delete y[T])}}}const xC={[il]:sl,[rl]:cl,[al]:ll,[zs]:ol,[sl]:il,[cl]:rl,[ll]:al,[ol]:zs};function TC(i,e){function t(){let D=!1;const ye=new It;let oe=null;const xe=new It(0,0,0,0);return{setMask:function(se){oe!==se&&!D&&(i.colorMask(se,se,se,se),oe=se)},setLocked:function(se){D=se},setClear:function(se,Q,ue,Fe,St){St===!0&&(se*=Fe,Q*=Fe,ue*=Fe),ye.set(se,Q,ue,Fe),xe.equals(ye)===!1&&(i.clearColor(se,Q,ue,Fe),xe.copy(ye))},reset:function(){D=!1,oe=null,xe.set(-1,0,0,0)}}}function n(){let D=!1,ye=!1,oe=null,xe=null,se=null;return{setReversed:function(Q){if(ye!==Q){const ue=e.get("EXT_clip_control");Q?ue.clipControlEXT(ue.LOWER_LEFT_EXT,ue.ZERO_TO_ONE_EXT):ue.clipControlEXT(ue.LOWER_LEFT_EXT,ue.NEGATIVE_ONE_TO_ONE_EXT),ye=Q;const Fe=se;se=null,this.setClear(Fe)}},getReversed:function(){return ye},setTest:function(Q){Q?ie(i.DEPTH_TEST):Ce(i.DEPTH_TEST)},setMask:function(Q){oe!==Q&&!D&&(i.depthMask(Q),oe=Q)},setFunc:function(Q){if(ye&&(Q=xC[Q]),xe!==Q){switch(Q){case il:i.depthFunc(i.NEVER);break;case sl:i.depthFunc(i.ALWAYS);break;case rl:i.depthFunc(i.LESS);break;case zs:i.depthFunc(i.LEQUAL);break;case al:i.depthFunc(i.EQUAL);break;case ol:i.depthFunc(i.GEQUAL);break;case cl:i.depthFunc(i.GREATER);break;case ll:i.depthFunc(i.NOTEQUAL);break;default:i.depthFunc(i.LEQUAL)}xe=Q}},setLocked:function(Q){D=Q},setClear:function(Q){se!==Q&&(ye&&(Q=1-Q),i.clearDepth(Q),se=Q)},reset:function(){D=!1,oe=null,xe=null,se=null,ye=!1}}}function s(){let D=!1,ye=null,oe=null,xe=null,se=null,Q=null,ue=null,Fe=null,St=null;return{setTest:function(lt){D||(lt?ie(i.STENCIL_TEST):Ce(i.STENCIL_TEST))},setMask:function(lt){ye!==lt&&!D&&(i.stencilMask(lt),ye=lt)},setFunc:function(lt,ai,Ai){(oe!==lt||xe!==ai||se!==Ai)&&(i.stencilFunc(lt,ai,Ai),oe=lt,xe=ai,se=Ai)},setOp:function(lt,ai,Ai){(Q!==lt||ue!==ai||Fe!==Ai)&&(i.stencilOp(lt,ai,Ai),Q=lt,ue=ai,Fe=Ai)},setLocked:function(lt){D=lt},setClear:function(lt){St!==lt&&(i.clearStencil(lt),St=lt)},reset:function(){D=!1,ye=null,oe=null,xe=null,se=null,Q=null,ue=null,Fe=null,St=null}}}const r=new t,a=new n,o=new s,c=new WeakMap,l=new WeakMap;let d={},u={},h=new WeakMap,f=[],g=null,v=!1,m=null,p=null,x=null,C=null,b=null,S=null,M=null,A=new Ze(0,0,0),k=0,y=!1,T=null,R=null,U=null,B=null,q=null;const K=i.getParameter(i.MAX_COMBINED_TEXTURE_IMAGE_UNITS);let H=!1,W=0;const te=i.getParameter(i.VERSION);te.indexOf("WebGL")!==-1?(W=parseFloat(/^WebGL (\d)/.exec(te)[1]),H=W>=1):te.indexOf("OpenGL ES")!==-1&&(W=parseFloat(/^OpenGL ES (\d)/.exec(te)[1]),H=W>=2);let ve=null,de={};const _e=i.getParameter(i.SCISSOR_BOX),Ve=i.getParameter(i.VIEWPORT),Be=new It().fromArray(_e),Ct=new It().fromArray(Ve);function mt(D,ye,oe,xe){const se=new Uint8Array(4),Q=i.createTexture();i.bindTexture(D,Q),i.texParameteri(D,i.TEXTURE_MIN_FILTER,i.NEAREST),i.texParameteri(D,i.TEXTURE_MAG_FILTER,i.NEAREST);for(let ue=0;ue<oe;ue++)D===i.TEXTURE_3D||D===i.TEXTURE_2D_ARRAY?i.texImage3D(ye,0,i.RGBA,1,1,xe,0,i.RGBA,i.UNSIGNED_BYTE,se):i.texImage2D(ye+ue,0,i.RGBA,1,1,0,i.RGBA,i.UNSIGNED_BYTE,se);return Q}const X={};X[i.TEXTURE_2D]=mt(i.TEXTURE_2D,i.TEXTURE_2D,1),X[i.TEXTURE_CUBE_MAP]=mt(i.TEXTURE_CUBE_MAP,i.TEXTURE_CUBE_MAP_POSITIVE_X,6),X[i.TEXTURE_2D_ARRAY]=mt(i.TEXTURE_2D_ARRAY,i.TEXTURE_2D_ARRAY,1,1),X[i.TEXTURE_3D]=mt(i.TEXTURE_3D,i.TEXTURE_3D,1,1),r.setClear(0,0,0,1),a.setClear(1),o.setClear(0),ie(i.DEPTH_TEST),a.setFunc(zs),qe(!1),Ot(Jf),ie(i.CULL_FACE),ct(vi);function ie(D){d[D]!==!0&&(i.enable(D),d[D]=!0)}function Ce(D){d[D]!==!1&&(i.disable(D),d[D]=!1)}function Ge(D,ye){return u[D]!==ye?(i.bindFramebuffer(D,ye),u[D]=ye,D===i.DRAW_FRAMEBUFFER&&(u[i.FRAMEBUFFER]=ye),D===i.FRAMEBUFFER&&(u[i.DRAW_FRAMEBUFFER]=ye),!0):!1}function we(D,ye){let oe=f,xe=!1;if(D){oe=h.get(ye),oe===void 0&&(oe=[],h.set(ye,oe));const se=D.textures;if(oe.length!==se.length||oe[0]!==i.COLOR_ATTACHMENT0){for(let Q=0,ue=se.length;Q<ue;Q++)oe[Q]=i.COLOR_ATTACHMENT0+Q;oe.length=se.length,xe=!0}}else oe[0]!==i.BACK&&(oe[0]=i.BACK,xe=!0);xe&&i.drawBuffers(oe)}function nt(D){return g!==D?(i.useProgram(D),g=D,!0):!1}const jt={[ls]:i.FUNC_ADD,[o_]:i.FUNC_SUBTRACT,[c_]:i.FUNC_REVERSE_SUBTRACT};jt[l_]=i.MIN,jt[d_]=i.MAX;const et={[u_]:i.ZERO,[h_]:i.ONE,[f_]:i.SRC_COLOR,[tl]:i.SRC_ALPHA,[__]:i.SRC_ALPHA_SATURATE,[v_]:i.DST_COLOR,[m_]:i.DST_ALPHA,[p_]:i.ONE_MINUS_SRC_COLOR,[nl]:i.ONE_MINUS_SRC_ALPHA,[b_]:i.ONE_MINUS_DST_COLOR,[g_]:i.ONE_MINUS_DST_ALPHA,[y_]:i.CONSTANT_COLOR,[S_]:i.ONE_MINUS_CONSTANT_COLOR,[x_]:i.CONSTANT_ALPHA,[T_]:i.ONE_MINUS_CONSTANT_ALPHA};function ct(D,ye,oe,xe,se,Q,ue,Fe,St,lt){if(D===vi){v===!0&&(Ce(i.BLEND),v=!1);return}if(v===!1&&(ie(i.BLEND),v=!0),D!==a_){if(D!==m||lt!==y){if((p!==ls||b!==ls)&&(i.blendEquation(i.FUNC_ADD),p=ls,b=ls),lt)switch(D){case Vs:i.blendFuncSeparate(i.ONE,i.ONE_MINUS_SRC_ALPHA,i.ONE,i.ONE_MINUS_SRC_ALPHA);break;case el:i.blendFunc(i.ONE,i.ONE);break;case Zf:i.blendFuncSeparate(i.ZERO,i.ONE_MINUS_SRC_COLOR,i.ZERO,i.ONE);break;case Qf:i.blendFuncSeparate(i.DST_COLOR,i.ONE_MINUS_SRC_ALPHA,i.ZERO,i.ONE);break;default:tt("WebGLState: Invalid blending: ",D);break}else switch(D){case Vs:i.blendFuncSeparate(i.SRC_ALPHA,i.ONE_MINUS_SRC_ALPHA,i.ONE,i.ONE_MINUS_SRC_ALPHA);break;case el:i.blendFuncSeparate(i.SRC_ALPHA,i.ONE,i.ONE,i.ONE);break;case Zf:tt("WebGLState: SubtractiveBlending requires material.premultipliedAlpha = true");break;case Qf:tt("WebGLState: MultiplyBlending requires material.premultipliedAlpha = true");break;default:tt("WebGLState: Invalid blending: ",D);break}x=null,C=null,S=null,M=null,A.set(0,0,0),k=0,m=D,y=lt}return}se=se||ye,Q=Q||oe,ue=ue||xe,(ye!==p||se!==b)&&(i.blendEquationSeparate(jt[ye],jt[se]),p=ye,b=se),(oe!==x||xe!==C||Q!==S||ue!==M)&&(i.blendFuncSeparate(et[oe],et[xe],et[Q],et[ue]),x=oe,C=xe,S=Q,M=ue),(Fe.equals(A)===!1||St!==k)&&(i.blendColor(Fe.r,Fe.g,Fe.b,St),A.copy(Fe),k=St),m=D,y=!1}function bt(D,ye){D.side===gi?Ce(i.CULL_FACE):ie(i.CULL_FACE);let oe=D.side===Zt;ye&&(oe=!oe),qe(oe),D.blending===Vs&&D.transparent===!1?ct(vi):ct(D.blending,D.blendEquation,D.blendSrc,D.blendDst,D.blendEquationAlpha,D.blendSrcAlpha,D.blendDstAlpha,D.blendColor,D.blendAlpha,D.premultipliedAlpha),a.setFunc(D.depthFunc),a.setTest(D.depthTest),a.setMask(D.depthWrite),r.setMask(D.colorWrite);const xe=D.stencilWrite;o.setTest(xe),xe&&(o.setMask(D.stencilWriteMask),o.setFunc(D.stencilFunc,D.stencilRef,D.stencilFuncMask),o.setOp(D.stencilFail,D.stencilZFail,D.stencilZPass)),Ft(D.polygonOffset,D.polygonOffsetFactor,D.polygonOffsetUnits),D.alphaToCoverage===!0?ie(i.SAMPLE_ALPHA_TO_COVERAGE):Ce(i.SAMPLE_ALPHA_TO_COVERAGE)}function qe(D){T!==D&&(D?i.frontFace(i.CW):i.frontFace(i.CCW),T=D)}function Ot(D){D!==i_?(ie(i.CULL_FACE),D!==R&&(D===Jf?i.cullFace(i.BACK):D===s_?i.cullFace(i.FRONT):i.cullFace(i.FRONT_AND_BACK))):Ce(i.CULL_FACE),R=D}function I(D){D!==U&&(H&&i.lineWidth(D),U=D)}function Ft(D,ye,oe){D?(ie(i.POLYGON_OFFSET_FILL),(B!==ye||q!==oe)&&(i.polygonOffset(ye,oe),B=ye,q=oe)):Ce(i.POLYGON_OFFSET_FILL)}function at(D){D?ie(i.SCISSOR_TEST):Ce(i.SCISSOR_TEST)}function yt(D){D===void 0&&(D=i.TEXTURE0+K-1),ve!==D&&(i.activeTexture(D),ve=D)}function Re(D,ye,oe){oe===void 0&&(ve===null?oe=i.TEXTURE0+K-1:oe=ve);let xe=de[oe];xe===void 0&&(xe={type:void 0,texture:void 0},de[oe]=xe),(xe.type!==D||xe.texture!==ye)&&(ve!==oe&&(i.activeTexture(oe),ve=oe),i.bindTexture(D,ye||X[D]),xe.type=D,xe.texture=ye)}function w(){const D=de[ve];D!==void 0&&D.type!==void 0&&(i.bindTexture(D.type,null),D.type=void 0,D.texture=void 0)}function _(){try{i.compressedTexImage2D(...arguments)}catch(D){tt("WebGLState:",D)}}function L(){try{i.compressedTexImage3D(...arguments)}catch(D){tt("WebGLState:",D)}}function $(){try{i.texSubImage2D(...arguments)}catch(D){tt("WebGLState:",D)}}function ee(){try{i.texSubImage3D(...arguments)}catch(D){tt("WebGLState:",D)}}function j(){try{i.compressedTexSubImage2D(...arguments)}catch(D){tt("WebGLState:",D)}}function ke(){try{i.compressedTexSubImage3D(...arguments)}catch(D){tt("WebGLState:",D)}}function he(){try{i.texStorage2D(...arguments)}catch(D){tt("WebGLState:",D)}}function Ae(){try{i.texStorage3D(...arguments)}catch(D){tt("WebGLState:",D)}}function Ue(){try{i.texImage2D(...arguments)}catch(D){tt("WebGLState:",D)}}function re(){try{i.texImage3D(...arguments)}catch(D){tt("WebGLState:",D)}}function pe(D){Be.equals(D)===!1&&(i.scissor(D.x,D.y,D.z,D.w),Be.copy(D))}function Me(D){Ct.equals(D)===!1&&(i.viewport(D.x,D.y,D.z,D.w),Ct.copy(D))}function Pe(D,ye){let oe=l.get(ye);oe===void 0&&(oe=new WeakMap,l.set(ye,oe));let xe=oe.get(D);xe===void 0&&(xe=i.getUniformBlockIndex(ye,D.name),oe.set(D,xe))}function fe(D,ye){const xe=l.get(ye).get(D);c.get(ye)!==xe&&(i.uniformBlockBinding(ye,xe,D.__bindingPointIndex),c.set(ye,xe))}function je(){i.disable(i.BLEND),i.disable(i.CULL_FACE),i.disable(i.DEPTH_TEST),i.disable(i.POLYGON_OFFSET_FILL),i.disable(i.SCISSOR_TEST),i.disable(i.STENCIL_TEST),i.disable(i.SAMPLE_ALPHA_TO_COVERAGE),i.blendEquation(i.FUNC_ADD),i.blendFunc(i.ONE,i.ZERO),i.blendFuncSeparate(i.ONE,i.ZERO,i.ONE,i.ZERO),i.blendColor(0,0,0,0),i.colorMask(!0,!0,!0,!0),i.clearColor(0,0,0,0),i.depthMask(!0),i.depthFunc(i.LESS),a.setReversed(!1),i.clearDepth(1),i.stencilMask(4294967295),i.stencilFunc(i.ALWAYS,0,4294967295),i.stencilOp(i.KEEP,i.KEEP,i.KEEP),i.clearStencil(0),i.cullFace(i.BACK),i.frontFace(i.CCW),i.polygonOffset(0,0),i.activeTexture(i.TEXTURE0),i.bindFramebuffer(i.FRAMEBUFFER,null),i.bindFramebuffer(i.DRAW_FRAMEBUFFER,null),i.bindFramebuffer(i.READ_FRAMEBUFFER,null),i.useProgram(null),i.lineWidth(1),i.scissor(0,0,i.canvas.width,i.canvas.height),i.viewport(0,0,i.canvas.width,i.canvas.height),d={},ve=null,de={},u={},h=new WeakMap,f=[],g=null,v=!1,m=null,p=null,x=null,C=null,b=null,S=null,M=null,A=new Ze(0,0,0),k=0,y=!1,T=null,R=null,U=null,B=null,q=null,Be.set(0,0,i.canvas.width,i.canvas.height),Ct.set(0,0,i.canvas.width,i.canvas.height),r.reset(),a.reset(),o.reset()}return{buffers:{color:r,depth:a,stencil:o},enable:ie,disable:Ce,bindFramebuffer:Ge,drawBuffers:we,useProgram:nt,setBlending:ct,setMaterial:bt,setFlipSided:qe,setCullFace:Ot,setLineWidth:I,setPolygonOffset:Ft,setScissorTest:at,activeTexture:yt,bindTexture:Re,unbindTexture:w,compressedTexImage2D:_,compressedTexImage3D:L,texImage2D:Ue,texImage3D:re,updateUBOMapping:Pe,uniformBlockBinding:fe,texStorage2D:he,texStorage3D:Ae,texSubImage2D:$,texSubImage3D:ee,compressedTexSubImage2D:j,compressedTexSubImage3D:ke,scissor:pe,viewport:Me,reset:je}}function CC(i,e,t,n,s,r,a){const o=e.has("WEBGL_multisampled_render_to_texture")?e.get("WEBGL_multisampled_render_to_texture"):null,c=typeof navigator>"u"?!1:/OculusBrowser/g.test(navigator.userAgent),l=new rt,d=new WeakMap;let u;const h=new WeakMap;let f=!1;try{f=typeof OffscreenCanvas<"u"&&new OffscreenCanvas(1,1).getContext("2d")!==null}catch{}function g(w,_){return f?new OffscreenCanvas(w,_):qa("canvas")}function v(w,_,L){let $=1;const ee=Re(w);if((ee.width>L||ee.height>L)&&($=L/Math.max(ee.width,ee.height)),$<1)if(typeof HTMLImageElement<"u"&&w instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&w instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&w instanceof ImageBitmap||typeof VideoFrame<"u"&&w instanceof VideoFrame){const j=Math.floor($*ee.width),ke=Math.floor($*ee.height);u===void 0&&(u=g(j,ke));const he=_?g(j,ke):u;return he.width=j,he.height=ke,he.getContext("2d").drawImage(w,0,0,j,ke),Oe("WebGLRenderer: Texture has been resized from ("+ee.width+"x"+ee.height+") to ("+j+"x"+ke+")."),he}else return"data"in w&&Oe("WebGLRenderer: Image in DataTexture is too big ("+ee.width+"x"+ee.height+")."),w;return w}function m(w){return w.generateMipmaps}function p(w){i.generateMipmap(w)}function x(w){return w.isWebGLCubeRenderTarget?i.TEXTURE_CUBE_MAP:w.isWebGL3DRenderTarget?i.TEXTURE_3D:w.isWebGLArrayRenderTarget||w.isCompressedArrayTexture?i.TEXTURE_2D_ARRAY:i.TEXTURE_2D}function C(w,_,L,$,ee=!1){if(w!==null){if(i[w]!==void 0)return i[w];Oe("WebGLRenderer: Attempt to use non-existing WebGL internal format '"+w+"'")}let j=_;if(_===i.RED&&(L===i.FLOAT&&(j=i.R32F),L===i.HALF_FLOAT&&(j=i.R16F),L===i.UNSIGNED_BYTE&&(j=i.R8)),_===i.RED_INTEGER&&(L===i.UNSIGNED_BYTE&&(j=i.R8UI),L===i.UNSIGNED_SHORT&&(j=i.R16UI),L===i.UNSIGNED_INT&&(j=i.R32UI),L===i.BYTE&&(j=i.R8I),L===i.SHORT&&(j=i.R16I),L===i.INT&&(j=i.R32I)),_===i.RG&&(L===i.FLOAT&&(j=i.RG32F),L===i.HALF_FLOAT&&(j=i.RG16F),L===i.UNSIGNED_BYTE&&(j=i.RG8)),_===i.RG_INTEGER&&(L===i.UNSIGNED_BYTE&&(j=i.RG8UI),L===i.UNSIGNED_SHORT&&(j=i.RG16UI),L===i.UNSIGNED_INT&&(j=i.RG32UI),L===i.BYTE&&(j=i.RG8I),L===i.SHORT&&(j=i.RG16I),L===i.INT&&(j=i.RG32I)),_===i.RGB_INTEGER&&(L===i.UNSIGNED_BYTE&&(j=i.RGB8UI),L===i.UNSIGNED_SHORT&&(j=i.RGB16UI),L===i.UNSIGNED_INT&&(j=i.RGB32UI),L===i.BYTE&&(j=i.RGB8I),L===i.SHORT&&(j=i.RGB16I),L===i.INT&&(j=i.RGB32I)),_===i.RGBA_INTEGER&&(L===i.UNSIGNED_BYTE&&(j=i.RGBA8UI),L===i.UNSIGNED_SHORT&&(j=i.RGBA16UI),L===i.UNSIGNED_INT&&(j=i.RGBA32UI),L===i.BYTE&&(j=i.RGBA8I),L===i.SHORT&&(j=i.RGBA16I),L===i.INT&&(j=i.RGBA32I)),_===i.RGB&&(L===i.UNSIGNED_INT_5_9_9_9_REV&&(j=i.RGB9_E5),L===i.UNSIGNED_INT_10F_11F_11F_REV&&(j=i.R11F_G11F_B10F)),_===i.RGBA){const ke=ee?Ha:Qe.getTransfer($);L===i.FLOAT&&(j=i.RGBA32F),L===i.HALF_FLOAT&&(j=i.RGBA16F),L===i.UNSIGNED_BYTE&&(j=ke===ot?i.SRGB8_ALPHA8:i.RGBA8),L===i.UNSIGNED_SHORT_4_4_4_4&&(j=i.RGBA4),L===i.UNSIGNED_SHORT_5_5_5_1&&(j=i.RGB5_A1)}return(j===i.R16F||j===i.R32F||j===i.RG16F||j===i.RG32F||j===i.RGBA16F||j===i.RGBA32F)&&e.get("EXT_color_buffer_float"),j}function b(w,_){let L;return w?_===null||_===Jn||_===Br?L=i.DEPTH24_STENCIL8:_===Zn?L=i.DEPTH32F_STENCIL8:_===Fr&&(L=i.DEPTH24_STENCIL8,Oe("DepthTexture: 16 bit depth attachment is not supported with stencil. Using 24-bit attachment.")):_===null||_===Jn||_===Br?L=i.DEPTH_COMPONENT24:_===Zn?L=i.DEPTH_COMPONENT32F:_===Fr&&(L=i.DEPTH_COMPONENT16),L}function S(w,_){return m(w)===!0||w.isFramebufferTexture&&w.minFilter!==Xt&&w.minFilter!==Kt?Math.log2(Math.max(_.width,_.height))+1:w.mipmaps!==void 0&&w.mipmaps.length>0?w.mipmaps.length:w.isCompressedTexture&&Array.isArray(w.image)?_.mipmaps.length:1}function M(w){const _=w.target;_.removeEventListener("dispose",M),k(_),_.isVideoTexture&&d.delete(_)}function A(w){const _=w.target;_.removeEventListener("dispose",A),T(_)}function k(w){const _=n.get(w);if(_.__webglInit===void 0)return;const L=w.source,$=h.get(L);if($){const ee=$[_.__cacheKey];ee.usedTimes--,ee.usedTimes===0&&y(w),Object.keys($).length===0&&h.delete(L)}n.remove(w)}function y(w){const _=n.get(w);i.deleteTexture(_.__webglTexture);const L=w.source,$=h.get(L);delete $[_.__cacheKey],a.memory.textures--}function T(w){const _=n.get(w);if(w.depthTexture&&(w.depthTexture.dispose(),n.remove(w.depthTexture)),w.isWebGLCubeRenderTarget)for(let $=0;$<6;$++){if(Array.isArray(_.__webglFramebuffer[$]))for(let ee=0;ee<_.__webglFramebuffer[$].length;ee++)i.deleteFramebuffer(_.__webglFramebuffer[$][ee]);else i.deleteFramebuffer(_.__webglFramebuffer[$]);_.__webglDepthbuffer&&i.deleteRenderbuffer(_.__webglDepthbuffer[$])}else{if(Array.isArray(_.__webglFramebuffer))for(let $=0;$<_.__webglFramebuffer.length;$++)i.deleteFramebuffer(_.__webglFramebuffer[$]);else i.deleteFramebuffer(_.__webglFramebuffer);if(_.__webglDepthbuffer&&i.deleteRenderbuffer(_.__webglDepthbuffer),_.__webglMultisampledFramebuffer&&i.deleteFramebuffer(_.__webglMultisampledFramebuffer),_.__webglColorRenderbuffer)for(let $=0;$<_.__webglColorRenderbuffer.length;$++)_.__webglColorRenderbuffer[$]&&i.deleteRenderbuffer(_.__webglColorRenderbuffer[$]);_.__webglDepthRenderbuffer&&i.deleteRenderbuffer(_.__webglDepthRenderbuffer)}const L=w.textures;for(let $=0,ee=L.length;$<ee;$++){const j=n.get(L[$]);j.__webglTexture&&(i.deleteTexture(j.__webglTexture),a.memory.textures--),n.remove(L[$])}n.remove(w)}let R=0;function U(){R=0}function B(){const w=R;return w>=s.maxTextures&&Oe("WebGLTextures: Trying to use "+w+" texture units while this GPU supports only "+s.maxTextures),R+=1,w}function q(w){const _=[];return _.push(w.wrapS),_.push(w.wrapT),_.push(w.wrapR||0),_.push(w.magFilter),_.push(w.minFilter),_.push(w.anisotropy),_.push(w.internalFormat),_.push(w.format),_.push(w.type),_.push(w.generateMipmaps),_.push(w.premultiplyAlpha),_.push(w.flipY),_.push(w.unpackAlignment),_.push(w.colorSpace),_.join()}function K(w,_){const L=n.get(w);if(w.isVideoTexture&&at(w),w.isRenderTargetTexture===!1&&w.isExternalTexture!==!0&&w.version>0&&L.__version!==w.version){const $=w.image;if($===null)Oe("WebGLRenderer: Texture marked for update but no image data found.");else if($.complete===!1)Oe("WebGLRenderer: Texture marked for update but image is incomplete");else{X(L,w,_);return}}else w.isExternalTexture&&(L.__webglTexture=w.sourceTexture?w.sourceTexture:null);t.bindTexture(i.TEXTURE_2D,L.__webglTexture,i.TEXTURE0+_)}function H(w,_){const L=n.get(w);if(w.isRenderTargetTexture===!1&&w.version>0&&L.__version!==w.version){X(L,w,_);return}else w.isExternalTexture&&(L.__webglTexture=w.sourceTexture?w.sourceTexture:null);t.bindTexture(i.TEXTURE_2D_ARRAY,L.__webglTexture,i.TEXTURE0+_)}function W(w,_){const L=n.get(w);if(w.isRenderTargetTexture===!1&&w.version>0&&L.__version!==w.version){X(L,w,_);return}t.bindTexture(i.TEXTURE_3D,L.__webglTexture,i.TEXTURE0+_)}function te(w,_){const L=n.get(w);if(w.isCubeDepthTexture!==!0&&w.version>0&&L.__version!==w.version){ie(L,w,_);return}t.bindTexture(i.TEXTURE_CUBE_MAP,L.__webglTexture,i.TEXTURE0+_)}const ve={[hl]:i.REPEAT,[bi]:i.CLAMP_TO_EDGE,[fl]:i.MIRRORED_REPEAT},de={[Xt]:i.NEAREST,[M_]:i.NEAREST_MIPMAP_NEAREST,[Fa]:i.NEAREST_MIPMAP_LINEAR,[Kt]:i.LINEAR,[pl]:i.LINEAR_MIPMAP_NEAREST,[us]:i.LINEAR_MIPMAP_LINEAR},_e={[P_]:i.NEVER,[N_]:i.ALWAYS,[k_]:i.LESS,[Ql]:i.LEQUAL,[I_]:i.EQUAL,[ed]:i.GEQUAL,[D_]:i.GREATER,[L_]:i.NOTEQUAL};function Ve(w,_){if(_.type===Zn&&e.has("OES_texture_float_linear")===!1&&(_.magFilter===Kt||_.magFilter===pl||_.magFilter===Fa||_.magFilter===us||_.minFilter===Kt||_.minFilter===pl||_.minFilter===Fa||_.minFilter===us)&&Oe("WebGLRenderer: Unable to use linear filtering with floating point textures. OES_texture_float_linear not supported on this device."),i.texParameteri(w,i.TEXTURE_WRAP_S,ve[_.wrapS]),i.texParameteri(w,i.TEXTURE_WRAP_T,ve[_.wrapT]),(w===i.TEXTURE_3D||w===i.TEXTURE_2D_ARRAY)&&i.texParameteri(w,i.TEXTURE_WRAP_R,ve[_.wrapR]),i.texParameteri(w,i.TEXTURE_MAG_FILTER,de[_.magFilter]),i.texParameteri(w,i.TEXTURE_MIN_FILTER,de[_.minFilter]),_.compareFunction&&(i.texParameteri(w,i.TEXTURE_COMPARE_MODE,i.COMPARE_REF_TO_TEXTURE),i.texParameteri(w,i.TEXTURE_COMPARE_FUNC,_e[_.compareFunction])),e.has("EXT_texture_filter_anisotropic")===!0){if(_.magFilter===Xt||_.minFilter!==Fa&&_.minFilter!==us||_.type===Zn&&e.has("OES_texture_float_linear")===!1)return;if(_.anisotropy>1||n.get(_).__currentAnisotropy){const L=e.get("EXT_texture_filter_anisotropic");i.texParameterf(w,L.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(_.anisotropy,s.getMaxAnisotropy())),n.get(_).__currentAnisotropy=_.anisotropy}}}function Be(w,_){let L=!1;w.__webglInit===void 0&&(w.__webglInit=!0,_.addEventListener("dispose",M));const $=_.source;let ee=h.get($);ee===void 0&&(ee={},h.set($,ee));const j=q(_);if(j!==w.__cacheKey){ee[j]===void 0&&(ee[j]={texture:i.createTexture(),usedTimes:0},a.memory.textures++,L=!0),ee[j].usedTimes++;const ke=ee[w.__cacheKey];ke!==void 0&&(ee[w.__cacheKey].usedTimes--,ke.usedTimes===0&&y(_)),w.__cacheKey=j,w.__webglTexture=ee[j].texture}return L}function Ct(w,_,L){return Math.floor(Math.floor(w/L)/_)}function mt(w,_,L,$){const j=w.updateRanges;if(j.length===0)t.texSubImage2D(i.TEXTURE_2D,0,0,0,_.width,_.height,L,$,_.data);else{j.sort((re,pe)=>re.start-pe.start);let ke=0;for(let re=1;re<j.length;re++){const pe=j[ke],Me=j[re],Pe=pe.start+pe.count,fe=Ct(Me.start,_.width,4),je=Ct(pe.start,_.width,4);Me.start<=Pe+1&&fe===je&&Ct(Me.start+Me.count-1,_.width,4)===fe?pe.count=Math.max(pe.count,Me.start+Me.count-pe.start):(++ke,j[ke]=Me)}j.length=ke+1;const he=i.getParameter(i.UNPACK_ROW_LENGTH),Ae=i.getParameter(i.UNPACK_SKIP_PIXELS),Ue=i.getParameter(i.UNPACK_SKIP_ROWS);i.pixelStorei(i.UNPACK_ROW_LENGTH,_.width);for(let re=0,pe=j.length;re<pe;re++){const Me=j[re],Pe=Math.floor(Me.start/4),fe=Math.ceil(Me.count/4),je=Pe%_.width,D=Math.floor(Pe/_.width),ye=fe,oe=1;i.pixelStorei(i.UNPACK_SKIP_PIXELS,je),i.pixelStorei(i.UNPACK_SKIP_ROWS,D),t.texSubImage2D(i.TEXTURE_2D,0,je,D,ye,oe,L,$,_.data)}w.clearUpdateRanges(),i.pixelStorei(i.UNPACK_ROW_LENGTH,he),i.pixelStorei(i.UNPACK_SKIP_PIXELS,Ae),i.pixelStorei(i.UNPACK_SKIP_ROWS,Ue)}}function X(w,_,L){let $=i.TEXTURE_2D;(_.isDataArrayTexture||_.isCompressedArrayTexture)&&($=i.TEXTURE_2D_ARRAY),_.isData3DTexture&&($=i.TEXTURE_3D);const ee=Be(w,_),j=_.source;t.bindTexture($,w.__webglTexture,i.TEXTURE0+L);const ke=n.get(j);if(j.version!==ke.__version||ee===!0){t.activeTexture(i.TEXTURE0+L);const he=Qe.getPrimaries(Qe.workingColorSpace),Ae=_.colorSpace===Wi?null:Qe.getPrimaries(_.colorSpace),Ue=_.colorSpace===Wi||he===Ae?i.NONE:i.BROWSER_DEFAULT_WEBGL;i.pixelStorei(i.UNPACK_FLIP_Y_WEBGL,_.flipY),i.pixelStorei(i.UNPACK_PREMULTIPLY_ALPHA_WEBGL,_.premultiplyAlpha),i.pixelStorei(i.UNPACK_ALIGNMENT,_.unpackAlignment),i.pixelStorei(i.UNPACK_COLORSPACE_CONVERSION_WEBGL,Ue);let re=v(_.image,!1,s.maxTextureSize);re=yt(_,re);const pe=r.convert(_.format,_.colorSpace),Me=r.convert(_.type);let Pe=C(_.internalFormat,pe,Me,_.colorSpace,_.isVideoTexture);Ve($,_);let fe;const je=_.mipmaps,D=_.isVideoTexture!==!0,ye=ke.__version===void 0||ee===!0,oe=j.dataReady,xe=S(_,re);if(_.isDepthTexture)Pe=b(_.format===hs,_.type),ye&&(D?t.texStorage2D(i.TEXTURE_2D,1,Pe,re.width,re.height):t.texImage2D(i.TEXTURE_2D,0,Pe,re.width,re.height,0,pe,Me,null));else if(_.isDataTexture)if(je.length>0){D&&ye&&t.texStorage2D(i.TEXTURE_2D,xe,Pe,je[0].width,je[0].height);for(let se=0,Q=je.length;se<Q;se++)fe=je[se],D?oe&&t.texSubImage2D(i.TEXTURE_2D,se,0,0,fe.width,fe.height,pe,Me,fe.data):t.texImage2D(i.TEXTURE_2D,se,Pe,fe.width,fe.height,0,pe,Me,fe.data);_.generateMipmaps=!1}else D?(ye&&t.texStorage2D(i.TEXTURE_2D,xe,Pe,re.width,re.height),oe&&mt(_,re,pe,Me)):t.texImage2D(i.TEXTURE_2D,0,Pe,re.width,re.height,0,pe,Me,re.data);else if(_.isCompressedTexture)if(_.isCompressedArrayTexture){D&&ye&&t.texStorage3D(i.TEXTURE_2D_ARRAY,xe,Pe,je[0].width,je[0].height,re.depth);for(let se=0,Q=je.length;se<Q;se++)if(fe=je[se],_.format!==Nn)if(pe!==null)if(D){if(oe)if(_.layerUpdates.size>0){const ue=Jp(fe.width,fe.height,_.format,_.type);for(const Fe of _.layerUpdates){const St=fe.data.subarray(Fe*ue/fe.data.BYTES_PER_ELEMENT,(Fe+1)*ue/fe.data.BYTES_PER_ELEMENT);t.compressedTexSubImage3D(i.TEXTURE_2D_ARRAY,se,0,0,Fe,fe.width,fe.height,1,pe,St)}_.clearLayerUpdates()}else t.compressedTexSubImage3D(i.TEXTURE_2D_ARRAY,se,0,0,0,fe.width,fe.height,re.depth,pe,fe.data)}else t.compressedTexImage3D(i.TEXTURE_2D_ARRAY,se,Pe,fe.width,fe.height,re.depth,0,fe.data,0,0);else Oe("WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()");else D?oe&&t.texSubImage3D(i.TEXTURE_2D_ARRAY,se,0,0,0,fe.width,fe.height,re.depth,pe,Me,fe.data):t.texImage3D(i.TEXTURE_2D_ARRAY,se,Pe,fe.width,fe.height,re.depth,0,pe,Me,fe.data)}else{D&&ye&&t.texStorage2D(i.TEXTURE_2D,xe,Pe,je[0].width,je[0].height);for(let se=0,Q=je.length;se<Q;se++)fe=je[se],_.format!==Nn?pe!==null?D?oe&&t.compressedTexSubImage2D(i.TEXTURE_2D,se,0,0,fe.width,fe.height,pe,fe.data):t.compressedTexImage2D(i.TEXTURE_2D,se,Pe,fe.width,fe.height,0,fe.data):Oe("WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()"):D?oe&&t.texSubImage2D(i.TEXTURE_2D,se,0,0,fe.width,fe.height,pe,Me,fe.data):t.texImage2D(i.TEXTURE_2D,se,Pe,fe.width,fe.height,0,pe,Me,fe.data)}else if(_.isDataArrayTexture)if(D){if(ye&&t.texStorage3D(i.TEXTURE_2D_ARRAY,xe,Pe,re.width,re.height,re.depth),oe)if(_.layerUpdates.size>0){const se=Jp(re.width,re.height,_.format,_.type);for(const Q of _.layerUpdates){const ue=re.data.subarray(Q*se/re.data.BYTES_PER_ELEMENT,(Q+1)*se/re.data.BYTES_PER_ELEMENT);t.texSubImage3D(i.TEXTURE_2D_ARRAY,0,0,0,Q,re.width,re.height,1,pe,Me,ue)}_.clearLayerUpdates()}else t.texSubImage3D(i.TEXTURE_2D_ARRAY,0,0,0,0,re.width,re.height,re.depth,pe,Me,re.data)}else t.texImage3D(i.TEXTURE_2D_ARRAY,0,Pe,re.width,re.height,re.depth,0,pe,Me,re.data);else if(_.isData3DTexture)D?(ye&&t.texStorage3D(i.TEXTURE_3D,xe,Pe,re.width,re.height,re.depth),oe&&t.texSubImage3D(i.TEXTURE_3D,0,0,0,0,re.width,re.height,re.depth,pe,Me,re.data)):t.texImage3D(i.TEXTURE_3D,0,Pe,re.width,re.height,re.depth,0,pe,Me,re.data);else if(_.isFramebufferTexture){if(ye)if(D)t.texStorage2D(i.TEXTURE_2D,xe,Pe,re.width,re.height);else{let se=re.width,Q=re.height;for(let ue=0;ue<xe;ue++)t.texImage2D(i.TEXTURE_2D,ue,Pe,se,Q,0,pe,Me,null),se>>=1,Q>>=1}}else if(je.length>0){if(D&&ye){const se=Re(je[0]);t.texStorage2D(i.TEXTURE_2D,xe,Pe,se.width,se.height)}for(let se=0,Q=je.length;se<Q;se++)fe=je[se],D?oe&&t.texSubImage2D(i.TEXTURE_2D,se,0,0,pe,Me,fe):t.texImage2D(i.TEXTURE_2D,se,Pe,pe,Me,fe);_.generateMipmaps=!1}else if(D){if(ye){const se=Re(re);t.texStorage2D(i.TEXTURE_2D,xe,Pe,se.width,se.height)}oe&&t.texSubImage2D(i.TEXTURE_2D,0,0,0,pe,Me,re)}else t.texImage2D(i.TEXTURE_2D,0,Pe,pe,Me,re);m(_)&&p($),ke.__version=j.version,_.onUpdate&&_.onUpdate(_)}w.__version=_.version}function ie(w,_,L){if(_.image.length!==6)return;const $=Be(w,_),ee=_.source;t.bindTexture(i.TEXTURE_CUBE_MAP,w.__webglTexture,i.TEXTURE0+L);const j=n.get(ee);if(ee.version!==j.__version||$===!0){t.activeTexture(i.TEXTURE0+L);const ke=Qe.getPrimaries(Qe.workingColorSpace),he=_.colorSpace===Wi?null:Qe.getPrimaries(_.colorSpace),Ae=_.colorSpace===Wi||ke===he?i.NONE:i.BROWSER_DEFAULT_WEBGL;i.pixelStorei(i.UNPACK_FLIP_Y_WEBGL,_.flipY),i.pixelStorei(i.UNPACK_PREMULTIPLY_ALPHA_WEBGL,_.premultiplyAlpha),i.pixelStorei(i.UNPACK_ALIGNMENT,_.unpackAlignment),i.pixelStorei(i.UNPACK_COLORSPACE_CONVERSION_WEBGL,Ae);const Ue=_.isCompressedTexture||_.image[0].isCompressedTexture,re=_.image[0]&&_.image[0].isDataTexture,pe=[];for(let Q=0;Q<6;Q++)!Ue&&!re?pe[Q]=v(_.image[Q],!0,s.maxCubemapSize):pe[Q]=re?_.image[Q].image:_.image[Q],pe[Q]=yt(_,pe[Q]);const Me=pe[0],Pe=r.convert(_.format,_.colorSpace),fe=r.convert(_.type),je=C(_.internalFormat,Pe,fe,_.colorSpace),D=_.isVideoTexture!==!0,ye=j.__version===void 0||$===!0,oe=ee.dataReady;let xe=S(_,Me);Ve(i.TEXTURE_CUBE_MAP,_);let se;if(Ue){D&&ye&&t.texStorage2D(i.TEXTURE_CUBE_MAP,xe,je,Me.width,Me.height);for(let Q=0;Q<6;Q++){se=pe[Q].mipmaps;for(let ue=0;ue<se.length;ue++){const Fe=se[ue];_.format!==Nn?Pe!==null?D?oe&&t.compressedTexSubImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+Q,ue,0,0,Fe.width,Fe.height,Pe,Fe.data):t.compressedTexImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+Q,ue,je,Fe.width,Fe.height,0,Fe.data):Oe("WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()"):D?oe&&t.texSubImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+Q,ue,0,0,Fe.width,Fe.height,Pe,fe,Fe.data):t.texImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+Q,ue,je,Fe.width,Fe.height,0,Pe,fe,Fe.data)}}}else{if(se=_.mipmaps,D&&ye){se.length>0&&xe++;const Q=Re(pe[0]);t.texStorage2D(i.TEXTURE_CUBE_MAP,xe,je,Q.width,Q.height)}for(let Q=0;Q<6;Q++)if(re){D?oe&&t.texSubImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+Q,0,0,0,pe[Q].width,pe[Q].height,Pe,fe,pe[Q].data):t.texImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+Q,0,je,pe[Q].width,pe[Q].height,0,Pe,fe,pe[Q].data);for(let ue=0;ue<se.length;ue++){const St=se[ue].image[Q].image;D?oe&&t.texSubImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+Q,ue+1,0,0,St.width,St.height,Pe,fe,St.data):t.texImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+Q,ue+1,je,St.width,St.height,0,Pe,fe,St.data)}}else{D?oe&&t.texSubImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+Q,0,0,0,Pe,fe,pe[Q]):t.texImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+Q,0,je,Pe,fe,pe[Q]);for(let ue=0;ue<se.length;ue++){const Fe=se[ue];D?oe&&t.texSubImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+Q,ue+1,0,0,Pe,fe,Fe.image[Q]):t.texImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+Q,ue+1,je,Pe,fe,Fe.image[Q])}}}m(_)&&p(i.TEXTURE_CUBE_MAP),j.__version=ee.version,_.onUpdate&&_.onUpdate(_)}w.__version=_.version}function Ce(w,_,L,$,ee,j){const ke=r.convert(L.format,L.colorSpace),he=r.convert(L.type),Ae=C(L.internalFormat,ke,he,L.colorSpace),Ue=n.get(_),re=n.get(L);if(re.__renderTarget=_,!Ue.__hasExternalTextures){const pe=Math.max(1,_.width>>j),Me=Math.max(1,_.height>>j);ee===i.TEXTURE_3D||ee===i.TEXTURE_2D_ARRAY?t.texImage3D(ee,j,Ae,pe,Me,_.depth,0,ke,he,null):t.texImage2D(ee,j,Ae,pe,Me,0,ke,he,null)}t.bindFramebuffer(i.FRAMEBUFFER,w),Ft(_)?o.framebufferTexture2DMultisampleEXT(i.FRAMEBUFFER,$,ee,re.__webglTexture,0,I(_)):(ee===i.TEXTURE_2D||ee>=i.TEXTURE_CUBE_MAP_POSITIVE_X&&ee<=i.TEXTURE_CUBE_MAP_NEGATIVE_Z)&&i.framebufferTexture2D(i.FRAMEBUFFER,$,ee,re.__webglTexture,j),t.bindFramebuffer(i.FRAMEBUFFER,null)}function Ge(w,_,L){if(i.bindRenderbuffer(i.RENDERBUFFER,w),_.depthBuffer){const $=_.depthTexture,ee=$&&$.isDepthTexture?$.type:null,j=b(_.stencilBuffer,ee),ke=_.stencilBuffer?i.DEPTH_STENCIL_ATTACHMENT:i.DEPTH_ATTACHMENT;Ft(_)?o.renderbufferStorageMultisampleEXT(i.RENDERBUFFER,I(_),j,_.width,_.height):L?i.renderbufferStorageMultisample(i.RENDERBUFFER,I(_),j,_.width,_.height):i.renderbufferStorage(i.RENDERBUFFER,j,_.width,_.height),i.framebufferRenderbuffer(i.FRAMEBUFFER,ke,i.RENDERBUFFER,w)}else{const $=_.textures;for(let ee=0;ee<$.length;ee++){const j=$[ee],ke=r.convert(j.format,j.colorSpace),he=r.convert(j.type),Ae=C(j.internalFormat,ke,he,j.colorSpace);Ft(_)?o.renderbufferStorageMultisampleEXT(i.RENDERBUFFER,I(_),Ae,_.width,_.height):L?i.renderbufferStorageMultisample(i.RENDERBUFFER,I(_),Ae,_.width,_.height):i.renderbufferStorage(i.RENDERBUFFER,Ae,_.width,_.height)}}i.bindRenderbuffer(i.RENDERBUFFER,null)}function we(w,_,L){const $=_.isWebGLCubeRenderTarget===!0;if(t.bindFramebuffer(i.FRAMEBUFFER,w),!(_.depthTexture&&_.depthTexture.isDepthTexture))throw new Error("renderTarget.depthTexture must be an instance of THREE.DepthTexture");const ee=n.get(_.depthTexture);if(ee.__renderTarget=_,(!ee.__webglTexture||_.depthTexture.image.width!==_.width||_.depthTexture.image.height!==_.height)&&(_.depthTexture.image.width=_.width,_.depthTexture.image.height=_.height,_.depthTexture.needsUpdate=!0),$){if(ee.__webglInit===void 0&&(ee.__webglInit=!0,_.depthTexture.addEventListener("dispose",M)),ee.__webglTexture===void 0){ee.__webglTexture=i.createTexture(),t.bindTexture(i.TEXTURE_CUBE_MAP,ee.__webglTexture),Ve(i.TEXTURE_CUBE_MAP,_.depthTexture);const Ue=r.convert(_.depthTexture.format),re=r.convert(_.depthTexture.type);let pe;_.depthTexture.format===yi?pe=i.DEPTH_COMPONENT24:_.depthTexture.format===hs&&(pe=i.DEPTH24_STENCIL8);for(let Me=0;Me<6;Me++)i.texImage2D(i.TEXTURE_CUBE_MAP_POSITIVE_X+Me,0,pe,_.width,_.height,0,Ue,re,null)}}else K(_.depthTexture,0);const j=ee.__webglTexture,ke=I(_),he=$?i.TEXTURE_CUBE_MAP_POSITIVE_X+L:i.TEXTURE_2D,Ae=_.depthTexture.format===hs?i.DEPTH_STENCIL_ATTACHMENT:i.DEPTH_ATTACHMENT;if(_.depthTexture.format===yi)Ft(_)?o.framebufferTexture2DMultisampleEXT(i.FRAMEBUFFER,Ae,he,j,0,ke):i.framebufferTexture2D(i.FRAMEBUFFER,Ae,he,j,0);else if(_.depthTexture.format===hs)Ft(_)?o.framebufferTexture2DMultisampleEXT(i.FRAMEBUFFER,Ae,he,j,0,ke):i.framebufferTexture2D(i.FRAMEBUFFER,Ae,he,j,0);else throw new Error("Unknown depthTexture format")}function nt(w){const _=n.get(w),L=w.isWebGLCubeRenderTarget===!0;if(_.__boundDepthTexture!==w.depthTexture){const $=w.depthTexture;if(_.__depthDisposeCallback&&_.__depthDisposeCallback(),$){const ee=()=>{delete _.__boundDepthTexture,delete _.__depthDisposeCallback,$.removeEventListener("dispose",ee)};$.addEventListener("dispose",ee),_.__depthDisposeCallback=ee}_.__boundDepthTexture=$}if(w.depthTexture&&!_.__autoAllocateDepthBuffer)if(L)for(let $=0;$<6;$++)we(_.__webglFramebuffer[$],w,$);else{const $=w.texture.mipmaps;$&&$.length>0?we(_.__webglFramebuffer[0],w,0):we(_.__webglFramebuffer,w,0)}else if(L){_.__webglDepthbuffer=[];for(let $=0;$<6;$++)if(t.bindFramebuffer(i.FRAMEBUFFER,_.__webglFramebuffer[$]),_.__webglDepthbuffer[$]===void 0)_.__webglDepthbuffer[$]=i.createRenderbuffer(),Ge(_.__webglDepthbuffer[$],w,!1);else{const ee=w.stencilBuffer?i.DEPTH_STENCIL_ATTACHMENT:i.DEPTH_ATTACHMENT,j=_.__webglDepthbuffer[$];i.bindRenderbuffer(i.RENDERBUFFER,j),i.framebufferRenderbuffer(i.FRAMEBUFFER,ee,i.RENDERBUFFER,j)}}else{const $=w.texture.mipmaps;if($&&$.length>0?t.bindFramebuffer(i.FRAMEBUFFER,_.__webglFramebuffer[0]):t.bindFramebuffer(i.FRAMEBUFFER,_.__webglFramebuffer),_.__webglDepthbuffer===void 0)_.__webglDepthbuffer=i.createRenderbuffer(),Ge(_.__webglDepthbuffer,w,!1);else{const ee=w.stencilBuffer?i.DEPTH_STENCIL_ATTACHMENT:i.DEPTH_ATTACHMENT,j=_.__webglDepthbuffer;i.bindRenderbuffer(i.RENDERBUFFER,j),i.framebufferRenderbuffer(i.FRAMEBUFFER,ee,i.RENDERBUFFER,j)}}t.bindFramebuffer(i.FRAMEBUFFER,null)}function jt(w,_,L){const $=n.get(w);_!==void 0&&Ce($.__webglFramebuffer,w,w.texture,i.COLOR_ATTACHMENT0,i.TEXTURE_2D,0),L!==void 0&&nt(w)}function et(w){const _=w.texture,L=n.get(w),$=n.get(_);w.addEventListener("dispose",A);const ee=w.textures,j=w.isWebGLCubeRenderTarget===!0,ke=ee.length>1;if(ke||($.__webglTexture===void 0&&($.__webglTexture=i.createTexture()),$.__version=_.version,a.memory.textures++),j){L.__webglFramebuffer=[];for(let he=0;he<6;he++)if(_.mipmaps&&_.mipmaps.length>0){L.__webglFramebuffer[he]=[];for(let Ae=0;Ae<_.mipmaps.length;Ae++)L.__webglFramebuffer[he][Ae]=i.createFramebuffer()}else L.__webglFramebuffer[he]=i.createFramebuffer()}else{if(_.mipmaps&&_.mipmaps.length>0){L.__webglFramebuffer=[];for(let he=0;he<_.mipmaps.length;he++)L.__webglFramebuffer[he]=i.createFramebuffer()}else L.__webglFramebuffer=i.createFramebuffer();if(ke)for(let he=0,Ae=ee.length;he<Ae;he++){const Ue=n.get(ee[he]);Ue.__webglTexture===void 0&&(Ue.__webglTexture=i.createTexture(),a.memory.textures++)}if(w.samples>0&&Ft(w)===!1){L.__webglMultisampledFramebuffer=i.createFramebuffer(),L.__webglColorRenderbuffer=[],t.bindFramebuffer(i.FRAMEBUFFER,L.__webglMultisampledFramebuffer);for(let he=0;he<ee.length;he++){const Ae=ee[he];L.__webglColorRenderbuffer[he]=i.createRenderbuffer(),i.bindRenderbuffer(i.RENDERBUFFER,L.__webglColorRenderbuffer[he]);const Ue=r.convert(Ae.format,Ae.colorSpace),re=r.convert(Ae.type),pe=C(Ae.internalFormat,Ue,re,Ae.colorSpace,w.isXRRenderTarget===!0),Me=I(w);i.renderbufferStorageMultisample(i.RENDERBUFFER,Me,pe,w.width,w.height),i.framebufferRenderbuffer(i.FRAMEBUFFER,i.COLOR_ATTACHMENT0+he,i.RENDERBUFFER,L.__webglColorRenderbuffer[he])}i.bindRenderbuffer(i.RENDERBUFFER,null),w.depthBuffer&&(L.__webglDepthRenderbuffer=i.createRenderbuffer(),Ge(L.__webglDepthRenderbuffer,w,!0)),t.bindFramebuffer(i.FRAMEBUFFER,null)}}if(j){t.bindTexture(i.TEXTURE_CUBE_MAP,$.__webglTexture),Ve(i.TEXTURE_CUBE_MAP,_);for(let he=0;he<6;he++)if(_.mipmaps&&_.mipmaps.length>0)for(let Ae=0;Ae<_.mipmaps.length;Ae++)Ce(L.__webglFramebuffer[he][Ae],w,_,i.COLOR_ATTACHMENT0,i.TEXTURE_CUBE_MAP_POSITIVE_X+he,Ae);else Ce(L.__webglFramebuffer[he],w,_,i.COLOR_ATTACHMENT0,i.TEXTURE_CUBE_MAP_POSITIVE_X+he,0);m(_)&&p(i.TEXTURE_CUBE_MAP),t.unbindTexture()}else if(ke){for(let he=0,Ae=ee.length;he<Ae;he++){const Ue=ee[he],re=n.get(Ue);let pe=i.TEXTURE_2D;(w.isWebGL3DRenderTarget||w.isWebGLArrayRenderTarget)&&(pe=w.isWebGL3DRenderTarget?i.TEXTURE_3D:i.TEXTURE_2D_ARRAY),t.bindTexture(pe,re.__webglTexture),Ve(pe,Ue),Ce(L.__webglFramebuffer,w,Ue,i.COLOR_ATTACHMENT0+he,pe,0),m(Ue)&&p(pe)}t.unbindTexture()}else{let he=i.TEXTURE_2D;if((w.isWebGL3DRenderTarget||w.isWebGLArrayRenderTarget)&&(he=w.isWebGL3DRenderTarget?i.TEXTURE_3D:i.TEXTURE_2D_ARRAY),t.bindTexture(he,$.__webglTexture),Ve(he,_),_.mipmaps&&_.mipmaps.length>0)for(let Ae=0;Ae<_.mipmaps.length;Ae++)Ce(L.__webglFramebuffer[Ae],w,_,i.COLOR_ATTACHMENT0,he,Ae);else Ce(L.__webglFramebuffer,w,_,i.COLOR_ATTACHMENT0,he,0);m(_)&&p(he),t.unbindTexture()}w.depthBuffer&&nt(w)}function ct(w){const _=w.textures;for(let L=0,$=_.length;L<$;L++){const ee=_[L];if(m(ee)){const j=x(w),ke=n.get(ee).__webglTexture;t.bindTexture(j,ke),p(j),t.unbindTexture()}}}const bt=[],qe=[];function Ot(w){if(w.samples>0){if(Ft(w)===!1){const _=w.textures,L=w.width,$=w.height;let ee=i.COLOR_BUFFER_BIT;const j=w.stencilBuffer?i.DEPTH_STENCIL_ATTACHMENT:i.DEPTH_ATTACHMENT,ke=n.get(w),he=_.length>1;if(he)for(let Ue=0;Ue<_.length;Ue++)t.bindFramebuffer(i.FRAMEBUFFER,ke.__webglMultisampledFramebuffer),i.framebufferRenderbuffer(i.FRAMEBUFFER,i.COLOR_ATTACHMENT0+Ue,i.RENDERBUFFER,null),t.bindFramebuffer(i.FRAMEBUFFER,ke.__webglFramebuffer),i.framebufferTexture2D(i.DRAW_FRAMEBUFFER,i.COLOR_ATTACHMENT0+Ue,i.TEXTURE_2D,null,0);t.bindFramebuffer(i.READ_FRAMEBUFFER,ke.__webglMultisampledFramebuffer);const Ae=w.texture.mipmaps;Ae&&Ae.length>0?t.bindFramebuffer(i.DRAW_FRAMEBUFFER,ke.__webglFramebuffer[0]):t.bindFramebuffer(i.DRAW_FRAMEBUFFER,ke.__webglFramebuffer);for(let Ue=0;Ue<_.length;Ue++){if(w.resolveDepthBuffer&&(w.depthBuffer&&(ee|=i.DEPTH_BUFFER_BIT),w.stencilBuffer&&w.resolveStencilBuffer&&(ee|=i.STENCIL_BUFFER_BIT)),he){i.framebufferRenderbuffer(i.READ_FRAMEBUFFER,i.COLOR_ATTACHMENT0,i.RENDERBUFFER,ke.__webglColorRenderbuffer[Ue]);const re=n.get(_[Ue]).__webglTexture;i.framebufferTexture2D(i.DRAW_FRAMEBUFFER,i.COLOR_ATTACHMENT0,i.TEXTURE_2D,re,0)}i.blitFramebuffer(0,0,L,$,0,0,L,$,ee,i.NEAREST),c===!0&&(bt.length=0,qe.length=0,bt.push(i.COLOR_ATTACHMENT0+Ue),w.depthBuffer&&w.resolveDepthBuffer===!1&&(bt.push(j),qe.push(j),i.invalidateFramebuffer(i.DRAW_FRAMEBUFFER,qe)),i.invalidateFramebuffer(i.READ_FRAMEBUFFER,bt))}if(t.bindFramebuffer(i.READ_FRAMEBUFFER,null),t.bindFramebuffer(i.DRAW_FRAMEBUFFER,null),he)for(let Ue=0;Ue<_.length;Ue++){t.bindFramebuffer(i.FRAMEBUFFER,ke.__webglMultisampledFramebuffer),i.framebufferRenderbuffer(i.FRAMEBUFFER,i.COLOR_ATTACHMENT0+Ue,i.RENDERBUFFER,ke.__webglColorRenderbuffer[Ue]);const re=n.get(_[Ue]).__webglTexture;t.bindFramebuffer(i.FRAMEBUFFER,ke.__webglFramebuffer),i.framebufferTexture2D(i.DRAW_FRAMEBUFFER,i.COLOR_ATTACHMENT0+Ue,i.TEXTURE_2D,re,0)}t.bindFramebuffer(i.DRAW_FRAMEBUFFER,ke.__webglMultisampledFramebuffer)}else if(w.depthBuffer&&w.resolveDepthBuffer===!1&&c){const _=w.stencilBuffer?i.DEPTH_STENCIL_ATTACHMENT:i.DEPTH_ATTACHMENT;i.invalidateFramebuffer(i.DRAW_FRAMEBUFFER,[_])}}}function I(w){return Math.min(s.maxSamples,w.samples)}function Ft(w){const _=n.get(w);return w.samples>0&&e.has("WEBGL_multisampled_render_to_texture")===!0&&_.__useRenderToTexture!==!1}function at(w){const _=a.render.frame;d.get(w)!==_&&(d.set(w,_),w.update())}function yt(w,_){const L=w.colorSpace,$=w.format,ee=w.type;return w.isCompressedTexture===!0||w.isVideoTexture===!0||L!==Ws&&L!==Wi&&(Qe.getTransfer(L)===ot?($!==Nn||ee!==Sn)&&Oe("WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType."):tt("WebGLTextures: Unsupported texture color space:",L)),_}function Re(w){return typeof HTMLImageElement<"u"&&w instanceof HTMLImageElement?(l.width=w.naturalWidth||w.width,l.height=w.naturalHeight||w.height):typeof VideoFrame<"u"&&w instanceof VideoFrame?(l.width=w.displayWidth,l.height=w.displayHeight):(l.width=w.width,l.height=w.height),l}this.allocateTextureUnit=B,this.resetTextureUnits=U,this.setTexture2D=K,this.setTexture2DArray=H,this.setTexture3D=W,this.setTextureCube=te,this.rebindTextures=jt,this.setupRenderTarget=et,this.updateRenderTargetMipmap=ct,this.updateMultisampleRenderTarget=Ot,this.setupDepthRenderbuffer=nt,this.setupFrameBufferTexture=Ce,this.useMultisampledRTT=Ft,this.isReversedDepthBuffer=function(){return t.buffers.depth.getReversed()}}function EC(i,e){function t(n,s=Wi){let r;const a=Qe.getTransfer(s);if(n===Sn)return i.UNSIGNED_BYTE;if(n===gl)return i.UNSIGNED_SHORT_4_4_4_4;if(n===vl)return i.UNSIGNED_SHORT_5_5_5_1;if(n===up)return i.UNSIGNED_INT_5_9_9_9_REV;if(n===hp)return i.UNSIGNED_INT_10F_11F_11F_REV;if(n===lp)return i.BYTE;if(n===dp)return i.SHORT;if(n===Fr)return i.UNSIGNED_SHORT;if(n===ml)return i.INT;if(n===Jn)return i.UNSIGNED_INT;if(n===Zn)return i.FLOAT;if(n===_i)return i.HALF_FLOAT;if(n===fp)return i.ALPHA;if(n===pp)return i.RGB;if(n===Nn)return i.RGBA;if(n===yi)return i.DEPTH_COMPONENT;if(n===hs)return i.DEPTH_STENCIL;if(n===mp)return i.RED;if(n===bl)return i.RED_INTEGER;if(n===Hs)return i.RG;if(n===_l)return i.RG_INTEGER;if(n===yl)return i.RGBA_INTEGER;if(n===Ba||n===Va||n===za||n===Ga)if(a===ot)if(r=e.get("WEBGL_compressed_texture_s3tc_srgb"),r!==null){if(n===Ba)return r.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(n===Va)return r.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(n===za)return r.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(n===Ga)return r.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else return null;else if(r=e.get("WEBGL_compressed_texture_s3tc"),r!==null){if(n===Ba)return r.COMPRESSED_RGB_S3TC_DXT1_EXT;if(n===Va)return r.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(n===za)return r.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(n===Ga)return r.COMPRESSED_RGBA_S3TC_DXT5_EXT}else return null;if(n===Sl||n===xl||n===Tl||n===Cl)if(r=e.get("WEBGL_compressed_texture_pvrtc"),r!==null){if(n===Sl)return r.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(n===xl)return r.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(n===Tl)return r.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(n===Cl)return r.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}else return null;if(n===El||n===Ml||n===wl||n===Al||n===Rl||n===Pl||n===kl)if(r=e.get("WEBGL_compressed_texture_etc"),r!==null){if(n===El||n===Ml)return a===ot?r.COMPRESSED_SRGB8_ETC2:r.COMPRESSED_RGB8_ETC2;if(n===wl)return a===ot?r.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:r.COMPRESSED_RGBA8_ETC2_EAC;if(n===Al)return r.COMPRESSED_R11_EAC;if(n===Rl)return r.COMPRESSED_SIGNED_R11_EAC;if(n===Pl)return r.COMPRESSED_RG11_EAC;if(n===kl)return r.COMPRESSED_SIGNED_RG11_EAC}else return null;if(n===Il||n===Dl||n===Ll||n===Nl||n===Ul||n===Ol||n===Fl||n===Bl||n===Vl||n===zl||n===Gl||n===Hl||n===Wl||n===ql)if(r=e.get("WEBGL_compressed_texture_astc"),r!==null){if(n===Il)return a===ot?r.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:r.COMPRESSED_RGBA_ASTC_4x4_KHR;if(n===Dl)return a===ot?r.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:r.COMPRESSED_RGBA_ASTC_5x4_KHR;if(n===Ll)return a===ot?r.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:r.COMPRESSED_RGBA_ASTC_5x5_KHR;if(n===Nl)return a===ot?r.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:r.COMPRESSED_RGBA_ASTC_6x5_KHR;if(n===Ul)return a===ot?r.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:r.COMPRESSED_RGBA_ASTC_6x6_KHR;if(n===Ol)return a===ot?r.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:r.COMPRESSED_RGBA_ASTC_8x5_KHR;if(n===Fl)return a===ot?r.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:r.COMPRESSED_RGBA_ASTC_8x6_KHR;if(n===Bl)return a===ot?r.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:r.COMPRESSED_RGBA_ASTC_8x8_KHR;if(n===Vl)return a===ot?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:r.COMPRESSED_RGBA_ASTC_10x5_KHR;if(n===zl)return a===ot?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:r.COMPRESSED_RGBA_ASTC_10x6_KHR;if(n===Gl)return a===ot?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:r.COMPRESSED_RGBA_ASTC_10x8_KHR;if(n===Hl)return a===ot?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:r.COMPRESSED_RGBA_ASTC_10x10_KHR;if(n===Wl)return a===ot?r.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:r.COMPRESSED_RGBA_ASTC_12x10_KHR;if(n===ql)return a===ot?r.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:r.COMPRESSED_RGBA_ASTC_12x12_KHR}else return null;if(n===jl||n===$l||n===Xl)if(r=e.get("EXT_texture_compression_bptc"),r!==null){if(n===jl)return a===ot?r.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:r.COMPRESSED_RGBA_BPTC_UNORM_EXT;if(n===$l)return r.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;if(n===Xl)return r.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT}else return null;if(n===Kl||n===Yl||n===Jl||n===Zl)if(r=e.get("EXT_texture_compression_rgtc"),r!==null){if(n===Kl)return r.COMPRESSED_RED_RGTC1_EXT;if(n===Yl)return r.COMPRESSED_SIGNED_RED_RGTC1_EXT;if(n===Jl)return r.COMPRESSED_RED_GREEN_RGTC2_EXT;if(n===Zl)return r.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}else return null;return n===Br?i.UNSIGNED_INT_24_8:i[n]!==void 0?i[n]:null}return{convert:t}}const MC=`
4079
4079
  void main() {
4080
4080
 
4081
4081
  gl_Position = vec4( position, 1.0 );
@@ -4099,7 +4099,7 @@ void main() {
4099
4099
 
4100
4100
  }
4101
4101
 
4102
- }`;class AC{constructor(){this.texture=null,this.mesh=null,this.depthNear=0,this.depthFar=0}init(e,t){if(this.texture===null){const n=new Kp(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 Tn({vertexShader:MC,fragmentShader:wC,uniforms:{depthColor:{value:this.texture},depthWidth:{value:t.z},depthHeight:{value:t.w}}});this.mesh=new Vn(new ho(20,20),n)}return this.mesh}reset(){this.texture=null,this.mesh=null}getDepthTexture(){return this.texture}}class RC 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 AC,p={},x=t.getContextAttributes();let C=null,b=null;const S=[],M=[],A=new rt;let k=null;const y=new Cn;y.viewport=new It;const T=new Cn;T.viewport=new It;const R=[y,T],U=new by;let B=null,q=null;this.cameraAutoUpdate=!0,this.enabled=!1,this.isPresenting=!1,this.getController=function(X){let ie=S[X];return ie===void 0&&(ie=new Md,S[X]=ie),ie.getTargetRaySpace()},this.getControllerGrip=function(X){let ie=S[X];return ie===void 0&&(ie=new Md,S[X]=ie),ie.getGripSpace()},this.getHand=function(X){let ie=S[X];return ie===void 0&&(ie=new Md,S[X]=ie),ie.getHandSpace()};function K(X){const ie=M.indexOf(X.inputSource);if(ie===-1)return;const Ce=S[ie];Ce!==void 0&&(Ce.update(X.inputSource,X.frame,l||a),Ce.dispatchEvent({type:X.type,data:X.inputSource}))}function H(){s.removeEventListener("select",K),s.removeEventListener("selectstart",K),s.removeEventListener("selectend",K),s.removeEventListener("squeeze",K),s.removeEventListener("squeezestart",K),s.removeEventListener("squeezeend",K),s.removeEventListener("end",H),s.removeEventListener("inputsourceschange",W);for(let X=0;X<S.length;X++){const ie=M[X];ie!==null&&(M[X]=null,S[X].disconnect(ie))}B=null,q=null,m.reset();for(const X in p)delete p[X];e.setRenderTarget(C),f=null,h=null,u=null,s=null,b=null,ht.stop(),n.isPresenting=!1,e.setPixelRatio(k),e.setSize(A.width,A.height,!1),n.dispatchEvent({type:"sessionend"})}this.setFramebufferScaleFactor=function(X){r=X,n.isPresenting===!0&&Oe("WebXRManager: Cannot change framebuffer scale while presenting.")},this.setReferenceSpaceType=function(X){o=X,n.isPresenting===!0&&Oe("WebXRManager: Cannot change reference space type while presenting.")},this.getReferenceSpace=function(){return l||a},this.setReferenceSpace=function(X){l=X},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(X){if(s=X,s!==null){if(C=e.getRenderTarget(),s.addEventListener("select",K),s.addEventListener("selectstart",K),s.addEventListener("selectend",K),s.addEventListener("squeeze",K),s.addEventListener("squeezestart",K),s.addEventListener("squeezeend",K),s.addEventListener("end",H),s.addEventListener("inputsourceschange",W),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?hs:yi,Ge=x.stencil?Br:Yn);const nt={colorFormat:t.RGBA8,depthFormat:we,scaleFactor:r};u=this.getBinding(),h=u.createProjectionLayer(nt),s.updateRenderState({layers:[h]}),e.setPixelRatio(1),e.setSize(h.textureWidth,h.textureHeight,!1),b=new Qn(h.textureWidth,h.textureHeight,{format:Ln,type:yn,depthTexture:new Yr(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 Qn(f.framebufferWidth,f.framebufferHeight,{format:Ln,type:yn,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),ht.setContext(s),ht.start(),n.isPresenting=!0,n.dispatchEvent({type:"sessionstart"})}},this.getEnvironmentBlendMode=function(){if(s!==null)return s.environmentBlendMode},this.getDepthTexture=function(){return m.getDepthTexture()};function W(X){for(let ie=0;ie<X.removed.length;ie++){const Ce=X.removed[ie],Ge=M.indexOf(Ce);Ge>=0&&(M[Ge]=null,S[Ge].disconnect(Ce))}for(let ie=0;ie<X.added.length;ie++){const Ce=X.added[ie];let Ge=M.indexOf(Ce);if(Ge===-1){for(let nt=0;nt<S.length;nt++)if(nt>=M.length){M.push(Ce),Ge=nt;break}else if(M[nt]===null){M[nt]=Ce,Ge=nt;break}if(Ge===-1)break}const we=S[Ge];we&&we.connect(Ce)}}const te=new F,ve=new F;function de(X,ie,Ce){te.setFromMatrixPosition(ie.matrixWorld),ve.setFromMatrixPosition(Ce.matrixWorld);const Ge=te.distanceTo(ve),we=ie.projectionMatrix.elements,nt=Ce.projectionMatrix.elements,jt=we[14]/(we[10]-1),et=we[14]/(we[10]+1),ct=(we[9]+1)/we[5],bt=(we[9]-1)/we[5],qe=(we[8]-1)/we[0],Ot=(nt[8]+1)/nt[0],I=jt*qe,Ft=jt*Ot,at=Ge/(-qe+Ot),yt=at*-qe;if(ie.matrixWorld.decompose(X.position,X.quaternion,X.scale),X.translateX(yt),X.translateZ(at),X.matrixWorld.compose(X.position,X.quaternion,X.scale),X.matrixWorldInverse.copy(X.matrixWorld).invert(),we[10]===-1)X.projectionMatrix.copy(ie.projectionMatrix),X.projectionMatrixInverse.copy(ie.projectionMatrixInverse);else{const Re=jt+at,w=et+at,_=I-yt,L=Ft+(Ge-yt),$=ct*et/w*Re,ee=bt*et/w*Re;X.projectionMatrix.makePerspective(_,L,$,ee,Re,w),X.projectionMatrixInverse.copy(X.projectionMatrix).invert()}}function _e(X,ie){ie===null?X.matrixWorld.copy(X.matrix):X.matrixWorld.multiplyMatrices(ie.matrixWorld,X.matrix),X.matrixWorldInverse.copy(X.matrixWorld).invert()}this.updateCamera=function(X){if(s===null)return;let ie=X.near,Ce=X.far;m.texture!==null&&(m.depthNear>0&&(ie=m.depthNear),m.depthFar>0&&(Ce=m.depthFar)),U.near=T.near=y.near=ie,U.far=T.far=y.far=Ce,(B!==U.near||q!==U.far)&&(s.updateRenderState({depthNear:U.near,depthFar:U.far}),B=U.near,q=U.far),U.layers.mask=X.layers.mask|6,y.layers.mask=U.layers.mask&3,T.layers.mask=U.layers.mask&5;const Ge=X.parent,we=U.cameras;_e(U,Ge);for(let nt=0;nt<we.length;nt++)_e(we[nt],Ge);we.length===2?de(U,y,T):U.projectionMatrix.copy(y.projectionMatrix),Ve(X,U,Ge)};function Ve(X,ie,Ce){Ce===null?X.matrix.copy(ie.matrixWorld):(X.matrix.copy(Ce.matrixWorld),X.matrix.invert(),X.matrix.multiply(ie.matrixWorld)),X.matrix.decompose(X.position,X.quaternion,X.scale),X.updateMatrixWorld(!0),X.projectionMatrix.copy(ie.projectionMatrix),X.projectionMatrixInverse.copy(ie.projectionMatrixInverse),X.isPerspectiveCamera&&(X.fov=nd*2*Math.atan(1/X.projectionMatrix.elements[5]),X.zoom=1)}this.getCamera=function(){return U},this.getFoveation=function(){if(!(h===null&&f===null))return c},this.setFoveation=function(X){c=X,h!==null&&(h.fixedFoveation=X),f!==null&&f.fixedFoveation!==void 0&&(f.fixedFoveation=X)},this.hasDepthSensing=function(){return m.texture!==null},this.getDepthSensingMesh=function(){return m.getMesh(U)},this.getCameraTexture=function(X){return p[X]};let Be=null;function Ct(X,ie){if(d=ie.getViewerPose(l||a),g=ie,d!==null){const Ce=d.views;f!==null&&(e.setRenderTargetFramebuffer(b,f.framebuffer),e.setRenderTarget(b));let Ge=!1;Ce.length!==U.cameras.length&&(U.cameras.length=0,Ge=!0);for(let et=0;et<Ce.length;et++){const ct=Ce[et];let bt=null;if(f!==null)bt=f.getViewport(ct);else{const Ot=u.getViewSubImage(h,ct);bt=Ot.viewport,et===0&&(e.setRenderTargetTextures(b,Ot.colorTexture,Ot.depthStencilTexture),e.setRenderTarget(b))}let qe=R[et];qe===void 0&&(qe=new Cn,qe.layers.enable(et),qe.viewport=new It,R[et]=qe),qe.matrix.fromArray(ct.transform.matrix),qe.matrix.decompose(qe.position,qe.quaternion,qe.scale),qe.projectionMatrix.fromArray(ct.projectionMatrix),qe.projectionMatrixInverse.copy(qe.projectionMatrix).invert(),qe.viewport.set(bt.x,bt.y,bt.width,bt.height),et===0&&(U.matrix.copy(qe.matrix),U.matrix.decompose(U.position,U.quaternion,U.scale)),Ge===!0&&U.cameras.push(qe)}const we=s.enabledFeatures;if(we&&we.includes("depth-sensing")&&s.depthUsage=="gpu-optimized"&&v){u=n.getBinding();const et=u.getDepthInformation(Ce[0]);et&&et.isValid&&et.texture&&m.init(et,s.renderState)}if(we&&we.includes("camera-access")&&v){e.state.unbindTexture(),u=n.getBinding();for(let et=0;et<Ce.length;et++){const ct=Ce[et].camera;if(ct){let bt=p[ct];bt||(bt=new Kp,p[ct]=bt);const qe=u.getCameraImage(ct);bt.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,ie,l||a)}Be&&Be(X,ie),ie.detectedPlanes&&n.dispatchEvent({type:"planesdetected",data:ie}),g=null}const ht=new Zp;ht.setAnimationLoop(Ct),this.setAnimationLoop=function(X){Be=X},this.dispose=function(){}}}const ys=new Ci,PC=new Nt;function kC(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,Gp(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===Zt&&(m.bumpScale.value*=-1)),p.normalMap&&(m.normalMap.value=p.normalMap,t(p.normalMap,m.normalMapTransform),m.normalScale.value.copy(p.normalScale),p.side===Zt&&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,ys.copy(b),ys.x*=-1,ys.y*=-1,ys.z*=-1,C.isCubeTexture&&C.isRenderTargetTexture===!1&&(ys.y*=-1,ys.z*=-1),m.envMapRotation.value.setFromMatrix4(PC.makeRotationFromEuler(ys)),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===Zt&&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 IC(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 tt("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 y=0,T=k.length;y<T;y++){const R=k[y];if(f(R,M,y,S)===!0){const U=R.__offset,B=Array.isArray(R.value)?R.value:[R.value];let q=0;for(let K=0;K<B.length;K++){const H=B[K],W=v(H);typeof H=="number"||typeof H=="boolean"?(R.__data[0]=H,i.bufferSubData(i.UNIFORM_BUFFER,U+q,R.__data)):H.isMatrix3?(R.__data[0]=H.elements[0],R.__data[1]=H.elements[1],R.__data[2]=H.elements[2],R.__data[3]=0,R.__data[4]=H.elements[3],R.__data[5]=H.elements[4],R.__data[6]=H.elements[5],R.__data[7]=0,R.__data[8]=H.elements[6],R.__data[9]=H.elements[7],R.__data[10]=H.elements[8],R.__data[11]=0):(H.toArray(R.__data,q),q+=W.storage/Float32Array.BYTES_PER_ELEMENT)}i.bufferSubData(i.UNIFORM_BUFFER,U,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 y=Array.isArray(C[A])?C[A]:[C[A]];for(let T=0,R=y.length;T<R;T++){const U=y[T],B=Array.isArray(U.value)?U.value:[U.value];for(let q=0,K=B.length;q<K;q++){const H=B[q],W=v(H),te=b%S,ve=te%W.boundary,de=te+ve;b+=ve,de!==0&&S-de<W.storage&&(b+=S-de),U.__data=new Float32Array(W.storage/Float32Array.BYTES_PER_ELEMENT),U.__offset=b,b+=W.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 DC=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 ni=null;function LC(){return ni===null&&(ni=new dy(DC,16,16,Hs,_i),ni.name="DFG_LUT",ni.minFilter=Kt,ni.magFilter=Kt,ni.wrapS=bi,ni.wrapT=bi,ni.generateMipmaps=!1,ni.needsUpdate=!0),ni}class NC{constructor(e={}){const{canvas:t=U_(),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=yn}=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([yl,_l,bl]),p=new Set([yn,Yn,Fr,Br,gl,vl]),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=Kn,this.toneMappingExposure=1,this.transmissionResolutionScale=1;const y=this;let T=!1;this._outputColorSpace=Sn;let R=0,U=0,B=null,q=-1,K=null;const H=new It,W=new It;let te=null;const ve=new Ze(0);let de=0,_e=t.width,Ve=t.height,Be=1,Ct=null,ht=null;const X=new It(0,0,_e,Ve),ie=new It(0,0,_e,Ve);let Ce=!1;const Ge=new Xp;let we=!1,nt=!1;const jt=new Nt,et=new F,ct=new It,bt={background:null,fog:null,environment:null,overrideMaterial:null,isScene:!0};let qe=!1;function Ot(){return B===null?Be:1}let I=n;function Ft(E,N){return t.getContext(E,N)}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${Qc}`),t.addEventListener("webglcontextlost",Fe,!1),t.addEventListener("webglcontextrestored",St,!1),t.addEventListener("webglcontextcreationerror",lt,!1),I===null){const N="webgl2";if(I=Ft(N,E),I===null)throw Ft(N)?new Error("Error creating WebGL context with your selected attributes."):new Error("Error creating WebGL context.")}}catch(E){throw tt("WebGLRenderer: "+E.message),E}let at,yt,Re,w,_,L,$,ee,j,ke,he,Ae,Ue,re,pe,Me,Pe,fe,je,D,ye,oe,xe,se;function Q(){at=new Lx(I),at.init(),oe=new EC(I,at),yt=new Ex(I,at,e,oe),Re=new TC(I,at),yt.reversedDepthBuffer&&h&&Re.buffers.depth.setReversed(!0),w=new Ox(I),_=new cC,L=new CC(I,at,Re,_,yt,oe,w),$=new wx(y),ee=new Dx(y),j=new Sy(I),xe=new Tx(I,j),ke=new Nx(I,j,w,xe),he=new Bx(I,ke,j,w),je=new Fx(I,yt,L),Me=new Mx(_),Ae=new oC(y,$,ee,at,yt,xe,Me),Ue=new kC(y,_),re=new dC,pe=new gC(at),fe=new xx(y,$,ee,Re,he,g,c),Pe=new SC(y,he,yt),se=new IC(I,w,yt,Re),D=new Cx(I,at,w),ye=new Ux(I,at,w),w.programs=Ae.programs,y.capabilities=yt,y.extensions=at,y.properties=_,y.renderLists=re,y.shadowMap=Pe,y.state=Re,y.info=w}Q(),v!==yn&&(k=new zx(v,t.width,t.height,s,r));const ue=new RC(y,I);this.xr=ue,this.getContext=function(){return I},this.getContextAttributes=function(){return I.getContextAttributes()},this.forceContextLoss=function(){const E=at.get("WEBGL_lose_context");E&&E.loseContext()},this.forceContextRestore=function(){const E=at.get("WEBGL_lose_context");E&&E.restoreContext()},this.getPixelRatio=function(){return Be},this.setPixelRatio=function(E){E!==void 0&&(Be=E,this.setSize(_e,Ve,!1))},this.getSize=function(E){return E.set(_e,Ve)},this.setSize=function(E,N,G=!0){if(ue.isPresenting){Oe("WebGLRenderer: Can't change size while VR device is presenting.");return}_e=E,Ve=N,t.width=Math.floor(E*Be),t.height=Math.floor(N*Be),G===!0&&(t.style.width=E+"px",t.style.height=N+"px"),k!==null&&k.setSize(t.width,t.height),this.setViewport(0,0,E,N)},this.getDrawingBufferSize=function(E){return E.set(_e*Be,Ve*Be).floor()},this.setDrawingBufferSize=function(E,N,G){_e=E,Ve=N,Be=G,t.width=Math.floor(E*G),t.height=Math.floor(N*G),this.setViewport(0,0,E,N)},this.setEffects=function(E){if(v===yn){console.error("THREE.WebGLRenderer: setEffects() requires outputBufferType set to HalfFloatType or FloatType.");return}if(E){for(let N=0;N<E.length;N++)if(E[N].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(H)},this.getViewport=function(E){return E.copy(X)},this.setViewport=function(E,N,G,V){E.isVector4?X.set(E.x,E.y,E.z,E.w):X.set(E,N,G,V),Re.viewport(H.copy(X).multiplyScalar(Be).round())},this.getScissor=function(E){return E.copy(ie)},this.setScissor=function(E,N,G,V){E.isVector4?ie.set(E.x,E.y,E.z,E.w):ie.set(E,N,G,V),Re.scissor(W.copy(ie).multiplyScalar(Be).round())},this.getScissorTest=function(){return Ce},this.setScissorTest=function(E){Re.setScissorTest(Ce=E)},this.setOpaqueSort=function(E){Ct=E},this.setTransparentSort=function(E){ht=E},this.getClearColor=function(E){return E.copy(fe.getClearColor())},this.setClearColor=function(){fe.setClearColor(...arguments)},this.getClearAlpha=function(){return fe.getClearAlpha()},this.setClearAlpha=function(){fe.setClearAlpha(...arguments)},this.clear=function(E=!0,N=!0,G=!0){let V=0;if(E){let O=!1;if(B!==null){const me=B.texture.format;O=m.has(me)}if(O){const me=B.texture.type,Te=p.has(me),be=fe.getClearColor(),Ee=fe.getClearAlpha(),Ie=be.r,Ne=be.g,De=be.b;Te?(x[0]=Ie,x[1]=Ne,x[2]=De,x[3]=Ee,I.clearBufferuiv(I.COLOR,0,x)):(C[0]=Ie,C[1]=Ne,C[2]=De,C[3]=Ee,I.clearBufferiv(I.COLOR,0,C))}else V|=I.COLOR_BUFFER_BIT}N&&(V|=I.DEPTH_BUFFER_BIT),G&&(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",St,!1),t.removeEventListener("webglcontextcreationerror",lt,!1),fe.dispose(),re.dispose(),pe.dispose(),_.dispose(),$.dispose(),ee.dispose(),he.dispose(),xe.dispose(),se.dispose(),Ae.dispose(),ue.dispose(),ue.removeEventListener("sessionstart",Pm),ue.removeEventListener("sessionend",km),xs.stop()};function Fe(E){E.preventDefault(),Sp("WebGLRenderer: Context Lost."),T=!0}function St(){Sp("WebGLRenderer: Context Restored."),T=!1;const E=w.autoReset,N=Pe.enabled,G=Pe.autoUpdate,V=Pe.needsUpdate,O=Pe.type;Q(),w.autoReset=E,Pe.enabled=N,Pe.autoUpdate=G,Pe.needsUpdate=V,Pe.type=O}function lt(E){tt("WebGLRenderer: A WebGL context could not be created. Reason: ",E.statusMessage)}function ri(E){const N=E.target;N.removeEventListener("dispose",ri),Ai(N)}function Ai(E){QC(E),_.remove(E)}function QC(E){const N=_.get(E).programs;N!==void 0&&(N.forEach(function(G){Ae.releaseProgram(G)}),E.isShaderMaterial&&Ae.releaseShaderCache(E))}this.renderBufferDirect=function(E,N,G,V,O,me){N===null&&(N=bt);const Te=O.isMesh&&O.matrixWorld.determinant()<0,be=tE(E,N,G,V,O);Re.setMaterial(V,Te);let Ee=G.index,Ie=1;if(V.wireframe===!0){if(Ee=ke.getWireframeAttribute(G),Ee===void 0)return;Ie=2}const Ne=G.drawRange,De=G.attributes.position;let $e=Ne.start*Ie,ft=(Ne.start+Ne.count)*Ie;me!==null&&($e=Math.max($e,me.start*Ie),ft=Math.min(ft,(me.start+me.count)*Ie)),Ee!==null?($e=Math.max($e,0),ft=Math.min(ft,Ee.count)):De!=null&&($e=Math.max($e,0),ft=Math.min(ft,De.count));const Rt=ft-$e;if(Rt<0||Rt===1/0)return;xe.setup(O,V,be,G,Ee);let Pt,_t=D;if(Ee!==null&&(Pt=j.get(Ee),_t=ye,_t.setIndex(Pt)),O.isMesh)V.wireframe===!0?(Re.setLineWidth(V.wireframeLinewidth*Ot()),_t.setMode(I.LINES)):_t.setMode(I.TRIANGLES);else if(O.isLine){let Le=V.linewidth;Le===void 0&&(Le=1),Re.setLineWidth(Le*Ot()),O.isLineSegments?_t.setMode(I.LINES):O.isLineLoop?_t.setMode(I.LINE_LOOP):_t.setMode(I.LINE_STRIP)}else O.isPoints?_t.setMode(I.POINTS):O.isSprite&&_t.setMode(I.TRIANGLES);if(O.isBatchedMesh)if(O._multiDrawInstances!==null)Vr("WebGLRenderer: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection."),_t.renderMultiDrawInstances(O._multiDrawStarts,O._multiDrawCounts,O._multiDrawCount,O._multiDrawInstances);else if(at.get("WEBGL_multi_draw"))_t.renderMultiDraw(O._multiDrawStarts,O._multiDrawCounts,O._multiDrawCount);else{const Le=O._multiDrawStarts,dt=O._multiDrawCounts,it=O._multiDrawCount,bn=Ee?j.get(Ee).bytesPerElement:1,hr=_.get(V).currentProgram.getUniforms();for(let _n=0;_n<it;_n++)hr.setValue(I,"_gl_DrawID",_n),_t.render(Le[_n]/bn,dt[_n])}else if(O.isInstancedMesh)_t.renderInstances($e,Rt,O.count);else if(G.isInstancedBufferGeometry){const Le=G._maxInstanceCount!==void 0?G._maxInstanceCount:1/0,dt=Math.min(G.instanceCount,Le);_t.renderInstances($e,Rt,dt)}else _t.render($e,Rt)};function Rm(E,N,G){E.transparent===!0&&E.side===gi&&E.forceSinglePass===!1?(E.side=Zt,E.needsUpdate=!0,yo(E,N,G),E.side=mi,E.needsUpdate=!0,yo(E,N,G),E.side=gi):yo(E,N,G)}this.compile=function(E,N,G=null){G===null&&(G=E),S=pe.get(G),S.init(N),A.push(S),G.traverseVisible(function(O){O.isLight&&O.layers.test(N.layers)&&(S.pushLight(O),O.castShadow&&S.pushShadow(O))}),E!==G&&E.traverseVisible(function(O){O.isLight&&O.layers.test(N.layers)&&(S.pushLight(O),O.castShadow&&S.pushShadow(O))}),S.setupLights();const V=new Set;return E.traverse(function(O){if(!(O.isMesh||O.isPoints||O.isLine||O.isSprite))return;const me=O.material;if(me)if(Array.isArray(me))for(let Te=0;Te<me.length;Te++){const be=me[Te];Rm(be,G,O),V.add(be)}else Rm(me,G,O),V.add(me)}),S=A.pop(),V},this.compileAsync=function(E,N,G=null){const V=this.compile(E,N,G);return new Promise(O=>{function me(){if(V.forEach(function(Te){_.get(Te).currentProgram.isReady()&&V.delete(Te)}),V.size===0){O(E);return}setTimeout(me,10)}at.get("KHR_parallel_shader_compile")!==null?me():setTimeout(me,10)})};let zd=null;function eE(E){zd&&zd(E)}function Pm(){xs.stop()}function km(){xs.start()}const xs=new Zp;xs.setAnimationLoop(eE),typeof self<"u"&&xs.setContext(self),this.setAnimationLoop=function(E){zd=E,ue.setAnimationLoop(E),E===null?xs.stop():xs.start()},ue.addEventListener("sessionstart",Pm),ue.addEventListener("sessionend",km),this.render=function(E,N){if(N!==void 0&&N.isCamera!==!0){tt("WebGLRenderer.render: camera is not an instance of THREE.Camera.");return}if(T===!0)return;const G=ue.enabled===!0&&ue.isPresenting===!0,V=k!==null&&(B===null||G)&&k.begin(y,B);if(E.matrixWorldAutoUpdate===!0&&E.updateMatrixWorld(),N.parent===null&&N.matrixWorldAutoUpdate===!0&&N.updateMatrixWorld(),ue.enabled===!0&&ue.isPresenting===!0&&(k===null||k.isCompositing()===!1)&&(ue.cameraAutoUpdate===!0&&ue.updateCamera(N),N=ue.getCamera()),E.isScene===!0&&E.onBeforeRender(y,E,N,B),S=pe.get(E,A.length),S.init(N),A.push(S),jt.multiplyMatrices(N.projectionMatrix,N.matrixWorldInverse),Ge.setFromProjectionMatrix(jt,Zn,N.reversedDepth),nt=this.localClippingEnabled,we=Me.init(this.clippingPlanes,nt),b=re.get(E,M.length),b.init(),M.push(b),ue.enabled===!0&&ue.isPresenting===!0){const Te=y.xr.getDepthSensingMesh();Te!==null&&Gd(Te,N,-1/0,y.sortObjects)}Gd(E,N,0,y.sortObjects),b.finish(),y.sortObjects===!0&&b.sort(Ct,ht),qe=ue.enabled===!1||ue.isPresenting===!1||ue.hasDepthSensing()===!1,qe&&fe.addToRenderList(b,E),this.info.render.frame++,we===!0&&Me.beginShadows();const O=S.state.shadowsArray;if(Pe.render(O,E,N),we===!0&&Me.endShadows(),this.info.autoReset===!0&&this.info.reset(),(V&&k.hasRenderPass())===!1){const Te=b.opaque,be=b.transmissive;if(S.setupLights(),N.isArrayCamera){const Ee=N.cameras;if(be.length>0)for(let Ie=0,Ne=Ee.length;Ie<Ne;Ie++){const De=Ee[Ie];Dm(Te,be,E,De)}qe&&fe.render(E);for(let Ie=0,Ne=Ee.length;Ie<Ne;Ie++){const De=Ee[Ie];Im(b,E,De,De.viewport)}}else be.length>0&&Dm(Te,be,E,N),qe&&fe.render(E),Im(b,E,N)}B!==null&&U===0&&(L.updateMultisampleRenderTarget(B),L.updateRenderTargetMipmap(B)),V&&k.end(y),E.isScene===!0&&E.onAfterRender(y,E,N),xe.resetDefaultState(),q=-1,K=null,A.pop(),A.length>0?(S=A[A.length-1],we===!0&&Me.setGlobalState(y.clippingPlanes,S.state.camera)):S=null,M.pop(),M.length>0?b=M[M.length-1]:b=null};function Gd(E,N,G,V){if(E.visible===!1)return;if(E.layers.test(N.layers)){if(E.isGroup)G=E.renderOrder;else if(E.isLOD)E.autoUpdate===!0&&E.update(N);else if(E.isLight)S.pushLight(E),E.castShadow&&S.pushShadow(E);else if(E.isSprite){if(!E.frustumCulled||Ge.intersectsSprite(E)){V&&ct.setFromMatrixPosition(E.matrixWorld).applyMatrix4(jt);const Te=he.update(E),be=E.material;be.visible&&b.push(E,Te,be,G,ct.z,null)}}else if((E.isMesh||E.isLine||E.isPoints)&&(!E.frustumCulled||Ge.intersectsObject(E))){const Te=he.update(E),be=E.material;if(V&&(E.boundingSphere!==void 0?(E.boundingSphere===null&&E.computeBoundingSphere(),ct.copy(E.boundingSphere.center)):(Te.boundingSphere===null&&Te.computeBoundingSphere(),ct.copy(Te.boundingSphere.center)),ct.applyMatrix4(E.matrixWorld).applyMatrix4(jt)),Array.isArray(be)){const Ee=Te.groups;for(let Ie=0,Ne=Ee.length;Ie<Ne;Ie++){const De=Ee[Ie],$e=be[De.materialIndex];$e&&$e.visible&&b.push(E,Te,$e,G,ct.z,De)}}else be.visible&&b.push(E,Te,be,G,ct.z,null)}}const me=E.children;for(let Te=0,be=me.length;Te<be;Te++)Gd(me[Te],N,G,V)}function Im(E,N,G,V){const{opaque:O,transmissive:me,transparent:Te}=E;S.setupLightsView(G),we===!0&&Me.setGlobalState(y.clippingPlanes,G),V&&Re.viewport(H.copy(V)),O.length>0&&_o(O,N,G),me.length>0&&_o(me,N,G),Te.length>0&&_o(Te,N,G),Re.buffers.depth.setTest(!0),Re.buffers.depth.setMask(!0),Re.buffers.color.setMask(!0),Re.setPolygonOffset(!1)}function Dm(E,N,G,V){if((G.isScene===!0?G.overrideMaterial:null)!==null)return;if(S.state.transmissionRenderTarget[V.id]===void 0){const $e=at.has("EXT_color_buffer_half_float")||at.has("EXT_color_buffer_float");S.state.transmissionRenderTarget[V.id]=new Qn(1,1,{generateMipmaps:!0,type:$e?_i:yn,minFilter:us,samples:yt.samples,stencilBuffer:r,resolveDepthBuffer:!1,resolveStencilBuffer:!1,colorSpace:Qe.workingColorSpace})}const me=S.state.transmissionRenderTarget[V.id],Te=V.viewport||H;me.setSize(Te.z*y.transmissionResolutionScale,Te.w*y.transmissionResolutionScale);const be=y.getRenderTarget(),Ee=y.getActiveCubeFace(),Ie=y.getActiveMipmapLevel();y.setRenderTarget(me),y.getClearColor(ve),de=y.getClearAlpha(),de<1&&y.setClearColor(16777215,.5),y.clear(),qe&&fe.render(G);const Ne=y.toneMapping;y.toneMapping=Kn;const De=V.viewport;if(V.viewport!==void 0&&(V.viewport=void 0),S.setupLightsView(V),we===!0&&Me.setGlobalState(y.clippingPlanes,V),_o(E,G,V),L.updateMultisampleRenderTarget(me),L.updateRenderTargetMipmap(me),at.has("WEBGL_multisampled_render_to_texture")===!1){let $e=!1;for(let ft=0,Rt=N.length;ft<Rt;ft++){const Pt=N[ft],{object:_t,geometry:Le,material:dt,group:it}=Pt;if(dt.side===gi&&_t.layers.test(V.layers)){const bn=dt.side;dt.side=Zt,dt.needsUpdate=!0,Lm(_t,G,V,Le,dt,it),dt.side=bn,dt.needsUpdate=!0,$e=!0}}$e===!0&&(L.updateMultisampleRenderTarget(me),L.updateRenderTargetMipmap(me))}y.setRenderTarget(be,Ee,Ie),y.setClearColor(ve,de),De!==void 0&&(V.viewport=De),y.toneMapping=Ne}function _o(E,N,G){const V=N.isScene===!0?N.overrideMaterial:null;for(let O=0,me=E.length;O<me;O++){const Te=E[O],{object:be,geometry:Ee,group:Ie}=Te;let Ne=Te.material;Ne.allowOverride===!0&&V!==null&&(Ne=V),be.layers.test(G.layers)&&Lm(be,N,G,Ee,Ne,Ie)}}function Lm(E,N,G,V,O,me){E.onBeforeRender(y,N,G,V,O,me),E.modelViewMatrix.multiplyMatrices(G.matrixWorldInverse,E.matrixWorld),E.normalMatrix.getNormalMatrix(E.modelViewMatrix),O.onBeforeRender(y,N,G,V,E,me),O.transparent===!0&&O.side===gi&&O.forceSinglePass===!1?(O.side=Zt,O.needsUpdate=!0,y.renderBufferDirect(G,N,V,O,E,me),O.side=mi,O.needsUpdate=!0,y.renderBufferDirect(G,N,V,O,E,me),O.side=gi):y.renderBufferDirect(G,N,V,O,E,me),E.onAfterRender(y,N,G,V,O,me)}function yo(E,N,G){N.isScene!==!0&&(N=bt);const V=_.get(E),O=S.state.lights,me=S.state.shadowsArray,Te=O.state.version,be=Ae.getParameters(E,O.state,me,N,G),Ee=Ae.getProgramCacheKey(be);let Ie=V.programs;V.environment=E.isMeshStandardMaterial?N.environment:null,V.fog=N.fog,V.envMap=(E.isMeshStandardMaterial?ee:$).get(E.envMap||V.environment),V.envMapRotation=V.environment!==null&&E.envMap===null?N.environmentRotation:E.envMapRotation,Ie===void 0&&(E.addEventListener("dispose",ri),Ie=new Map,V.programs=Ie);let Ne=Ie.get(Ee);if(Ne!==void 0){if(V.currentProgram===Ne&&V.lightsStateVersion===Te)return Um(E,be),Ne}else be.uniforms=Ae.getUniforms(E),E.onBeforeCompile(be,y),Ne=Ae.acquireProgram(be,Ee),Ie.set(Ee,Ne),V.uniforms=be.uniforms;const De=V.uniforms;return(!E.isShaderMaterial&&!E.isRawShaderMaterial||E.clipping===!0)&&(De.clippingPlanes=Me.uniform),Um(E,be),V.needsLights=iE(E),V.lightsStateVersion=Te,V.needsLights&&(De.ambientLightColor.value=O.state.ambient,De.lightProbe.value=O.state.probe,De.directionalLights.value=O.state.directional,De.directionalLightShadows.value=O.state.directionalShadow,De.spotLights.value=O.state.spot,De.spotLightShadows.value=O.state.spotShadow,De.rectAreaLights.value=O.state.rectArea,De.ltc_1.value=O.state.rectAreaLTC1,De.ltc_2.value=O.state.rectAreaLTC2,De.pointLights.value=O.state.point,De.pointLightShadows.value=O.state.pointShadow,De.hemisphereLights.value=O.state.hemi,De.directionalShadowMap.value=O.state.directionalShadowMap,De.directionalShadowMatrix.value=O.state.directionalShadowMatrix,De.spotShadowMap.value=O.state.spotShadowMap,De.spotLightMatrix.value=O.state.spotLightMatrix,De.spotLightMap.value=O.state.spotLightMap,De.pointShadowMap.value=O.state.pointShadowMap,De.pointShadowMatrix.value=O.state.pointShadowMatrix),V.currentProgram=Ne,V.uniformsList=null,Ne}function Nm(E){if(E.uniformsList===null){const N=E.currentProgram.getUniforms();E.uniformsList=go.seqWithValue(N.seq,E.uniforms)}return E.uniformsList}function Um(E,N){const G=_.get(E);G.outputColorSpace=N.outputColorSpace,G.batching=N.batching,G.batchingColor=N.batchingColor,G.instancing=N.instancing,G.instancingColor=N.instancingColor,G.instancingMorph=N.instancingMorph,G.skinning=N.skinning,G.morphTargets=N.morphTargets,G.morphNormals=N.morphNormals,G.morphColors=N.morphColors,G.morphTargetsCount=N.morphTargetsCount,G.numClippingPlanes=N.numClippingPlanes,G.numIntersection=N.numClipIntersection,G.vertexAlphas=N.vertexAlphas,G.vertexTangents=N.vertexTangents,G.toneMapping=N.toneMapping}function tE(E,N,G,V,O){N.isScene!==!0&&(N=bt),L.resetTextureUnits();const me=N.fog,Te=V.isMeshStandardMaterial?N.environment:null,be=B===null?y.outputColorSpace:B.isXRRenderTarget===!0?B.texture.colorSpace:Ws,Ee=(V.isMeshStandardMaterial?ee:$).get(V.envMap||Te),Ie=V.vertexColors===!0&&!!G.attributes.color&&G.attributes.color.itemSize===4,Ne=!!G.attributes.tangent&&(!!V.normalMap||V.anisotropy>0),De=!!G.morphAttributes.position,$e=!!G.morphAttributes.normal,ft=!!G.morphAttributes.color;let Rt=Kn;V.toneMapped&&(B===null||B.isXRRenderTarget===!0)&&(Rt=y.toneMapping);const Pt=G.morphAttributes.position||G.morphAttributes.normal||G.morphAttributes.color,_t=Pt!==void 0?Pt.length:0,Le=_.get(V),dt=S.state.lights;if(we===!0&&(nt===!0||E!==K)){const nn=E===K&&V.id===q;Me.setState(V,E,nn)}let it=!1;V.version===Le.__version?(Le.needsLights&&Le.lightsStateVersion!==dt.state.version||Le.outputColorSpace!==be||O.isBatchedMesh&&Le.batching===!1||!O.isBatchedMesh&&Le.batching===!0||O.isBatchedMesh&&Le.batchingColor===!0&&O.colorTexture===null||O.isBatchedMesh&&Le.batchingColor===!1&&O.colorTexture!==null||O.isInstancedMesh&&Le.instancing===!1||!O.isInstancedMesh&&Le.instancing===!0||O.isSkinnedMesh&&Le.skinning===!1||!O.isSkinnedMesh&&Le.skinning===!0||O.isInstancedMesh&&Le.instancingColor===!0&&O.instanceColor===null||O.isInstancedMesh&&Le.instancingColor===!1&&O.instanceColor!==null||O.isInstancedMesh&&Le.instancingMorph===!0&&O.morphTexture===null||O.isInstancedMesh&&Le.instancingMorph===!1&&O.morphTexture!==null||Le.envMap!==Ee||V.fog===!0&&Le.fog!==me||Le.numClippingPlanes!==void 0&&(Le.numClippingPlanes!==Me.numPlanes||Le.numIntersection!==Me.numIntersection)||Le.vertexAlphas!==Ie||Le.vertexTangents!==Ne||Le.morphTargets!==De||Le.morphNormals!==$e||Le.morphColors!==ft||Le.toneMapping!==Rt||Le.morphTargetsCount!==_t)&&(it=!0):(it=!0,Le.__version=V.version);let bn=Le.currentProgram;it===!0&&(bn=yo(V,N,O));let hr=!1,_n=!1,ta=!1;const xt=bn.getUniforms(),dn=Le.uniforms;if(Re.useProgram(bn.program)&&(hr=!0,_n=!0,ta=!0),V.id!==q&&(q=V.id,_n=!0),hr||K!==E){Re.buffers.depth.getReversed()&&E.reversedDepth!==!0&&(E._reversedDepth=!0,E.updateProjectionMatrix()),xt.setValue(I,"projectionMatrix",E.projectionMatrix),xt.setValue(I,"viewMatrix",E.matrixWorldInverse);const un=xt.map.cameraPosition;un!==void 0&&un.setValue(I,et.setFromMatrixPosition(E.matrixWorld)),yt.logarithmicDepthBuffer&&xt.setValue(I,"logDepthBufFC",2/(Math.log(E.far+1)/Math.LN2)),(V.isMeshPhongMaterial||V.isMeshToonMaterial||V.isMeshLambertMaterial||V.isMeshBasicMaterial||V.isMeshStandardMaterial||V.isShaderMaterial)&&xt.setValue(I,"isOrthographic",E.isOrthographicCamera===!0),K!==E&&(K=E,_n=!0,ta=!0)}if(Le.needsLights&&(dt.state.directionalShadowMap.length>0&&xt.setValue(I,"directionalShadowMap",dt.state.directionalShadowMap,L),dt.state.spotShadowMap.length>0&&xt.setValue(I,"spotShadowMap",dt.state.spotShadowMap,L),dt.state.pointShadowMap.length>0&&xt.setValue(I,"pointShadowMap",dt.state.pointShadowMap,L)),O.isSkinnedMesh){xt.setOptional(I,O,"bindMatrix"),xt.setOptional(I,O,"bindMatrixInverse");const nn=O.skeleton;nn&&(nn.boneTexture===null&&nn.computeBoneTexture(),xt.setValue(I,"boneTexture",nn.boneTexture,L))}O.isBatchedMesh&&(xt.setOptional(I,O,"batchingTexture"),xt.setValue(I,"batchingTexture",O._matricesTexture,L),xt.setOptional(I,O,"batchingIdTexture"),xt.setValue(I,"batchingIdTexture",O._indirectTexture,L),xt.setOptional(I,O,"batchingColorTexture"),O._colorsTexture!==null&&xt.setValue(I,"batchingColorTexture",O._colorsTexture,L));const En=G.morphAttributes;if((En.position!==void 0||En.normal!==void 0||En.color!==void 0)&&je.update(O,G,bn),(_n||Le.receiveShadow!==O.receiveShadow)&&(Le.receiveShadow=O.receiveShadow,xt.setValue(I,"receiveShadow",O.receiveShadow)),V.isMeshGouraudMaterial&&V.envMap!==null&&(dn.envMap.value=Ee,dn.flipEnvMap.value=Ee.isCubeTexture&&Ee.isRenderTargetTexture===!1?-1:1),V.isMeshStandardMaterial&&V.envMap===null&&N.environment!==null&&(dn.envMapIntensity.value=N.environmentIntensity),dn.dfgLUT!==void 0&&(dn.dfgLUT.value=LC()),_n&&(xt.setValue(I,"toneMappingExposure",y.toneMappingExposure),Le.needsLights&&nE(dn,ta),me&&V.fog===!0&&Ue.refreshFogUniforms(dn,me),Ue.refreshMaterialUniforms(dn,V,Be,Ve,S.state.transmissionRenderTarget[E.id]),go.upload(I,Nm(Le),dn,L)),V.isShaderMaterial&&V.uniformsNeedUpdate===!0&&(go.upload(I,Nm(Le),dn,L),V.uniformsNeedUpdate=!1),V.isSpriteMaterial&&xt.setValue(I,"center",O.center),xt.setValue(I,"modelViewMatrix",O.modelViewMatrix),xt.setValue(I,"normalMatrix",O.normalMatrix),xt.setValue(I,"modelMatrix",O.matrixWorld),V.isShaderMaterial||V.isRawShaderMaterial){const nn=V.uniformsGroups;for(let un=0,Hd=nn.length;un<Hd;un++){const Ts=nn[un];se.update(Ts,bn),se.bind(Ts,bn)}}return bn}function nE(E,N){E.ambientLightColor.needsUpdate=N,E.lightProbe.needsUpdate=N,E.directionalLights.needsUpdate=N,E.directionalLightShadows.needsUpdate=N,E.pointLights.needsUpdate=N,E.pointLightShadows.needsUpdate=N,E.spotLights.needsUpdate=N,E.spotLightShadows.needsUpdate=N,E.rectAreaLights.needsUpdate=N,E.hemisphereLights.needsUpdate=N}function iE(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 U},this.getRenderTarget=function(){return B},this.setRenderTargetTextures=function(E,N,G){const V=_.get(E);V.__autoAllocateDepthBuffer=E.resolveDepthBuffer===!1,V.__autoAllocateDepthBuffer===!1&&(V.__useRenderToTexture=!1),_.get(E.texture).__webglTexture=N,_.get(E.depthTexture).__webglTexture=V.__autoAllocateDepthBuffer?void 0:G,V.__hasExternalTextures=!0},this.setRenderTargetFramebuffer=function(E,N){const G=_.get(E);G.__webglFramebuffer=N,G.__useDefaultFramebuffer=N===void 0};const sE=I.createFramebuffer();this.setRenderTarget=function(E,N=0,G=0){B=E,R=N,U=G;let V=null,O=!1,me=!1;if(E){const be=_.get(E);if(be.__useDefaultFramebuffer!==void 0){Re.bindFramebuffer(I.FRAMEBUFFER,be.__webglFramebuffer),H.copy(E.viewport),W.copy(E.scissor),te=E.scissorTest,Re.viewport(H),Re.scissor(W),Re.setScissorTest(te),q=-1;return}else if(be.__webglFramebuffer===void 0)L.setupRenderTarget(E);else if(be.__hasExternalTextures)L.rebindTextures(E,_.get(E.texture).__webglTexture,_.get(E.depthTexture).__webglTexture);else if(E.depthBuffer){const Ne=E.depthTexture;if(be.__boundDepthTexture!==Ne){if(Ne!==null&&_.has(Ne)&&(E.width!==Ne.image.width||E.height!==Ne.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)&&(me=!0);const Ie=_.get(E).__webglFramebuffer;E.isWebGLCubeRenderTarget?(Array.isArray(Ie[N])?V=Ie[N][G]:V=Ie[N],O=!0):E.samples>0&&L.useMultisampledRTT(E)===!1?V=_.get(E).__webglMultisampledFramebuffer:Array.isArray(Ie)?V=Ie[G]:V=Ie,H.copy(E.viewport),W.copy(E.scissor),te=E.scissorTest}else H.copy(X).multiplyScalar(Be).floor(),W.copy(ie).multiplyScalar(Be).floor(),te=Ce;if(G!==0&&(V=sE),Re.bindFramebuffer(I.FRAMEBUFFER,V)&&Re.drawBuffers(E,V),Re.viewport(H),Re.scissor(W),Re.setScissorTest(te),O){const be=_.get(E.texture);I.framebufferTexture2D(I.FRAMEBUFFER,I.COLOR_ATTACHMENT0,I.TEXTURE_CUBE_MAP_POSITIVE_X+N,be.__webglTexture,G)}else if(me){const be=N;for(let Ee=0;Ee<E.textures.length;Ee++){const Ie=_.get(E.textures[Ee]);I.framebufferTextureLayer(I.FRAMEBUFFER,I.COLOR_ATTACHMENT0+Ee,Ie.__webglTexture,G,be)}}else if(E!==null&&G!==0){const be=_.get(E.texture);I.framebufferTexture2D(I.FRAMEBUFFER,I.COLOR_ATTACHMENT0,I.TEXTURE_2D,be.__webglTexture,G)}q=-1},this.readRenderTargetPixels=function(E,N,G,V,O,me,Te,be=0){if(!(E&&E.isWebGLRenderTarget)){tt("WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");return}let Ee=_.get(E).__webglFramebuffer;if(E.isWebGLCubeRenderTarget&&Te!==void 0&&(Ee=Ee[Te]),Ee){Re.bindFramebuffer(I.FRAMEBUFFER,Ee);try{const Ie=E.textures[be],Ne=Ie.format,De=Ie.type;if(!yt.textureFormatReadable(Ne)){tt("WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.");return}if(!yt.textureTypeReadable(De)){tt("WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.");return}N>=0&&N<=E.width-V&&G>=0&&G<=E.height-O&&(E.textures.length>1&&I.readBuffer(I.COLOR_ATTACHMENT0+be),I.readPixels(N,G,V,O,oe.convert(Ne),oe.convert(De),me))}finally{const Ie=B!==null?_.get(B).__webglFramebuffer:null;Re.bindFramebuffer(I.FRAMEBUFFER,Ie)}}},this.readRenderTargetPixelsAsync=async function(E,N,G,V,O,me,Te,be=0){if(!(E&&E.isWebGLRenderTarget))throw new Error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");let Ee=_.get(E).__webglFramebuffer;if(E.isWebGLCubeRenderTarget&&Te!==void 0&&(Ee=Ee[Te]),Ee)if(N>=0&&N<=E.width-V&&G>=0&&G<=E.height-O){Re.bindFramebuffer(I.FRAMEBUFFER,Ee);const Ie=E.textures[be],Ne=Ie.format,De=Ie.type;if(!yt.textureFormatReadable(Ne))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.");if(!yt.textureTypeReadable(De))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.");const $e=I.createBuffer();I.bindBuffer(I.PIXEL_PACK_BUFFER,$e),I.bufferData(I.PIXEL_PACK_BUFFER,me.byteLength,I.STREAM_READ),E.textures.length>1&&I.readBuffer(I.COLOR_ATTACHMENT0+be),I.readPixels(N,G,V,O,oe.convert(Ne),oe.convert(De),0);const ft=B!==null?_.get(B).__webglFramebuffer:null;Re.bindFramebuffer(I.FRAMEBUFFER,ft);const Rt=I.fenceSync(I.SYNC_GPU_COMMANDS_COMPLETE,0);return I.flush(),await O_(I,Rt,4),I.bindBuffer(I.PIXEL_PACK_BUFFER,$e),I.getBufferSubData(I.PIXEL_PACK_BUFFER,0,me),I.deleteBuffer($e),I.deleteSync(Rt),me}else throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range.")},this.copyFramebufferToTexture=function(E,N=null,G=0){const V=Math.pow(2,-G),O=Math.floor(E.image.width*V),me=Math.floor(E.image.height*V),Te=N!==null?N.x:0,be=N!==null?N.y:0;L.setTexture2D(E,0),I.copyTexSubImage2D(I.TEXTURE_2D,G,0,0,Te,be,O,me),Re.unbindTexture()};const rE=I.createFramebuffer(),aE=I.createFramebuffer();this.copyTextureToTexture=function(E,N,G=null,V=null,O=0,me=null){me===null&&(O!==0?(Vr("WebGLRenderer: copyTextureToTexture function signature has changed to support src and dst mipmap levels."),me=O,O=0):me=0);let Te,be,Ee,Ie,Ne,De,$e,ft,Rt;const Pt=E.isCompressedTexture?E.mipmaps[me]:E.image;if(G!==null)Te=G.max.x-G.min.x,be=G.max.y-G.min.y,Ee=G.isBox3?G.max.z-G.min.z:1,Ie=G.min.x,Ne=G.min.y,De=G.isBox3?G.min.z:0;else{const En=Math.pow(2,-O);Te=Math.floor(Pt.width*En),be=Math.floor(Pt.height*En),E.isDataArrayTexture?Ee=Pt.depth:E.isData3DTexture?Ee=Math.floor(Pt.depth*En):Ee=1,Ie=0,Ne=0,De=0}V!==null?($e=V.x,ft=V.y,Rt=V.z):($e=0,ft=0,Rt=0);const _t=oe.convert(N.format),Le=oe.convert(N.type);let dt;N.isData3DTexture?(L.setTexture3D(N,0),dt=I.TEXTURE_3D):N.isDataArrayTexture||N.isCompressedArrayTexture?(L.setTexture2DArray(N,0),dt=I.TEXTURE_2D_ARRAY):(L.setTexture2D(N,0),dt=I.TEXTURE_2D),I.pixelStorei(I.UNPACK_FLIP_Y_WEBGL,N.flipY),I.pixelStorei(I.UNPACK_PREMULTIPLY_ALPHA_WEBGL,N.premultiplyAlpha),I.pixelStorei(I.UNPACK_ALIGNMENT,N.unpackAlignment);const it=I.getParameter(I.UNPACK_ROW_LENGTH),bn=I.getParameter(I.UNPACK_IMAGE_HEIGHT),hr=I.getParameter(I.UNPACK_SKIP_PIXELS),_n=I.getParameter(I.UNPACK_SKIP_ROWS),ta=I.getParameter(I.UNPACK_SKIP_IMAGES);I.pixelStorei(I.UNPACK_ROW_LENGTH,Pt.width),I.pixelStorei(I.UNPACK_IMAGE_HEIGHT,Pt.height),I.pixelStorei(I.UNPACK_SKIP_PIXELS,Ie),I.pixelStorei(I.UNPACK_SKIP_ROWS,Ne),I.pixelStorei(I.UNPACK_SKIP_IMAGES,De);const xt=E.isDataArrayTexture||E.isData3DTexture,dn=N.isDataArrayTexture||N.isData3DTexture;if(E.isDepthTexture){const En=_.get(E),nn=_.get(N),un=_.get(En.__renderTarget),Hd=_.get(nn.__renderTarget);Re.bindFramebuffer(I.READ_FRAMEBUFFER,un.__webglFramebuffer),Re.bindFramebuffer(I.DRAW_FRAMEBUFFER,Hd.__webglFramebuffer);for(let Ts=0;Ts<Ee;Ts++)xt&&(I.framebufferTextureLayer(I.READ_FRAMEBUFFER,I.COLOR_ATTACHMENT0,_.get(E).__webglTexture,O,De+Ts),I.framebufferTextureLayer(I.DRAW_FRAMEBUFFER,I.COLOR_ATTACHMENT0,_.get(N).__webglTexture,me,Rt+Ts)),I.blitFramebuffer(Ie,Ne,Te,be,$e,ft,Te,be,I.DEPTH_BUFFER_BIT,I.NEAREST);Re.bindFramebuffer(I.READ_FRAMEBUFFER,null),Re.bindFramebuffer(I.DRAW_FRAMEBUFFER,null)}else if(O!==0||E.isRenderTargetTexture||_.has(E)){const En=_.get(E),nn=_.get(N);Re.bindFramebuffer(I.READ_FRAMEBUFFER,rE),Re.bindFramebuffer(I.DRAW_FRAMEBUFFER,aE);for(let un=0;un<Ee;un++)xt?I.framebufferTextureLayer(I.READ_FRAMEBUFFER,I.COLOR_ATTACHMENT0,En.__webglTexture,O,De+un):I.framebufferTexture2D(I.READ_FRAMEBUFFER,I.COLOR_ATTACHMENT0,I.TEXTURE_2D,En.__webglTexture,O),dn?I.framebufferTextureLayer(I.DRAW_FRAMEBUFFER,I.COLOR_ATTACHMENT0,nn.__webglTexture,me,Rt+un):I.framebufferTexture2D(I.DRAW_FRAMEBUFFER,I.COLOR_ATTACHMENT0,I.TEXTURE_2D,nn.__webglTexture,me),O!==0?I.blitFramebuffer(Ie,Ne,Te,be,$e,ft,Te,be,I.COLOR_BUFFER_BIT,I.NEAREST):dn?I.copyTexSubImage3D(dt,me,$e,ft,Rt+un,Ie,Ne,Te,be):I.copyTexSubImage2D(dt,me,$e,ft,Ie,Ne,Te,be);Re.bindFramebuffer(I.READ_FRAMEBUFFER,null),Re.bindFramebuffer(I.DRAW_FRAMEBUFFER,null)}else dn?E.isDataTexture||E.isData3DTexture?I.texSubImage3D(dt,me,$e,ft,Rt,Te,be,Ee,_t,Le,Pt.data):N.isCompressedArrayTexture?I.compressedTexSubImage3D(dt,me,$e,ft,Rt,Te,be,Ee,_t,Pt.data):I.texSubImage3D(dt,me,$e,ft,Rt,Te,be,Ee,_t,Le,Pt):E.isDataTexture?I.texSubImage2D(I.TEXTURE_2D,me,$e,ft,Te,be,_t,Le,Pt.data):E.isCompressedTexture?I.compressedTexSubImage2D(I.TEXTURE_2D,me,$e,ft,Pt.width,Pt.height,_t,Pt.data):I.texSubImage2D(I.TEXTURE_2D,me,$e,ft,Te,be,_t,Le,Pt);I.pixelStorei(I.UNPACK_ROW_LENGTH,it),I.pixelStorei(I.UNPACK_IMAGE_HEIGHT,bn),I.pixelStorei(I.UNPACK_SKIP_PIXELS,hr),I.pixelStorei(I.UNPACK_SKIP_ROWS,_n),I.pixelStorei(I.UNPACK_SKIP_IMAGES,ta),me===0&&N.generateMipmaps&&I.generateMipmap(dt),Re.unbindTexture()},this.initRenderTarget=function(E){_.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,U=0,B=null,Re.reset(),xe.reset()},typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}get coordinateSystem(){return Zn}get outputColorSpace(){return this._outputColorSpace}set outputColorSpace(e){this._outputColorSpace=e;const t=this.getContext();t.drawingBufferColorSpace=Qe._getDrawingBufferColorSpace(e),t.unpackColorSpace=Qe._getUnpackColorSpace()}}const UC=`
4102
+ }`;class AC{constructor(){this.texture=null,this.mesh=null,this.depthNear=0,this.depthFar=0}init(e,t){if(this.texture===null){const n=new Kp(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 Cn({vertexShader:MC,fragmentShader:wC,uniforms:{depthColor:{value:this.texture},depthWidth:{value:t.z},depthHeight:{value:t.w}}});this.mesh=new zn(new ho(20,20),n)}return this.mesh}reset(){this.texture=null,this.mesh=null}getDepthTexture(){return this.texture}}class RC 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 AC,p={},x=t.getContextAttributes();let C=null,b=null;const S=[],M=[],A=new rt;let k=null;const y=new En;y.viewport=new It;const T=new En;T.viewport=new It;const R=[y,T],U=new by;let B=null,q=null;this.cameraAutoUpdate=!0,this.enabled=!1,this.isPresenting=!1,this.getController=function(X){let ie=S[X];return ie===void 0&&(ie=new Md,S[X]=ie),ie.getTargetRaySpace()},this.getControllerGrip=function(X){let ie=S[X];return ie===void 0&&(ie=new Md,S[X]=ie),ie.getGripSpace()},this.getHand=function(X){let ie=S[X];return ie===void 0&&(ie=new Md,S[X]=ie),ie.getHandSpace()};function K(X){const ie=M.indexOf(X.inputSource);if(ie===-1)return;const Ce=S[ie];Ce!==void 0&&(Ce.update(X.inputSource,X.frame,l||a),Ce.dispatchEvent({type:X.type,data:X.inputSource}))}function H(){s.removeEventListener("select",K),s.removeEventListener("selectstart",K),s.removeEventListener("selectend",K),s.removeEventListener("squeeze",K),s.removeEventListener("squeezestart",K),s.removeEventListener("squeezeend",K),s.removeEventListener("end",H),s.removeEventListener("inputsourceschange",W);for(let X=0;X<S.length;X++){const ie=M[X];ie!==null&&(M[X]=null,S[X].disconnect(ie))}B=null,q=null,m.reset();for(const X in p)delete p[X];e.setRenderTarget(C),f=null,h=null,u=null,s=null,b=null,mt.stop(),n.isPresenting=!1,e.setPixelRatio(k),e.setSize(A.width,A.height,!1),n.dispatchEvent({type:"sessionend"})}this.setFramebufferScaleFactor=function(X){r=X,n.isPresenting===!0&&Oe("WebXRManager: Cannot change framebuffer scale while presenting.")},this.setReferenceSpaceType=function(X){o=X,n.isPresenting===!0&&Oe("WebXRManager: Cannot change reference space type while presenting.")},this.getReferenceSpace=function(){return l||a},this.setReferenceSpace=function(X){l=X},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(X){if(s=X,s!==null){if(C=e.getRenderTarget(),s.addEventListener("select",K),s.addEventListener("selectstart",K),s.addEventListener("selectend",K),s.addEventListener("squeeze",K),s.addEventListener("squeezestart",K),s.addEventListener("squeezeend",K),s.addEventListener("end",H),s.addEventListener("inputsourceschange",W),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?hs:yi,Ge=x.stencil?Br:Jn);const nt={colorFormat:t.RGBA8,depthFormat:we,scaleFactor:r};u=this.getBinding(),h=u.createProjectionLayer(nt),s.updateRenderState({layers:[h]}),e.setPixelRatio(1),e.setSize(h.textureWidth,h.textureHeight,!1),b=new ei(h.textureWidth,h.textureHeight,{format:Nn,type:Sn,depthTexture:new Yr(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 ei(f.framebufferWidth,f.framebufferHeight,{format:Nn,type:Sn,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),mt.setContext(s),mt.start(),n.isPresenting=!0,n.dispatchEvent({type:"sessionstart"})}},this.getEnvironmentBlendMode=function(){if(s!==null)return s.environmentBlendMode},this.getDepthTexture=function(){return m.getDepthTexture()};function W(X){for(let ie=0;ie<X.removed.length;ie++){const Ce=X.removed[ie],Ge=M.indexOf(Ce);Ge>=0&&(M[Ge]=null,S[Ge].disconnect(Ce))}for(let ie=0;ie<X.added.length;ie++){const Ce=X.added[ie];let Ge=M.indexOf(Ce);if(Ge===-1){for(let nt=0;nt<S.length;nt++)if(nt>=M.length){M.push(Ce),Ge=nt;break}else if(M[nt]===null){M[nt]=Ce,Ge=nt;break}if(Ge===-1)break}const we=S[Ge];we&&we.connect(Ce)}}const te=new F,ve=new F;function de(X,ie,Ce){te.setFromMatrixPosition(ie.matrixWorld),ve.setFromMatrixPosition(Ce.matrixWorld);const Ge=te.distanceTo(ve),we=ie.projectionMatrix.elements,nt=Ce.projectionMatrix.elements,jt=we[14]/(we[10]-1),et=we[14]/(we[10]+1),ct=(we[9]+1)/we[5],bt=(we[9]-1)/we[5],qe=(we[8]-1)/we[0],Ot=(nt[8]+1)/nt[0],I=jt*qe,Ft=jt*Ot,at=Ge/(-qe+Ot),yt=at*-qe;if(ie.matrixWorld.decompose(X.position,X.quaternion,X.scale),X.translateX(yt),X.translateZ(at),X.matrixWorld.compose(X.position,X.quaternion,X.scale),X.matrixWorldInverse.copy(X.matrixWorld).invert(),we[10]===-1)X.projectionMatrix.copy(ie.projectionMatrix),X.projectionMatrixInverse.copy(ie.projectionMatrixInverse);else{const Re=jt+at,w=et+at,_=I-yt,L=Ft+(Ge-yt),$=ct*et/w*Re,ee=bt*et/w*Re;X.projectionMatrix.makePerspective(_,L,$,ee,Re,w),X.projectionMatrixInverse.copy(X.projectionMatrix).invert()}}function _e(X,ie){ie===null?X.matrixWorld.copy(X.matrix):X.matrixWorld.multiplyMatrices(ie.matrixWorld,X.matrix),X.matrixWorldInverse.copy(X.matrixWorld).invert()}this.updateCamera=function(X){if(s===null)return;let ie=X.near,Ce=X.far;m.texture!==null&&(m.depthNear>0&&(ie=m.depthNear),m.depthFar>0&&(Ce=m.depthFar)),U.near=T.near=y.near=ie,U.far=T.far=y.far=Ce,(B!==U.near||q!==U.far)&&(s.updateRenderState({depthNear:U.near,depthFar:U.far}),B=U.near,q=U.far),U.layers.mask=X.layers.mask|6,y.layers.mask=U.layers.mask&3,T.layers.mask=U.layers.mask&5;const Ge=X.parent,we=U.cameras;_e(U,Ge);for(let nt=0;nt<we.length;nt++)_e(we[nt],Ge);we.length===2?de(U,y,T):U.projectionMatrix.copy(y.projectionMatrix),Ve(X,U,Ge)};function Ve(X,ie,Ce){Ce===null?X.matrix.copy(ie.matrixWorld):(X.matrix.copy(Ce.matrixWorld),X.matrix.invert(),X.matrix.multiply(ie.matrixWorld)),X.matrix.decompose(X.position,X.quaternion,X.scale),X.updateMatrixWorld(!0),X.projectionMatrix.copy(ie.projectionMatrix),X.projectionMatrixInverse.copy(ie.projectionMatrixInverse),X.isPerspectiveCamera&&(X.fov=nd*2*Math.atan(1/X.projectionMatrix.elements[5]),X.zoom=1)}this.getCamera=function(){return U},this.getFoveation=function(){if(!(h===null&&f===null))return c},this.setFoveation=function(X){c=X,h!==null&&(h.fixedFoveation=X),f!==null&&f.fixedFoveation!==void 0&&(f.fixedFoveation=X)},this.hasDepthSensing=function(){return m.texture!==null},this.getDepthSensingMesh=function(){return m.getMesh(U)},this.getCameraTexture=function(X){return p[X]};let Be=null;function Ct(X,ie){if(d=ie.getViewerPose(l||a),g=ie,d!==null){const Ce=d.views;f!==null&&(e.setRenderTargetFramebuffer(b,f.framebuffer),e.setRenderTarget(b));let Ge=!1;Ce.length!==U.cameras.length&&(U.cameras.length=0,Ge=!0);for(let et=0;et<Ce.length;et++){const ct=Ce[et];let bt=null;if(f!==null)bt=f.getViewport(ct);else{const Ot=u.getViewSubImage(h,ct);bt=Ot.viewport,et===0&&(e.setRenderTargetTextures(b,Ot.colorTexture,Ot.depthStencilTexture),e.setRenderTarget(b))}let qe=R[et];qe===void 0&&(qe=new En,qe.layers.enable(et),qe.viewport=new It,R[et]=qe),qe.matrix.fromArray(ct.transform.matrix),qe.matrix.decompose(qe.position,qe.quaternion,qe.scale),qe.projectionMatrix.fromArray(ct.projectionMatrix),qe.projectionMatrixInverse.copy(qe.projectionMatrix).invert(),qe.viewport.set(bt.x,bt.y,bt.width,bt.height),et===0&&(U.matrix.copy(qe.matrix),U.matrix.decompose(U.position,U.quaternion,U.scale)),Ge===!0&&U.cameras.push(qe)}const we=s.enabledFeatures;if(we&&we.includes("depth-sensing")&&s.depthUsage=="gpu-optimized"&&v){u=n.getBinding();const et=u.getDepthInformation(Ce[0]);et&&et.isValid&&et.texture&&m.init(et,s.renderState)}if(we&&we.includes("camera-access")&&v){e.state.unbindTexture(),u=n.getBinding();for(let et=0;et<Ce.length;et++){const ct=Ce[et].camera;if(ct){let bt=p[ct];bt||(bt=new Kp,p[ct]=bt);const qe=u.getCameraImage(ct);bt.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,ie,l||a)}Be&&Be(X,ie),ie.detectedPlanes&&n.dispatchEvent({type:"planesdetected",data:ie}),g=null}const mt=new Zp;mt.setAnimationLoop(Ct),this.setAnimationLoop=function(X){Be=X},this.dispose=function(){}}}const ys=new Ci,PC=new Nt;function kC(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,Gp(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===Zt&&(m.bumpScale.value*=-1)),p.normalMap&&(m.normalMap.value=p.normalMap,t(p.normalMap,m.normalMapTransform),m.normalScale.value.copy(p.normalScale),p.side===Zt&&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,ys.copy(b),ys.x*=-1,ys.y*=-1,ys.z*=-1,C.isCubeTexture&&C.isRenderTargetTexture===!1&&(ys.y*=-1,ys.z*=-1),m.envMapRotation.value.setFromMatrix4(PC.makeRotationFromEuler(ys)),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===Zt&&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 IC(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 tt("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 y=0,T=k.length;y<T;y++){const R=k[y];if(f(R,M,y,S)===!0){const U=R.__offset,B=Array.isArray(R.value)?R.value:[R.value];let q=0;for(let K=0;K<B.length;K++){const H=B[K],W=v(H);typeof H=="number"||typeof H=="boolean"?(R.__data[0]=H,i.bufferSubData(i.UNIFORM_BUFFER,U+q,R.__data)):H.isMatrix3?(R.__data[0]=H.elements[0],R.__data[1]=H.elements[1],R.__data[2]=H.elements[2],R.__data[3]=0,R.__data[4]=H.elements[3],R.__data[5]=H.elements[4],R.__data[6]=H.elements[5],R.__data[7]=0,R.__data[8]=H.elements[6],R.__data[9]=H.elements[7],R.__data[10]=H.elements[8],R.__data[11]=0):(H.toArray(R.__data,q),q+=W.storage/Float32Array.BYTES_PER_ELEMENT)}i.bufferSubData(i.UNIFORM_BUFFER,U,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 y=Array.isArray(C[A])?C[A]:[C[A]];for(let T=0,R=y.length;T<R;T++){const U=y[T],B=Array.isArray(U.value)?U.value:[U.value];for(let q=0,K=B.length;q<K;q++){const H=B[q],W=v(H),te=b%S,ve=te%W.boundary,de=te+ve;b+=ve,de!==0&&S-de<W.storage&&(b+=S-de),U.__data=new Float32Array(W.storage/Float32Array.BYTES_PER_ELEMENT),U.__offset=b,b+=W.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 DC=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 ii=null;function LC(){return ii===null&&(ii=new dy(DC,16,16,Hs,_i),ii.name="DFG_LUT",ii.minFilter=Kt,ii.magFilter=Kt,ii.wrapS=bi,ii.wrapT=bi,ii.generateMipmaps=!1,ii.needsUpdate=!0),ii}class NC{constructor(e={}){const{canvas:t=U_(),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=Sn}=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([yl,_l,bl]),p=new Set([Sn,Jn,Fr,Br,gl,vl]),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=Yn,this.toneMappingExposure=1,this.transmissionResolutionScale=1;const y=this;let T=!1;this._outputColorSpace=xn;let R=0,U=0,B=null,q=-1,K=null;const H=new It,W=new It;let te=null;const ve=new Ze(0);let de=0,_e=t.width,Ve=t.height,Be=1,Ct=null,mt=null;const X=new It(0,0,_e,Ve),ie=new It(0,0,_e,Ve);let Ce=!1;const Ge=new Xp;let we=!1,nt=!1;const jt=new Nt,et=new F,ct=new It,bt={background:null,fog:null,environment:null,overrideMaterial:null,isScene:!0};let qe=!1;function Ot(){return B===null?Be:1}let I=n;function Ft(E,N){return t.getContext(E,N)}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${Qc}`),t.addEventListener("webglcontextlost",Fe,!1),t.addEventListener("webglcontextrestored",St,!1),t.addEventListener("webglcontextcreationerror",lt,!1),I===null){const N="webgl2";if(I=Ft(N,E),I===null)throw Ft(N)?new Error("Error creating WebGL context with your selected attributes."):new Error("Error creating WebGL context.")}}catch(E){throw tt("WebGLRenderer: "+E.message),E}let at,yt,Re,w,_,L,$,ee,j,ke,he,Ae,Ue,re,pe,Me,Pe,fe,je,D,ye,oe,xe,se;function Q(){at=new Lx(I),at.init(),oe=new EC(I,at),yt=new Ex(I,at,e,oe),Re=new TC(I,at),yt.reversedDepthBuffer&&h&&Re.buffers.depth.setReversed(!0),w=new Ox(I),_=new cC,L=new CC(I,at,Re,_,yt,oe,w),$=new wx(y),ee=new Dx(y),j=new Sy(I),xe=new Tx(I,j),ke=new Nx(I,j,w,xe),he=new Bx(I,ke,j,w),je=new Fx(I,yt,L),Me=new Mx(_),Ae=new oC(y,$,ee,at,yt,xe,Me),Ue=new kC(y,_),re=new dC,pe=new gC(at),fe=new xx(y,$,ee,Re,he,g,c),Pe=new SC(y,he,yt),se=new IC(I,w,yt,Re),D=new Cx(I,at,w),ye=new Ux(I,at,w),w.programs=Ae.programs,y.capabilities=yt,y.extensions=at,y.properties=_,y.renderLists=re,y.shadowMap=Pe,y.state=Re,y.info=w}Q(),v!==Sn&&(k=new zx(v,t.width,t.height,s,r));const ue=new RC(y,I);this.xr=ue,this.getContext=function(){return I},this.getContextAttributes=function(){return I.getContextAttributes()},this.forceContextLoss=function(){const E=at.get("WEBGL_lose_context");E&&E.loseContext()},this.forceContextRestore=function(){const E=at.get("WEBGL_lose_context");E&&E.restoreContext()},this.getPixelRatio=function(){return Be},this.setPixelRatio=function(E){E!==void 0&&(Be=E,this.setSize(_e,Ve,!1))},this.getSize=function(E){return E.set(_e,Ve)},this.setSize=function(E,N,G=!0){if(ue.isPresenting){Oe("WebGLRenderer: Can't change size while VR device is presenting.");return}_e=E,Ve=N,t.width=Math.floor(E*Be),t.height=Math.floor(N*Be),G===!0&&(t.style.width=E+"px",t.style.height=N+"px"),k!==null&&k.setSize(t.width,t.height),this.setViewport(0,0,E,N)},this.getDrawingBufferSize=function(E){return E.set(_e*Be,Ve*Be).floor()},this.setDrawingBufferSize=function(E,N,G){_e=E,Ve=N,Be=G,t.width=Math.floor(E*G),t.height=Math.floor(N*G),this.setViewport(0,0,E,N)},this.setEffects=function(E){if(v===Sn){console.error("THREE.WebGLRenderer: setEffects() requires outputBufferType set to HalfFloatType or FloatType.");return}if(E){for(let N=0;N<E.length;N++)if(E[N].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(H)},this.getViewport=function(E){return E.copy(X)},this.setViewport=function(E,N,G,V){E.isVector4?X.set(E.x,E.y,E.z,E.w):X.set(E,N,G,V),Re.viewport(H.copy(X).multiplyScalar(Be).round())},this.getScissor=function(E){return E.copy(ie)},this.setScissor=function(E,N,G,V){E.isVector4?ie.set(E.x,E.y,E.z,E.w):ie.set(E,N,G,V),Re.scissor(W.copy(ie).multiplyScalar(Be).round())},this.getScissorTest=function(){return Ce},this.setScissorTest=function(E){Re.setScissorTest(Ce=E)},this.setOpaqueSort=function(E){Ct=E},this.setTransparentSort=function(E){mt=E},this.getClearColor=function(E){return E.copy(fe.getClearColor())},this.setClearColor=function(){fe.setClearColor(...arguments)},this.getClearAlpha=function(){return fe.getClearAlpha()},this.setClearAlpha=function(){fe.setClearAlpha(...arguments)},this.clear=function(E=!0,N=!0,G=!0){let V=0;if(E){let O=!1;if(B!==null){const me=B.texture.format;O=m.has(me)}if(O){const me=B.texture.type,Te=p.has(me),be=fe.getClearColor(),Ee=fe.getClearAlpha(),Ie=be.r,Ne=be.g,De=be.b;Te?(x[0]=Ie,x[1]=Ne,x[2]=De,x[3]=Ee,I.clearBufferuiv(I.COLOR,0,x)):(C[0]=Ie,C[1]=Ne,C[2]=De,C[3]=Ee,I.clearBufferiv(I.COLOR,0,C))}else V|=I.COLOR_BUFFER_BIT}N&&(V|=I.DEPTH_BUFFER_BIT),G&&(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",St,!1),t.removeEventListener("webglcontextcreationerror",lt,!1),fe.dispose(),re.dispose(),pe.dispose(),_.dispose(),$.dispose(),ee.dispose(),he.dispose(),xe.dispose(),se.dispose(),Ae.dispose(),ue.dispose(),ue.removeEventListener("sessionstart",Pm),ue.removeEventListener("sessionend",km),xs.stop()};function Fe(E){E.preventDefault(),Sp("WebGLRenderer: Context Lost."),T=!0}function St(){Sp("WebGLRenderer: Context Restored."),T=!1;const E=w.autoReset,N=Pe.enabled,G=Pe.autoUpdate,V=Pe.needsUpdate,O=Pe.type;Q(),w.autoReset=E,Pe.enabled=N,Pe.autoUpdate=G,Pe.needsUpdate=V,Pe.type=O}function lt(E){tt("WebGLRenderer: A WebGL context could not be created. Reason: ",E.statusMessage)}function ai(E){const N=E.target;N.removeEventListener("dispose",ai),Ai(N)}function Ai(E){QC(E),_.remove(E)}function QC(E){const N=_.get(E).programs;N!==void 0&&(N.forEach(function(G){Ae.releaseProgram(G)}),E.isShaderMaterial&&Ae.releaseShaderCache(E))}this.renderBufferDirect=function(E,N,G,V,O,me){N===null&&(N=bt);const Te=O.isMesh&&O.matrixWorld.determinant()<0,be=tE(E,N,G,V,O);Re.setMaterial(V,Te);let Ee=G.index,Ie=1;if(V.wireframe===!0){if(Ee=ke.getWireframeAttribute(G),Ee===void 0)return;Ie=2}const Ne=G.drawRange,De=G.attributes.position;let $e=Ne.start*Ie,gt=(Ne.start+Ne.count)*Ie;me!==null&&($e=Math.max($e,me.start*Ie),gt=Math.min(gt,(me.start+me.count)*Ie)),Ee!==null?($e=Math.max($e,0),gt=Math.min(gt,Ee.count)):De!=null&&($e=Math.max($e,0),gt=Math.min(gt,De.count));const Rt=gt-$e;if(Rt<0||Rt===1/0)return;xe.setup(O,V,be,G,Ee);let Pt,_t=D;if(Ee!==null&&(Pt=j.get(Ee),_t=ye,_t.setIndex(Pt)),O.isMesh)V.wireframe===!0?(Re.setLineWidth(V.wireframeLinewidth*Ot()),_t.setMode(I.LINES)):_t.setMode(I.TRIANGLES);else if(O.isLine){let Le=V.linewidth;Le===void 0&&(Le=1),Re.setLineWidth(Le*Ot()),O.isLineSegments?_t.setMode(I.LINES):O.isLineLoop?_t.setMode(I.LINE_LOOP):_t.setMode(I.LINE_STRIP)}else O.isPoints?_t.setMode(I.POINTS):O.isSprite&&_t.setMode(I.TRIANGLES);if(O.isBatchedMesh)if(O._multiDrawInstances!==null)Vr("WebGLRenderer: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection."),_t.renderMultiDrawInstances(O._multiDrawStarts,O._multiDrawCounts,O._multiDrawCount,O._multiDrawInstances);else if(at.get("WEBGL_multi_draw"))_t.renderMultiDraw(O._multiDrawStarts,O._multiDrawCounts,O._multiDrawCount);else{const Le=O._multiDrawStarts,dt=O._multiDrawCounts,it=O._multiDrawCount,bn=Ee?j.get(Ee).bytesPerElement:1,hr=_.get(V).currentProgram.getUniforms();for(let _n=0;_n<it;_n++)hr.setValue(I,"_gl_DrawID",_n),_t.render(Le[_n]/bn,dt[_n])}else if(O.isInstancedMesh)_t.renderInstances($e,Rt,O.count);else if(G.isInstancedBufferGeometry){const Le=G._maxInstanceCount!==void 0?G._maxInstanceCount:1/0,dt=Math.min(G.instanceCount,Le);_t.renderInstances($e,Rt,dt)}else _t.render($e,Rt)};function Rm(E,N,G){E.transparent===!0&&E.side===gi&&E.forceSinglePass===!1?(E.side=Zt,E.needsUpdate=!0,yo(E,N,G),E.side=mi,E.needsUpdate=!0,yo(E,N,G),E.side=gi):yo(E,N,G)}this.compile=function(E,N,G=null){G===null&&(G=E),S=pe.get(G),S.init(N),A.push(S),G.traverseVisible(function(O){O.isLight&&O.layers.test(N.layers)&&(S.pushLight(O),O.castShadow&&S.pushShadow(O))}),E!==G&&E.traverseVisible(function(O){O.isLight&&O.layers.test(N.layers)&&(S.pushLight(O),O.castShadow&&S.pushShadow(O))}),S.setupLights();const V=new Set;return E.traverse(function(O){if(!(O.isMesh||O.isPoints||O.isLine||O.isSprite))return;const me=O.material;if(me)if(Array.isArray(me))for(let Te=0;Te<me.length;Te++){const be=me[Te];Rm(be,G,O),V.add(be)}else Rm(me,G,O),V.add(me)}),S=A.pop(),V},this.compileAsync=function(E,N,G=null){const V=this.compile(E,N,G);return new Promise(O=>{function me(){if(V.forEach(function(Te){_.get(Te).currentProgram.isReady()&&V.delete(Te)}),V.size===0){O(E);return}setTimeout(me,10)}at.get("KHR_parallel_shader_compile")!==null?me():setTimeout(me,10)})};let zd=null;function eE(E){zd&&zd(E)}function Pm(){xs.stop()}function km(){xs.start()}const xs=new Zp;xs.setAnimationLoop(eE),typeof self<"u"&&xs.setContext(self),this.setAnimationLoop=function(E){zd=E,ue.setAnimationLoop(E),E===null?xs.stop():xs.start()},ue.addEventListener("sessionstart",Pm),ue.addEventListener("sessionend",km),this.render=function(E,N){if(N!==void 0&&N.isCamera!==!0){tt("WebGLRenderer.render: camera is not an instance of THREE.Camera.");return}if(T===!0)return;const G=ue.enabled===!0&&ue.isPresenting===!0,V=k!==null&&(B===null||G)&&k.begin(y,B);if(E.matrixWorldAutoUpdate===!0&&E.updateMatrixWorld(),N.parent===null&&N.matrixWorldAutoUpdate===!0&&N.updateMatrixWorld(),ue.enabled===!0&&ue.isPresenting===!0&&(k===null||k.isCompositing()===!1)&&(ue.cameraAutoUpdate===!0&&ue.updateCamera(N),N=ue.getCamera()),E.isScene===!0&&E.onBeforeRender(y,E,N,B),S=pe.get(E,A.length),S.init(N),A.push(S),jt.multiplyMatrices(N.projectionMatrix,N.matrixWorldInverse),Ge.setFromProjectionMatrix(jt,Qn,N.reversedDepth),nt=this.localClippingEnabled,we=Me.init(this.clippingPlanes,nt),b=re.get(E,M.length),b.init(),M.push(b),ue.enabled===!0&&ue.isPresenting===!0){const Te=y.xr.getDepthSensingMesh();Te!==null&&Gd(Te,N,-1/0,y.sortObjects)}Gd(E,N,0,y.sortObjects),b.finish(),y.sortObjects===!0&&b.sort(Ct,mt),qe=ue.enabled===!1||ue.isPresenting===!1||ue.hasDepthSensing()===!1,qe&&fe.addToRenderList(b,E),this.info.render.frame++,we===!0&&Me.beginShadows();const O=S.state.shadowsArray;if(Pe.render(O,E,N),we===!0&&Me.endShadows(),this.info.autoReset===!0&&this.info.reset(),(V&&k.hasRenderPass())===!1){const Te=b.opaque,be=b.transmissive;if(S.setupLights(),N.isArrayCamera){const Ee=N.cameras;if(be.length>0)for(let Ie=0,Ne=Ee.length;Ie<Ne;Ie++){const De=Ee[Ie];Dm(Te,be,E,De)}qe&&fe.render(E);for(let Ie=0,Ne=Ee.length;Ie<Ne;Ie++){const De=Ee[Ie];Im(b,E,De,De.viewport)}}else be.length>0&&Dm(Te,be,E,N),qe&&fe.render(E),Im(b,E,N)}B!==null&&U===0&&(L.updateMultisampleRenderTarget(B),L.updateRenderTargetMipmap(B)),V&&k.end(y),E.isScene===!0&&E.onAfterRender(y,E,N),xe.resetDefaultState(),q=-1,K=null,A.pop(),A.length>0?(S=A[A.length-1],we===!0&&Me.setGlobalState(y.clippingPlanes,S.state.camera)):S=null,M.pop(),M.length>0?b=M[M.length-1]:b=null};function Gd(E,N,G,V){if(E.visible===!1)return;if(E.layers.test(N.layers)){if(E.isGroup)G=E.renderOrder;else if(E.isLOD)E.autoUpdate===!0&&E.update(N);else if(E.isLight)S.pushLight(E),E.castShadow&&S.pushShadow(E);else if(E.isSprite){if(!E.frustumCulled||Ge.intersectsSprite(E)){V&&ct.setFromMatrixPosition(E.matrixWorld).applyMatrix4(jt);const Te=he.update(E),be=E.material;be.visible&&b.push(E,Te,be,G,ct.z,null)}}else if((E.isMesh||E.isLine||E.isPoints)&&(!E.frustumCulled||Ge.intersectsObject(E))){const Te=he.update(E),be=E.material;if(V&&(E.boundingSphere!==void 0?(E.boundingSphere===null&&E.computeBoundingSphere(),ct.copy(E.boundingSphere.center)):(Te.boundingSphere===null&&Te.computeBoundingSphere(),ct.copy(Te.boundingSphere.center)),ct.applyMatrix4(E.matrixWorld).applyMatrix4(jt)),Array.isArray(be)){const Ee=Te.groups;for(let Ie=0,Ne=Ee.length;Ie<Ne;Ie++){const De=Ee[Ie],$e=be[De.materialIndex];$e&&$e.visible&&b.push(E,Te,$e,G,ct.z,De)}}else be.visible&&b.push(E,Te,be,G,ct.z,null)}}const me=E.children;for(let Te=0,be=me.length;Te<be;Te++)Gd(me[Te],N,G,V)}function Im(E,N,G,V){const{opaque:O,transmissive:me,transparent:Te}=E;S.setupLightsView(G),we===!0&&Me.setGlobalState(y.clippingPlanes,G),V&&Re.viewport(H.copy(V)),O.length>0&&_o(O,N,G),me.length>0&&_o(me,N,G),Te.length>0&&_o(Te,N,G),Re.buffers.depth.setTest(!0),Re.buffers.depth.setMask(!0),Re.buffers.color.setMask(!0),Re.setPolygonOffset(!1)}function Dm(E,N,G,V){if((G.isScene===!0?G.overrideMaterial:null)!==null)return;if(S.state.transmissionRenderTarget[V.id]===void 0){const $e=at.has("EXT_color_buffer_half_float")||at.has("EXT_color_buffer_float");S.state.transmissionRenderTarget[V.id]=new ei(1,1,{generateMipmaps:!0,type:$e?_i:Sn,minFilter:us,samples:yt.samples,stencilBuffer:r,resolveDepthBuffer:!1,resolveStencilBuffer:!1,colorSpace:Qe.workingColorSpace})}const me=S.state.transmissionRenderTarget[V.id],Te=V.viewport||H;me.setSize(Te.z*y.transmissionResolutionScale,Te.w*y.transmissionResolutionScale);const be=y.getRenderTarget(),Ee=y.getActiveCubeFace(),Ie=y.getActiveMipmapLevel();y.setRenderTarget(me),y.getClearColor(ve),de=y.getClearAlpha(),de<1&&y.setClearColor(16777215,.5),y.clear(),qe&&fe.render(G);const Ne=y.toneMapping;y.toneMapping=Yn;const De=V.viewport;if(V.viewport!==void 0&&(V.viewport=void 0),S.setupLightsView(V),we===!0&&Me.setGlobalState(y.clippingPlanes,V),_o(E,G,V),L.updateMultisampleRenderTarget(me),L.updateRenderTargetMipmap(me),at.has("WEBGL_multisampled_render_to_texture")===!1){let $e=!1;for(let gt=0,Rt=N.length;gt<Rt;gt++){const Pt=N[gt],{object:_t,geometry:Le,material:dt,group:it}=Pt;if(dt.side===gi&&_t.layers.test(V.layers)){const bn=dt.side;dt.side=Zt,dt.needsUpdate=!0,Lm(_t,G,V,Le,dt,it),dt.side=bn,dt.needsUpdate=!0,$e=!0}}$e===!0&&(L.updateMultisampleRenderTarget(me),L.updateRenderTargetMipmap(me))}y.setRenderTarget(be,Ee,Ie),y.setClearColor(ve,de),De!==void 0&&(V.viewport=De),y.toneMapping=Ne}function _o(E,N,G){const V=N.isScene===!0?N.overrideMaterial:null;for(let O=0,me=E.length;O<me;O++){const Te=E[O],{object:be,geometry:Ee,group:Ie}=Te;let Ne=Te.material;Ne.allowOverride===!0&&V!==null&&(Ne=V),be.layers.test(G.layers)&&Lm(be,N,G,Ee,Ne,Ie)}}function Lm(E,N,G,V,O,me){E.onBeforeRender(y,N,G,V,O,me),E.modelViewMatrix.multiplyMatrices(G.matrixWorldInverse,E.matrixWorld),E.normalMatrix.getNormalMatrix(E.modelViewMatrix),O.onBeforeRender(y,N,G,V,E,me),O.transparent===!0&&O.side===gi&&O.forceSinglePass===!1?(O.side=Zt,O.needsUpdate=!0,y.renderBufferDirect(G,N,V,O,E,me),O.side=mi,O.needsUpdate=!0,y.renderBufferDirect(G,N,V,O,E,me),O.side=gi):y.renderBufferDirect(G,N,V,O,E,me),E.onAfterRender(y,N,G,V,O,me)}function yo(E,N,G){N.isScene!==!0&&(N=bt);const V=_.get(E),O=S.state.lights,me=S.state.shadowsArray,Te=O.state.version,be=Ae.getParameters(E,O.state,me,N,G),Ee=Ae.getProgramCacheKey(be);let Ie=V.programs;V.environment=E.isMeshStandardMaterial?N.environment:null,V.fog=N.fog,V.envMap=(E.isMeshStandardMaterial?ee:$).get(E.envMap||V.environment),V.envMapRotation=V.environment!==null&&E.envMap===null?N.environmentRotation:E.envMapRotation,Ie===void 0&&(E.addEventListener("dispose",ai),Ie=new Map,V.programs=Ie);let Ne=Ie.get(Ee);if(Ne!==void 0){if(V.currentProgram===Ne&&V.lightsStateVersion===Te)return Um(E,be),Ne}else be.uniforms=Ae.getUniforms(E),E.onBeforeCompile(be,y),Ne=Ae.acquireProgram(be,Ee),Ie.set(Ee,Ne),V.uniforms=be.uniforms;const De=V.uniforms;return(!E.isShaderMaterial&&!E.isRawShaderMaterial||E.clipping===!0)&&(De.clippingPlanes=Me.uniform),Um(E,be),V.needsLights=iE(E),V.lightsStateVersion=Te,V.needsLights&&(De.ambientLightColor.value=O.state.ambient,De.lightProbe.value=O.state.probe,De.directionalLights.value=O.state.directional,De.directionalLightShadows.value=O.state.directionalShadow,De.spotLights.value=O.state.spot,De.spotLightShadows.value=O.state.spotShadow,De.rectAreaLights.value=O.state.rectArea,De.ltc_1.value=O.state.rectAreaLTC1,De.ltc_2.value=O.state.rectAreaLTC2,De.pointLights.value=O.state.point,De.pointLightShadows.value=O.state.pointShadow,De.hemisphereLights.value=O.state.hemi,De.directionalShadowMap.value=O.state.directionalShadowMap,De.directionalShadowMatrix.value=O.state.directionalShadowMatrix,De.spotShadowMap.value=O.state.spotShadowMap,De.spotLightMatrix.value=O.state.spotLightMatrix,De.spotLightMap.value=O.state.spotLightMap,De.pointShadowMap.value=O.state.pointShadowMap,De.pointShadowMatrix.value=O.state.pointShadowMatrix),V.currentProgram=Ne,V.uniformsList=null,Ne}function Nm(E){if(E.uniformsList===null){const N=E.currentProgram.getUniforms();E.uniformsList=go.seqWithValue(N.seq,E.uniforms)}return E.uniformsList}function Um(E,N){const G=_.get(E);G.outputColorSpace=N.outputColorSpace,G.batching=N.batching,G.batchingColor=N.batchingColor,G.instancing=N.instancing,G.instancingColor=N.instancingColor,G.instancingMorph=N.instancingMorph,G.skinning=N.skinning,G.morphTargets=N.morphTargets,G.morphNormals=N.morphNormals,G.morphColors=N.morphColors,G.morphTargetsCount=N.morphTargetsCount,G.numClippingPlanes=N.numClippingPlanes,G.numIntersection=N.numClipIntersection,G.vertexAlphas=N.vertexAlphas,G.vertexTangents=N.vertexTangents,G.toneMapping=N.toneMapping}function tE(E,N,G,V,O){N.isScene!==!0&&(N=bt),L.resetTextureUnits();const me=N.fog,Te=V.isMeshStandardMaterial?N.environment:null,be=B===null?y.outputColorSpace:B.isXRRenderTarget===!0?B.texture.colorSpace:Ws,Ee=(V.isMeshStandardMaterial?ee:$).get(V.envMap||Te),Ie=V.vertexColors===!0&&!!G.attributes.color&&G.attributes.color.itemSize===4,Ne=!!G.attributes.tangent&&(!!V.normalMap||V.anisotropy>0),De=!!G.morphAttributes.position,$e=!!G.morphAttributes.normal,gt=!!G.morphAttributes.color;let Rt=Yn;V.toneMapped&&(B===null||B.isXRRenderTarget===!0)&&(Rt=y.toneMapping);const Pt=G.morphAttributes.position||G.morphAttributes.normal||G.morphAttributes.color,_t=Pt!==void 0?Pt.length:0,Le=_.get(V),dt=S.state.lights;if(we===!0&&(nt===!0||E!==K)){const nn=E===K&&V.id===q;Me.setState(V,E,nn)}let it=!1;V.version===Le.__version?(Le.needsLights&&Le.lightsStateVersion!==dt.state.version||Le.outputColorSpace!==be||O.isBatchedMesh&&Le.batching===!1||!O.isBatchedMesh&&Le.batching===!0||O.isBatchedMesh&&Le.batchingColor===!0&&O.colorTexture===null||O.isBatchedMesh&&Le.batchingColor===!1&&O.colorTexture!==null||O.isInstancedMesh&&Le.instancing===!1||!O.isInstancedMesh&&Le.instancing===!0||O.isSkinnedMesh&&Le.skinning===!1||!O.isSkinnedMesh&&Le.skinning===!0||O.isInstancedMesh&&Le.instancingColor===!0&&O.instanceColor===null||O.isInstancedMesh&&Le.instancingColor===!1&&O.instanceColor!==null||O.isInstancedMesh&&Le.instancingMorph===!0&&O.morphTexture===null||O.isInstancedMesh&&Le.instancingMorph===!1&&O.morphTexture!==null||Le.envMap!==Ee||V.fog===!0&&Le.fog!==me||Le.numClippingPlanes!==void 0&&(Le.numClippingPlanes!==Me.numPlanes||Le.numIntersection!==Me.numIntersection)||Le.vertexAlphas!==Ie||Le.vertexTangents!==Ne||Le.morphTargets!==De||Le.morphNormals!==$e||Le.morphColors!==gt||Le.toneMapping!==Rt||Le.morphTargetsCount!==_t)&&(it=!0):(it=!0,Le.__version=V.version);let bn=Le.currentProgram;it===!0&&(bn=yo(V,N,O));let hr=!1,_n=!1,ta=!1;const xt=bn.getUniforms(),dn=Le.uniforms;if(Re.useProgram(bn.program)&&(hr=!0,_n=!0,ta=!0),V.id!==q&&(q=V.id,_n=!0),hr||K!==E){Re.buffers.depth.getReversed()&&E.reversedDepth!==!0&&(E._reversedDepth=!0,E.updateProjectionMatrix()),xt.setValue(I,"projectionMatrix",E.projectionMatrix),xt.setValue(I,"viewMatrix",E.matrixWorldInverse);const un=xt.map.cameraPosition;un!==void 0&&un.setValue(I,et.setFromMatrixPosition(E.matrixWorld)),yt.logarithmicDepthBuffer&&xt.setValue(I,"logDepthBufFC",2/(Math.log(E.far+1)/Math.LN2)),(V.isMeshPhongMaterial||V.isMeshToonMaterial||V.isMeshLambertMaterial||V.isMeshBasicMaterial||V.isMeshStandardMaterial||V.isShaderMaterial)&&xt.setValue(I,"isOrthographic",E.isOrthographicCamera===!0),K!==E&&(K=E,_n=!0,ta=!0)}if(Le.needsLights&&(dt.state.directionalShadowMap.length>0&&xt.setValue(I,"directionalShadowMap",dt.state.directionalShadowMap,L),dt.state.spotShadowMap.length>0&&xt.setValue(I,"spotShadowMap",dt.state.spotShadowMap,L),dt.state.pointShadowMap.length>0&&xt.setValue(I,"pointShadowMap",dt.state.pointShadowMap,L)),O.isSkinnedMesh){xt.setOptional(I,O,"bindMatrix"),xt.setOptional(I,O,"bindMatrixInverse");const nn=O.skeleton;nn&&(nn.boneTexture===null&&nn.computeBoneTexture(),xt.setValue(I,"boneTexture",nn.boneTexture,L))}O.isBatchedMesh&&(xt.setOptional(I,O,"batchingTexture"),xt.setValue(I,"batchingTexture",O._matricesTexture,L),xt.setOptional(I,O,"batchingIdTexture"),xt.setValue(I,"batchingIdTexture",O._indirectTexture,L),xt.setOptional(I,O,"batchingColorTexture"),O._colorsTexture!==null&&xt.setValue(I,"batchingColorTexture",O._colorsTexture,L));const Mn=G.morphAttributes;if((Mn.position!==void 0||Mn.normal!==void 0||Mn.color!==void 0)&&je.update(O,G,bn),(_n||Le.receiveShadow!==O.receiveShadow)&&(Le.receiveShadow=O.receiveShadow,xt.setValue(I,"receiveShadow",O.receiveShadow)),V.isMeshGouraudMaterial&&V.envMap!==null&&(dn.envMap.value=Ee,dn.flipEnvMap.value=Ee.isCubeTexture&&Ee.isRenderTargetTexture===!1?-1:1),V.isMeshStandardMaterial&&V.envMap===null&&N.environment!==null&&(dn.envMapIntensity.value=N.environmentIntensity),dn.dfgLUT!==void 0&&(dn.dfgLUT.value=LC()),_n&&(xt.setValue(I,"toneMappingExposure",y.toneMappingExposure),Le.needsLights&&nE(dn,ta),me&&V.fog===!0&&Ue.refreshFogUniforms(dn,me),Ue.refreshMaterialUniforms(dn,V,Be,Ve,S.state.transmissionRenderTarget[E.id]),go.upload(I,Nm(Le),dn,L)),V.isShaderMaterial&&V.uniformsNeedUpdate===!0&&(go.upload(I,Nm(Le),dn,L),V.uniformsNeedUpdate=!1),V.isSpriteMaterial&&xt.setValue(I,"center",O.center),xt.setValue(I,"modelViewMatrix",O.modelViewMatrix),xt.setValue(I,"normalMatrix",O.normalMatrix),xt.setValue(I,"modelMatrix",O.matrixWorld),V.isShaderMaterial||V.isRawShaderMaterial){const nn=V.uniformsGroups;for(let un=0,Hd=nn.length;un<Hd;un++){const Ts=nn[un];se.update(Ts,bn),se.bind(Ts,bn)}}return bn}function nE(E,N){E.ambientLightColor.needsUpdate=N,E.lightProbe.needsUpdate=N,E.directionalLights.needsUpdate=N,E.directionalLightShadows.needsUpdate=N,E.pointLights.needsUpdate=N,E.pointLightShadows.needsUpdate=N,E.spotLights.needsUpdate=N,E.spotLightShadows.needsUpdate=N,E.rectAreaLights.needsUpdate=N,E.hemisphereLights.needsUpdate=N}function iE(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 U},this.getRenderTarget=function(){return B},this.setRenderTargetTextures=function(E,N,G){const V=_.get(E);V.__autoAllocateDepthBuffer=E.resolveDepthBuffer===!1,V.__autoAllocateDepthBuffer===!1&&(V.__useRenderToTexture=!1),_.get(E.texture).__webglTexture=N,_.get(E.depthTexture).__webglTexture=V.__autoAllocateDepthBuffer?void 0:G,V.__hasExternalTextures=!0},this.setRenderTargetFramebuffer=function(E,N){const G=_.get(E);G.__webglFramebuffer=N,G.__useDefaultFramebuffer=N===void 0};const sE=I.createFramebuffer();this.setRenderTarget=function(E,N=0,G=0){B=E,R=N,U=G;let V=null,O=!1,me=!1;if(E){const be=_.get(E);if(be.__useDefaultFramebuffer!==void 0){Re.bindFramebuffer(I.FRAMEBUFFER,be.__webglFramebuffer),H.copy(E.viewport),W.copy(E.scissor),te=E.scissorTest,Re.viewport(H),Re.scissor(W),Re.setScissorTest(te),q=-1;return}else if(be.__webglFramebuffer===void 0)L.setupRenderTarget(E);else if(be.__hasExternalTextures)L.rebindTextures(E,_.get(E.texture).__webglTexture,_.get(E.depthTexture).__webglTexture);else if(E.depthBuffer){const Ne=E.depthTexture;if(be.__boundDepthTexture!==Ne){if(Ne!==null&&_.has(Ne)&&(E.width!==Ne.image.width||E.height!==Ne.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)&&(me=!0);const Ie=_.get(E).__webglFramebuffer;E.isWebGLCubeRenderTarget?(Array.isArray(Ie[N])?V=Ie[N][G]:V=Ie[N],O=!0):E.samples>0&&L.useMultisampledRTT(E)===!1?V=_.get(E).__webglMultisampledFramebuffer:Array.isArray(Ie)?V=Ie[G]:V=Ie,H.copy(E.viewport),W.copy(E.scissor),te=E.scissorTest}else H.copy(X).multiplyScalar(Be).floor(),W.copy(ie).multiplyScalar(Be).floor(),te=Ce;if(G!==0&&(V=sE),Re.bindFramebuffer(I.FRAMEBUFFER,V)&&Re.drawBuffers(E,V),Re.viewport(H),Re.scissor(W),Re.setScissorTest(te),O){const be=_.get(E.texture);I.framebufferTexture2D(I.FRAMEBUFFER,I.COLOR_ATTACHMENT0,I.TEXTURE_CUBE_MAP_POSITIVE_X+N,be.__webglTexture,G)}else if(me){const be=N;for(let Ee=0;Ee<E.textures.length;Ee++){const Ie=_.get(E.textures[Ee]);I.framebufferTextureLayer(I.FRAMEBUFFER,I.COLOR_ATTACHMENT0+Ee,Ie.__webglTexture,G,be)}}else if(E!==null&&G!==0){const be=_.get(E.texture);I.framebufferTexture2D(I.FRAMEBUFFER,I.COLOR_ATTACHMENT0,I.TEXTURE_2D,be.__webglTexture,G)}q=-1},this.readRenderTargetPixels=function(E,N,G,V,O,me,Te,be=0){if(!(E&&E.isWebGLRenderTarget)){tt("WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");return}let Ee=_.get(E).__webglFramebuffer;if(E.isWebGLCubeRenderTarget&&Te!==void 0&&(Ee=Ee[Te]),Ee){Re.bindFramebuffer(I.FRAMEBUFFER,Ee);try{const Ie=E.textures[be],Ne=Ie.format,De=Ie.type;if(!yt.textureFormatReadable(Ne)){tt("WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.");return}if(!yt.textureTypeReadable(De)){tt("WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.");return}N>=0&&N<=E.width-V&&G>=0&&G<=E.height-O&&(E.textures.length>1&&I.readBuffer(I.COLOR_ATTACHMENT0+be),I.readPixels(N,G,V,O,oe.convert(Ne),oe.convert(De),me))}finally{const Ie=B!==null?_.get(B).__webglFramebuffer:null;Re.bindFramebuffer(I.FRAMEBUFFER,Ie)}}},this.readRenderTargetPixelsAsync=async function(E,N,G,V,O,me,Te,be=0){if(!(E&&E.isWebGLRenderTarget))throw new Error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");let Ee=_.get(E).__webglFramebuffer;if(E.isWebGLCubeRenderTarget&&Te!==void 0&&(Ee=Ee[Te]),Ee)if(N>=0&&N<=E.width-V&&G>=0&&G<=E.height-O){Re.bindFramebuffer(I.FRAMEBUFFER,Ee);const Ie=E.textures[be],Ne=Ie.format,De=Ie.type;if(!yt.textureFormatReadable(Ne))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.");if(!yt.textureTypeReadable(De))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.");const $e=I.createBuffer();I.bindBuffer(I.PIXEL_PACK_BUFFER,$e),I.bufferData(I.PIXEL_PACK_BUFFER,me.byteLength,I.STREAM_READ),E.textures.length>1&&I.readBuffer(I.COLOR_ATTACHMENT0+be),I.readPixels(N,G,V,O,oe.convert(Ne),oe.convert(De),0);const gt=B!==null?_.get(B).__webglFramebuffer:null;Re.bindFramebuffer(I.FRAMEBUFFER,gt);const Rt=I.fenceSync(I.SYNC_GPU_COMMANDS_COMPLETE,0);return I.flush(),await O_(I,Rt,4),I.bindBuffer(I.PIXEL_PACK_BUFFER,$e),I.getBufferSubData(I.PIXEL_PACK_BUFFER,0,me),I.deleteBuffer($e),I.deleteSync(Rt),me}else throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range.")},this.copyFramebufferToTexture=function(E,N=null,G=0){const V=Math.pow(2,-G),O=Math.floor(E.image.width*V),me=Math.floor(E.image.height*V),Te=N!==null?N.x:0,be=N!==null?N.y:0;L.setTexture2D(E,0),I.copyTexSubImage2D(I.TEXTURE_2D,G,0,0,Te,be,O,me),Re.unbindTexture()};const rE=I.createFramebuffer(),aE=I.createFramebuffer();this.copyTextureToTexture=function(E,N,G=null,V=null,O=0,me=null){me===null&&(O!==0?(Vr("WebGLRenderer: copyTextureToTexture function signature has changed to support src and dst mipmap levels."),me=O,O=0):me=0);let Te,be,Ee,Ie,Ne,De,$e,gt,Rt;const Pt=E.isCompressedTexture?E.mipmaps[me]:E.image;if(G!==null)Te=G.max.x-G.min.x,be=G.max.y-G.min.y,Ee=G.isBox3?G.max.z-G.min.z:1,Ie=G.min.x,Ne=G.min.y,De=G.isBox3?G.min.z:0;else{const Mn=Math.pow(2,-O);Te=Math.floor(Pt.width*Mn),be=Math.floor(Pt.height*Mn),E.isDataArrayTexture?Ee=Pt.depth:E.isData3DTexture?Ee=Math.floor(Pt.depth*Mn):Ee=1,Ie=0,Ne=0,De=0}V!==null?($e=V.x,gt=V.y,Rt=V.z):($e=0,gt=0,Rt=0);const _t=oe.convert(N.format),Le=oe.convert(N.type);let dt;N.isData3DTexture?(L.setTexture3D(N,0),dt=I.TEXTURE_3D):N.isDataArrayTexture||N.isCompressedArrayTexture?(L.setTexture2DArray(N,0),dt=I.TEXTURE_2D_ARRAY):(L.setTexture2D(N,0),dt=I.TEXTURE_2D),I.pixelStorei(I.UNPACK_FLIP_Y_WEBGL,N.flipY),I.pixelStorei(I.UNPACK_PREMULTIPLY_ALPHA_WEBGL,N.premultiplyAlpha),I.pixelStorei(I.UNPACK_ALIGNMENT,N.unpackAlignment);const it=I.getParameter(I.UNPACK_ROW_LENGTH),bn=I.getParameter(I.UNPACK_IMAGE_HEIGHT),hr=I.getParameter(I.UNPACK_SKIP_PIXELS),_n=I.getParameter(I.UNPACK_SKIP_ROWS),ta=I.getParameter(I.UNPACK_SKIP_IMAGES);I.pixelStorei(I.UNPACK_ROW_LENGTH,Pt.width),I.pixelStorei(I.UNPACK_IMAGE_HEIGHT,Pt.height),I.pixelStorei(I.UNPACK_SKIP_PIXELS,Ie),I.pixelStorei(I.UNPACK_SKIP_ROWS,Ne),I.pixelStorei(I.UNPACK_SKIP_IMAGES,De);const xt=E.isDataArrayTexture||E.isData3DTexture,dn=N.isDataArrayTexture||N.isData3DTexture;if(E.isDepthTexture){const Mn=_.get(E),nn=_.get(N),un=_.get(Mn.__renderTarget),Hd=_.get(nn.__renderTarget);Re.bindFramebuffer(I.READ_FRAMEBUFFER,un.__webglFramebuffer),Re.bindFramebuffer(I.DRAW_FRAMEBUFFER,Hd.__webglFramebuffer);for(let Ts=0;Ts<Ee;Ts++)xt&&(I.framebufferTextureLayer(I.READ_FRAMEBUFFER,I.COLOR_ATTACHMENT0,_.get(E).__webglTexture,O,De+Ts),I.framebufferTextureLayer(I.DRAW_FRAMEBUFFER,I.COLOR_ATTACHMENT0,_.get(N).__webglTexture,me,Rt+Ts)),I.blitFramebuffer(Ie,Ne,Te,be,$e,gt,Te,be,I.DEPTH_BUFFER_BIT,I.NEAREST);Re.bindFramebuffer(I.READ_FRAMEBUFFER,null),Re.bindFramebuffer(I.DRAW_FRAMEBUFFER,null)}else if(O!==0||E.isRenderTargetTexture||_.has(E)){const Mn=_.get(E),nn=_.get(N);Re.bindFramebuffer(I.READ_FRAMEBUFFER,rE),Re.bindFramebuffer(I.DRAW_FRAMEBUFFER,aE);for(let un=0;un<Ee;un++)xt?I.framebufferTextureLayer(I.READ_FRAMEBUFFER,I.COLOR_ATTACHMENT0,Mn.__webglTexture,O,De+un):I.framebufferTexture2D(I.READ_FRAMEBUFFER,I.COLOR_ATTACHMENT0,I.TEXTURE_2D,Mn.__webglTexture,O),dn?I.framebufferTextureLayer(I.DRAW_FRAMEBUFFER,I.COLOR_ATTACHMENT0,nn.__webglTexture,me,Rt+un):I.framebufferTexture2D(I.DRAW_FRAMEBUFFER,I.COLOR_ATTACHMENT0,I.TEXTURE_2D,nn.__webglTexture,me),O!==0?I.blitFramebuffer(Ie,Ne,Te,be,$e,gt,Te,be,I.COLOR_BUFFER_BIT,I.NEAREST):dn?I.copyTexSubImage3D(dt,me,$e,gt,Rt+un,Ie,Ne,Te,be):I.copyTexSubImage2D(dt,me,$e,gt,Ie,Ne,Te,be);Re.bindFramebuffer(I.READ_FRAMEBUFFER,null),Re.bindFramebuffer(I.DRAW_FRAMEBUFFER,null)}else dn?E.isDataTexture||E.isData3DTexture?I.texSubImage3D(dt,me,$e,gt,Rt,Te,be,Ee,_t,Le,Pt.data):N.isCompressedArrayTexture?I.compressedTexSubImage3D(dt,me,$e,gt,Rt,Te,be,Ee,_t,Pt.data):I.texSubImage3D(dt,me,$e,gt,Rt,Te,be,Ee,_t,Le,Pt):E.isDataTexture?I.texSubImage2D(I.TEXTURE_2D,me,$e,gt,Te,be,_t,Le,Pt.data):E.isCompressedTexture?I.compressedTexSubImage2D(I.TEXTURE_2D,me,$e,gt,Pt.width,Pt.height,_t,Pt.data):I.texSubImage2D(I.TEXTURE_2D,me,$e,gt,Te,be,_t,Le,Pt);I.pixelStorei(I.UNPACK_ROW_LENGTH,it),I.pixelStorei(I.UNPACK_IMAGE_HEIGHT,bn),I.pixelStorei(I.UNPACK_SKIP_PIXELS,hr),I.pixelStorei(I.UNPACK_SKIP_ROWS,_n),I.pixelStorei(I.UNPACK_SKIP_IMAGES,ta),me===0&&N.generateMipmaps&&I.generateMipmap(dt),Re.unbindTexture()},this.initRenderTarget=function(E){_.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,U=0,B=null,Re.reset(),xe.reset()},typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}get coordinateSystem(){return Qn}get outputColorSpace(){return this._outputColorSpace}set outputColorSpace(e){this._outputColorSpace=e;const t=this.getContext();t.drawingBufferColorSpace=Qe._getDrawingBufferColorSpace(e),t.unpackColorSpace=Qe._getUnpackColorSpace()}}const UC=`
4103
4103
  uniform float uTime;
4104
4104
  uniform float uAudioBass;
4105
4105
  uniform float uAudioMid;
@@ -4468,7 +4468,7 @@ void main() {
4468
4468
  // Softer alpha for more diffuse appearance
4469
4469
  gl_FragColor = vec4(glowColor, glow * 0.4);
4470
4470
  }
4471
- `,Ss={primary:"#6366f1",secondary:"#8b5cf6",accent:"#06b6d4",glow:"#818cf8",atmosphere:"#c4b5fd",depth:"#312e81",highlight:"#e0e7ff"},VC={size:1,segments:128,colors:Ss,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 Bd{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={...VC,...t},this.clock=new _y;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 ly;const r=e.clientWidth*this.canvasPadding,a=e.clientHeight*this.canvasPadding,o=r/a;this.camera=new Cn(45,o,.1,100);const c=3,l=9;this.camera.position.z=l*(this.canvasPadding/c),this.renderer=new NC({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={...Ss,...this.config.colors},t=new Rd(this.config.size,this.config.segments/4);this.orbMaterial=new Tn({vertexShader:UC,fragmentShader:OC,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 Ze(e.primary)},uColorSecondary:{value:new Ze(e.secondary)},uColorAccent:{value:new Ze(e.accent)},uColorDepth:{value:new Ze(e.depth||Ss.depth)},uColorHighlight:{value:new Ze(e.highlight||Ss.highlight)},uFresnelPower:{value:this.config.fresnelPower},uGlowIntensity:{value:this.config.glowIntensity},uColorContrast:{value:this.config.colorContrast}},transparent:!0,side:mi}),this.orb=new Vn(t,this.orbMaterial),this.scene.add(this.orb);const n=new Pd(this.config.size,64,64);this.glowMaterial=new Tn({vertexShader:FC,fragmentShader:BC,uniforms:{uTime:{value:0},uAudioLevel:{value:0},uGlowColor:{value:new Ze(e.glow)},uGlowIntensity:{value:this.config.glowIntensity*.6},uPulseSpeed:{value:2}},transparent:!0,side:Zt,blending:el,depthWrite:!1}),this.glowMesh=new Vn(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={...Ss,...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||Ss.depth),this.orbMaterial.uniforms.uColorHighlight.value.set(t.highlight||Ss.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 lr{constructor(){this.audioContext=null,this.refCount=0,this.resumePromise=null}static getInstance(){return lr.instance||(lr.instance=new lr),lr.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 dr=lr.getInstance();typeof window<"u"&&window.addEventListener("pagehide",()=>{dr.forceClose()});class Vd{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 dr.acquire(),this.audioContext&&(this.hasAcquiredContext=!0);else if(!await dr.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&&(dr.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 bo{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 dr.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&&(dr.release(),this.hasAcquired=!1)}}const ii={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"}},si={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"}};function zC(i,e="dark"){const t=e==="dark"?ii:si;return t[i]||t[Object.keys(t)[0]]}function GC(i="dark"){return Object.keys(i==="dark"?ii:si)}const ur={default:{dark:{colors:ii.default,glowIntensity:1.2,idleGlowMultiplier:.6},light:{colors:si.indigo,glowIntensity:1.8,idleGlowMultiplier:1.2}},emerald:{dark:{colors:ii.emerald,glowIntensity:1.2,idleGlowMultiplier:.6},light:{colors:si.teal,glowIntensity:1.8,idleGlowMultiplier:1.2}},rose:{dark:{colors:ii.rose,glowIntensity:1.2,idleGlowMultiplier:.6},light:{colors:si.pink,glowIntensity:1.8,idleGlowMultiplier:1.2}},amber:{dark:{colors:ii.amber,glowIntensity:1.2,idleGlowMultiplier:.6},light:{colors:si.orange,glowIntensity:1.8,idleGlowMultiplier:1.2}},cyan:{dark:{colors:ii.cyan,glowIntensity:1.2,idleGlowMultiplier:.6},light:{colors:si.blue,glowIntensity:1.8,idleGlowMultiplier:1.2}},purple:{dark:{colors:ii.purple,glowIntensity:1.2,idleGlowMultiplier:.6},light:{colors:si.violet,glowIntensity:1.8,idleGlowMultiplier:1.2}},blue:{dark:{colors:ii.blue,glowIntensity:1.2,idleGlowMultiplier:.6},light:{colors:si.blue,glowIntensity:1.8,idleGlowMultiplier:1.2}}},HC=Object.fromEntries(Object.entries(ur).map(([i,e])=>[i,e.dark])),WC=Object.fromEntries(Object.entries(ur).map(([i,e])=>[i,e.light]));function Mm(){return typeof window>"u"||window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}function ea(i,e="auto"){const t=ur[i]||ur.default,n=e==="auto"?Mm():e;return t[n]}function qC(){return Object.keys(ur)}function wm(i,e,t="auto"){const n=ea(e,t);i.orbColors=n.colors,i.glowIntensity=n.glowIntensity,i.idleGlowMultiplier=n.idleGlowMultiplier}function jC(i,e){if(typeof window>"u")return()=>{};const t=window.matchMedia("(prefers-color-scheme: dark)"),n=()=>{const s=t.matches?"dark":"light";wm(i,e,s)};return n(),t.addEventListener("change",n),()=>{t.removeEventListener("change",n)}}var $C=Object.defineProperty,XC=Object.getOwnPropertyDescriptor,mt=(i,e,t,n)=>{for(var s=n>1?void 0:n?XC(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&&$C(e,t,s),s};Y.InlineCall=class extends ts{constructor(){super(),this.callManager=new Jc,this.healthMonitor=new Zc,this.orbRenderer=null,this.audioAnalyzer=null,this.soundManager=null,this.orbContainerRef=ko(),this.animationId=null,this.pendingTimers=new Set,this.isPageVisible=!0,this.animationStartTime=0,this.intersectionObserver=null,this.isOrbInitialized=!1,this.intersectionTimeoutId=null,this.callStatus="idle",this.microphoneEnabled=!1,this.serviceUnavailable=!1,this.buttonStartText="Try to call",this.buttonConnectingText="Connecting...",this.size=370,this.containerPadding=45,this.theme="default",this.themeMode="auto",this.orbColors={},this.glowIntensity=.8,this.idleGlowMultiplier=.4,this.morphStrength=1,this.noiseScale=1.5,this.noiseSpeed=.3,this.fresnelPower=2.5,this.rotationSpeed=.1,this.audioReactivity=3,this.audioSmoothing=.9,this.idleMorphMultiplier=.25,this.colorContrast=1.5,this.soundEnabled=!0,this.soundVolume=.25,this.soundPreset="1",this.handleAudioTrack=async e=>{const n=e.detail;if(!(!n||!this.audioAnalyzer))try{const s=new MediaStream([n]);await this.audioAnalyzer.connectStream(s)}catch(s){console.error("Failed to connect audio stream:",s)}},this.handleLocalAudioTrack=async e=>{const n=e.detail;if(!(!n||!this.audioAnalyzer))try{const s=new MediaStream([n]);await this.audioAnalyzer.connectLocalStream(s)}catch(s){console.error("Failed to connect local audio stream:",s)}},this.handleMicrophoneEnabled=()=>{this.microphoneEnabled=!0},this.handleMicrophoneDisabled=()=>{this.microphoneEnabled=!1},this.handleHealthChange=e=>{const t=e.detail;this.serviceUnavailable=t==="unhealthy"},this.handleStatusChange=e=>{var n,s,r,a,o;switch(e.detail){case"connecting":this.callStatus="connecting";break;case"connected":this.callStatus="connected",(n=this.orbRenderer)==null||n.setActive(!0),this.startRealAudioLoop(),this.scheduleTimer(()=>{var c;(c=this.soundManager)==null||c.playCallStartSound()},300),this.dispatchEvent(new Event("call-start",{bubbles:!0,composed:!0}));break;case"disconnected":this.callStatus="idle",(s=this.orbRenderer)==null||s.setActive(!1),(r=this.audioAnalyzer)==null||r.disconnect(),this.startIdleAnimation(),this.scheduleTimer(()=>{var c;(c=this.soundManager)==null||c.playCallEndSound()},150),this.dispatchEvent(new Event("call-end",{bubbles:!0,composed:!0}));break;case"error":this.callStatus="error",(a=this.orbRenderer)==null||a.setActive(!1),(o=this.audioAnalyzer)==null||o.disconnect(),this.scheduleTimer(()=>{this.callStatus==="error"&&(this.callStatus="idle",this.startIdleAnimation())},3e3);break}},this.toggleCall=async()=>{var e;this.agentId&&(this.callStatus==="idle"&&!this.healthMonitor.isHealthy||(await((e=this.soundManager)==null?void 0:e.prewarm()),this.callStatus==="idle"?(this.callStatus="connecting",await this.callManager.makeCall({agentId:this.agentId})):this.callStatus==="connected"&&this.callManager.hangUp()))},this.boundHandleVisibilityChange=this.handleVisibilityChange.bind(this)}connectedCallback(){super.connectedCallback(),document.addEventListener("visibilitychange",this.boundHandleVisibilityChange),this.voiceServiceUrl&&(this.callManager.serviceUrl=this.voiceServiceUrl),this.soundManager=new bo({enabled:this.soundEnabled,volume:this.soundVolume,preset:this.soundPreset}),this.callManager.addEventListener("status-changed",this.handleStatusChange),this.callManager.addEventListener("audio-track",this.handleAudioTrack),this.callManager.addEventListener("local-audio-track",this.handleLocalAudioTrack),this.callManager.addEventListener("microphone-enabled",this.handleMicrophoneEnabled),this.callManager.addEventListener("microphone-disabled",this.handleMicrophoneDisabled),this.healthMonitor.serviceUrl=this.callManager.serviceUrl,this.healthMonitor.addEventListener("health-changed",this.handleHealthChange),this.healthMonitor.start()}disconnectedCallback(){var e;super.disconnectedCallback(),document.removeEventListener("visibilitychange",this.boundHandleVisibilityChange),this.intersectionObserver&&(this.intersectionObserver.disconnect(),this.intersectionObserver=null),this.clearAllTimers(),this.callManager.removeEventListener("status-changed",this.handleStatusChange),this.callManager.removeEventListener("audio-track",this.handleAudioTrack),this.callManager.removeEventListener("local-audio-track",this.handleLocalAudioTrack),this.callManager.removeEventListener("microphone-enabled",this.handleMicrophoneEnabled),this.callManager.removeEventListener("microphone-disabled",this.handleMicrophoneDisabled),this.healthMonitor.stop(),this.healthMonitor.removeEventListener("health-changed",this.handleHealthChange),this.callManager.destroy(),this.cleanupOrb(),(e=this.soundManager)==null||e.destroy(),this.soundManager=null}handleVisibilityChange(){const e=this.isPageVisible;this.isPageVisible=document.visibilityState==="visible",!this.isPageVisible&&e?this.stopAnimation():this.isPageVisible&&!e&&this.resumeAnimation()}stopAnimation(){this.animationId!==null&&(cancelAnimationFrame(this.animationId),this.animationId=null)}resumeAnimation(){this.callStatus==="idle"?this.startIdleAnimation():this.callStatus==="connected"&&this.startRealAudioLoop()}scheduleTimer(e,t){const n=setTimeout(()=>{this.pendingTimers.delete(n),e()},t);return this.pendingTimers.add(n),n}clearAllTimers(){this.pendingTimers.forEach(e=>clearTimeout(e)),this.pendingTimers.clear()}firstUpdated(){this.applyTheme(),this.setupLazyInitialization()}setupLazyInitialization(){const e=this.orbContainerRef.value;if(!e){this.initializeOrb();return}if(!("IntersectionObserver"in window)){this.initializeOrb();return}this.intersectionObserver=new IntersectionObserver(t=>{for(const n of t)n.isIntersecting&&!this.isOrbInitialized?this.intersectionTimeoutId||(this.intersectionTimeoutId=setTimeout(()=>{var s;this.initializeOrb(),this.isOrbInitialized=!0,(s=this.intersectionObserver)==null||s.disconnect(),this.intersectionObserver=null,this.intersectionTimeoutId=null},200),this.pendingTimers.add(this.intersectionTimeoutId)):!n.isIntersecting&&this.intersectionTimeoutId&&(clearTimeout(this.intersectionTimeoutId),this.pendingTimers.delete(this.intersectionTimeoutId),this.intersectionTimeoutId=null)},{threshold:.5}),this.intersectionObserver.observe(e)}updated(e){var t,n,s;super.updated(e),e.has("agentId")&&(this.callManager.hangUp(),this.callStatus="idle"),e.has("voiceServiceUrl")&&this.voiceServiceUrl&&(this.callManager.serviceUrl=this.voiceServiceUrl,this.healthMonitor.serviceUrl=this.voiceServiceUrl),(e.has("theme")||e.has("themeMode"))&&this.applyTheme(),e.has("soundEnabled")&&((t=this.soundManager)==null||t.setEnabled(this.soundEnabled)),e.has("soundVolume")&&((n=this.soundManager)==null||n.setVolume(this.soundVolume)),e.has("soundPreset")&&((s=this.soundManager)==null||s.setPreset(this.soundPreset))}applyTheme(){if(this.theme){const e=ea(this.theme,this.themeMode);this.orbColors=e.colors,this.glowIntensity=e.glowIntensity,this.idleGlowMultiplier=e.idleGlowMultiplier,this.orbRenderer&&(this.orbRenderer.setColors(this.orbColors),this.orbRenderer.setGlowSettings(this.glowIntensity,this.idleGlowMultiplier))}}initializeOrb(){const e=this.orbContainerRef.value;e&&(this.orbRenderer=new Bd(e,{size:1,colors:this.orbColors,glowIntensity:this.glowIntensity,idleGlowMultiplier:this.idleGlowMultiplier,morphStrength:this.morphStrength,noiseScale:this.noiseScale,noiseSpeed:this.noiseSpeed,fresnelPower:this.fresnelPower,rotationSpeed:this.rotationSpeed,audioReactivity:this.audioReactivity,audioSmoothing:this.audioSmoothing,idleMorphMultiplier:this.idleMorphMultiplier,colorContrast:this.colorContrast}),this.audioAnalyzer=new Vd,this.orbRenderer.start(),this.startIdleAnimation())}cleanupOrb(){var e,t;this.animationId!==null&&(cancelAnimationFrame(this.animationId),this.animationId=null),(e=this.audioAnalyzer)==null||e.disconnect(),(t=this.orbRenderer)==null||t.destroy(),this.audioAnalyzer=null,this.orbRenderer=null}startIdleAnimation(){if(this.animationId!==null&&(cancelAnimationFrame(this.animationId),this.animationId=null),!this.isPageVisible)return;this.animationStartTime=performance.now();const e=t=>{if(this.callStatus!=="idle"||!this.orbRenderer||!this.isPageVisible){this.animationId=null;return}const n=(t-this.animationStartTime)/1e3,s=Math.sin(n*.5)*.15+.15,r=Math.sin(n*.7+1)*.12+.12,a=Math.sin(n*.9+2)*.08+.08,o=(s+r+a)/3;this.orbRenderer.setSimulatedAudio(s,r,a,o),this.animationId=requestAnimationFrame(e)};this.animationId=requestAnimationFrame(e)}startRealAudioLoop(){if(this.animationId!==null&&(cancelAnimationFrame(this.animationId),this.animationId=null),!this.isPageVisible)return;const e=()=>{var n;if(this.callStatus!=="connected"||!this.orbRenderer||!this.isPageVisible){this.animationId=null;return}const t=(n=this.audioAnalyzer)==null?void 0:n.getAudioData();t&&this.orbRenderer.updateAudio(t),this.animationId=requestAnimationFrame(e)};this.animationId=requestAnimationFrame(e)}getButtonIcon(){return this.callStatus==="connecting"?Gt`
4471
+ `,Ss={primary:"#6366f1",secondary:"#8b5cf6",accent:"#06b6d4",glow:"#818cf8",atmosphere:"#c4b5fd",depth:"#312e81",highlight:"#e0e7ff"},VC={size:1,segments:128,colors:Ss,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 Bd{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={...VC,...t},this.clock=new _y;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 ly;const r=e.clientWidth*this.canvasPadding,a=e.clientHeight*this.canvasPadding,o=r/a;this.camera=new En(45,o,.1,100);const c=3,l=9;this.camera.position.z=l*(this.canvasPadding/c),this.renderer=new NC({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={...Ss,...this.config.colors},t=new Rd(this.config.size,this.config.segments/4);this.orbMaterial=new Cn({vertexShader:UC,fragmentShader:OC,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 Ze(e.primary)},uColorSecondary:{value:new Ze(e.secondary)},uColorAccent:{value:new Ze(e.accent)},uColorDepth:{value:new Ze(e.depth||Ss.depth)},uColorHighlight:{value:new Ze(e.highlight||Ss.highlight)},uFresnelPower:{value:this.config.fresnelPower},uGlowIntensity:{value:this.config.glowIntensity},uColorContrast:{value:this.config.colorContrast}},transparent:!0,side:mi}),this.orb=new zn(t,this.orbMaterial),this.scene.add(this.orb);const n=new Pd(this.config.size,64,64);this.glowMaterial=new Cn({vertexShader:FC,fragmentShader:BC,uniforms:{uTime:{value:0},uAudioLevel:{value:0},uGlowColor:{value:new Ze(e.glow)},uGlowIntensity:{value:this.config.glowIntensity*.6},uPulseSpeed:{value:2}},transparent:!0,side:Zt,blending:el,depthWrite:!1}),this.glowMesh=new zn(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={...Ss,...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||Ss.depth),this.orbMaterial.uniforms.uColorHighlight.value.set(t.highlight||Ss.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 lr{constructor(){this.audioContext=null,this.refCount=0,this.resumePromise=null}static getInstance(){return lr.instance||(lr.instance=new lr),lr.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 dr=lr.getInstance();typeof window<"u"&&window.addEventListener("pagehide",()=>{dr.forceClose()});class Vd{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 dr.acquire(),this.audioContext&&(this.hasAcquiredContext=!0);else if(!await dr.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&&(dr.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 bo{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 dr.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&&(dr.release(),this.hasAcquired=!1)}}const si={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"}},ri={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"}};function zC(i,e="dark"){const t=e==="dark"?si:ri;return t[i]||t[Object.keys(t)[0]]}function GC(i="dark"){return Object.keys(i==="dark"?si:ri)}const ur={default:{dark:{colors:si.default,glowIntensity:1.2,idleGlowMultiplier:.6},light:{colors:ri.indigo,glowIntensity:1.8,idleGlowMultiplier:1.2}},emerald:{dark:{colors:si.emerald,glowIntensity:1.2,idleGlowMultiplier:.6},light:{colors:ri.teal,glowIntensity:1.8,idleGlowMultiplier:1.2}},rose:{dark:{colors:si.rose,glowIntensity:1.2,idleGlowMultiplier:.6},light:{colors:ri.pink,glowIntensity:1.8,idleGlowMultiplier:1.2}},amber:{dark:{colors:si.amber,glowIntensity:1.2,idleGlowMultiplier:.6},light:{colors:ri.orange,glowIntensity:1.8,idleGlowMultiplier:1.2}},cyan:{dark:{colors:si.cyan,glowIntensity:1.2,idleGlowMultiplier:.6},light:{colors:ri.blue,glowIntensity:1.8,idleGlowMultiplier:1.2}},purple:{dark:{colors:si.purple,glowIntensity:1.2,idleGlowMultiplier:.6},light:{colors:ri.violet,glowIntensity:1.8,idleGlowMultiplier:1.2}},blue:{dark:{colors:si.blue,glowIntensity:1.2,idleGlowMultiplier:.6},light:{colors:ri.blue,glowIntensity:1.8,idleGlowMultiplier:1.2}}},HC=Object.fromEntries(Object.entries(ur).map(([i,e])=>[i,e.dark])),WC=Object.fromEntries(Object.entries(ur).map(([i,e])=>[i,e.light]));function Mm(){return typeof window>"u"||window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}function ea(i,e="auto"){const t=ur[i]||ur.default,n=e==="auto"?Mm():e;return t[n]}function qC(){return Object.keys(ur)}function wm(i,e,t="auto"){const n=ea(e,t);i.orbColors=n.colors,i.glowIntensity=n.glowIntensity,i.idleGlowMultiplier=n.idleGlowMultiplier}function jC(i,e){if(typeof window>"u")return()=>{};const t=window.matchMedia("(prefers-color-scheme: dark)"),n=()=>{const s=t.matches?"dark":"light";wm(i,e,s)};return n(),t.addEventListener("change",n),()=>{t.removeEventListener("change",n)}}var $C=Object.defineProperty,XC=Object.getOwnPropertyDescriptor,ht=(i,e,t,n)=>{for(var s=n>1?void 0:n?XC(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&&$C(e,t,s),s};Y.InlineCall=class extends ts{constructor(){super(),this.callManager=new Jc,this.healthMonitor=new Zc,this.orbRenderer=null,this.audioAnalyzer=null,this.soundManager=null,this.orbContainerRef=ko(),this.animationId=null,this.pendingTimers=new Set,this.isPageVisible=!0,this.animationStartTime=0,this.intersectionObserver=null,this.isOrbInitialized=!1,this.intersectionTimeoutId=null,this.callStatus="idle",this.microphoneEnabled=!1,this.microphoneInitialized=!1,this.serviceUnavailable=!1,this.buttonStartText="Try to call",this.buttonConnectingText="Connecting...",this.size=370,this.containerPadding=45,this.theme="default",this.themeMode="auto",this.orbColors={},this.glowIntensity=.8,this.idleGlowMultiplier=.4,this.morphStrength=1,this.noiseScale=1.5,this.noiseSpeed=.3,this.fresnelPower=2.5,this.rotationSpeed=.1,this.audioReactivity=3,this.audioSmoothing=.9,this.idleMorphMultiplier=.25,this.colorContrast=1.5,this.soundEnabled=!0,this.soundVolume=.25,this.soundPreset="1",this.handleAudioTrack=async e=>{const n=e.detail;if(!(!n||!this.audioAnalyzer))try{const s=new MediaStream([n]);await this.audioAnalyzer.connectStream(s)}catch(s){console.error("Failed to connect audio stream:",s)}},this.handleLocalAudioTrack=async e=>{const n=e.detail;if(!(!n||!this.audioAnalyzer))try{const s=new MediaStream([n]);await this.audioAnalyzer.connectLocalStream(s)}catch(s){console.error("Failed to connect local audio stream:",s)}},this.handleMicrophoneEnabled=()=>{this.microphoneEnabled=!0,this.microphoneInitialized=!0},this.handleMicrophoneDisabled=()=>{this.microphoneEnabled=!1,this.microphoneInitialized=!0},this.handleHealthChange=e=>{const t=e.detail;this.serviceUnavailable=t==="unhealthy"},this.handleStatusChange=e=>{var n,s,r,a,o;switch(e.detail){case"connecting":this.callStatus="connecting";break;case"connected":this.callStatus="connected",(n=this.orbRenderer)==null||n.setActive(!0),this.startRealAudioLoop(),this.scheduleTimer(()=>{var c;(c=this.soundManager)==null||c.playCallStartSound()},300),this.dispatchEvent(new Event("call-start",{bubbles:!0,composed:!0}));break;case"disconnected":this.callStatus="idle",this.microphoneInitialized=!1,(s=this.orbRenderer)==null||s.setActive(!1),(r=this.audioAnalyzer)==null||r.disconnect(),this.startIdleAnimation(),this.scheduleTimer(()=>{var c;(c=this.soundManager)==null||c.playCallEndSound()},150),this.dispatchEvent(new Event("call-end",{bubbles:!0,composed:!0}));break;case"error":this.callStatus="error",(a=this.orbRenderer)==null||a.setActive(!1),(o=this.audioAnalyzer)==null||o.disconnect(),this.scheduleTimer(()=>{this.callStatus==="error"&&(this.callStatus="idle",this.startIdleAnimation())},3e3);break}},this.toggleCall=async()=>{var e;this.agentId&&(this.callStatus==="idle"&&!this.healthMonitor.isHealthy||(await((e=this.soundManager)==null?void 0:e.prewarm()),this.callStatus==="idle"?(this.callStatus="connecting",await this.callManager.makeCall({agentId:this.agentId})):this.callStatus==="connected"&&this.callManager.hangUp()))},this.boundHandleVisibilityChange=this.handleVisibilityChange.bind(this)}connectedCallback(){super.connectedCallback(),document.addEventListener("visibilitychange",this.boundHandleVisibilityChange),this.voiceServiceUrl&&(this.callManager.serviceUrl=this.voiceServiceUrl),this.soundManager=new bo({enabled:this.soundEnabled,volume:this.soundVolume,preset:this.soundPreset}),this.callManager.addEventListener("status-changed",this.handleStatusChange),this.callManager.addEventListener("audio-track",this.handleAudioTrack),this.callManager.addEventListener("local-audio-track",this.handleLocalAudioTrack),this.callManager.addEventListener("microphone-enabled",this.handleMicrophoneEnabled),this.callManager.addEventListener("microphone-disabled",this.handleMicrophoneDisabled),this.healthMonitor.serviceUrl=this.callManager.serviceUrl,this.healthMonitor.addEventListener("health-changed",this.handleHealthChange),this.healthMonitor.start()}disconnectedCallback(){var e;super.disconnectedCallback(),document.removeEventListener("visibilitychange",this.boundHandleVisibilityChange),this.intersectionObserver&&(this.intersectionObserver.disconnect(),this.intersectionObserver=null),this.clearAllTimers(),this.callManager.removeEventListener("status-changed",this.handleStatusChange),this.callManager.removeEventListener("audio-track",this.handleAudioTrack),this.callManager.removeEventListener("local-audio-track",this.handleLocalAudioTrack),this.callManager.removeEventListener("microphone-enabled",this.handleMicrophoneEnabled),this.callManager.removeEventListener("microphone-disabled",this.handleMicrophoneDisabled),this.healthMonitor.stop(),this.healthMonitor.removeEventListener("health-changed",this.handleHealthChange),this.callManager.destroy(),this.cleanupOrb(),(e=this.soundManager)==null||e.destroy(),this.soundManager=null}handleVisibilityChange(){const e=this.isPageVisible;this.isPageVisible=document.visibilityState==="visible",!this.isPageVisible&&e?this.stopAnimation():this.isPageVisible&&!e&&this.resumeAnimation()}stopAnimation(){this.animationId!==null&&(cancelAnimationFrame(this.animationId),this.animationId=null)}resumeAnimation(){this.callStatus==="idle"?this.startIdleAnimation():this.callStatus==="connected"&&this.startRealAudioLoop()}scheduleTimer(e,t){const n=setTimeout(()=>{this.pendingTimers.delete(n),e()},t);return this.pendingTimers.add(n),n}clearAllTimers(){this.pendingTimers.forEach(e=>clearTimeout(e)),this.pendingTimers.clear()}firstUpdated(){this.applyTheme(),this.setupLazyInitialization()}setupLazyInitialization(){const e=this.orbContainerRef.value;if(!e){this.initializeOrb();return}if(!("IntersectionObserver"in window)){this.initializeOrb();return}this.intersectionObserver=new IntersectionObserver(t=>{for(const n of t)n.isIntersecting&&!this.isOrbInitialized?this.intersectionTimeoutId||(this.intersectionTimeoutId=setTimeout(()=>{var s;this.initializeOrb(),this.isOrbInitialized=!0,(s=this.intersectionObserver)==null||s.disconnect(),this.intersectionObserver=null,this.intersectionTimeoutId=null},200),this.pendingTimers.add(this.intersectionTimeoutId)):!n.isIntersecting&&this.intersectionTimeoutId&&(clearTimeout(this.intersectionTimeoutId),this.pendingTimers.delete(this.intersectionTimeoutId),this.intersectionTimeoutId=null)},{threshold:.5}),this.intersectionObserver.observe(e)}updated(e){var t,n,s;super.updated(e),e.has("agentId")&&(this.callManager.hangUp(),this.callStatus="idle"),e.has("voiceServiceUrl")&&this.voiceServiceUrl&&(this.callManager.serviceUrl=this.voiceServiceUrl,this.healthMonitor.serviceUrl=this.voiceServiceUrl),(e.has("theme")||e.has("themeMode"))&&this.applyTheme(),e.has("soundEnabled")&&((t=this.soundManager)==null||t.setEnabled(this.soundEnabled)),e.has("soundVolume")&&((n=this.soundManager)==null||n.setVolume(this.soundVolume)),e.has("soundPreset")&&((s=this.soundManager)==null||s.setPreset(this.soundPreset))}applyTheme(){if(this.theme){const e=ea(this.theme,this.themeMode);this.orbColors=e.colors,this.glowIntensity=e.glowIntensity,this.idleGlowMultiplier=e.idleGlowMultiplier,this.orbRenderer&&(this.orbRenderer.setColors(this.orbColors),this.orbRenderer.setGlowSettings(this.glowIntensity,this.idleGlowMultiplier))}}initializeOrb(){const e=this.orbContainerRef.value;e&&(this.orbRenderer=new Bd(e,{size:1,colors:this.orbColors,glowIntensity:this.glowIntensity,idleGlowMultiplier:this.idleGlowMultiplier,morphStrength:this.morphStrength,noiseScale:this.noiseScale,noiseSpeed:this.noiseSpeed,fresnelPower:this.fresnelPower,rotationSpeed:this.rotationSpeed,audioReactivity:this.audioReactivity,audioSmoothing:this.audioSmoothing,idleMorphMultiplier:this.idleMorphMultiplier,colorContrast:this.colorContrast}),this.audioAnalyzer=new Vd,this.orbRenderer.start(),this.startIdleAnimation())}cleanupOrb(){var e,t;this.animationId!==null&&(cancelAnimationFrame(this.animationId),this.animationId=null),(e=this.audioAnalyzer)==null||e.disconnect(),(t=this.orbRenderer)==null||t.destroy(),this.audioAnalyzer=null,this.orbRenderer=null}startIdleAnimation(){if(this.animationId!==null&&(cancelAnimationFrame(this.animationId),this.animationId=null),!this.isPageVisible)return;this.animationStartTime=performance.now();const e=t=>{if(this.callStatus!=="idle"||!this.orbRenderer||!this.isPageVisible){this.animationId=null;return}const n=(t-this.animationStartTime)/1e3,s=Math.sin(n*.5)*.15+.15,r=Math.sin(n*.7+1)*.12+.12,a=Math.sin(n*.9+2)*.08+.08,o=(s+r+a)/3;this.orbRenderer.setSimulatedAudio(s,r,a,o),this.animationId=requestAnimationFrame(e)};this.animationId=requestAnimationFrame(e)}startRealAudioLoop(){if(this.animationId!==null&&(cancelAnimationFrame(this.animationId),this.animationId=null),!this.isPageVisible)return;const e=()=>{var n;if(this.callStatus!=="connected"||!this.orbRenderer||!this.isPageVisible){this.animationId=null;return}const t=(n=this.audioAnalyzer)==null?void 0:n.getAudioData();t&&this.orbRenderer.updateAudio(t),this.animationId=requestAnimationFrame(e)};this.animationId=requestAnimationFrame(e)}getButtonIcon(){return this.callStatus==="connecting"?Gt`
4472
4472
  <svg width="16" height="16" viewBox="0 0 16 16" fill="none" class="hanc-spinner">
4473
4473
  <circle
4474
4474
  cx="8"
@@ -4731,7 +4731,7 @@ void main() {
4731
4731
  @click=${this.toggleCall}
4732
4732
  ${Do(this.orbContainerRef)}
4733
4733
  >
4734
- ${this.callStatus==="connected"&&!this.microphoneEnabled?Gt`
4734
+ ${this.callStatus==="connected"&&this.microphoneInitialized&&!this.microphoneEnabled?Gt`
4735
4735
  <div class="microphone-indicator visible">
4736
4736
  <svg viewBox="0 0 24 24" fill="none">
4737
4737
  <path
@@ -4781,7 +4781,7 @@ void main() {
4781
4781
  display: inline-block;
4782
4782
  contain: layout style;
4783
4783
  }
4784
- `,mt([Se({type:String,attribute:"agent-id"})],Y.InlineCall.prototype,"agentId",2),mt([Se({type:String,attribute:"voice-service-url"})],Y.InlineCall.prototype,"voiceServiceUrl",2),mt([ai()],Y.InlineCall.prototype,"callStatus",2),mt([ai()],Y.InlineCall.prototype,"microphoneEnabled",2),mt([ai()],Y.InlineCall.prototype,"serviceUnavailable",2),mt([Se({type:String,attribute:"button-start-text"})],Y.InlineCall.prototype,"buttonStartText",2),mt([Se({type:String,attribute:"button-connecting-text"})],Y.InlineCall.prototype,"buttonConnectingText",2),mt([Se({type:Number,attribute:"size"})],Y.InlineCall.prototype,"size",2),mt([Se({type:Number,attribute:"container-padding"})],Y.InlineCall.prototype,"containerPadding",2),mt([Se({type:String,attribute:"theme",reflect:!0})],Y.InlineCall.prototype,"theme",2),mt([Se({type:String,attribute:"theme-mode"})],Y.InlineCall.prototype,"themeMode",2),mt([Se({type:Object,attribute:"orb-colors"})],Y.InlineCall.prototype,"orbColors",2),mt([Se({type:Number,attribute:"glow-intensity"})],Y.InlineCall.prototype,"glowIntensity",2),mt([Se({type:Number,attribute:"idle-glow-multiplier"})],Y.InlineCall.prototype,"idleGlowMultiplier",2),mt([Se({type:Number,attribute:"morph-strength"})],Y.InlineCall.prototype,"morphStrength",2),mt([Se({type:Number,attribute:"noise-scale"})],Y.InlineCall.prototype,"noiseScale",2),mt([Se({type:Number,attribute:"noise-speed"})],Y.InlineCall.prototype,"noiseSpeed",2),mt([Se({type:Number,attribute:"fresnel-power"})],Y.InlineCall.prototype,"fresnelPower",2),mt([Se({type:Number,attribute:"rotation-speed"})],Y.InlineCall.prototype,"rotationSpeed",2),mt([Se({type:Number,attribute:"audio-reactivity"})],Y.InlineCall.prototype,"audioReactivity",2),mt([Se({type:Number,attribute:"audio-smoothing"})],Y.InlineCall.prototype,"audioSmoothing",2),mt([Se({type:Number,attribute:"idle-morph-multiplier"})],Y.InlineCall.prototype,"idleMorphMultiplier",2),mt([Se({type:Number,attribute:"color-contrast"})],Y.InlineCall.prototype,"colorContrast",2),mt([Se({type:Boolean,attribute:"sound-enabled"})],Y.InlineCall.prototype,"soundEnabled",2),mt([Se({type:Number,attribute:"sound-volume"})],Y.InlineCall.prototype,"soundVolume",2),mt([Se({type:String,attribute:"sound-preset"})],Y.InlineCall.prototype,"soundPreset",2),Y.InlineCall=mt([Po("hanc-ai-inline-call")],Y.InlineCall);var KC=Object.defineProperty,YC=Object.getOwnPropertyDescriptor,gt=(i,e,t,n)=>{for(var s=n>1?void 0:n?YC(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&&KC(e,t,s),s};Y.FloatingCall=class extends ts{constructor(){super(),this.callManager=new Jc,this.healthMonitor=new Zc,this.orbRenderer=null,this.audioAnalyzer=null,this.soundManager=null,this.orbContainerRef=ko(),this.animationId=null,this.pendingTimers=new Set,this.isPageVisible=!0,this.animationStartTime=0,this.intersectionObserver=null,this.isOrbInitialized=!1,this.callStatus="idle",this.microphoneEnabled=!1,this.serviceUnavailable=!1,this.buttonStartText="Call",this.buttonConnectingText="Connecting...",this.position="bottom-right",this.size=120,this.theme="default",this.themeMode="auto",this.orbColors={},this.glowIntensity=.8,this.idleGlowMultiplier=.4,this.morphStrength=1,this.noiseScale=1.5,this.noiseSpeed=.3,this.fresnelPower=2.5,this.rotationSpeed=.1,this.audioReactivity=3,this.audioSmoothing=.9,this.idleMorphMultiplier=.25,this.colorContrast=1.5,this.soundEnabled=!0,this.soundVolume=.25,this.soundPreset="1",this.handleAudioTrack=async e=>{const n=e.detail;if(!(!n||!this.audioAnalyzer))try{const s=new MediaStream([n]);await this.audioAnalyzer.connectStream(s)}catch(s){console.error("Failed to connect audio stream:",s)}},this.handleLocalAudioTrack=async e=>{const n=e.detail;if(!(!n||!this.audioAnalyzer))try{const s=new MediaStream([n]);await this.audioAnalyzer.connectLocalStream(s)}catch(s){console.error("Failed to connect local audio stream:",s)}},this.handleMicrophoneEnabled=()=>{this.microphoneEnabled=!0},this.handleMicrophoneDisabled=()=>{this.microphoneEnabled=!1},this.handleHealthChange=e=>{const t=e.detail;this.serviceUnavailable=t==="unhealthy"},this.handleStatusChange=e=>{var n,s,r,a,o;switch(e.detail){case"connecting":this.callStatus="connecting";break;case"connected":this.callStatus="connected",(n=this.orbRenderer)==null||n.setActive(!0),this.startRealAudioLoop(),this.scheduleTimer(()=>{var c;(c=this.soundManager)==null||c.playCallStartSound()},300),this.dispatchEvent(new Event("call-start",{bubbles:!0,composed:!0}));break;case"disconnected":this.callStatus="idle",(s=this.orbRenderer)==null||s.setActive(!1),(r=this.audioAnalyzer)==null||r.disconnect(),this.startIdleAnimation(),this.scheduleTimer(()=>{var c;(c=this.soundManager)==null||c.playCallEndSound()},150),this.dispatchEvent(new Event("call-end",{bubbles:!0,composed:!0}));break;case"error":this.callStatus="error",(a=this.orbRenderer)==null||a.setActive(!1),(o=this.audioAnalyzer)==null||o.disconnect(),this.scheduleTimer(()=>{this.callStatus==="error"&&(this.callStatus="idle",this.startIdleAnimation())},3e3);break}},this.toggleCall=async()=>{var e;this.agentId&&(this.callStatus==="idle"&&!this.healthMonitor.isHealthy||(await((e=this.soundManager)==null?void 0:e.prewarm()),this.callStatus==="idle"?(this.callStatus="connecting",await this.callManager.makeCall({agentId:this.agentId})):this.callStatus==="connected"&&this.callManager.hangUp()))},this.boundHandleVisibilityChange=this.handleVisibilityChange.bind(this)}connectedCallback(){super.connectedCallback(),document.addEventListener("visibilitychange",this.boundHandleVisibilityChange),this.voiceServiceUrl&&(this.callManager.serviceUrl=this.voiceServiceUrl),this.soundManager=new bo({enabled:this.soundEnabled,volume:this.soundVolume,preset:this.soundPreset}),this.callManager.addEventListener("status-changed",this.handleStatusChange),this.callManager.addEventListener("audio-track",this.handleAudioTrack),this.callManager.addEventListener("local-audio-track",this.handleLocalAudioTrack),this.callManager.addEventListener("microphone-enabled",this.handleMicrophoneEnabled),this.callManager.addEventListener("microphone-disabled",this.handleMicrophoneDisabled),this.healthMonitor.serviceUrl=this.callManager.serviceUrl,this.healthMonitor.addEventListener("health-changed",this.handleHealthChange),this.healthMonitor.start()}disconnectedCallback(){var e;super.disconnectedCallback(),document.removeEventListener("visibilitychange",this.boundHandleVisibilityChange),this.intersectionObserver&&(this.intersectionObserver.disconnect(),this.intersectionObserver=null),this.clearAllTimers(),this.callManager.removeEventListener("status-changed",this.handleStatusChange),this.callManager.removeEventListener("audio-track",this.handleAudioTrack),this.callManager.removeEventListener("local-audio-track",this.handleLocalAudioTrack),this.callManager.removeEventListener("microphone-enabled",this.handleMicrophoneEnabled),this.callManager.removeEventListener("microphone-disabled",this.handleMicrophoneDisabled),this.healthMonitor.stop(),this.healthMonitor.removeEventListener("health-changed",this.handleHealthChange),this.callManager.destroy(),this.cleanupOrb(),(e=this.soundManager)==null||e.destroy(),this.soundManager=null}handleVisibilityChange(){const e=this.isPageVisible;this.isPageVisible=document.visibilityState==="visible",!this.isPageVisible&&e?this.stopAnimation():this.isPageVisible&&!e&&this.resumeAnimation()}stopAnimation(){this.animationId!==null&&(cancelAnimationFrame(this.animationId),this.animationId=null)}resumeAnimation(){this.callStatus==="idle"?this.startIdleAnimation():this.callStatus==="connected"&&this.startRealAudioLoop()}scheduleTimer(e,t){const n=setTimeout(()=>{this.pendingTimers.delete(n),e()},t);return this.pendingTimers.add(n),n}clearAllTimers(){this.pendingTimers.forEach(e=>clearTimeout(e)),this.pendingTimers.clear()}firstUpdated(){this.applyTheme(),this.setupLazyInitialization()}setupLazyInitialization(){const e=this.orbContainerRef.value;if(!e){this.initializeOrb();return}if(!("IntersectionObserver"in window)){this.initializeOrb();return}this.intersectionObserver=new IntersectionObserver(t=>{var n;for(const s of t)s.isIntersecting&&!this.isOrbInitialized&&(this.initializeOrb(),this.isOrbInitialized=!0,(n=this.intersectionObserver)==null||n.disconnect(),this.intersectionObserver=null)},{threshold:.5}),this.intersectionObserver.observe(e)}updated(e){var t,n,s;super.updated(e),e.has("agentId")&&(this.callManager.hangUp(),this.callStatus="idle"),e.has("voiceServiceUrl")&&this.voiceServiceUrl&&(this.callManager.serviceUrl=this.voiceServiceUrl,this.healthMonitor.serviceUrl=this.voiceServiceUrl),(e.has("theme")||e.has("themeMode"))&&this.applyTheme(),e.has("soundEnabled")&&((t=this.soundManager)==null||t.setEnabled(this.soundEnabled)),e.has("soundVolume")&&((n=this.soundManager)==null||n.setVolume(this.soundVolume)),e.has("soundPreset")&&((s=this.soundManager)==null||s.setPreset(this.soundPreset))}applyTheme(){if(this.theme){const e=ea(this.theme,this.themeMode);this.orbColors=e.colors,this.glowIntensity=e.glowIntensity,this.idleGlowMultiplier=e.idleGlowMultiplier,this.orbRenderer&&(this.orbRenderer.setColors(this.orbColors),this.orbRenderer.setGlowSettings(this.glowIntensity,this.idleGlowMultiplier))}}initializeOrb(){const e=this.orbContainerRef.value;e&&(this.orbRenderer=new Bd(e,{size:1,colors:this.orbColors,glowIntensity:this.glowIntensity,idleGlowMultiplier:this.idleGlowMultiplier,morphStrength:this.morphStrength,noiseScale:this.noiseScale,noiseSpeed:this.noiseSpeed,fresnelPower:this.fresnelPower,rotationSpeed:this.rotationSpeed,audioReactivity:this.audioReactivity,audioSmoothing:this.audioSmoothing,idleMorphMultiplier:this.idleMorphMultiplier,colorContrast:this.colorContrast}),this.audioAnalyzer=new Vd,this.orbRenderer.start(),this.startIdleAnimation())}cleanupOrb(){var e,t;this.animationId!==null&&(cancelAnimationFrame(this.animationId),this.animationId=null),(e=this.audioAnalyzer)==null||e.disconnect(),(t=this.orbRenderer)==null||t.destroy(),this.audioAnalyzer=null,this.orbRenderer=null}startIdleAnimation(){if(this.animationId!==null&&(cancelAnimationFrame(this.animationId),this.animationId=null),!this.isPageVisible)return;this.animationStartTime=performance.now();const e=t=>{if(this.callStatus!=="idle"||!this.orbRenderer||!this.isPageVisible){this.animationId=null;return}const n=(t-this.animationStartTime)/1e3,s=Math.sin(n*.5)*.15+.15,r=Math.sin(n*.7+1)*.12+.12,a=Math.sin(n*.9+2)*.08+.08,o=(s+r+a)/3;this.orbRenderer.setSimulatedAudio(s,r,a,o),this.animationId=requestAnimationFrame(e)};this.animationId=requestAnimationFrame(e)}startRealAudioLoop(){if(this.animationId!==null&&(cancelAnimationFrame(this.animationId),this.animationId=null),!this.isPageVisible)return;const e=()=>{var n;if(this.callStatus!=="connected"||!this.orbRenderer||!this.isPageVisible){this.animationId=null;return}const t=(n=this.audioAnalyzer)==null?void 0:n.getAudioData();t&&this.orbRenderer.updateAudio(t),this.animationId=requestAnimationFrame(e)};this.animationId=requestAnimationFrame(e)}getButtonIcon(){return this.callStatus==="connecting"?Gt`
4784
+ `,ht([Se({type:String,attribute:"agent-id"})],Y.InlineCall.prototype,"agentId",2),ht([Se({type:String,attribute:"voice-service-url"})],Y.InlineCall.prototype,"voiceServiceUrl",2),ht([yn()],Y.InlineCall.prototype,"callStatus",2),ht([yn()],Y.InlineCall.prototype,"microphoneEnabled",2),ht([yn()],Y.InlineCall.prototype,"microphoneInitialized",2),ht([yn()],Y.InlineCall.prototype,"serviceUnavailable",2),ht([Se({type:String,attribute:"button-start-text"})],Y.InlineCall.prototype,"buttonStartText",2),ht([Se({type:String,attribute:"button-connecting-text"})],Y.InlineCall.prototype,"buttonConnectingText",2),ht([Se({type:Number,attribute:"size"})],Y.InlineCall.prototype,"size",2),ht([Se({type:Number,attribute:"container-padding"})],Y.InlineCall.prototype,"containerPadding",2),ht([Se({type:String,attribute:"theme",reflect:!0})],Y.InlineCall.prototype,"theme",2),ht([Se({type:String,attribute:"theme-mode"})],Y.InlineCall.prototype,"themeMode",2),ht([Se({type:Object,attribute:"orb-colors"})],Y.InlineCall.prototype,"orbColors",2),ht([Se({type:Number,attribute:"glow-intensity"})],Y.InlineCall.prototype,"glowIntensity",2),ht([Se({type:Number,attribute:"idle-glow-multiplier"})],Y.InlineCall.prototype,"idleGlowMultiplier",2),ht([Se({type:Number,attribute:"morph-strength"})],Y.InlineCall.prototype,"morphStrength",2),ht([Se({type:Number,attribute:"noise-scale"})],Y.InlineCall.prototype,"noiseScale",2),ht([Se({type:Number,attribute:"noise-speed"})],Y.InlineCall.prototype,"noiseSpeed",2),ht([Se({type:Number,attribute:"fresnel-power"})],Y.InlineCall.prototype,"fresnelPower",2),ht([Se({type:Number,attribute:"rotation-speed"})],Y.InlineCall.prototype,"rotationSpeed",2),ht([Se({type:Number,attribute:"audio-reactivity"})],Y.InlineCall.prototype,"audioReactivity",2),ht([Se({type:Number,attribute:"audio-smoothing"})],Y.InlineCall.prototype,"audioSmoothing",2),ht([Se({type:Number,attribute:"idle-morph-multiplier"})],Y.InlineCall.prototype,"idleMorphMultiplier",2),ht([Se({type:Number,attribute:"color-contrast"})],Y.InlineCall.prototype,"colorContrast",2),ht([Se({type:Boolean,attribute:"sound-enabled"})],Y.InlineCall.prototype,"soundEnabled",2),ht([Se({type:Number,attribute:"sound-volume"})],Y.InlineCall.prototype,"soundVolume",2),ht([Se({type:String,attribute:"sound-preset"})],Y.InlineCall.prototype,"soundPreset",2),Y.InlineCall=ht([Po("hanc-ai-inline-call")],Y.InlineCall);var KC=Object.defineProperty,YC=Object.getOwnPropertyDescriptor,ft=(i,e,t,n)=>{for(var s=n>1?void 0:n?YC(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&&KC(e,t,s),s};Y.FloatingCall=class extends ts{constructor(){super(),this.callManager=new Jc,this.healthMonitor=new Zc,this.orbRenderer=null,this.audioAnalyzer=null,this.soundManager=null,this.orbContainerRef=ko(),this.animationId=null,this.pendingTimers=new Set,this.isPageVisible=!0,this.animationStartTime=0,this.intersectionObserver=null,this.isOrbInitialized=!1,this.callStatus="idle",this.microphoneEnabled=!1,this.microphoneInitialized=!1,this.serviceUnavailable=!1,this.buttonStartText="Call",this.buttonConnectingText="Connecting...",this.position="bottom-right",this.size=120,this.theme="default",this.themeMode="auto",this.orbColors={},this.glowIntensity=.8,this.idleGlowMultiplier=.4,this.morphStrength=1,this.noiseScale=1.5,this.noiseSpeed=.3,this.fresnelPower=2.5,this.rotationSpeed=.1,this.audioReactivity=3,this.audioSmoothing=.9,this.idleMorphMultiplier=.25,this.colorContrast=1.5,this.soundEnabled=!0,this.soundVolume=.25,this.soundPreset="1",this.handleAudioTrack=async e=>{const n=e.detail;if(!(!n||!this.audioAnalyzer))try{const s=new MediaStream([n]);await this.audioAnalyzer.connectStream(s)}catch(s){console.error("Failed to connect audio stream:",s)}},this.handleLocalAudioTrack=async e=>{const n=e.detail;if(!(!n||!this.audioAnalyzer))try{const s=new MediaStream([n]);await this.audioAnalyzer.connectLocalStream(s)}catch(s){console.error("Failed to connect local audio stream:",s)}},this.handleMicrophoneEnabled=()=>{this.microphoneEnabled=!0,this.microphoneInitialized=!0},this.handleMicrophoneDisabled=()=>{this.microphoneEnabled=!1,this.microphoneInitialized=!0},this.handleHealthChange=e=>{const t=e.detail;this.serviceUnavailable=t==="unhealthy"},this.handleStatusChange=e=>{var n,s,r,a,o;switch(e.detail){case"connecting":this.callStatus="connecting";break;case"connected":this.callStatus="connected",(n=this.orbRenderer)==null||n.setActive(!0),this.startRealAudioLoop(),this.scheduleTimer(()=>{var c;(c=this.soundManager)==null||c.playCallStartSound()},300),this.dispatchEvent(new Event("call-start",{bubbles:!0,composed:!0}));break;case"disconnected":this.callStatus="idle",this.microphoneInitialized=!1,(s=this.orbRenderer)==null||s.setActive(!1),(r=this.audioAnalyzer)==null||r.disconnect(),this.startIdleAnimation(),this.scheduleTimer(()=>{var c;(c=this.soundManager)==null||c.playCallEndSound()},150),this.dispatchEvent(new Event("call-end",{bubbles:!0,composed:!0}));break;case"error":this.callStatus="error",(a=this.orbRenderer)==null||a.setActive(!1),(o=this.audioAnalyzer)==null||o.disconnect(),this.scheduleTimer(()=>{this.callStatus==="error"&&(this.callStatus="idle",this.startIdleAnimation())},3e3);break}},this.toggleCall=async()=>{var e;this.agentId&&(this.callStatus==="idle"&&!this.healthMonitor.isHealthy||(await((e=this.soundManager)==null?void 0:e.prewarm()),this.callStatus==="idle"?(this.callStatus="connecting",await this.callManager.makeCall({agentId:this.agentId})):this.callStatus==="connected"&&this.callManager.hangUp()))},this.boundHandleVisibilityChange=this.handleVisibilityChange.bind(this)}connectedCallback(){super.connectedCallback(),document.addEventListener("visibilitychange",this.boundHandleVisibilityChange),this.voiceServiceUrl&&(this.callManager.serviceUrl=this.voiceServiceUrl),this.soundManager=new bo({enabled:this.soundEnabled,volume:this.soundVolume,preset:this.soundPreset}),this.callManager.addEventListener("status-changed",this.handleStatusChange),this.callManager.addEventListener("audio-track",this.handleAudioTrack),this.callManager.addEventListener("local-audio-track",this.handleLocalAudioTrack),this.callManager.addEventListener("microphone-enabled",this.handleMicrophoneEnabled),this.callManager.addEventListener("microphone-disabled",this.handleMicrophoneDisabled),this.healthMonitor.serviceUrl=this.callManager.serviceUrl,this.healthMonitor.addEventListener("health-changed",this.handleHealthChange),this.healthMonitor.start()}disconnectedCallback(){var e;super.disconnectedCallback(),document.removeEventListener("visibilitychange",this.boundHandleVisibilityChange),this.intersectionObserver&&(this.intersectionObserver.disconnect(),this.intersectionObserver=null),this.clearAllTimers(),this.callManager.removeEventListener("status-changed",this.handleStatusChange),this.callManager.removeEventListener("audio-track",this.handleAudioTrack),this.callManager.removeEventListener("local-audio-track",this.handleLocalAudioTrack),this.callManager.removeEventListener("microphone-enabled",this.handleMicrophoneEnabled),this.callManager.removeEventListener("microphone-disabled",this.handleMicrophoneDisabled),this.healthMonitor.stop(),this.healthMonitor.removeEventListener("health-changed",this.handleHealthChange),this.callManager.destroy(),this.cleanupOrb(),(e=this.soundManager)==null||e.destroy(),this.soundManager=null}handleVisibilityChange(){const e=this.isPageVisible;this.isPageVisible=document.visibilityState==="visible",!this.isPageVisible&&e?this.stopAnimation():this.isPageVisible&&!e&&this.resumeAnimation()}stopAnimation(){this.animationId!==null&&(cancelAnimationFrame(this.animationId),this.animationId=null)}resumeAnimation(){this.callStatus==="idle"?this.startIdleAnimation():this.callStatus==="connected"&&this.startRealAudioLoop()}scheduleTimer(e,t){const n=setTimeout(()=>{this.pendingTimers.delete(n),e()},t);return this.pendingTimers.add(n),n}clearAllTimers(){this.pendingTimers.forEach(e=>clearTimeout(e)),this.pendingTimers.clear()}firstUpdated(){this.applyTheme(),this.setupLazyInitialization()}setupLazyInitialization(){const e=this.orbContainerRef.value;if(!e){this.initializeOrb();return}if(!("IntersectionObserver"in window)){this.initializeOrb();return}this.intersectionObserver=new IntersectionObserver(t=>{var n;for(const s of t)s.isIntersecting&&!this.isOrbInitialized&&(this.initializeOrb(),this.isOrbInitialized=!0,(n=this.intersectionObserver)==null||n.disconnect(),this.intersectionObserver=null)},{threshold:.5}),this.intersectionObserver.observe(e)}updated(e){var t,n,s;super.updated(e),e.has("agentId")&&(this.callManager.hangUp(),this.callStatus="idle"),e.has("voiceServiceUrl")&&this.voiceServiceUrl&&(this.callManager.serviceUrl=this.voiceServiceUrl,this.healthMonitor.serviceUrl=this.voiceServiceUrl),(e.has("theme")||e.has("themeMode"))&&this.applyTheme(),e.has("soundEnabled")&&((t=this.soundManager)==null||t.setEnabled(this.soundEnabled)),e.has("soundVolume")&&((n=this.soundManager)==null||n.setVolume(this.soundVolume)),e.has("soundPreset")&&((s=this.soundManager)==null||s.setPreset(this.soundPreset))}applyTheme(){if(this.theme){const e=ea(this.theme,this.themeMode);this.orbColors=e.colors,this.glowIntensity=e.glowIntensity,this.idleGlowMultiplier=e.idleGlowMultiplier,this.orbRenderer&&(this.orbRenderer.setColors(this.orbColors),this.orbRenderer.setGlowSettings(this.glowIntensity,this.idleGlowMultiplier))}}initializeOrb(){const e=this.orbContainerRef.value;e&&(this.orbRenderer=new Bd(e,{size:1,colors:this.orbColors,glowIntensity:this.glowIntensity,idleGlowMultiplier:this.idleGlowMultiplier,morphStrength:this.morphStrength,noiseScale:this.noiseScale,noiseSpeed:this.noiseSpeed,fresnelPower:this.fresnelPower,rotationSpeed:this.rotationSpeed,audioReactivity:this.audioReactivity,audioSmoothing:this.audioSmoothing,idleMorphMultiplier:this.idleMorphMultiplier,colorContrast:this.colorContrast}),this.audioAnalyzer=new Vd,this.orbRenderer.start(),this.startIdleAnimation())}cleanupOrb(){var e,t;this.animationId!==null&&(cancelAnimationFrame(this.animationId),this.animationId=null),(e=this.audioAnalyzer)==null||e.disconnect(),(t=this.orbRenderer)==null||t.destroy(),this.audioAnalyzer=null,this.orbRenderer=null}startIdleAnimation(){if(this.animationId!==null&&(cancelAnimationFrame(this.animationId),this.animationId=null),!this.isPageVisible)return;this.animationStartTime=performance.now();const e=t=>{if(this.callStatus!=="idle"||!this.orbRenderer||!this.isPageVisible){this.animationId=null;return}const n=(t-this.animationStartTime)/1e3,s=Math.sin(n*.5)*.15+.15,r=Math.sin(n*.7+1)*.12+.12,a=Math.sin(n*.9+2)*.08+.08,o=(s+r+a)/3;this.orbRenderer.setSimulatedAudio(s,r,a,o),this.animationId=requestAnimationFrame(e)};this.animationId=requestAnimationFrame(e)}startRealAudioLoop(){if(this.animationId!==null&&(cancelAnimationFrame(this.animationId),this.animationId=null),!this.isPageVisible)return;const e=()=>{var n;if(this.callStatus!=="connected"||!this.orbRenderer||!this.isPageVisible){this.animationId=null;return}const t=(n=this.audioAnalyzer)==null?void 0:n.getAudioData();t&&this.orbRenderer.updateAudio(t),this.animationId=requestAnimationFrame(e)};this.animationId=requestAnimationFrame(e)}getButtonIcon(){return this.callStatus==="connecting"?Gt`
4785
4785
  <svg width="16" height="16" viewBox="0 0 16 16" fill="none" class="hanc-spinner">
4786
4786
  <circle
4787
4787
  cx="8"
@@ -5031,7 +5031,7 @@ void main() {
5031
5031
  @click=${this.toggleCall}
5032
5032
  ${Do(this.orbContainerRef)}
5033
5033
  >
5034
- ${this.callStatus==="connected"&&!this.microphoneEnabled?Gt`
5034
+ ${this.callStatus==="connected"&&this.microphoneInitialized&&!this.microphoneEnabled?Gt`
5035
5035
  <div class="microphone-indicator visible">
5036
5036
  <svg viewBox="0 0 24 24" fill="none">
5037
5037
  <path
@@ -5079,7 +5079,7 @@ void main() {
5079
5079
  :host {
5080
5080
  display: block;
5081
5081
  }
5082
- `,gt([Se({type:String,attribute:"agent-id"})],Y.FloatingCall.prototype,"agentId",2),gt([Se({type:String,attribute:"voice-service-url"})],Y.FloatingCall.prototype,"voiceServiceUrl",2),gt([ai()],Y.FloatingCall.prototype,"callStatus",2),gt([ai()],Y.FloatingCall.prototype,"microphoneEnabled",2),gt([ai()],Y.FloatingCall.prototype,"serviceUnavailable",2),gt([Se({type:String,attribute:"button-start-text"})],Y.FloatingCall.prototype,"buttonStartText",2),gt([Se({type:String,attribute:"button-connecting-text"})],Y.FloatingCall.prototype,"buttonConnectingText",2),gt([Se({type:String,attribute:"position"})],Y.FloatingCall.prototype,"position",2),gt([Se({type:Number,attribute:"size"})],Y.FloatingCall.prototype,"size",2),gt([Se({type:String,attribute:"theme"})],Y.FloatingCall.prototype,"theme",2),gt([Se({type:String,attribute:"theme-mode"})],Y.FloatingCall.prototype,"themeMode",2),gt([Se({type:Object,attribute:"orb-colors"})],Y.FloatingCall.prototype,"orbColors",2),gt([Se({type:Number,attribute:"glow-intensity"})],Y.FloatingCall.prototype,"glowIntensity",2),gt([Se({type:Number,attribute:"idle-glow-multiplier"})],Y.FloatingCall.prototype,"idleGlowMultiplier",2),gt([Se({type:Number,attribute:"morph-strength"})],Y.FloatingCall.prototype,"morphStrength",2),gt([Se({type:Number,attribute:"noise-scale"})],Y.FloatingCall.prototype,"noiseScale",2),gt([Se({type:Number,attribute:"noise-speed"})],Y.FloatingCall.prototype,"noiseSpeed",2),gt([Se({type:Number,attribute:"fresnel-power"})],Y.FloatingCall.prototype,"fresnelPower",2),gt([Se({type:Number,attribute:"rotation-speed"})],Y.FloatingCall.prototype,"rotationSpeed",2),gt([Se({type:Number,attribute:"audio-reactivity"})],Y.FloatingCall.prototype,"audioReactivity",2),gt([Se({type:Number,attribute:"audio-smoothing"})],Y.FloatingCall.prototype,"audioSmoothing",2),gt([Se({type:Number,attribute:"idle-morph-multiplier"})],Y.FloatingCall.prototype,"idleMorphMultiplier",2),gt([Se({type:Number,attribute:"color-contrast"})],Y.FloatingCall.prototype,"colorContrast",2),gt([Se({type:Boolean,attribute:"sound-enabled"})],Y.FloatingCall.prototype,"soundEnabled",2),gt([Se({type:Number,attribute:"sound-volume"})],Y.FloatingCall.prototype,"soundVolume",2),gt([Se({type:String,attribute:"sound-preset"})],Y.FloatingCall.prototype,"soundPreset",2),Y.FloatingCall=gt([Po("hanc-ai-floating-call")],Y.FloatingCall);var JC=Object.defineProperty,ZC=Object.getOwnPropertyDescriptor,vt=(i,e,t,n)=>{for(var s=n>1?void 0:n?ZC(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&&JC(e,t,s),s};Y.PillCall=class extends ts{constructor(){super(),this.callManager=new Jc,this.healthMonitor=new Zc,this.orbRenderer=null,this.audioAnalyzer=null,this.soundManager=null,this.orbContainerRef=ko(),this.animationId=null,this.pendingTimers=new Set,this.isPageVisible=!0,this.animationStartTime=0,this.intersectionObserver=null,this.isOrbInitialized=!1,this.callStatus="idle",this.microphoneEnabled=!1,this.serviceUnavailable=!1,this.buttonStartText="Talk to AI Agent",this.buttonConnectingText="Connecting...",this.buttonEndText="End call",this.orbSize=48,this.theme="default",this.themeMode="auto",this.orbColors={},this.glowIntensity=.8,this.idleGlowMultiplier=.4,this.morphStrength=1,this.noiseScale=1.5,this.noiseSpeed=.3,this.fresnelPower=2.5,this.rotationSpeed=.1,this.audioReactivity=3,this.audioSmoothing=.9,this.idleMorphMultiplier=.25,this.colorContrast=1.5,this.soundEnabled=!0,this.soundVolume=.25,this.soundPreset="1",this.handleAudioTrack=async e=>{const n=e.detail;if(!(!n||!this.audioAnalyzer))try{const s=new MediaStream([n]);await this.audioAnalyzer.connectStream(s)}catch(s){console.error("Failed to connect audio stream:",s)}},this.handleLocalAudioTrack=async e=>{const n=e.detail;if(!(!n||!this.audioAnalyzer))try{const s=new MediaStream([n]);await this.audioAnalyzer.connectLocalStream(s)}catch(s){console.error("Failed to connect local audio stream:",s)}},this.handleMicrophoneEnabled=()=>{this.microphoneEnabled=!0},this.handleMicrophoneDisabled=()=>{this.microphoneEnabled=!1},this.handleHealthChange=e=>{const t=e.detail;this.serviceUnavailable=t==="unhealthy"},this.handleStatusChange=e=>{var n,s,r,a,o;switch(e.detail){case"connecting":this.callStatus="connecting";break;case"connected":this.callStatus="connected",(n=this.orbRenderer)==null||n.setActive(!0),this.startRealAudioLoop(),this.scheduleTimer(()=>{var c;(c=this.soundManager)==null||c.playCallStartSound()},300),this.dispatchEvent(new Event("call-start",{bubbles:!0,composed:!0}));break;case"disconnected":this.callStatus="idle",(s=this.orbRenderer)==null||s.setActive(!1),(r=this.audioAnalyzer)==null||r.disconnect(),this.startIdleAnimation(),this.scheduleTimer(()=>{var c;(c=this.soundManager)==null||c.playCallEndSound()},150),this.dispatchEvent(new Event("call-end",{bubbles:!0,composed:!0}));break;case"error":this.callStatus="error",(a=this.orbRenderer)==null||a.setActive(!1),(o=this.audioAnalyzer)==null||o.disconnect(),this.scheduleTimer(()=>{this.callStatus==="error"&&(this.callStatus="idle",this.startIdleAnimation())},3e3);break}},this.toggleCall=async()=>{var e;this.agentId&&(this.callStatus==="idle"&&!this.healthMonitor.isHealthy||(await((e=this.soundManager)==null?void 0:e.prewarm()),this.callStatus==="idle"?(this.callStatus="connecting",await this.callManager.makeCall({agentId:this.agentId})):this.callStatus==="connected"&&this.callManager.hangUp()))},this.boundHandleVisibilityChange=this.handleVisibilityChange.bind(this)}connectedCallback(){super.connectedCallback(),document.addEventListener("visibilitychange",this.boundHandleVisibilityChange),this.voiceServiceUrl&&(this.callManager.serviceUrl=this.voiceServiceUrl),this.soundManager=new bo({enabled:this.soundEnabled,volume:this.soundVolume,preset:this.soundPreset}),this.callManager.addEventListener("status-changed",this.handleStatusChange),this.callManager.addEventListener("audio-track",this.handleAudioTrack),this.callManager.addEventListener("local-audio-track",this.handleLocalAudioTrack),this.callManager.addEventListener("microphone-enabled",this.handleMicrophoneEnabled),this.callManager.addEventListener("microphone-disabled",this.handleMicrophoneDisabled),this.healthMonitor.serviceUrl=this.callManager.serviceUrl,this.healthMonitor.addEventListener("health-changed",this.handleHealthChange),this.healthMonitor.start()}disconnectedCallback(){var e;super.disconnectedCallback(),document.removeEventListener("visibilitychange",this.boundHandleVisibilityChange),this.intersectionObserver&&(this.intersectionObserver.disconnect(),this.intersectionObserver=null),this.clearAllTimers(),this.callManager.removeEventListener("status-changed",this.handleStatusChange),this.callManager.removeEventListener("audio-track",this.handleAudioTrack),this.callManager.removeEventListener("local-audio-track",this.handleLocalAudioTrack),this.callManager.removeEventListener("microphone-enabled",this.handleMicrophoneEnabled),this.callManager.removeEventListener("microphone-disabled",this.handleMicrophoneDisabled),this.healthMonitor.stop(),this.healthMonitor.removeEventListener("health-changed",this.handleHealthChange),this.callManager.destroy(),this.cleanupOrb(),(e=this.soundManager)==null||e.destroy(),this.soundManager=null}handleVisibilityChange(){const e=this.isPageVisible;this.isPageVisible=document.visibilityState==="visible",!this.isPageVisible&&e?this.stopAnimation():this.isPageVisible&&!e&&this.resumeAnimation()}stopAnimation(){this.animationId!==null&&(cancelAnimationFrame(this.animationId),this.animationId=null)}resumeAnimation(){this.callStatus==="idle"?this.startIdleAnimation():this.callStatus==="connected"&&this.startRealAudioLoop()}scheduleTimer(e,t){const n=setTimeout(()=>{this.pendingTimers.delete(n),e()},t);return this.pendingTimers.add(n),n}clearAllTimers(){this.pendingTimers.forEach(e=>clearTimeout(e)),this.pendingTimers.clear()}firstUpdated(){this.applyTheme(),this.setupLazyInitialization()}setupLazyInitialization(){const e=this.orbContainerRef.value;if(!e){this.initializeOrb();return}if(!("IntersectionObserver"in window)){this.initializeOrb();return}this.intersectionObserver=new IntersectionObserver(t=>{var n;for(const s of t)s.isIntersecting&&!this.isOrbInitialized&&(this.initializeOrb(),this.isOrbInitialized=!0,(n=this.intersectionObserver)==null||n.disconnect(),this.intersectionObserver=null)},{threshold:.5}),this.intersectionObserver.observe(e)}updated(e){var t,n,s;super.updated(e),e.has("agentId")&&(this.callManager.hangUp(),this.callStatus="idle"),e.has("voiceServiceUrl")&&this.voiceServiceUrl&&(this.callManager.serviceUrl=this.voiceServiceUrl,this.healthMonitor.serviceUrl=this.voiceServiceUrl),(e.has("theme")||e.has("themeMode"))&&this.applyTheme(),e.has("soundEnabled")&&((t=this.soundManager)==null||t.setEnabled(this.soundEnabled)),e.has("soundVolume")&&((n=this.soundManager)==null||n.setVolume(this.soundVolume)),e.has("soundPreset")&&((s=this.soundManager)==null||s.setPreset(this.soundPreset))}applyTheme(){if(this.theme){const e=ea(this.theme,this.themeMode);this.orbColors=e.colors,this.glowIntensity=e.glowIntensity,this.idleGlowMultiplier=e.idleGlowMultiplier,this.orbRenderer&&(this.orbRenderer.setColors(this.orbColors),this.orbRenderer.setGlowSettings(this.glowIntensity,this.idleGlowMultiplier))}}initializeOrb(){const e=this.orbContainerRef.value;e&&(this.orbRenderer=new Bd(e,{size:1,colors:this.orbColors,glowIntensity:this.glowIntensity,idleGlowMultiplier:this.idleGlowMultiplier,morphStrength:this.morphStrength,noiseScale:this.noiseScale,noiseSpeed:this.noiseSpeed,fresnelPower:this.fresnelPower,rotationSpeed:this.rotationSpeed,audioReactivity:this.audioReactivity,audioSmoothing:this.audioSmoothing,idleMorphMultiplier:this.idleMorphMultiplier,colorContrast:this.colorContrast}),this.audioAnalyzer=new Vd,this.orbRenderer.start(),this.startIdleAnimation())}cleanupOrb(){var e,t;this.animationId!==null&&(cancelAnimationFrame(this.animationId),this.animationId=null),(e=this.audioAnalyzer)==null||e.disconnect(),(t=this.orbRenderer)==null||t.destroy(),this.audioAnalyzer=null,this.orbRenderer=null}startIdleAnimation(){if(this.animationId!==null&&(cancelAnimationFrame(this.animationId),this.animationId=null),!this.isPageVisible)return;this.animationStartTime=performance.now();const e=t=>{if(this.callStatus!=="idle"||!this.orbRenderer||!this.isPageVisible){this.animationId=null;return}const n=(t-this.animationStartTime)/1e3,s=Math.sin(n*.5)*.15+.15,r=Math.sin(n*.7+1)*.12+.12,a=Math.sin(n*.9+2)*.08+.08,o=(s+r+a)/3;this.orbRenderer.setSimulatedAudio(s,r,a,o),this.animationId=requestAnimationFrame(e)};this.animationId=requestAnimationFrame(e)}startRealAudioLoop(){if(this.animationId!==null&&(cancelAnimationFrame(this.animationId),this.animationId=null),!this.isPageVisible)return;const e=()=>{var n;if(this.callStatus!=="connected"||!this.orbRenderer||!this.isPageVisible){this.animationId=null;return}const t=(n=this.audioAnalyzer)==null?void 0:n.getAudioData();t&&this.orbRenderer.updateAudio(t),this.animationId=requestAnimationFrame(e)};this.animationId=requestAnimationFrame(e)}getButtonIcon(){return this.callStatus==="connecting"?Gt`
5082
+ `,ft([Se({type:String,attribute:"agent-id"})],Y.FloatingCall.prototype,"agentId",2),ft([Se({type:String,attribute:"voice-service-url"})],Y.FloatingCall.prototype,"voiceServiceUrl",2),ft([yn()],Y.FloatingCall.prototype,"callStatus",2),ft([yn()],Y.FloatingCall.prototype,"microphoneEnabled",2),ft([yn()],Y.FloatingCall.prototype,"microphoneInitialized",2),ft([yn()],Y.FloatingCall.prototype,"serviceUnavailable",2),ft([Se({type:String,attribute:"button-start-text"})],Y.FloatingCall.prototype,"buttonStartText",2),ft([Se({type:String,attribute:"button-connecting-text"})],Y.FloatingCall.prototype,"buttonConnectingText",2),ft([Se({type:String,attribute:"position"})],Y.FloatingCall.prototype,"position",2),ft([Se({type:Number,attribute:"size"})],Y.FloatingCall.prototype,"size",2),ft([Se({type:String,attribute:"theme"})],Y.FloatingCall.prototype,"theme",2),ft([Se({type:String,attribute:"theme-mode"})],Y.FloatingCall.prototype,"themeMode",2),ft([Se({type:Object,attribute:"orb-colors"})],Y.FloatingCall.prototype,"orbColors",2),ft([Se({type:Number,attribute:"glow-intensity"})],Y.FloatingCall.prototype,"glowIntensity",2),ft([Se({type:Number,attribute:"idle-glow-multiplier"})],Y.FloatingCall.prototype,"idleGlowMultiplier",2),ft([Se({type:Number,attribute:"morph-strength"})],Y.FloatingCall.prototype,"morphStrength",2),ft([Se({type:Number,attribute:"noise-scale"})],Y.FloatingCall.prototype,"noiseScale",2),ft([Se({type:Number,attribute:"noise-speed"})],Y.FloatingCall.prototype,"noiseSpeed",2),ft([Se({type:Number,attribute:"fresnel-power"})],Y.FloatingCall.prototype,"fresnelPower",2),ft([Se({type:Number,attribute:"rotation-speed"})],Y.FloatingCall.prototype,"rotationSpeed",2),ft([Se({type:Number,attribute:"audio-reactivity"})],Y.FloatingCall.prototype,"audioReactivity",2),ft([Se({type:Number,attribute:"audio-smoothing"})],Y.FloatingCall.prototype,"audioSmoothing",2),ft([Se({type:Number,attribute:"idle-morph-multiplier"})],Y.FloatingCall.prototype,"idleMorphMultiplier",2),ft([Se({type:Number,attribute:"color-contrast"})],Y.FloatingCall.prototype,"colorContrast",2),ft([Se({type:Boolean,attribute:"sound-enabled"})],Y.FloatingCall.prototype,"soundEnabled",2),ft([Se({type:Number,attribute:"sound-volume"})],Y.FloatingCall.prototype,"soundVolume",2),ft([Se({type:String,attribute:"sound-preset"})],Y.FloatingCall.prototype,"soundPreset",2),Y.FloatingCall=ft([Po("hanc-ai-floating-call")],Y.FloatingCall);var JC=Object.defineProperty,ZC=Object.getOwnPropertyDescriptor,pt=(i,e,t,n)=>{for(var s=n>1?void 0:n?ZC(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&&JC(e,t,s),s};Y.PillCall=class extends ts{constructor(){super(),this.callManager=new Jc,this.healthMonitor=new Zc,this.orbRenderer=null,this.audioAnalyzer=null,this.soundManager=null,this.orbContainerRef=ko(),this.animationId=null,this.pendingTimers=new Set,this.isPageVisible=!0,this.animationStartTime=0,this.intersectionObserver=null,this.isOrbInitialized=!1,this.callStatus="idle",this.microphoneEnabled=!1,this.microphoneInitialized=!1,this.serviceUnavailable=!1,this.buttonStartText="Talk to AI Agent",this.buttonConnectingText="Connecting...",this.buttonEndText="End call",this.orbSize=48,this.theme="default",this.themeMode="auto",this.orbColors={},this.glowIntensity=.8,this.idleGlowMultiplier=.4,this.morphStrength=1,this.noiseScale=1.5,this.noiseSpeed=.3,this.fresnelPower=2.5,this.rotationSpeed=.1,this.audioReactivity=3,this.audioSmoothing=.9,this.idleMorphMultiplier=.25,this.colorContrast=1.5,this.soundEnabled=!0,this.soundVolume=.25,this.soundPreset="1",this.handleAudioTrack=async e=>{const n=e.detail;if(!(!n||!this.audioAnalyzer))try{const s=new MediaStream([n]);await this.audioAnalyzer.connectStream(s)}catch(s){console.error("Failed to connect audio stream:",s)}},this.handleLocalAudioTrack=async e=>{const n=e.detail;if(!(!n||!this.audioAnalyzer))try{const s=new MediaStream([n]);await this.audioAnalyzer.connectLocalStream(s)}catch(s){console.error("Failed to connect local audio stream:",s)}},this.handleMicrophoneEnabled=()=>{this.microphoneEnabled=!0,this.microphoneInitialized=!0},this.handleMicrophoneDisabled=()=>{this.microphoneEnabled=!1,this.microphoneInitialized=!0},this.handleHealthChange=e=>{const t=e.detail;this.serviceUnavailable=t==="unhealthy"},this.handleStatusChange=e=>{var n,s,r,a,o;switch(e.detail){case"connecting":this.callStatus="connecting";break;case"connected":this.callStatus="connected",(n=this.orbRenderer)==null||n.setActive(!0),this.startRealAudioLoop(),this.scheduleTimer(()=>{var c;(c=this.soundManager)==null||c.playCallStartSound()},300),this.dispatchEvent(new Event("call-start",{bubbles:!0,composed:!0}));break;case"disconnected":this.callStatus="idle",this.microphoneInitialized=!1,(s=this.orbRenderer)==null||s.setActive(!1),(r=this.audioAnalyzer)==null||r.disconnect(),this.startIdleAnimation(),this.scheduleTimer(()=>{var c;(c=this.soundManager)==null||c.playCallEndSound()},150),this.dispatchEvent(new Event("call-end",{bubbles:!0,composed:!0}));break;case"error":this.callStatus="error",(a=this.orbRenderer)==null||a.setActive(!1),(o=this.audioAnalyzer)==null||o.disconnect(),this.scheduleTimer(()=>{this.callStatus==="error"&&(this.callStatus="idle",this.startIdleAnimation())},3e3);break}},this.toggleCall=async()=>{var e;this.agentId&&(this.callStatus==="idle"&&!this.healthMonitor.isHealthy||(await((e=this.soundManager)==null?void 0:e.prewarm()),this.callStatus==="idle"?(this.callStatus="connecting",await this.callManager.makeCall({agentId:this.agentId})):this.callStatus==="connected"&&this.callManager.hangUp()))},this.boundHandleVisibilityChange=this.handleVisibilityChange.bind(this)}connectedCallback(){super.connectedCallback(),document.addEventListener("visibilitychange",this.boundHandleVisibilityChange),this.voiceServiceUrl&&(this.callManager.serviceUrl=this.voiceServiceUrl),this.soundManager=new bo({enabled:this.soundEnabled,volume:this.soundVolume,preset:this.soundPreset}),this.callManager.addEventListener("status-changed",this.handleStatusChange),this.callManager.addEventListener("audio-track",this.handleAudioTrack),this.callManager.addEventListener("local-audio-track",this.handleLocalAudioTrack),this.callManager.addEventListener("microphone-enabled",this.handleMicrophoneEnabled),this.callManager.addEventListener("microphone-disabled",this.handleMicrophoneDisabled),this.healthMonitor.serviceUrl=this.callManager.serviceUrl,this.healthMonitor.addEventListener("health-changed",this.handleHealthChange),this.healthMonitor.start()}disconnectedCallback(){var e;super.disconnectedCallback(),document.removeEventListener("visibilitychange",this.boundHandleVisibilityChange),this.intersectionObserver&&(this.intersectionObserver.disconnect(),this.intersectionObserver=null),this.clearAllTimers(),this.callManager.removeEventListener("status-changed",this.handleStatusChange),this.callManager.removeEventListener("audio-track",this.handleAudioTrack),this.callManager.removeEventListener("local-audio-track",this.handleLocalAudioTrack),this.callManager.removeEventListener("microphone-enabled",this.handleMicrophoneEnabled),this.callManager.removeEventListener("microphone-disabled",this.handleMicrophoneDisabled),this.healthMonitor.stop(),this.healthMonitor.removeEventListener("health-changed",this.handleHealthChange),this.callManager.destroy(),this.cleanupOrb(),(e=this.soundManager)==null||e.destroy(),this.soundManager=null}handleVisibilityChange(){const e=this.isPageVisible;this.isPageVisible=document.visibilityState==="visible",!this.isPageVisible&&e?this.stopAnimation():this.isPageVisible&&!e&&this.resumeAnimation()}stopAnimation(){this.animationId!==null&&(cancelAnimationFrame(this.animationId),this.animationId=null)}resumeAnimation(){this.callStatus==="idle"?this.startIdleAnimation():this.callStatus==="connected"&&this.startRealAudioLoop()}scheduleTimer(e,t){const n=setTimeout(()=>{this.pendingTimers.delete(n),e()},t);return this.pendingTimers.add(n),n}clearAllTimers(){this.pendingTimers.forEach(e=>clearTimeout(e)),this.pendingTimers.clear()}firstUpdated(){this.applyTheme(),this.setupLazyInitialization()}setupLazyInitialization(){const e=this.orbContainerRef.value;if(!e){this.initializeOrb();return}if(!("IntersectionObserver"in window)){this.initializeOrb();return}this.intersectionObserver=new IntersectionObserver(t=>{var n;for(const s of t)s.isIntersecting&&!this.isOrbInitialized&&(this.initializeOrb(),this.isOrbInitialized=!0,(n=this.intersectionObserver)==null||n.disconnect(),this.intersectionObserver=null)},{threshold:.5}),this.intersectionObserver.observe(e)}updated(e){var t,n,s;super.updated(e),e.has("agentId")&&(this.callManager.hangUp(),this.callStatus="idle"),e.has("voiceServiceUrl")&&this.voiceServiceUrl&&(this.callManager.serviceUrl=this.voiceServiceUrl,this.healthMonitor.serviceUrl=this.voiceServiceUrl),(e.has("theme")||e.has("themeMode"))&&this.applyTheme(),e.has("soundEnabled")&&((t=this.soundManager)==null||t.setEnabled(this.soundEnabled)),e.has("soundVolume")&&((n=this.soundManager)==null||n.setVolume(this.soundVolume)),e.has("soundPreset")&&((s=this.soundManager)==null||s.setPreset(this.soundPreset))}applyTheme(){if(this.theme){const e=ea(this.theme,this.themeMode);this.orbColors=e.colors,this.glowIntensity=e.glowIntensity,this.idleGlowMultiplier=e.idleGlowMultiplier,this.orbRenderer&&(this.orbRenderer.setColors(this.orbColors),this.orbRenderer.setGlowSettings(this.glowIntensity,this.idleGlowMultiplier))}}initializeOrb(){const e=this.orbContainerRef.value;e&&(this.orbRenderer=new Bd(e,{size:1,colors:this.orbColors,glowIntensity:this.glowIntensity,idleGlowMultiplier:this.idleGlowMultiplier,morphStrength:this.morphStrength,noiseScale:this.noiseScale,noiseSpeed:this.noiseSpeed,fresnelPower:this.fresnelPower,rotationSpeed:this.rotationSpeed,audioReactivity:this.audioReactivity,audioSmoothing:this.audioSmoothing,idleMorphMultiplier:this.idleMorphMultiplier,colorContrast:this.colorContrast}),this.audioAnalyzer=new Vd,this.orbRenderer.start(),this.startIdleAnimation())}cleanupOrb(){var e,t;this.animationId!==null&&(cancelAnimationFrame(this.animationId),this.animationId=null),(e=this.audioAnalyzer)==null||e.disconnect(),(t=this.orbRenderer)==null||t.destroy(),this.audioAnalyzer=null,this.orbRenderer=null}startIdleAnimation(){if(this.animationId!==null&&(cancelAnimationFrame(this.animationId),this.animationId=null),!this.isPageVisible)return;this.animationStartTime=performance.now();const e=t=>{if(this.callStatus!=="idle"||!this.orbRenderer||!this.isPageVisible){this.animationId=null;return}const n=(t-this.animationStartTime)/1e3,s=Math.sin(n*.5)*.15+.15,r=Math.sin(n*.7+1)*.12+.12,a=Math.sin(n*.9+2)*.08+.08,o=(s+r+a)/3;this.orbRenderer.setSimulatedAudio(s,r,a,o),this.animationId=requestAnimationFrame(e)};this.animationId=requestAnimationFrame(e)}startRealAudioLoop(){if(this.animationId!==null&&(cancelAnimationFrame(this.animationId),this.animationId=null),!this.isPageVisible)return;const e=()=>{var n;if(this.callStatus!=="connected"||!this.orbRenderer||!this.isPageVisible){this.animationId=null;return}const t=(n=this.audioAnalyzer)==null?void 0:n.getAudioData();t&&this.orbRenderer.updateAudio(t),this.animationId=requestAnimationFrame(e)};this.animationId=requestAnimationFrame(e)}getButtonIcon(){return this.callStatus==="connecting"?Gt`
5083
5083
  <svg width="16" height="16" viewBox="0 0 16 16" fill="none" class="hanc-spinner">
5084
5084
  <circle
5085
5085
  cx="8"
@@ -5241,7 +5241,7 @@ void main() {
5241
5241
  part="orb-container"
5242
5242
  ${Do(this.orbContainerRef)}
5243
5243
  ></div>
5244
- ${this.callStatus==="connected"&&!this.microphoneEnabled?Gt`
5244
+ ${this.callStatus==="connected"&&this.microphoneInitialized&&!this.microphoneEnabled?Gt`
5245
5245
  <div class="microphone-indicator visible">
5246
5246
  <svg viewBox="0 0 24 24" fill="none">
5247
5247
  <path
@@ -5275,4 +5275,4 @@ void main() {
5275
5275
  display: inline-block;
5276
5276
  contain: layout style;
5277
5277
  }
5278
- `,vt([Se({type:String,attribute:"agent-id"})],Y.PillCall.prototype,"agentId",2),vt([Se({type:String,attribute:"voice-service-url"})],Y.PillCall.prototype,"voiceServiceUrl",2),vt([ai()],Y.PillCall.prototype,"callStatus",2),vt([ai()],Y.PillCall.prototype,"microphoneEnabled",2),vt([ai()],Y.PillCall.prototype,"serviceUnavailable",2),vt([Se({type:String,attribute:"button-start-text"})],Y.PillCall.prototype,"buttonStartText",2),vt([Se({type:String,attribute:"button-connecting-text"})],Y.PillCall.prototype,"buttonConnectingText",2),vt([Se({type:String,attribute:"button-end-text"})],Y.PillCall.prototype,"buttonEndText",2),vt([Se({type:Number,attribute:"orb-size"})],Y.PillCall.prototype,"orbSize",2),vt([Se({type:String,attribute:"theme"})],Y.PillCall.prototype,"theme",2),vt([Se({type:String,attribute:"theme-mode"})],Y.PillCall.prototype,"themeMode",2),vt([Se({type:Object,attribute:"orb-colors"})],Y.PillCall.prototype,"orbColors",2),vt([Se({type:Number,attribute:"glow-intensity"})],Y.PillCall.prototype,"glowIntensity",2),vt([Se({type:Number,attribute:"idle-glow-multiplier"})],Y.PillCall.prototype,"idleGlowMultiplier",2),vt([Se({type:Number,attribute:"morph-strength"})],Y.PillCall.prototype,"morphStrength",2),vt([Se({type:Number,attribute:"noise-scale"})],Y.PillCall.prototype,"noiseScale",2),vt([Se({type:Number,attribute:"noise-speed"})],Y.PillCall.prototype,"noiseSpeed",2),vt([Se({type:Number,attribute:"fresnel-power"})],Y.PillCall.prototype,"fresnelPower",2),vt([Se({type:Number,attribute:"rotation-speed"})],Y.PillCall.prototype,"rotationSpeed",2),vt([Se({type:Number,attribute:"audio-reactivity"})],Y.PillCall.prototype,"audioReactivity",2),vt([Se({type:Number,attribute:"audio-smoothing"})],Y.PillCall.prototype,"audioSmoothing",2),vt([Se({type:Number,attribute:"idle-morph-multiplier"})],Y.PillCall.prototype,"idleMorphMultiplier",2),vt([Se({type:Number,attribute:"color-contrast"})],Y.PillCall.prototype,"colorContrast",2),vt([Se({type:Boolean,attribute:"sound-enabled"})],Y.PillCall.prototype,"soundEnabled",2),vt([Se({type:Number,attribute:"sound-volume"})],Y.PillCall.prototype,"soundVolume",2),vt([Se({type:String,attribute:"sound-preset"})],Y.PillCall.prototype,"soundPreset",2),Y.PillCall=vt([Po("hanc-ai-pill-call")],Y.PillCall),Y.SoundManager=bo,Y.applyTheme=wm,Y.darkPresets=ii,Y.darkThemes=HC,Y.detectSystemTheme=Mm,Y.getColorPreset=zC,Y.getPresetNames=GC,Y.getTheme=ea,Y.getThemeNames=qC,Y.lightPresets=si,Y.lightThemes=WC,Y.themes=ur,Y.watchSystemTheme=jC,Object.defineProperty(Y,Symbol.toStringTag,{value:"Module"})});
5278
+ `,pt([Se({type:String,attribute:"agent-id"})],Y.PillCall.prototype,"agentId",2),pt([Se({type:String,attribute:"voice-service-url"})],Y.PillCall.prototype,"voiceServiceUrl",2),pt([yn()],Y.PillCall.prototype,"callStatus",2),pt([yn()],Y.PillCall.prototype,"microphoneEnabled",2),pt([yn()],Y.PillCall.prototype,"microphoneInitialized",2),pt([yn()],Y.PillCall.prototype,"serviceUnavailable",2),pt([Se({type:String,attribute:"button-start-text"})],Y.PillCall.prototype,"buttonStartText",2),pt([Se({type:String,attribute:"button-connecting-text"})],Y.PillCall.prototype,"buttonConnectingText",2),pt([Se({type:String,attribute:"button-end-text"})],Y.PillCall.prototype,"buttonEndText",2),pt([Se({type:Number,attribute:"orb-size"})],Y.PillCall.prototype,"orbSize",2),pt([Se({type:String,attribute:"theme"})],Y.PillCall.prototype,"theme",2),pt([Se({type:String,attribute:"theme-mode"})],Y.PillCall.prototype,"themeMode",2),pt([Se({type:Object,attribute:"orb-colors"})],Y.PillCall.prototype,"orbColors",2),pt([Se({type:Number,attribute:"glow-intensity"})],Y.PillCall.prototype,"glowIntensity",2),pt([Se({type:Number,attribute:"idle-glow-multiplier"})],Y.PillCall.prototype,"idleGlowMultiplier",2),pt([Se({type:Number,attribute:"morph-strength"})],Y.PillCall.prototype,"morphStrength",2),pt([Se({type:Number,attribute:"noise-scale"})],Y.PillCall.prototype,"noiseScale",2),pt([Se({type:Number,attribute:"noise-speed"})],Y.PillCall.prototype,"noiseSpeed",2),pt([Se({type:Number,attribute:"fresnel-power"})],Y.PillCall.prototype,"fresnelPower",2),pt([Se({type:Number,attribute:"rotation-speed"})],Y.PillCall.prototype,"rotationSpeed",2),pt([Se({type:Number,attribute:"audio-reactivity"})],Y.PillCall.prototype,"audioReactivity",2),pt([Se({type:Number,attribute:"audio-smoothing"})],Y.PillCall.prototype,"audioSmoothing",2),pt([Se({type:Number,attribute:"idle-morph-multiplier"})],Y.PillCall.prototype,"idleMorphMultiplier",2),pt([Se({type:Number,attribute:"color-contrast"})],Y.PillCall.prototype,"colorContrast",2),pt([Se({type:Boolean,attribute:"sound-enabled"})],Y.PillCall.prototype,"soundEnabled",2),pt([Se({type:Number,attribute:"sound-volume"})],Y.PillCall.prototype,"soundVolume",2),pt([Se({type:String,attribute:"sound-preset"})],Y.PillCall.prototype,"soundPreset",2),Y.PillCall=pt([Po("hanc-ai-pill-call")],Y.PillCall),Y.SoundManager=bo,Y.applyTheme=wm,Y.darkPresets=si,Y.darkThemes=HC,Y.detectSystemTheme=Mm,Y.getColorPreset=zC,Y.getPresetNames=GC,Y.getTheme=ea,Y.getThemeNames=qC,Y.lightPresets=ri,Y.lightThemes=WC,Y.themes=ur,Y.watchSystemTheme=jC,Object.defineProperty(Y,Symbol.toStringTag,{value:"Module"})});