obi-sdk 0.2.0 → 0.3.1

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.
Files changed (39) hide show
  1. package/dist/core/constants.d.ts +1 -0
  2. package/dist/core/index.d.ts +3 -0
  3. package/dist/core/init.d.ts +1 -0
  4. package/dist/core/types.d.ts +46 -0
  5. package/dist/empty-loader.d.ts +5 -0
  6. package/dist/index.d.ts +2 -0
  7. package/dist/loader.d.ts +29 -0
  8. package/dist/obi-sdk.es.js +12683 -10687
  9. package/dist/obi-sdk.umd.js +118 -93
  10. package/dist/ui/components/audio-equalizer.d.ts +20 -0
  11. package/dist/ui/components/control-panel.d.ts +12 -0
  12. package/dist/ui/components/courses/course-modal.d.ts +18 -0
  13. package/dist/ui/components/courses/courses.d.ts +26 -0
  14. package/dist/ui/components/courses/index.d.ts +1 -0
  15. package/dist/ui/components/dot-loader.d.ts +20 -0
  16. package/dist/ui/components/icons.d.ts +6 -0
  17. package/dist/ui/components/index.d.ts +11 -0
  18. package/dist/ui/components/nav-icon.d.ts +10 -0
  19. package/dist/ui/components/navigation-bar.d.ts +19 -0
  20. package/dist/ui/components/obi-widget.d.ts +50 -0
  21. package/dist/ui/components/searching-loader.d.ts +5 -0
  22. package/dist/ui/components/status-widget.d.ts +8 -0
  23. package/dist/ui/index.d.ts +1 -0
  24. package/dist/utils/index.d.ts +1 -0
  25. package/dist/utils/storage.d.ts +45 -0
  26. package/package.json +18 -19
  27. package/dist/modular/chunks/index-2d0b05af.js +0 -26738
  28. package/dist/modular/chunks/index-2d0b05af.js.map +0 -1
  29. package/dist/modular/chunks/obi-widget-0970cbbe.js +0 -2221
  30. package/dist/modular/chunks/obi-widget-0970cbbe.js.map +0 -1
  31. package/dist/modular/core.js +0 -9
  32. package/dist/modular/core.js.map +0 -1
  33. package/dist/modular/index.js +0 -29
  34. package/dist/modular/index.js.map +0 -1
  35. package/dist/modular/ui.js +0 -253
  36. package/dist/modular/ui.js.map +0 -1
  37. package/dist/obi-loader.js +0 -8
  38. package/dist/obi-sdk.standalone.iife.js +0 -558
  39. package/dist/obi-sdk.standalone.iife.js.map +0 -1
@@ -1,57 +1,78 @@
1
- (function(et,L){typeof exports=="object"&&typeof module<"u"?L(exports,require("lit")):typeof define=="function"&&define.amd?define(["exports","lit"],L):(et=typeof globalThis<"u"?globalThis:et||self,L(et.ObiSDK={},et.lit))})(this,function(et,L){"use strict";/**
1
+ (function(nt,_){typeof exports=="object"&&typeof module<"u"?_(exports,require("lit")):typeof define=="function"&&define.amd?define(["exports","lit"],_):(nt=typeof globalThis<"u"?globalThis:nt||self,_(nt.ObiSDK={},nt.lit))})(this,function(nt,_){"use strict";const _r="http://localhost:5173/api";function Uh(n){return n&&n.__esModule&&Object.prototype.hasOwnProperty.call(n,"default")?n.default:n}var ha={exports:{}};(function(n){var e=Object.prototype.hasOwnProperty,A="~";function t(){}Object.create&&(t.prototype=Object.create(null),new t().__proto__||(A=!1));function i(a,c,l){this.fn=a,this.context=c,this.once=l||!1}function r(a,c,l,u,d){if(typeof l!="function")throw new TypeError("The listener must be a function");var h=new i(l,u||a,d),f=A?A+c:c;return a._events[f]?a._events[f].fn?a._events[f]=[a._events[f],h]:a._events[f].push(h):(a._events[f]=h,a._eventsCount++),a}function s(a,c){--a._eventsCount===0?a._events=new t:delete a._events[c]}function o(){this._events=new t,this._eventsCount=0}o.prototype.eventNames=function(){var c=[],l,u;if(this._eventsCount===0)return c;for(u in l=this._events)e.call(l,u)&&c.push(A?u.slice(1):u);return Object.getOwnPropertySymbols?c.concat(Object.getOwnPropertySymbols(l)):c},o.prototype.listeners=function(c){var l=A?A+c:c,u=this._events[l];if(!u)return[];if(u.fn)return[u.fn];for(var d=0,h=u.length,f=new Array(h);d<h;d++)f[d]=u[d].fn;return f},o.prototype.listenerCount=function(c){var l=A?A+c:c,u=this._events[l];return u?u.fn?1:u.length:0},o.prototype.emit=function(c,l,u,d,h,f){var g=A?A+c:c;if(!this._events[g])return!1;var m=this._events[g],C=arguments.length,y,U;if(m.fn){switch(m.once&&this.removeListener(c,m.fn,void 0,!0),C){case 1:return m.fn.call(m.context),!0;case 2:return m.fn.call(m.context,l),!0;case 3:return m.fn.call(m.context,l,u),!0;case 4:return m.fn.call(m.context,l,u,d),!0;case 5:return m.fn.call(m.context,l,u,d,h),!0;case 6:return m.fn.call(m.context,l,u,d,h,f),!0}for(U=1,y=new Array(C-1);U<C;U++)y[U-1]=arguments[U];m.fn.apply(m.context,y)}else{var v=m.length,B;for(U=0;U<v;U++)switch(m[U].once&&this.removeListener(c,m[U].fn,void 0,!0),C){case 1:m[U].fn.call(m[U].context);break;case 2:m[U].fn.call(m[U].context,l);break;case 3:m[U].fn.call(m[U].context,l,u);break;case 4:m[U].fn.call(m[U].context,l,u,d);break;default:if(!y)for(B=1,y=new Array(C-1);B<C;B++)y[B-1]=arguments[B];m[U].fn.apply(m[U].context,y)}}return!0},o.prototype.on=function(c,l,u){return r(this,c,l,u,!1)},o.prototype.once=function(c,l,u){return r(this,c,l,u,!0)},o.prototype.removeListener=function(c,l,u,d){var h=A?A+c:c;if(!this._events[h])return this;if(!l)return s(this,h),this;var f=this._events[h];if(f.fn)f.fn===l&&(!d||f.once)&&(!u||f.context===u)&&s(this,h);else{for(var g=0,m=[],C=f.length;g<C;g++)(f[g].fn!==l||d&&!f[g].once||u&&f[g].context!==u)&&m.push(f[g]);m.length?this._events[h]=m.length===1?m[0]:m:s(this,h)}return this},o.prototype.removeAllListeners=function(c){var l;return c?(l=A?A+c:c,this._events[l]&&s(this,l)):(this._events=new t,this._eventsCount=0),this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prefixed=A,o.EventEmitter=o,n.exports=o})(ha);var Qh=ha.exports;const Eh=Uh(Qh);function Sh(n,e){return e.forEach(function(A){A&&typeof A!="string"&&!Array.isArray(A)&&Object.keys(A).forEach(function(t){if(t!=="default"&&!(t in n)){var i=Object.getOwnPropertyDescriptor(A,t);Object.defineProperty(n,t,i.get?i:{enumerable:!0,get:function(){return A[t]}})}})}),Object.freeze(n)}var Th=Object.defineProperty,Fh=(n,e,A)=>e in n?Th(n,e,{enumerable:!0,configurable:!0,writable:!0,value:A}):n[e]=A,fa=(n,e,A)=>Fh(n,typeof e!="symbol"?e+"":e,A);let Te=class{constructor(){fa(this,"_locking"),fa(this,"_locks"),this._locking=Promise.resolve(),this._locks=0}isLocked(){return this._locks>0}lock(){this._locks+=1;let e;const A=new Promise(i=>e=()=>{this._locks-=1,i()}),t=this._locking.then(()=>e);return this._locking=this._locking.then(()=>A),t}};function re(n,e){if(!n)throw new Error(e)}const kh=34028234663852886e22,Ih=-34028234663852886e22,Rh=4294967295,xh=2147483647,Ph=-2147483648;function qn(n){if(typeof n!="number")throw new Error("invalid int 32: "+typeof n);if(!Number.isInteger(n)||n>xh||n<Ph)throw new Error("invalid int 32: "+n)}function Hr(n){if(typeof n!="number")throw new Error("invalid uint 32: "+typeof n);if(!Number.isInteger(n)||n>Rh||n<0)throw new Error("invalid uint 32: "+n)}function ga(n){if(typeof n!="number")throw new Error("invalid float 32: "+typeof n);if(Number.isFinite(n)&&(n>kh||n<Ih))throw new Error("invalid float 32: "+n)}const pa=Symbol("@bufbuild/protobuf/enum-type");function Lh(n){const e=n[pa];return re(e,"missing enum type on enum object"),e}function ma(n,e,A,t){n[pa]=Ba(e,A.map(i=>({no:i.no,name:i.name,localName:n[i.no]})))}function Ba(n,e,A){const t=Object.create(null),i=Object.create(null),r=[];for(const s of e){const o=va(s);r.push(o),t[s.name]=o,i[s.no]=o}return{typeName:n,values:r,findName(s){return t[s]},findNumber(s){return i[s]}}}function Dh(n,e,A){const t={};for(const i of e){const r=va(i);t[r.localName]=r.no,t[r.no]=r.localName}return ma(t,n,e),t}function va(n){return"localName"in n?n:Object.assign(Object.assign({},n),{localName:n.name})}class Or{equals(e){return this.getType().runtime.util.equals(this.getType(),this,e)}clone(){return this.getType().runtime.util.clone(this)}fromBinary(e,A){const t=this.getType(),i=t.runtime.bin,r=i.makeReadOptions(A);return i.readMessage(this,r.readerFactory(e),e.byteLength,r),this}fromJson(e,A){const t=this.getType(),i=t.runtime.json,r=i.makeReadOptions(A);return i.readMessage(t,e,r,this),this}fromJsonString(e,A){let t;try{t=JSON.parse(e)}catch(i){throw new Error("cannot decode ".concat(this.getType().typeName," from JSON: ").concat(i instanceof Error?i.message:String(i)))}return this.fromJson(t,A)}toBinary(e){const A=this.getType(),t=A.runtime.bin,i=t.makeWriteOptions(e),r=i.writerFactory();return t.writeMessage(this,r,i),r.finish()}toJson(e){const A=this.getType(),t=A.runtime.json,i=t.makeWriteOptions(e);return t.writeMessage(this,i)}toJsonString(e){var A;const t=this.toJson(e);return JSON.stringify(t,null,(A=e==null?void 0:e.prettySpaces)!==null&&A!==void 0?A:0)}toJSON(){return this.toJson({emitDefaultValues:!0})}getType(){return Object.getPrototypeOf(this).constructor}}function _h(n,e,A,t){var i;const r=(i=t==null?void 0:t.localName)!==null&&i!==void 0?i:e.substring(e.lastIndexOf(".")+1),s={[r]:function(o){n.util.initFields(this),n.util.initPartial(o,this)}}[r];return Object.setPrototypeOf(s.prototype,new Or),Object.assign(s,{runtime:n,typeName:e,fields:n.util.newFieldList(A),fromBinary(o,a){return new s().fromBinary(o,a)},fromJson(o,a){return new s().fromJson(o,a)},fromJsonString(o,a){return new s().fromJsonString(o,a)},equals(o,a){return n.util.equals(s,o,a)}}),s}function Hh(){let n=0,e=0;for(let t=0;t<28;t+=7){let i=this.buf[this.pos++];if(n|=(i&127)<<t,!(i&128))return this.assertBounds(),[n,e]}let A=this.buf[this.pos++];if(n|=(A&15)<<28,e=(A&112)>>4,!(A&128))return this.assertBounds(),[n,e];for(let t=3;t<=31;t+=7){let i=this.buf[this.pos++];if(e|=(i&127)<<t,!(i&128))return this.assertBounds(),[n,e]}throw new Error("invalid varint")}function Mr(n,e,A){for(let r=0;r<28;r=r+7){const s=n>>>r,o=!(!(s>>>7)&&e==0),a=(o?s|128:s)&255;if(A.push(a),!o)return}const t=n>>>28&15|(e&7)<<4,i=!!(e>>3);if(A.push((i?t|128:t)&255),!!i){for(let r=3;r<31;r=r+7){const s=e>>>r,o=!!(s>>>7),a=(o?s|128:s)&255;if(A.push(a),!o)return}A.push(e>>>31&1)}}const Zn=4294967296;function Ca(n){const e=n[0]==="-";e&&(n=n.slice(1));const A=1e6;let t=0,i=0;function r(s,o){const a=Number(n.slice(s,o));i*=A,t=t*A+a,t>=Zn&&(i=i+(t/Zn|0),t=t%Zn)}return r(-24,-18),r(-18,-12),r(-12,-6),r(-6),e?ya(t,i):Nr(t,i)}function Oh(n,e){let A=Nr(n,e);const t=A.hi&2147483648;t&&(A=ya(A.lo,A.hi));const i=wa(A.lo,A.hi);return t?"-"+i:i}function wa(n,e){if({lo:n,hi:e}=Mh(n,e),e<=2097151)return String(Zn*e+n);const A=n&16777215,t=(n>>>24|e<<8)&16777215,i=e>>16&65535;let r=A+t*6777216+i*6710656,s=t+i*8147497,o=i*2;const a=1e7;return r>=a&&(s+=Math.floor(r/a),r%=a),s>=a&&(o+=Math.floor(s/a),s%=a),o.toString()+ba(s)+ba(r)}function Mh(n,e){return{lo:n>>>0,hi:e>>>0}}function Nr(n,e){return{lo:n|0,hi:e|0}}function ya(n,e){return e=~e,n?n=~n+1:e+=1,Nr(n,e)}const ba=n=>{const e=String(n);return"0000000".slice(e.length)+e};function Ua(n,e){if(n>=0){for(;n>127;)e.push(n&127|128),n=n>>>7;e.push(n)}else{for(let A=0;A<9;A++)e.push(n&127|128),n=n>>7;e.push(1)}}function Nh(){let n=this.buf[this.pos++],e=n&127;if(!(n&128))return this.assertBounds(),e;if(n=this.buf[this.pos++],e|=(n&127)<<7,!(n&128))return this.assertBounds(),e;if(n=this.buf[this.pos++],e|=(n&127)<<14,!(n&128))return this.assertBounds(),e;if(n=this.buf[this.pos++],e|=(n&127)<<21,!(n&128))return this.assertBounds(),e;n=this.buf[this.pos++],e|=(n&15)<<28;for(let A=5;n&128&&A<10;A++)n=this.buf[this.pos++];if(n&128)throw new Error("invalid varint");return this.assertBounds(),e>>>0}function Kh(){const n=new DataView(new ArrayBuffer(8));if(typeof BigInt=="function"&&typeof n.getBigInt64=="function"&&typeof n.getBigUint64=="function"&&typeof n.setBigInt64=="function"&&typeof n.setBigUint64=="function"&&(typeof process!="object"||typeof process.env!="object"||process.env.BUF_BIGINT_DISABLE!=="1")){const i=BigInt("-9223372036854775808"),r=BigInt("9223372036854775807"),s=BigInt("0"),o=BigInt("18446744073709551615");return{zero:BigInt(0),supported:!0,parse(a){const c=typeof a=="bigint"?a:BigInt(a);if(c>r||c<i)throw new Error("int64 invalid: ".concat(a));return c},uParse(a){const c=typeof a=="bigint"?a:BigInt(a);if(c>o||c<s)throw new Error("uint64 invalid: ".concat(a));return c},enc(a){return n.setBigInt64(0,this.parse(a),!0),{lo:n.getInt32(0,!0),hi:n.getInt32(4,!0)}},uEnc(a){return n.setBigInt64(0,this.uParse(a),!0),{lo:n.getInt32(0,!0),hi:n.getInt32(4,!0)}},dec(a,c){return n.setInt32(0,a,!0),n.setInt32(4,c,!0),n.getBigInt64(0,!0)},uDec(a,c){return n.setInt32(0,a,!0),n.setInt32(4,c,!0),n.getBigUint64(0,!0)}}}const A=i=>re(/^-?[0-9]+$/.test(i),"int64 invalid: ".concat(i)),t=i=>re(/^[0-9]+$/.test(i),"uint64 invalid: ".concat(i));return{zero:"0",supported:!1,parse(i){return typeof i!="string"&&(i=i.toString()),A(i),i},uParse(i){return typeof i!="string"&&(i=i.toString()),t(i),i},enc(i){return typeof i!="string"&&(i=i.toString()),A(i),Ca(i)},uEnc(i){return typeof i!="string"&&(i=i.toString()),t(i),Ca(i)},dec(i,r){return Oh(i,r)},uDec(i,r){return wa(i,r)}}}const ne=Kh();var E;(function(n){n[n.DOUBLE=1]="DOUBLE",n[n.FLOAT=2]="FLOAT",n[n.INT64=3]="INT64",n[n.UINT64=4]="UINT64",n[n.INT32=5]="INT32",n[n.FIXED64=6]="FIXED64",n[n.FIXED32=7]="FIXED32",n[n.BOOL=8]="BOOL",n[n.STRING=9]="STRING",n[n.BYTES=12]="BYTES",n[n.UINT32=13]="UINT32",n[n.SFIXED32=15]="SFIXED32",n[n.SFIXED64=16]="SFIXED64",n[n.SINT32=17]="SINT32",n[n.SINT64=18]="SINT64"})(E||(E={}));var TA;(function(n){n[n.BIGINT=0]="BIGINT",n[n.STRING=1]="STRING"})(TA||(TA={}));function FA(n,e,A){if(e===A)return!0;if(n==E.BYTES){if(!(e instanceof Uint8Array)||!(A instanceof Uint8Array)||e.length!==A.length)return!1;for(let t=0;t<e.length;t++)if(e[t]!==A[t])return!1;return!0}switch(n){case E.UINT64:case E.FIXED64:case E.INT64:case E.SFIXED64:case E.SINT64:return e==A}return!1}function St(n,e){switch(n){case E.BOOL:return!1;case E.UINT64:case E.FIXED64:case E.INT64:case E.SFIXED64:case E.SINT64:return e==0?ne.zero:"0";case E.DOUBLE:case E.FLOAT:return 0;case E.BYTES:return new Uint8Array(0);case E.STRING:return"";default:return 0}}function Qa(n,e){switch(n){case E.BOOL:return e===!1;case E.STRING:return e==="";case E.BYTES:return e instanceof Uint8Array&&!e.byteLength;default:return e==0}}var ce;(function(n){n[n.Varint=0]="Varint",n[n.Bit64=1]="Bit64",n[n.LengthDelimited=2]="LengthDelimited",n[n.StartGroup=3]="StartGroup",n[n.EndGroup=4]="EndGroup",n[n.Bit32=5]="Bit32"})(ce||(ce={}));class Vh{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 i=0;i<this.chunks.length;i++)e+=this.chunks[i].length;let A=new Uint8Array(e),t=0;for(let i=0;i<this.chunks.length;i++)A.set(this.chunks[i],t),t+=this.chunks[i].length;return this.chunks=[],A}fork(){return this.stack.push({chunks:this.chunks,buf:this.buf}),this.chunks=[],this.buf=[],this}join(){let e=this.finish(),A=this.stack.pop();if(!A)throw new Error("invalid state, fork stack empty");return this.chunks=A.chunks,this.buf=A.buf,this.uint32(e.byteLength),this.raw(e)}tag(e,A){return this.uint32((e<<3|A)>>>0)}raw(e){return this.buf.length&&(this.chunks.push(new Uint8Array(this.buf)),this.buf=[]),this.chunks.push(e),this}uint32(e){for(Hr(e);e>127;)this.buf.push(e&127|128),e=e>>>7;return this.buf.push(e),this}int32(e){return qn(e),Ua(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 A=this.textEncoder.encode(e);return this.uint32(A.byteLength),this.raw(A)}float(e){ga(e);let A=new Uint8Array(4);return new DataView(A.buffer).setFloat32(0,e,!0),this.raw(A)}double(e){let A=new Uint8Array(8);return new DataView(A.buffer).setFloat64(0,e,!0),this.raw(A)}fixed32(e){Hr(e);let A=new Uint8Array(4);return new DataView(A.buffer).setUint32(0,e,!0),this.raw(A)}sfixed32(e){qn(e);let A=new Uint8Array(4);return new DataView(A.buffer).setInt32(0,e,!0),this.raw(A)}sint32(e){return qn(e),e=(e<<1^e>>31)>>>0,Ua(e,this.buf),this}sfixed64(e){let A=new Uint8Array(8),t=new DataView(A.buffer),i=ne.enc(e);return t.setInt32(0,i.lo,!0),t.setInt32(4,i.hi,!0),this.raw(A)}fixed64(e){let A=new Uint8Array(8),t=new DataView(A.buffer),i=ne.uEnc(e);return t.setInt32(0,i.lo,!0),t.setInt32(4,i.hi,!0),this.raw(A)}int64(e){let A=ne.enc(e);return Mr(A.lo,A.hi,this.buf),this}sint64(e){let A=ne.enc(e),t=A.hi>>31,i=A.lo<<1^t,r=(A.hi<<1|A.lo>>>31)^t;return Mr(i,r,this.buf),this}uint64(e){let A=ne.uEnc(e);return Mr(A.lo,A.hi,this.buf),this}}class Gh{constructor(e,A){this.varint64=Hh,this.uint32=Nh,this.buf=e,this.len=e.length,this.pos=0,this.view=new DataView(e.buffer,e.byteOffset,e.byteLength),this.textDecoder=A??new TextDecoder}tag(){let e=this.uint32(),A=e>>>3,t=e&7;if(A<=0||t<0||t>5)throw new Error("illegal tag: field no "+A+" wire type "+t);return[A,t]}skip(e,A){let t=this.pos;switch(e){case ce.Varint:for(;this.buf[this.pos++]&128;);break;case ce.Bit64:this.pos+=4;case ce.Bit32:this.pos+=4;break;case ce.LengthDelimited:let i=this.uint32();this.pos+=i;break;case ce.StartGroup:for(;;){const[r,s]=this.tag();if(s===ce.EndGroup){if(A!==void 0&&r!==A)throw new Error("invalid end group tag");break}this.skip(s,r)}break;default:throw new Error("cant skip wire type "+e)}return this.assertBounds(),this.buf.subarray(t,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 ne.dec(...this.varint64())}uint64(){return ne.uDec(...this.varint64())}sint64(){let[e,A]=this.varint64(),t=-(e&1);return e=(e>>>1|(A&1)<<31)^t,A=A>>>1^t,ne.dec(e,A)}bool(){let[e,A]=this.varint64();return e!==0||A!==0}fixed32(){return this.view.getUint32((this.pos+=4)-4,!0)}sfixed32(){return this.view.getInt32((this.pos+=4)-4,!0)}fixed64(){return ne.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return ne.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(),A=this.pos;return this.pos+=e,this.assertBounds(),this.buf.subarray(A,A+e)}string(){return this.textDecoder.decode(this.bytes())}}function jh(n,e,A,t){let i;return{typeName:e,extendee:A,get field(){if(!i){const r=typeof t=="function"?t():t;r.name=e.split(".").pop(),r.jsonName="[".concat(e,"]"),i=n.util.newFieldList([r]).list()[0]}return i},runtime:n}}function Ea(n){const e=n.field.localName,A=Object.create(null);return A[e]=Jh(n),[A,()=>A[e]]}function Jh(n){const e=n.field;if(e.repeated)return[];if(e.default!==void 0)return e.default;switch(e.kind){case"enum":return e.T.values[0].no;case"scalar":return St(e.T,e.L);case"message":const A=e.T,t=new A;return A.fieldWrapper?A.fieldWrapper.unwrapField(t):t;case"map":throw"map fields are not allowed to be extensions"}}function Wh(n,e){if(!e.repeated&&(e.kind=="enum"||e.kind=="scalar")){for(let A=n.length-1;A>=0;--A)if(n[A].no==e.no)return[n[A]];return[]}return n.filter(A=>A.no===e.no)}let gA="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),zn=[];for(let n=0;n<gA.length;n++)zn[gA[n].charCodeAt(0)]=n;zn["-".charCodeAt(0)]=gA.indexOf("+"),zn["_".charCodeAt(0)]=gA.indexOf("/");const Sa={dec(n){let e=n.length*3/4;n[n.length-2]=="="?e-=2:n[n.length-1]=="="&&(e-=1);let A=new Uint8Array(e),t=0,i=0,r,s=0;for(let o=0;o<n.length;o++){if(r=zn[n.charCodeAt(o)],r===void 0)switch(n[o]){case"=":i=0;case`
2
+ `:case"\r":case" ":case" ":continue;default:throw Error("invalid base64 string.")}switch(i){case 0:s=r,i=1;break;case 1:A[t++]=s<<2|(r&48)>>4,s=r,i=2;break;case 2:A[t++]=(s&15)<<4|(r&60)>>2,s=r,i=3;break;case 3:A[t++]=(s&3)<<6|r,i=0;break}}if(i==1)throw Error("invalid base64 string.");return A.subarray(0,t)},enc(n){let e="",A=0,t,i=0;for(let r=0;r<n.length;r++)switch(t=n[r],A){case 0:e+=gA[t>>2],i=(t&3)<<4,A=1;break;case 1:e+=gA[i|t>>4],i=(t&15)<<2,A=2;break;case 2:e+=gA[i|t>>6],e+=gA[t&63],A=0;break}return A&&(e+=gA[i],e+="=",A==1&&(e+="=")),e}};function Xh(n,e,A){Fa(e,n);const t=e.runtime.bin.makeReadOptions(A),i=Wh(n.getType().runtime.bin.listUnknownFields(n),e.field),[r,s]=Ea(e);for(const o of i)e.runtime.bin.readField(r,t.readerFactory(o.data),e.field,o.wireType,t);return s()}function $h(n,e,A,t){Fa(e,n);const i=e.runtime.bin.makeReadOptions(t),r=e.runtime.bin.makeWriteOptions(t);if(Ta(n,e)){const c=n.getType().runtime.bin.listUnknownFields(n).filter(l=>l.no!=e.field.no);n.getType().runtime.bin.discardUnknownFields(n);for(const l of c)n.getType().runtime.bin.onUnknownField(n,l.no,l.wireType,l.data)}const s=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,A,s,r);const a=i.readerFactory(s.finish());for(;a.pos<a.len;){const[c,l]=a.tag(),u=a.skip(l,c);n.getType().runtime.bin.onUnknownField(n,c,l,u)}}function Ta(n,e){const A=n.getType();return e.extendee.typeName===A.typeName&&!!A.runtime.bin.listUnknownFields(n).find(t=>t.no==e.field.no)}function Fa(n,e){re(n.extendee.typeName==e.getType().typeName,"extension ".concat(n.typeName," can only be applied to message ").concat(n.extendee.typeName))}function ka(n,e){const A=n.localName;if(n.repeated)return e[A].length>0;if(n.oneof)return e[n.oneof.localName].case===A;switch(n.kind){case"enum":case"scalar":return n.opt||n.req?e[A]!==void 0:n.kind=="enum"?e[A]!==n.T.values[0].no:!Qa(n.T,e[A]);case"message":return e[A]!==void 0;case"map":return Object.keys(e[A]).length>0}}function Ia(n,e){const A=n.localName,t=!n.opt&&!n.req;if(n.repeated)e[A]=[];else if(n.oneof)e[n.oneof.localName]={case:void 0};else switch(n.kind){case"map":e[A]={};break;case"enum":e[A]=t?n.T.values[0].no:void 0;break;case"scalar":e[A]=t?St(n.T,n.L):void 0;break;case"message":e[A]=void 0;break}}function it(n,e){if(n===null||typeof n!="object"||!Object.getOwnPropertyNames(Or.prototype).every(t=>t in n&&typeof n[t]=="function"))return!1;const A=n.getType();return A===null||typeof A!="function"||!("typeName"in A)||typeof A.typeName!="string"?!1:e===void 0?!0:A.typeName==e.typeName}function Ra(n,e){return it(e)||!n.fieldWrapper?e:n.fieldWrapper.wrapField(e)}E.DOUBLE,E.FLOAT,E.INT64,E.UINT64,E.INT32,E.UINT32,E.BOOL,E.STRING,E.BYTES;const xa={ignoreUnknownFields:!1},Pa={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0};function Yh(n){return n?Object.assign(Object.assign({},xa),n):xa}function qh(n){return n?Object.assign(Object.assign({},Pa),n):Pa}const ei=Symbol(),Ai=Symbol();function Zh(){return{makeReadOptions:Yh,makeWriteOptions:qh,readMessage(n,e,A,t){if(e==null||Array.isArray(e)||typeof e!="object")throw new Error("cannot decode message ".concat(n.typeName," from JSON: ").concat(iA(e)));t=t??new n;const i=new Map,r=A.typeRegistry;for(const[s,o]of Object.entries(e)){const a=n.fields.findJsonName(s);if(a){if(a.oneof){if(o===null&&a.kind=="scalar")continue;const c=i.get(a.oneof);if(c!==void 0)throw new Error("cannot decode message ".concat(n.typeName,' from JSON: multiple keys for oneof "').concat(a.oneof.name,'" present: "').concat(c,'", "').concat(s,'"'));i.set(a.oneof,s)}La(t,o,a,A,n)}else{let c=!1;if(r!=null&&r.findExtension&&s.startsWith("[")&&s.endsWith("]")){const l=r.findExtension(s.substring(1,s.length-1));if(l&&l.extendee.typeName==n.typeName){c=!0;const[u,d]=Ea(l);La(u,o,l.field,A,l),$h(t,l,d(),A)}}if(!c&&!A.ignoreUnknownFields)throw new Error("cannot decode message ".concat(n.typeName,' from JSON: key "').concat(s,'" is unknown'))}}return t},writeMessage(n,e){const A=n.getType(),t={};let i;try{for(i of A.fields.byNumber()){if(!ka(i,n)){if(i.req)throw"required field not set";if(!e.emitDefaultValues||!ef(i))continue}const s=i.oneof?n[i.oneof.localName].value:n[i.localName],o=Da(i,s,e);o!==void 0&&(t[e.useProtoFieldName?i.name:i.jsonName]=o)}const r=e.typeRegistry;if(r!=null&&r.findExtensionFor)for(const s of A.runtime.bin.listUnknownFields(n)){const o=r.findExtensionFor(A.typeName,s.no);if(o&&Ta(n,o)){const a=Xh(n,o,e),c=Da(o.field,a,e);c!==void 0&&(t[o.field.jsonName]=c)}}}catch(r){const s=i?"cannot encode field ".concat(A.typeName,".").concat(i.name," to JSON"):"cannot encode message ".concat(A.typeName," to JSON"),o=r instanceof Error?r.message:String(r);throw new Error(s+(o.length>0?": ".concat(o):""))}return t},readScalar(n,e,A){return sn(n,e,A??TA.BIGINT,!0)},writeScalar(n,e,A){if(e!==void 0&&(A||Qa(n,e)))return ti(n,e)},debug:iA}}function iA(n){if(n===null)return"null";switch(typeof n){case"object":return Array.isArray(n)?"array":"object";case"string":return n.length>100?"string":'"'.concat(n.split('"').join('\\"'),'"');default:return String(n)}}function La(n,e,A,t,i){let r=A.localName;if(A.repeated){if(re(A.kind!="map"),e===null)return;if(!Array.isArray(e))throw new Error("cannot decode field ".concat(i.typeName,".").concat(A.name," from JSON: ").concat(iA(e)));const s=n[r];for(const o of e){if(o===null)throw new Error("cannot decode field ".concat(i.typeName,".").concat(A.name," from JSON: ").concat(iA(o)));switch(A.kind){case"message":s.push(A.T.fromJson(o,t));break;case"enum":const a=Kr(A.T,o,t.ignoreUnknownFields,!0);a!==Ai&&s.push(a);break;case"scalar":try{s.push(sn(A.T,o,A.L,!0))}catch(c){let l="cannot decode field ".concat(i.typeName,".").concat(A.name," from JSON: ").concat(iA(o));throw c instanceof Error&&c.message.length>0&&(l+=": ".concat(c.message)),new Error(l)}break}}}else if(A.kind=="map"){if(e===null)return;if(typeof e!="object"||Array.isArray(e))throw new Error("cannot decode field ".concat(i.typeName,".").concat(A.name," from JSON: ").concat(iA(e)));const s=n[r];for(const[o,a]of Object.entries(e)){if(a===null)throw new Error("cannot decode field ".concat(i.typeName,".").concat(A.name," from JSON: map value null"));let c;try{c=zh(A.K,o)}catch(l){let u="cannot decode map key for field ".concat(i.typeName,".").concat(A.name," from JSON: ").concat(iA(e));throw l instanceof Error&&l.message.length>0&&(u+=": ".concat(l.message)),new Error(u)}switch(A.V.kind){case"message":s[c]=A.V.T.fromJson(a,t);break;case"enum":const l=Kr(A.V.T,a,t.ignoreUnknownFields,!0);l!==Ai&&(s[c]=l);break;case"scalar":try{s[c]=sn(A.V.T,a,TA.BIGINT,!0)}catch(u){let d="cannot decode map value for field ".concat(i.typeName,".").concat(A.name," from JSON: ").concat(iA(e));throw u instanceof Error&&u.message.length>0&&(d+=": ".concat(u.message)),new Error(d)}break}}}else switch(A.oneof&&(n=n[A.oneof.localName]={case:r},r="value"),A.kind){case"message":const s=A.T;if(e===null&&s.typeName!="google.protobuf.Value")return;let o=n[r];it(o)?o.fromJson(e,t):(n[r]=o=s.fromJson(e,t),s.fieldWrapper&&!A.oneof&&(n[r]=s.fieldWrapper.unwrapField(o)));break;case"enum":const a=Kr(A.T,e,t.ignoreUnknownFields,!1);switch(a){case ei:Ia(A,n);break;case Ai:break;default:n[r]=a;break}break;case"scalar":try{const c=sn(A.T,e,A.L,!1);switch(c){case ei:Ia(A,n);break;default:n[r]=c;break}}catch(c){let l="cannot decode field ".concat(i.typeName,".").concat(A.name," from JSON: ").concat(iA(e));throw c instanceof Error&&c.message.length>0&&(l+=": ".concat(c.message)),new Error(l)}break}}function zh(n,e){if(n===E.BOOL)switch(e){case"true":e=!0;break;case"false":e=!1;break}return sn(n,e,TA.BIGINT,!0).toString()}function sn(n,e,A,t){if(e===null)return t?St(n,A):ei;switch(n){case E.DOUBLE:case E.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 i=Number(e);if(Number.isNaN(i)||!Number.isFinite(i))break;return n==E.FLOAT&&ga(i),i;case E.INT32:case E.FIXED32:case E.SFIXED32:case E.SINT32:case E.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 n==E.UINT32||n==E.FIXED32?Hr(r):qn(r),r;case E.INT64:case E.SFIXED64:case E.SINT64:if(typeof e!="number"&&typeof e!="string")break;const s=ne.parse(e);return A?s.toString():s;case E.FIXED64:case E.UINT64:if(typeof e!="number"&&typeof e!="string")break;const o=ne.uParse(e);return A?o.toString():o;case E.BOOL:if(typeof e!="boolean")break;return e;case E.STRING:if(typeof e!="string")break;try{encodeURIComponent(e)}catch{throw new Error("invalid UTF8")}return e;case E.BYTES:if(e==="")return new Uint8Array(0);if(typeof e!="string")break;return Sa.dec(e)}throw new Error}function Kr(n,e,A,t){if(e===null)return n.typeName=="google.protobuf.NullValue"?0:t?n.values[0].no:ei;switch(typeof e){case"number":if(Number.isInteger(e))return e;break;case"string":const i=n.findName(e);if(i!==void 0)return i.no;if(A)return Ai;break}throw new Error("cannot decode enum ".concat(n.typeName," from JSON: ").concat(iA(e)))}function ef(n){return n.repeated||n.kind=="map"?!0:!(n.oneof||n.kind=="message"||n.opt||n.req)}function Da(n,e,A){if(n.kind=="map"){re(typeof e=="object"&&e!=null);const t={},i=Object.entries(e);switch(n.V.kind){case"scalar":for(const[s,o]of i)t[s.toString()]=ti(n.V.T,o);break;case"message":for(const[s,o]of i)t[s.toString()]=o.toJson(A);break;case"enum":const r=n.V.T;for(const[s,o]of i)t[s.toString()]=Vr(r,o,A.enumAsInteger);break}return A.emitDefaultValues||i.length>0?t:void 0}if(n.repeated){re(Array.isArray(e));const t=[];switch(n.kind){case"scalar":for(let i=0;i<e.length;i++)t.push(ti(n.T,e[i]));break;case"enum":for(let i=0;i<e.length;i++)t.push(Vr(n.T,e[i],A.enumAsInteger));break;case"message":for(let i=0;i<e.length;i++)t.push(e[i].toJson(A));break}return A.emitDefaultValues||t.length>0?t:void 0}switch(n.kind){case"scalar":return ti(n.T,e);case"enum":return Vr(n.T,e,A.enumAsInteger);case"message":return Ra(n.T,e).toJson(A)}}function Vr(n,e,A){var t;if(re(typeof e=="number"),n.typeName=="google.protobuf.NullValue")return null;if(A)return e;const i=n.findNumber(e);return(t=i==null?void 0:i.name)!==null&&t!==void 0?t:e}function ti(n,e){switch(n){case E.INT32:case E.SFIXED32:case E.SINT32:case E.FIXED32:case E.UINT32:return re(typeof e=="number"),e;case E.FLOAT:case E.DOUBLE:return re(typeof e=="number"),Number.isNaN(e)?"NaN":e===Number.POSITIVE_INFINITY?"Infinity":e===Number.NEGATIVE_INFINITY?"-Infinity":e;case E.STRING:return re(typeof e=="string"),e;case E.BOOL:return re(typeof e=="boolean"),e;case E.UINT64:case E.FIXED64:case E.INT64:case E.SFIXED64:case E.SINT64:return re(typeof e=="bigint"||typeof e=="string"||typeof e=="number"),e.toString();case E.BYTES:return re(e instanceof Uint8Array),Sa.enc(e)}}const Tt=Symbol("@bufbuild/protobuf/unknown-fields"),_a={readUnknownFields:!0,readerFactory:n=>new Gh(n)},Ha={writeUnknownFields:!0,writerFactory:()=>new Vh};function Af(n){return n?Object.assign(Object.assign({},_a),n):_a}function tf(n){return n?Object.assign(Object.assign({},Ha),n):Ha}function nf(){return{makeReadOptions:Af,makeWriteOptions:tf,listUnknownFields(n){var e;return(e=n[Tt])!==null&&e!==void 0?e:[]},discardUnknownFields(n){delete n[Tt]},writeUnknownFields(n,e){const t=n[Tt];if(t)for(const i of t)e.tag(i.no,i.wireType).raw(i.data)},onUnknownField(n,e,A,t){const i=n;Array.isArray(i[Tt])||(i[Tt]=[]),i[Tt].push({no:e,wireType:A,data:t})},readMessage(n,e,A,t,i){const r=n.getType(),s=i?e.len:e.pos+A;let o,a;for(;e.pos<s&&([o,a]=e.tag(),!(i===!0&&a==ce.EndGroup));){const c=r.fields.find(o);if(!c){const l=e.skip(a,o);t.readUnknownFields&&this.onUnknownField(n,o,a,l);continue}Oa(n,e,c,a,t)}if(i&&(a!=ce.EndGroup||o!==A))throw new Error("invalid end group tag")},readField:Oa,writeMessage(n,e,A){const t=n.getType();for(const i of t.fields.byNumber()){if(!ka(i,n)){if(i.req)throw new Error("cannot encode field ".concat(t.typeName,".").concat(i.name," to binary: required field not set"));continue}const r=i.oneof?n[i.oneof.localName].value:n[i.localName];Ma(i,r,e,A)}return A.writeUnknownFields&&this.writeUnknownFields(n,e),e},writeField(n,e,A,t){e!==void 0&&Ma(n,e,A,t)}}}function Oa(n,e,A,t,i){let{repeated:r,localName:s}=A;switch(A.oneof&&(n=n[A.oneof.localName],n.case!=s&&delete n.value,n.case=s,s="value"),A.kind){case"scalar":case"enum":const o=A.kind=="enum"?E.INT32:A.T;let a=ii;if(A.kind=="scalar"&&A.L>0&&(a=sf),r){let d=n[s];if(t==ce.LengthDelimited&&o!=E.STRING&&o!=E.BYTES){let f=e.uint32()+e.pos;for(;e.pos<f;)d.push(a(e,o))}else d.push(a(e,o))}else n[s]=a(e,o);break;case"message":const c=A.T;r?n[s].push(ni(e,new c,i,A)):it(n[s])?ni(e,n[s],i,A):(n[s]=ni(e,new c,i,A),c.fieldWrapper&&!A.oneof&&!A.repeated&&(n[s]=c.fieldWrapper.unwrapField(n[s])));break;case"map":let[l,u]=rf(A,e,i);n[s][l]=u;break}}function ni(n,e,A,t){const i=e.getType().runtime.bin,r=t==null?void 0:t.delimited;return i.readMessage(e,n,r?t.no:n.uint32(),A,r),e}function rf(n,e,A){const t=e.uint32(),i=e.pos+t;let r,s;for(;e.pos<i;){const[o]=e.tag();switch(o){case 1:r=ii(e,n.K);break;case 2:switch(n.V.kind){case"scalar":s=ii(e,n.V.T);break;case"enum":s=e.int32();break;case"message":s=ni(e,new n.V.T,A,void 0);break}break}}if(r===void 0&&(r=St(n.K,TA.BIGINT)),typeof r!="string"&&typeof r!="number"&&(r=r.toString()),s===void 0)switch(n.V.kind){case"scalar":s=St(n.V.T,TA.BIGINT);break;case"enum":s=n.V.T.values[0].no;break;case"message":s=new n.V.T;break}return[r,s]}function sf(n,e){const A=ii(n,e);return typeof A=="bigint"?A.toString():A}function ii(n,e){switch(e){case E.STRING:return n.string();case E.BOOL:return n.bool();case E.DOUBLE:return n.double();case E.FLOAT:return n.float();case E.INT32:return n.int32();case E.INT64:return n.int64();case E.UINT64:return n.uint64();case E.FIXED64:return n.fixed64();case E.BYTES:return n.bytes();case E.FIXED32:return n.fixed32();case E.SFIXED32:return n.sfixed32();case E.SFIXED64:return n.sfixed64();case E.SINT64:return n.sint64();case E.UINT32:return n.uint32();case E.SINT32:return n.sint32()}}function Ma(n,e,A,t){re(e!==void 0);const i=n.repeated;switch(n.kind){case"scalar":case"enum":let r=n.kind=="enum"?E.INT32:n.T;if(i)if(re(Array.isArray(e)),n.packed)af(A,r,n.no,e);else for(const s of e)on(A,r,n.no,s);else on(A,r,n.no,e);break;case"message":if(i){re(Array.isArray(e));for(const s of e)Na(A,t,n,s)}else Na(A,t,n,e);break;case"map":re(typeof e=="object"&&e!=null);for(const[s,o]of Object.entries(e))of(A,t,n,s,o);break}}function of(n,e,A,t,i){n.tag(A.no,ce.LengthDelimited),n.fork();let r=t;switch(A.K){case E.INT32:case E.FIXED32:case E.UINT32:case E.SFIXED32:case E.SINT32:r=Number.parseInt(t);break;case E.BOOL:re(t=="true"||t=="false"),r=t=="true";break}switch(on(n,A.K,1,r),A.V.kind){case"scalar":on(n,A.V.T,2,i);break;case"enum":on(n,E.INT32,2,i);break;case"message":re(i!==void 0),n.tag(2,ce.LengthDelimited).bytes(i.toBinary(e));break}n.join()}function Na(n,e,A,t){const i=Ra(A.T,t);A.delimited?n.tag(A.no,ce.StartGroup).raw(i.toBinary(e)).tag(A.no,ce.EndGroup):n.tag(A.no,ce.LengthDelimited).bytes(i.toBinary(e))}function on(n,e,A,t){re(t!==void 0);let[i,r]=Ka(e);n.tag(A,i)[r](t)}function af(n,e,A,t){if(!t.length)return;n.tag(A,ce.LengthDelimited).fork();let[,i]=Ka(e);for(let r=0;r<t.length;r++)n[i](t[r]);n.join()}function Ka(n){let e=ce.Varint;switch(n){case E.BYTES:case E.STRING:e=ce.LengthDelimited;break;case E.DOUBLE:case E.FIXED64:case E.SFIXED64:e=ce.Bit64;break;case E.FIXED32:case E.SFIXED32:case E.FLOAT:e=ce.Bit32;break}const A=E[n].toLowerCase();return[e,A]}function cf(){return{setEnumType:ma,initPartial(n,e){if(n===void 0)return;const A=e.getType();for(const t of A.fields.byMember()){const i=t.localName,r=e,s=n;if(s[i]!=null)switch(t.kind){case"oneof":const o=s[i].case;if(o===void 0)continue;const a=t.findField(o);let c=s[i].value;a&&a.kind=="message"&&!it(c,a.T)?c=new a.T(c):a&&a.kind==="scalar"&&a.T===E.BYTES&&(c=an(c)),r[i]={case:o,value:c};break;case"scalar":case"enum":let l=s[i];t.T===E.BYTES&&(l=t.repeated?l.map(an):an(l)),r[i]=l;break;case"map":switch(t.V.kind){case"scalar":case"enum":if(t.V.T===E.BYTES)for(const[h,f]of Object.entries(s[i]))r[i][h]=an(f);else Object.assign(r[i],s[i]);break;case"message":const d=t.V.T;for(const h of Object.keys(s[i])){let f=s[i][h];d.fieldWrapper||(f=new d(f)),r[i][h]=f}break}break;case"message":const u=t.T;if(t.repeated)r[i]=s[i].map(d=>it(d,u)?d:new u(d));else{const d=s[i];u.fieldWrapper?u.typeName==="google.protobuf.BytesValue"?r[i]=an(d):r[i]=d:r[i]=it(d,u)?d:new u(d)}break}}},equals(n,e,A){return e===A?!0:!e||!A?!1:n.fields.byMember().every(t=>{const i=e[t.localName],r=A[t.localName];if(t.repeated){if(i.length!==r.length)return!1;switch(t.kind){case"message":return i.every((s,o)=>t.T.equals(s,r[o]));case"scalar":return i.every((s,o)=>FA(t.T,s,r[o]));case"enum":return i.every((s,o)=>FA(E.INT32,s,r[o]))}throw new Error("repeated cannot contain ".concat(t.kind))}switch(t.kind){case"message":return t.T.equals(i,r);case"enum":return FA(E.INT32,i,r);case"scalar":return FA(t.T,i,r);case"oneof":if(i.case!==r.case)return!1;const s=t.findField(i.case);if(s===void 0)return!0;switch(s.kind){case"message":return s.T.equals(i.value,r.value);case"enum":return FA(E.INT32,i.value,r.value);case"scalar":return FA(s.T,i.value,r.value)}throw new Error("oneof cannot contain ".concat(s.kind));case"map":const o=Object.keys(i).concat(Object.keys(r));switch(t.V.kind){case"message":const a=t.V.T;return o.every(l=>a.equals(i[l],r[l]));case"enum":return o.every(l=>FA(E.INT32,i[l],r[l]));case"scalar":const c=t.V.T;return o.every(l=>FA(c,i[l],r[l]))}break}})},clone(n){const e=n.getType(),A=new e,t=A;for(const i of e.fields.byMember()){const r=n[i.localName];let s;if(i.repeated)s=r.map(ri);else if(i.kind=="map"){s=t[i.localName];for(const[o,a]of Object.entries(r))s[o]=ri(a)}else i.kind=="oneof"?s=i.findField(r.case)?{case:r.case,value:ri(r.value)}:{case:void 0}:s=ri(r);t[i.localName]=s}for(const i of e.runtime.bin.listUnknownFields(n))e.runtime.bin.onUnknownField(t,i.no,i.wireType,i.data);return A}}}function ri(n){if(n===void 0)return n;if(it(n))return n.clone();if(n instanceof Uint8Array){const e=new Uint8Array(n.byteLength);return e.set(n),e}return n}function an(n){return n instanceof Uint8Array?n:new Uint8Array(n)}function lf(n,e,A){return{syntax:n,json:Zh(),bin:nf(),util:Object.assign(Object.assign({},cf()),{newFieldList:e,initFields:A}),makeMessageType(t,i,r){return _h(this,t,i,r)},makeEnum:Dh,makeEnumType:Ba,getEnumType:Lh,makeExtension(t,i,r){return jh(this,t,i,r)}}}class uf{constructor(e,A){this._fields=e,this._normalizer=A}findJsonName(e){if(!this.jsonNames){const A={};for(const t of this.list())A[t.jsonName]=A[t.name]=t;this.jsonNames=A}return this.jsonNames[e]}find(e){if(!this.numbers){const A={};for(const t of this.list())A[t.no]=t;this.numbers=A}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,A)=>e.no-A.no)),this.numbersAsc}byMember(){if(!this.members){this.members=[];const e=this.members;let A;for(const t of this.list())t.oneof?t.oneof!==A&&(A=t.oneof,e.push(A)):e.push(t)}return this.members}}function Va(n,e){const A=Ga(n);return e?A:mf(pf(A))}function df(n){return Va(n,!1)}const hf=Ga;function Ga(n){let e=!1;const A=[];for(let t=0;t<n.length;t++){let i=n.charAt(t);switch(i){case"_":e=!0;break;case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":A.push(i),e=!1;break;default:e&&(e=!1,i=i.toUpperCase()),A.push(i);break}}return A.join("")}const ff=new Set(["constructor","toString","toJSON","valueOf"]),gf=new Set(["getType","clone","equals","fromBinary","fromJson","fromJsonString","toBinary","toJson","toJsonString","toObject"]),ja=n=>"".concat(n,"$"),pf=n=>gf.has(n)?ja(n):n,mf=n=>ff.has(n)?ja(n):n;class Bf{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=df(e)}addField(e){re(e.oneof===this,"field ".concat(e.name," not one of ").concat(this.name)),this.fields.push(e)}findField(e){if(!this._lookup){this._lookup=Object.create(null);for(let A=0;A<this.fields.length;A++)this._lookup[this.fields[A].localName]=this.fields[A]}return this._lookup[e]}}function vf(n,e){var A,t,i,r,s,o;const a=[];let c;for(const l of typeof n=="function"?n():n){const u=l;if(u.localName=Va(l.name,l.oneof!==void 0),u.jsonName=(A=l.jsonName)!==null&&A!==void 0?A:hf(l.name),u.repeated=(t=l.repeated)!==null&&t!==void 0?t:!1,l.kind=="scalar"&&(u.L=(i=l.L)!==null&&i!==void 0?i:TA.BIGINT),u.delimited=(r=l.delimited)!==null&&r!==void 0?r:!1,u.req=(s=l.req)!==null&&s!==void 0?s:!1,u.opt=(o=l.opt)!==null&&o!==void 0?o:!1,l.packed===void 0&&(u.packed=l.kind=="enum"||l.kind=="scalar"&&l.T!=E.BYTES&&l.T!=E.STRING),l.oneof!==void 0){const d=typeof l.oneof=="string"?l.oneof:l.oneof.name;(!c||c.name!=d)&&(c=new Bf(d)),u.oneof=c,c.addField(u)}a.push(u)}return a}const b=lf("proto3",n=>new uf(n,e=>vf(e)),n=>{for(const e of n.getType().fields.byMember()){if(e.opt)continue;const A=e.localName,t=n;if(e.repeated){t[A]=[];continue}switch(e.kind){case"oneof":t[A]={case:void 0};break;case"enum":t[A]=0;break;case"map":t[A]={};break;case"scalar":t[A]=St(e.T,e.L);break}}});class Fe extends Or{constructor(e){super(),this.seconds=ne.zero,this.nanos=0,b.util.initPartial(e,this)}fromJson(e,A){if(typeof e!="string")throw new Error("cannot decode google.protobuf.Timestamp from JSON: ".concat(b.json.debug(e)));const t=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(!t)throw new Error("cannot decode google.protobuf.Timestamp from JSON: invalid RFC 3339 string");const i=Date.parse(t[1]+"-"+t[2]+"-"+t[3]+"T"+t[4]+":"+t[5]+":"+t[6]+(t[8]?t[8]:"Z"));if(Number.isNaN(i))throw new Error("cannot decode google.protobuf.Timestamp from JSON: invalid RFC 3339 string");if(i<Date.parse("0001-01-01T00:00:00Z")||i>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=ne.parse(i/1e3),this.nanos=0,t[7]&&(this.nanos=parseInt("1"+t[7]+"0".repeat(9-t[7].length))-1e9),this}toJson(e){const A=Number(this.seconds)*1e3;if(A<Date.parse("0001-01-01T00:00:00Z")||A>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 t="Z";if(this.nanos>0){const i=(this.nanos+1e9).toString().substring(1);i.substring(3)==="000000"?t="."+i.substring(0,3)+"Z":i.substring(6)==="000"?t="."+i.substring(0,6)+"Z":t="."+i+"Z"}return new Date(A).toISOString().replace(".000Z",t)}toDate(){return new Date(Number(this.seconds)*1e3+Math.ceil(this.nanos/1e6))}static now(){return Fe.fromDate(new Date)}static fromDate(e){const A=e.getTime();return new Fe({seconds:ne.parse(Math.floor(A/1e3)),nanos:A%1e3*1e6})}static fromBinary(e,A){return new Fe().fromBinary(e,A)}static fromJson(e,A){return new Fe().fromJson(e,A)}static fromJsonString(e,A){return new Fe().fromJsonString(e,A)}static equals(e,A){return b.util.equals(Fe,e,A)}}Fe.runtime=b,Fe.typeName="google.protobuf.Timestamp",Fe.fields=b.util.newFieldList(()=>[{no:1,name:"seconds",kind:"scalar",T:3},{no:2,name:"nanos",kind:"scalar",T:5}]);const Cf=b.makeMessageType("livekit.MetricsBatch",()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:Fe},{no:3,name:"str_data",kind:"scalar",T:9,repeated:!0},{no:4,name:"time_series",kind:"message",T:wf,repeated:!0},{no:5,name:"events",kind:"message",T:bf,repeated:!0}]),wf=b.makeMessageType("livekit.TimeSeriesMetric",()=>[{no:1,name:"label",kind:"scalar",T:13},{no:2,name:"participant_identity",kind:"scalar",T:13},{no:3,name:"track_sid",kind:"scalar",T:13},{no:4,name:"samples",kind:"message",T:yf,repeated:!0},{no:5,name:"rid",kind:"scalar",T:13}]),yf=b.makeMessageType("livekit.MetricSample",()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:Fe},{no:3,name:"value",kind:"scalar",T:2}]),bf=b.makeMessageType("livekit.EventMetric",()=>[{no:1,name:"label",kind:"scalar",T:13},{no:2,name:"participant_identity",kind:"scalar",T:13},{no:3,name:"track_sid",kind:"scalar",T:13},{no:4,name:"start_timestamp_ms",kind:"scalar",T:3},{no:5,name:"end_timestamp_ms",kind:"scalar",T:3,opt:!0},{no:6,name:"normalized_start_timestamp",kind:"message",T:Fe},{no:7,name:"normalized_end_timestamp",kind:"message",T:Fe,opt:!0},{no:8,name:"metadata",kind:"scalar",T:9},{no:9,name:"rid",kind:"scalar",T:13}]),Ja=b.makeEnum("livekit.BackupCodecPolicy",[{no:0,name:"PREFER_REGRESSION"},{no:1,name:"SIMULCAST"},{no:2,name:"REGRESSION"}]),Je=b.makeEnum("livekit.TrackType",[{no:0,name:"AUDIO"},{no:1,name:"VIDEO"},{no:2,name:"DATA"}]),de=b.makeEnum("livekit.TrackSource",[{no:0,name:"UNKNOWN"},{no:1,name:"CAMERA"},{no:2,name:"MICROPHONE"},{no:3,name:"SCREEN_SHARE"},{no:4,name:"SCREEN_SHARE_AUDIO"}]),Ft=b.makeEnum("livekit.VideoQuality",[{no:0,name:"LOW"},{no:1,name:"MEDIUM"},{no:2,name:"HIGH"},{no:3,name:"OFF"}]),cn=b.makeEnum("livekit.ConnectionQuality",[{no:0,name:"POOR"},{no:1,name:"GOOD"},{no:2,name:"EXCELLENT"},{no:3,name:"LOST"}]),ln=b.makeEnum("livekit.ClientConfigSetting",[{no:0,name:"UNSET"},{no:1,name:"DISABLED"},{no:2,name:"ENABLED"}]),We=b.makeEnum("livekit.DisconnectReason",[{no:0,name:"UNKNOWN_REASON"},{no:1,name:"CLIENT_INITIATED"},{no:2,name:"DUPLICATE_IDENTITY"},{no:3,name:"SERVER_SHUTDOWN"},{no:4,name:"PARTICIPANT_REMOVED"},{no:5,name:"ROOM_DELETED"},{no:6,name:"STATE_MISMATCH"},{no:7,name:"JOIN_FAILURE"},{no:8,name:"MIGRATION"},{no:9,name:"SIGNAL_CLOSE"},{no:10,name:"ROOM_CLOSED"},{no:11,name:"USER_UNAVAILABLE"},{no:12,name:"USER_REJECTED"},{no:13,name:"SIP_TRUNK_FAILURE"},{no:14,name:"CONNECTION_TIMEOUT"}]),kt=b.makeEnum("livekit.ReconnectReason",[{no:0,name:"RR_UNKNOWN"},{no:1,name:"RR_SIGNAL_DISCONNECTED"},{no:2,name:"RR_PUBLISHER_FAILED"},{no:3,name:"RR_SUBSCRIBER_FAILED"},{no:4,name:"RR_SWITCH_CANDIDATE"}]),Uf=b.makeEnum("livekit.SubscriptionError",[{no:0,name:"SE_UNKNOWN"},{no:1,name:"SE_CODEC_UNSUPPORTED"},{no:2,name:"SE_TRACK_NOTFOUND"}]),Xe=b.makeEnum("livekit.AudioTrackFeature",[{no:0,name:"TF_STEREO"},{no:1,name:"TF_NO_DTX"},{no:2,name:"TF_AUTO_GAIN_CONTROL"},{no:3,name:"TF_ECHO_CANCELLATION"},{no:4,name:"TF_NOISE_SUPPRESSION"},{no:5,name:"TF_ENHANCED_NOISE_CANCELLATION"},{no:6,name:"TF_PRECONNECT_BUFFER"}]),si=b.makeMessageType("livekit.Room",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",T:9},{no:3,name:"empty_timeout",kind:"scalar",T:13},{no:14,name:"departure_timeout",kind:"scalar",T:13},{no:4,name:"max_participants",kind:"scalar",T:13},{no:5,name:"creation_time",kind:"scalar",T:3},{no:15,name:"creation_time_ms",kind:"scalar",T:3},{no:6,name:"turn_password",kind:"scalar",T:9},{no:7,name:"enabled_codecs",kind:"message",T:oi,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:rc}]),oi=b.makeMessageType("livekit.Codec",()=>[{no:1,name:"mime",kind:"scalar",T:9},{no:2,name:"fmtp_line",kind:"scalar",T:9}]),Qf=b.makeMessageType("livekit.ParticipantPermission",()=>[{no:1,name:"can_subscribe",kind:"scalar",T:8},{no:2,name:"can_publish",kind:"scalar",T:8},{no:3,name:"can_publish_data",kind:"scalar",T:8},{no:9,name:"can_publish_sources",kind:"enum",T:b.getEnumType(de),repeated:!0},{no:7,name:"hidden",kind:"scalar",T:8},{no:8,name:"recorder",kind:"scalar",T:8},{no:10,name:"can_update_metadata",kind:"scalar",T:8},{no:11,name:"agent",kind:"scalar",T:8},{no:12,name:"can_subscribe_metrics",kind:"scalar",T:8}]),rt=b.makeMessageType("livekit.ParticipantInfo",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"identity",kind:"scalar",T:9},{no:3,name:"state",kind:"enum",T:b.getEnumType(It)},{no:4,name:"tracks",kind:"message",T:Rt,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:Qf},{no:12,name:"region",kind:"scalar",T:9},{no:13,name:"is_publisher",kind:"scalar",T:8},{no:14,name:"kind",kind:"enum",T:b.getEnumType(ai)},{no:15,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:16,name:"disconnect_reason",kind:"enum",T:b.getEnumType(We)},{no:18,name:"kind_details",kind:"enum",T:b.getEnumType(Ef),repeated:!0}]),It=b.makeEnum("livekit.ParticipantInfo.State",[{no:0,name:"JOINING"},{no:1,name:"JOINED"},{no:2,name:"ACTIVE"},{no:3,name:"DISCONNECTED"}]),ai=b.makeEnum("livekit.ParticipantInfo.Kind",[{no:0,name:"STANDARD"},{no:1,name:"INGRESS"},{no:2,name:"EGRESS"},{no:3,name:"SIP"},{no:4,name:"AGENT"}]),Ef=b.makeEnum("livekit.ParticipantInfo.KindDetail",[{no:0,name:"CLOUD_AGENT"},{no:1,name:"FORWARDED"}]),He=b.makeEnum("livekit.Encryption.Type",[{no:0,name:"NONE"},{no:1,name:"GCM"},{no:2,name:"CUSTOM"}]),Sf=b.makeMessageType("livekit.SimulcastCodecInfo",()=>[{no:1,name:"mime_type",kind:"scalar",T:9},{no:2,name:"mid",kind:"scalar",T:9},{no:3,name:"cid",kind:"scalar",T:9},{no:4,name:"layers",kind:"message",T:st,repeated:!0}]),Rt=b.makeMessageType("livekit.TrackInfo",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"type",kind:"enum",T:b.getEnumType(Je)},{no:3,name:"name",kind:"scalar",T:9},{no:4,name:"muted",kind:"scalar",T:8},{no:5,name:"width",kind:"scalar",T:13},{no:6,name:"height",kind:"scalar",T:13},{no:7,name:"simulcast",kind:"scalar",T:8},{no:8,name:"disable_dtx",kind:"scalar",T:8},{no:9,name:"source",kind:"enum",T:b.getEnumType(de)},{no:10,name:"layers",kind:"message",T:st,repeated:!0},{no:11,name:"mime_type",kind:"scalar",T:9},{no:12,name:"mid",kind:"scalar",T:9},{no:13,name:"codecs",kind:"message",T:Sf,repeated:!0},{no:14,name:"stereo",kind:"scalar",T:8},{no:15,name:"disable_red",kind:"scalar",T:8},{no:16,name:"encryption",kind:"enum",T:b.getEnumType(He)},{no:17,name:"stream",kind:"scalar",T:9},{no:18,name:"version",kind:"message",T:rc},{no:19,name:"audio_features",kind:"enum",T:b.getEnumType(Xe),repeated:!0},{no:20,name:"backup_codec_policy",kind:"enum",T:b.getEnumType(Ja)}]),st=b.makeMessageType("livekit.VideoLayer",()=>[{no:1,name:"quality",kind:"enum",T:b.getEnumType(Ft)},{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}]),ke=b.makeMessageType("livekit.DataPacket",()=>[{no:1,name:"kind",kind:"enum",T:b.getEnumType(J)},{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:Xa,oneof:"value"},{no:3,name:"speaker",kind:"message",T:Tf,oneof:"value"},{no:6,name:"sip_dtmf",kind:"message",T:$a,oneof:"value"},{no:7,name:"transcription",kind:"message",T:Ff,oneof:"value"},{no:8,name:"metrics",kind:"message",T:Cf,oneof:"value"},{no:9,name:"chat_message",kind:"message",T:Gr,oneof:"value"},{no:10,name:"rpc_request",kind:"message",T:Ya,oneof:"value"},{no:11,name:"rpc_ack",kind:"message",T:qa,oneof:"value"},{no:12,name:"rpc_response",kind:"message",T:Za,oneof:"value"},{no:13,name:"stream_header",kind:"message",T:Jr,oneof:"value"},{no:14,name:"stream_chunk",kind:"message",T:Wr,oneof:"value"},{no:15,name:"stream_trailer",kind:"message",T:Xr,oneof:"value"}]),J=b.makeEnum("livekit.DataPacket.Kind",[{no:0,name:"RELIABLE"},{no:1,name:"LOSSY"}]),Tf=b.makeMessageType("livekit.ActiveSpeakerUpdate",()=>[{no:1,name:"speakers",kind:"message",T:Wa,repeated:!0}]),Wa=b.makeMessageType("livekit.SpeakerInfo",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"level",kind:"scalar",T:2},{no:3,name:"active",kind:"scalar",T:8}]),Xa=b.makeMessageType("livekit.UserPacket",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:5,name:"participant_identity",kind:"scalar",T:9},{no:2,name:"payload",kind:"scalar",T:12},{no:3,name:"destination_sids",kind:"scalar",T:9,repeated:!0},{no:6,name:"destination_identities",kind:"scalar",T:9,repeated:!0},{no:4,name:"topic",kind:"scalar",T:9,opt:!0},{no:8,name:"id",kind:"scalar",T:9,opt:!0},{no:9,name:"start_time",kind:"scalar",T:4,opt:!0},{no:10,name:"end_time",kind:"scalar",T:4,opt:!0},{no:11,name:"nonce",kind:"scalar",T:12}]),$a=b.makeMessageType("livekit.SipDTMF",()=>[{no:3,name:"code",kind:"scalar",T:13},{no:4,name:"digit",kind:"scalar",T:9}]),Ff=b.makeMessageType("livekit.Transcription",()=>[{no:2,name:"transcribed_participant_identity",kind:"scalar",T:9},{no:3,name:"track_id",kind:"scalar",T:9},{no:4,name:"segments",kind:"message",T:kf,repeated:!0}]),kf=b.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}]),Gr=b.makeMessageType("livekit.ChatMessage",()=>[{no:1,name:"id",kind:"scalar",T:9},{no:2,name:"timestamp",kind:"scalar",T:3},{no:3,name:"edit_timestamp",kind:"scalar",T:3,opt:!0},{no:4,name:"message",kind:"scalar",T:9},{no:5,name:"deleted",kind:"scalar",T:8},{no:6,name:"generated",kind:"scalar",T:8}]),Ya=b.makeMessageType("livekit.RpcRequest",()=>[{no:1,name:"id",kind:"scalar",T:9},{no:2,name:"method",kind:"scalar",T:9},{no:3,name:"payload",kind:"scalar",T:9},{no:4,name:"response_timeout_ms",kind:"scalar",T:13},{no:5,name:"version",kind:"scalar",T:13}]),qa=b.makeMessageType("livekit.RpcAck",()=>[{no:1,name:"request_id",kind:"scalar",T:9}]),Za=b.makeMessageType("livekit.RpcResponse",()=>[{no:1,name:"request_id",kind:"scalar",T:9},{no:2,name:"payload",kind:"scalar",T:9,oneof:"value"},{no:3,name:"error",kind:"message",T:za,oneof:"value"}]),za=b.makeMessageType("livekit.RpcError",()=>[{no:1,name:"code",kind:"scalar",T:13},{no:2,name:"message",kind:"scalar",T:9},{no:3,name:"data",kind:"scalar",T:9}]),ec=b.makeMessageType("livekit.ParticipantTracks",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"track_sids",kind:"scalar",T:9,repeated:!0}]),If=b.makeMessageType("livekit.ServerInfo",()=>[{no:1,name:"edition",kind:"enum",T:b.getEnumType(Ac)},{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}]),Ac=b.makeEnum("livekit.ServerInfo.Edition",[{no:0,name:"Standard"},{no:1,name:"Cloud"}]),Rf=b.makeMessageType("livekit.ClientInfo",()=>[{no:1,name:"sdk",kind:"enum",T:b.getEnumType(tc)},{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}]),tc=b.makeEnum("livekit.ClientInfo.SDK",[{no:0,name:"UNKNOWN"},{no:1,name:"JS"},{no:2,name:"SWIFT"},{no:3,name:"ANDROID"},{no:4,name:"FLUTTER"},{no:5,name:"GO"},{no:6,name:"UNITY"},{no:7,name:"REACT_NATIVE"},{no:8,name:"RUST"},{no:9,name:"PYTHON"},{no:10,name:"CPP"},{no:11,name:"UNITY_WEB"},{no:12,name:"NODE"},{no:13,name:"UNREAL"}]),nc=b.makeMessageType("livekit.ClientConfiguration",()=>[{no:1,name:"video",kind:"message",T:ic},{no:2,name:"screen",kind:"message",T:ic},{no:3,name:"resume_connection",kind:"enum",T:b.getEnumType(ln)},{no:4,name:"disabled_codecs",kind:"message",T:xf},{no:5,name:"force_relay",kind:"enum",T:b.getEnumType(ln)}]),ic=b.makeMessageType("livekit.VideoConfiguration",()=>[{no:1,name:"hardware_encoder",kind:"enum",T:b.getEnumType(ln)}]),xf=b.makeMessageType("livekit.DisabledCodecs",()=>[{no:1,name:"codecs",kind:"message",T:oi,repeated:!0},{no:2,name:"publish",kind:"message",T:oi,repeated:!0}]),rc=b.makeMessageType("livekit.TimedVersion",()=>[{no:1,name:"unix_micro",kind:"scalar",T:3},{no:2,name:"ticks",kind:"scalar",T:5}]),jr=b.makeEnum("livekit.DataStream.OperationType",[{no:0,name:"CREATE"},{no:1,name:"UPDATE"},{no:2,name:"DELETE"},{no:3,name:"REACTION"}]),sc=b.makeMessageType("livekit.DataStream.TextHeader",()=>[{no:1,name:"operation_type",kind:"enum",T:b.getEnumType(jr)},{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"}),oc=b.makeMessageType("livekit.DataStream.ByteHeader",()=>[{no:1,name:"name",kind:"scalar",T:9}],{localName:"DataStream_ByteHeader"}),Jr=b.makeMessageType("livekit.DataStream.Header",()=>[{no:1,name:"stream_id",kind:"scalar",T:9},{no:2,name:"timestamp",kind:"scalar",T:3},{no:3,name:"topic",kind:"scalar",T:9},{no:4,name:"mime_type",kind:"scalar",T:9},{no:5,name:"total_length",kind:"scalar",T:4,opt:!0},{no:7,name:"encryption_type",kind:"enum",T:b.getEnumType(He)},{no:8,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:9,name:"text_header",kind:"message",T:sc,oneof:"content_header"},{no:10,name:"byte_header",kind:"message",T:oc,oneof:"content_header"}],{localName:"DataStream_Header"}),Wr=b.makeMessageType("livekit.DataStream.Chunk",()=>[{no:1,name:"stream_id",kind:"scalar",T:9},{no:2,name:"chunk_index",kind:"scalar",T:4},{no:3,name:"content",kind:"scalar",T:12},{no:4,name:"version",kind:"scalar",T:5},{no:5,name:"iv",kind:"scalar",T:12,opt:!0}],{localName:"DataStream_Chunk"}),Xr=b.makeMessageType("livekit.DataStream.Trailer",()=>[{no:1,name:"stream_id",kind:"scalar",T:9},{no:2,name:"reason",kind:"scalar",T:9},{no:3,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}}],{localName:"DataStream_Trailer"}),$e=b.makeEnum("livekit.SignalTarget",[{no:0,name:"PUBLISHER"},{no:1,name:"SUBSCRIBER"}]),$r=b.makeEnum("livekit.StreamState",[{no:0,name:"ACTIVE"},{no:1,name:"PAUSED"}]),Pf=b.makeEnum("livekit.CandidateProtocol",[{no:0,name:"UDP"},{no:1,name:"TCP"},{no:2,name:"TLS"}]),Lf=b.makeMessageType("livekit.SignalRequest",()=>[{no:1,name:"offer",kind:"message",T:ot,oneof:"message"},{no:2,name:"answer",kind:"message",T:ot,oneof:"message"},{no:3,name:"trickle",kind:"message",T:Zr,oneof:"message"},{no:4,name:"add_track",kind:"message",T:qr,oneof:"message"},{no:5,name:"mute",kind:"message",T:zr,oneof:"message"},{no:6,name:"subscription",kind:"message",T:ci,oneof:"message"},{no:7,name:"track_setting",kind:"message",T:cc,oneof:"message"},{no:8,name:"leave",kind:"message",T:li,oneof:"message"},{no:10,name:"update_layers",kind:"message",T:uc,oneof:"message"},{no:11,name:"subscription_permission",kind:"message",T:gc,oneof:"message"},{no:12,name:"sync_state",kind:"message",T:pc,oneof:"message"},{no:13,name:"simulate",kind:"message",T:rA,oneof:"message"},{no:14,name:"ping",kind:"scalar",T:3,oneof:"message"},{no:15,name:"update_metadata",kind:"message",T:dc,oneof:"message"},{no:16,name:"ping_req",kind:"message",T:Bc,oneof:"message"},{no:17,name:"update_audio_track",kind:"message",T:lc,oneof:"message"},{no:18,name:"update_video_track",kind:"message",T:Mf,oneof:"message"}]),ac=b.makeMessageType("livekit.SignalResponse",()=>[{no:1,name:"join",kind:"message",T:Df,oneof:"message"},{no:2,name:"answer",kind:"message",T:ot,oneof:"message"},{no:3,name:"offer",kind:"message",T:ot,oneof:"message"},{no:4,name:"trickle",kind:"message",T:Zr,oneof:"message"},{no:5,name:"update",kind:"message",T:Of,oneof:"message"},{no:6,name:"track_published",kind:"message",T:es,oneof:"message"},{no:8,name:"leave",kind:"message",T:li,oneof:"message"},{no:9,name:"mute",kind:"message",T:zr,oneof:"message"},{no:10,name:"speakers_changed",kind:"message",T:Nf,oneof:"message"},{no:11,name:"room_update",kind:"message",T:Kf,oneof:"message"},{no:12,name:"connection_quality",kind:"message",T:Gf,oneof:"message"},{no:13,name:"stream_state_update",kind:"message",T:Jf,oneof:"message"},{no:14,name:"subscribed_quality_update",kind:"message",T:Xf,oneof:"message"},{no:15,name:"subscription_permission_update",kind:"message",T:$f,oneof:"message"},{no:16,name:"refresh_token",kind:"scalar",T:9,oneof:"message"},{no:17,name:"track_unpublished",kind:"message",T:Hf,oneof:"message"},{no:18,name:"pong",kind:"scalar",T:3,oneof:"message"},{no:19,name:"reconnect",kind:"message",T:_f,oneof:"message"},{no:20,name:"pong_resp",kind:"message",T:qf,oneof:"message"},{no:21,name:"subscription_response",kind:"message",T:eg,oneof:"message"},{no:22,name:"request_response",kind:"message",T:Ag,oneof:"message"},{no:23,name:"track_subscribed",kind:"message",T:tg,oneof:"message"},{no:24,name:"room_moved",kind:"message",T:Yf,oneof:"message"}]),Yr=b.makeMessageType("livekit.SimulcastCodec",()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"cid",kind:"scalar",T:9}]),qr=b.makeMessageType("livekit.AddTrackRequest",()=>[{no:1,name:"cid",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",T:9},{no:3,name:"type",kind:"enum",T:b.getEnumType(Je)},{no:4,name:"width",kind:"scalar",T:13},{no:5,name:"height",kind:"scalar",T:13},{no:6,name:"muted",kind:"scalar",T:8},{no:7,name:"disable_dtx",kind:"scalar",T:8},{no:8,name:"source",kind:"enum",T:b.getEnumType(de)},{no:9,name:"layers",kind:"message",T:st,repeated:!0},{no:10,name:"simulcast_codecs",kind:"message",T:Yr,repeated:!0},{no:11,name:"sid",kind:"scalar",T:9},{no:12,name:"stereo",kind:"scalar",T:8},{no:13,name:"disable_red",kind:"scalar",T:8},{no:14,name:"encryption",kind:"enum",T:b.getEnumType(He)},{no:15,name:"stream",kind:"scalar",T:9},{no:16,name:"backup_codec_policy",kind:"enum",T:b.getEnumType(Ja)},{no:17,name:"audio_features",kind:"enum",T:b.getEnumType(Xe),repeated:!0}]),Zr=b.makeMessageType("livekit.TrickleRequest",()=>[{no:1,name:"candidateInit",kind:"scalar",T:9},{no:2,name:"target",kind:"enum",T:b.getEnumType($e)},{no:3,name:"final",kind:"scalar",T:8}]),zr=b.makeMessageType("livekit.MuteTrackRequest",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"muted",kind:"scalar",T:8}]),Df=b.makeMessageType("livekit.JoinResponse",()=>[{no:1,name:"room",kind:"message",T:si},{no:2,name:"participant",kind:"message",T:rt},{no:3,name:"other_participants",kind:"message",T:rt,repeated:!0},{no:4,name:"server_version",kind:"scalar",T:9},{no:5,name:"ice_servers",kind:"message",T:hc,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:nc},{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:If},{no:13,name:"sif_trailer",kind:"scalar",T:12},{no:14,name:"enabled_publish_codecs",kind:"message",T:oi,repeated:!0},{no:15,name:"fast_publish",kind:"scalar",T:8}]),_f=b.makeMessageType("livekit.ReconnectResponse",()=>[{no:1,name:"ice_servers",kind:"message",T:hc,repeated:!0},{no:2,name:"client_configuration",kind:"message",T:nc}]),es=b.makeMessageType("livekit.TrackPublishedResponse",()=>[{no:1,name:"cid",kind:"scalar",T:9},{no:2,name:"track",kind:"message",T:Rt}]),Hf=b.makeMessageType("livekit.TrackUnpublishedResponse",()=>[{no:1,name:"track_sid",kind:"scalar",T:9}]),ot=b.makeMessageType("livekit.SessionDescription",()=>[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"sdp",kind:"scalar",T:9}]),Of=b.makeMessageType("livekit.ParticipantUpdate",()=>[{no:1,name:"participants",kind:"message",T:rt,repeated:!0}]),ci=b.makeMessageType("livekit.UpdateSubscription",()=>[{no:1,name:"track_sids",kind:"scalar",T:9,repeated:!0},{no:2,name:"subscribe",kind:"scalar",T:8},{no:3,name:"participant_tracks",kind:"message",T:ec,repeated:!0}]),cc=b.makeMessageType("livekit.UpdateTrackSettings",()=>[{no:1,name:"track_sids",kind:"scalar",T:9,repeated:!0},{no:3,name:"disabled",kind:"scalar",T:8},{no:4,name:"quality",kind:"enum",T:b.getEnumType(Ft)},{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}]),lc=b.makeMessageType("livekit.UpdateLocalAudioTrack",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"features",kind:"enum",T:b.getEnumType(Xe),repeated:!0}]),Mf=b.makeMessageType("livekit.UpdateLocalVideoTrack",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"width",kind:"scalar",T:13},{no:3,name:"height",kind:"scalar",T:13}]),li=b.makeMessageType("livekit.LeaveRequest",()=>[{no:1,name:"can_reconnect",kind:"scalar",T:8},{no:2,name:"reason",kind:"enum",T:b.getEnumType(We)},{no:3,name:"action",kind:"enum",T:b.getEnumType(xt)},{no:4,name:"regions",kind:"message",T:Zf}]),xt=b.makeEnum("livekit.LeaveRequest.Action",[{no:0,name:"DISCONNECT"},{no:1,name:"RESUME"},{no:2,name:"RECONNECT"}]),uc=b.makeMessageType("livekit.UpdateVideoLayers",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"layers",kind:"message",T:st,repeated:!0}]),dc=b.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}]),hc=b.makeMessageType("livekit.ICEServer",()=>[{no:1,name:"urls",kind:"scalar",T:9,repeated:!0},{no:2,name:"username",kind:"scalar",T:9},{no:3,name:"credential",kind:"scalar",T:9}]),Nf=b.makeMessageType("livekit.SpeakersChanged",()=>[{no:1,name:"speakers",kind:"message",T:Wa,repeated:!0}]),Kf=b.makeMessageType("livekit.RoomUpdate",()=>[{no:1,name:"room",kind:"message",T:si}]),Vf=b.makeMessageType("livekit.ConnectionQualityInfo",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"quality",kind:"enum",T:b.getEnumType(cn)},{no:3,name:"score",kind:"scalar",T:2}]),Gf=b.makeMessageType("livekit.ConnectionQualityUpdate",()=>[{no:1,name:"updates",kind:"message",T:Vf,repeated:!0}]),jf=b.makeMessageType("livekit.StreamStateInfo",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"track_sid",kind:"scalar",T:9},{no:3,name:"state",kind:"enum",T:b.getEnumType($r)}]),Jf=b.makeMessageType("livekit.StreamStateUpdate",()=>[{no:1,name:"stream_states",kind:"message",T:jf,repeated:!0}]),As=b.makeMessageType("livekit.SubscribedQuality",()=>[{no:1,name:"quality",kind:"enum",T:b.getEnumType(Ft)},{no:2,name:"enabled",kind:"scalar",T:8}]),Wf=b.makeMessageType("livekit.SubscribedCodec",()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"qualities",kind:"message",T:As,repeated:!0}]),Xf=b.makeMessageType("livekit.SubscribedQualityUpdate",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribed_qualities",kind:"message",T:As,repeated:!0},{no:3,name:"subscribed_codecs",kind:"message",T:Wf,repeated:!0}]),fc=b.makeMessageType("livekit.TrackPermission",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"all_tracks",kind:"scalar",T:8},{no:3,name:"track_sids",kind:"scalar",T:9,repeated:!0},{no:4,name:"participant_identity",kind:"scalar",T:9}]),gc=b.makeMessageType("livekit.SubscriptionPermission",()=>[{no:1,name:"all_participants",kind:"scalar",T:8},{no:2,name:"track_permissions",kind:"message",T:fc,repeated:!0}]),$f=b.makeMessageType("livekit.SubscriptionPermissionUpdate",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"track_sid",kind:"scalar",T:9},{no:3,name:"allowed",kind:"scalar",T:8}]),Yf=b.makeMessageType("livekit.RoomMovedResponse",()=>[{no:1,name:"room",kind:"message",T:si},{no:2,name:"token",kind:"scalar",T:9},{no:3,name:"participant",kind:"message",T:rt},{no:4,name:"other_participants",kind:"message",T:rt,repeated:!0}]),pc=b.makeMessageType("livekit.SyncState",()=>[{no:1,name:"answer",kind:"message",T:ot},{no:2,name:"subscription",kind:"message",T:ci},{no:3,name:"publish_tracks",kind:"message",T:es,repeated:!0},{no:4,name:"data_channels",kind:"message",T:mc,repeated:!0},{no:5,name:"offer",kind:"message",T:ot},{no:6,name:"track_sids_disabled",kind:"scalar",T:9,repeated:!0}]),mc=b.makeMessageType("livekit.DataChannelInfo",()=>[{no:1,name:"label",kind:"scalar",T:9},{no:2,name:"id",kind:"scalar",T:13},{no:3,name:"target",kind:"enum",T:b.getEnumType($e)}]),rA=b.makeMessageType("livekit.SimulateScenario",()=>[{no:1,name:"speaker_update",kind:"scalar",T:5,oneof:"scenario"},{no:2,name:"node_failure",kind:"scalar",T:8,oneof:"scenario"},{no:3,name:"migration",kind:"scalar",T:8,oneof:"scenario"},{no:4,name:"server_leave",kind:"scalar",T:8,oneof:"scenario"},{no:5,name:"switch_candidate_protocol",kind:"enum",T:b.getEnumType(Pf),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"}]),Bc=b.makeMessageType("livekit.Ping",()=>[{no:1,name:"timestamp",kind:"scalar",T:3},{no:2,name:"rtt",kind:"scalar",T:3}]),qf=b.makeMessageType("livekit.Pong",()=>[{no:1,name:"last_ping_timestamp",kind:"scalar",T:3},{no:2,name:"timestamp",kind:"scalar",T:3}]),Zf=b.makeMessageType("livekit.RegionSettings",()=>[{no:1,name:"regions",kind:"message",T:zf,repeated:!0}]),zf=b.makeMessageType("livekit.RegionInfo",()=>[{no:1,name:"region",kind:"scalar",T:9},{no:2,name:"url",kind:"scalar",T:9},{no:3,name:"distance",kind:"scalar",T:3}]),eg=b.makeMessageType("livekit.SubscriptionResponse",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"err",kind:"enum",T:b.getEnumType(Uf)}]),Ag=b.makeMessageType("livekit.RequestResponse",()=>[{no:1,name:"request_id",kind:"scalar",T:13},{no:2,name:"reason",kind:"enum",T:b.getEnumType(ts)},{no:3,name:"message",kind:"scalar",T:9}]),ts=b.makeEnum("livekit.RequestResponse.Reason",[{no:0,name:"OK"},{no:1,name:"NOT_FOUND"},{no:2,name:"NOT_ALLOWED"},{no:3,name:"LIMIT_EXCEEDED"}]),tg=b.makeMessageType("livekit.TrackSubscribed",()=>[{no:1,name:"track_sid",kind:"scalar",T:9}]);function ng(n){return n&&n.__esModule&&Object.prototype.hasOwnProperty.call(n,"default")?n.default:n}var ui={exports:{}},ig=ui.exports,vc;function rg(){return vc||(vc=1,function(n){(function(e,A){n.exports?n.exports=A():e.log=A()})(ig,function(){var e=function(){},A="undefined",t=typeof window!==A&&typeof window.navigator!==A&&/Trident\/|MSIE /.test(window.navigator.userAgent),i=["trace","debug","info","warn","error"],r={},s=null;function o(g,m){var C=g[m];if(typeof C.bind=="function")return C.bind(g);try{return Function.prototype.bind.call(C,g)}catch{return function(){return Function.prototype.apply.apply(C,[g,arguments])}}}function a(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function c(g){return g==="debug"&&(g="log"),typeof console===A?!1:g==="trace"&&t?a:console[g]!==void 0?o(console,g):console.log!==void 0?o(console,"log"):e}function l(){for(var g=this.getLevel(),m=0;m<i.length;m++){var C=i[m];this[C]=m<g?e:this.methodFactory(C,g,this.name)}if(this.log=this.debug,typeof console===A&&g<this.levels.SILENT)return"No console available for logging"}function u(g){return function(){typeof console!==A&&(l.call(this),this[g].apply(this,arguments))}}function d(g,m,C){return c(g)||u.apply(this,arguments)}function h(g,m){var C=this,y,U,v,B="loglevel";typeof g=="string"?B+=":"+g:typeof g=="symbol"&&(B=void 0);function w(H){var N=(i[H]||"silent").toUpperCase();if(!(typeof window===A||!B)){try{window.localStorage[B]=N;return}catch{}try{window.document.cookie=encodeURIComponent(B)+"="+N+";"}catch{}}}function S(){var H;if(!(typeof window===A||!B)){try{H=window.localStorage[B]}catch{}if(typeof H===A)try{var N=window.document.cookie,K=encodeURIComponent(B),ae=N.indexOf(K+"=");ae!==-1&&(H=/^([^;]+)/.exec(N.slice(ae+K.length+1))[1])}catch{}return C.levels[H]===void 0&&(H=void 0),H}}function F(){if(!(typeof window===A||!B)){try{window.localStorage.removeItem(B)}catch{}try{window.document.cookie=encodeURIComponent(B)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}function R(H){var N=H;if(typeof N=="string"&&C.levels[N.toUpperCase()]!==void 0&&(N=C.levels[N.toUpperCase()]),typeof N=="number"&&N>=0&&N<=C.levels.SILENT)return N;throw new TypeError("log.setLevel() called with invalid level: "+H)}C.name=g,C.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},C.methodFactory=m||d,C.getLevel=function(){return v??U??y},C.setLevel=function(H,N){return v=R(H),N!==!1&&w(v),l.call(C)},C.setDefaultLevel=function(H){U=R(H),S()||C.setLevel(H,!1)},C.resetLevel=function(){v=null,F(),l.call(C)},C.enableAll=function(H){C.setLevel(C.levels.TRACE,H)},C.disableAll=function(H){C.setLevel(C.levels.SILENT,H)},C.rebuild=function(){if(s!==C&&(y=R(s.getLevel())),l.call(C),s===C)for(var H in r)r[H].rebuild()},y=R(s?s.getLevel():"WARN");var D=S();D!=null&&(v=R(D)),l.call(C)}s=new h,s.getLogger=function(m){if(typeof m!="symbol"&&typeof m!="string"||m==="")throw new TypeError("You must supply a name when creating a logger.");var C=r[m];return C||(C=r[m]=new h(m,s.methodFactory)),C};var f=typeof window!==A?window.log:void 0;return s.noConflict=function(){return typeof window!==A&&window.log===s&&(window.log=f),s},s.getLoggers=function(){return r},s.default=s,s})}(ui)),ui.exports}var di=rg(),ns;(function(n){n[n.trace=0]="trace",n[n.debug=1]="debug",n[n.info=2]="info",n[n.warn=3]="warn",n[n.error=4]="error",n[n.silent=5]="silent"})(ns||(ns={}));var Ye;(function(n){n.Default="livekit",n.Room="livekit-room",n.Participant="livekit-participant",n.Track="livekit-track",n.Publication="livekit-track-publication",n.Engine="livekit-engine",n.Signal="livekit-signal",n.PCManager="livekit-pc-manager",n.PCTransport="livekit-pc-transport",n.E2EE="lk-e2ee"})(Ye||(Ye={}));let V=di.getLogger("livekit");Object.values(Ye).map(n=>di.getLogger(n)),V.setDefaultLevel(ns.info);function pA(n){const e=di.getLogger(n);return e.setDefaultLevel(V.getLevel()),e}const sg=di.getLogger("lk-e2ee"),un=7e3,og=[0,300,2*2*300,3*3*300,4*4*300,un,un,un,un,un];class ag{constructor(e){this._retryDelays=e!==void 0?[...e]:og}nextRetryDelayInMs(e){if(e.retryCount>=this._retryDelays.length)return null;const A=this._retryDelays[e.retryCount];return e.retryCount<=1?A:A+Math.random()*1e3}}function cg(n,e){var A={};for(var t in n)Object.prototype.hasOwnProperty.call(n,t)&&e.indexOf(t)<0&&(A[t]=n[t]);if(n!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,t=Object.getOwnPropertySymbols(n);i<t.length;i++)e.indexOf(t[i])<0&&Object.prototype.propertyIsEnumerable.call(n,t[i])&&(A[t[i]]=n[t[i]]);return A}function p(n,e,A,t){function i(r){return r instanceof A?r:new A(function(s){s(r)})}return new(A||(A=Promise))(function(r,s){function o(l){try{c(t.next(l))}catch(u){s(u)}}function a(l){try{c(t.throw(l))}catch(u){s(u)}}function c(l){l.done?r(l.value):i(l.value).then(o,a)}c((t=t.apply(n,e||[])).next())})}function Cc(n){var e=typeof Symbol=="function"&&Symbol.iterator,A=e&&n[e],t=0;if(A)return A.call(n);if(n&&typeof n.length=="number")return{next:function(){return n&&t>=n.length&&(n=void 0),{value:n&&n[t++],done:!n}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function kA(n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=n[Symbol.asyncIterator],A;return e?e.call(n):(n=typeof Cc=="function"?Cc(n):n[Symbol.iterator](),A={},t("next"),t("throw"),t("return"),A[Symbol.asyncIterator]=function(){return this},A);function t(r){A[r]=n[r]&&function(s){return new Promise(function(o,a){s=n[r](s),i(o,a,s.done,s.value)})}}function i(r,s,o,a){Promise.resolve(a).then(function(c){r({value:c,done:o})},s)}}typeof SuppressedError=="function"&&SuppressedError;var hi={exports:{}},wc;function lg(){if(wc)return hi.exports;wc=1;var n=typeof Reflect=="object"?Reflect:null,e=n&&typeof n.apply=="function"?n.apply:function(B,w,S){return Function.prototype.apply.call(B,w,S)},A;n&&typeof n.ownKeys=="function"?A=n.ownKeys:Object.getOwnPropertySymbols?A=function(B){return Object.getOwnPropertyNames(B).concat(Object.getOwnPropertySymbols(B))}:A=function(B){return Object.getOwnPropertyNames(B)};function t(v){console&&console.warn&&console.warn(v)}var i=Number.isNaN||function(B){return B!==B};function r(){r.init.call(this)}hi.exports=r,hi.exports.once=C,r.EventEmitter=r,r.prototype._events=void 0,r.prototype._eventsCount=0,r.prototype._maxListeners=void 0;var s=10;function o(v){if(typeof v!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof v)}Object.defineProperty(r,"defaultMaxListeners",{enumerable:!0,get:function(){return s},set:function(v){if(typeof v!="number"||v<0||i(v))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+v+".");s=v}}),r.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},r.prototype.setMaxListeners=function(B){if(typeof B!="number"||B<0||i(B))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+B+".");return this._maxListeners=B,this};function a(v){return v._maxListeners===void 0?r.defaultMaxListeners:v._maxListeners}r.prototype.getMaxListeners=function(){return a(this)},r.prototype.emit=function(B){for(var w=[],S=1;S<arguments.length;S++)w.push(arguments[S]);var F=B==="error",R=this._events;if(R!==void 0)F=F&&R.error===void 0;else if(!F)return!1;if(F){var D;if(w.length>0&&(D=w[0]),D instanceof Error)throw D;var H=new Error("Unhandled error."+(D?" ("+D.message+")":""));throw H.context=D,H}var N=R[B];if(N===void 0)return!1;if(typeof N=="function")e(N,this,w);else for(var K=N.length,ae=f(N,K),S=0;S<K;++S)e(ae[S],this,w);return!0};function c(v,B,w,S){var F,R,D;if(o(w),R=v._events,R===void 0?(R=v._events=Object.create(null),v._eventsCount=0):(R.newListener!==void 0&&(v.emit("newListener",B,w.listener?w.listener:w),R=v._events),D=R[B]),D===void 0)D=R[B]=w,++v._eventsCount;else if(typeof D=="function"?D=R[B]=S?[w,D]:[D,w]:S?D.unshift(w):D.push(w),F=a(v),F>0&&D.length>F&&!D.warned){D.warned=!0;var H=new Error("Possible EventEmitter memory leak detected. "+D.length+" "+String(B)+" listeners added. Use emitter.setMaxListeners() to increase limit");H.name="MaxListenersExceededWarning",H.emitter=v,H.type=B,H.count=D.length,t(H)}return v}r.prototype.addListener=function(B,w){return c(this,B,w,!1)},r.prototype.on=r.prototype.addListener,r.prototype.prependListener=function(B,w){return c(this,B,w,!0)};function l(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function u(v,B,w){var S={fired:!1,wrapFn:void 0,target:v,type:B,listener:w},F=l.bind(S);return F.listener=w,S.wrapFn=F,F}r.prototype.once=function(B,w){return o(w),this.on(B,u(this,B,w)),this},r.prototype.prependOnceListener=function(B,w){return o(w),this.prependListener(B,u(this,B,w)),this},r.prototype.removeListener=function(B,w){var S,F,R,D,H;if(o(w),F=this._events,F===void 0)return this;if(S=F[B],S===void 0)return this;if(S===w||S.listener===w)--this._eventsCount===0?this._events=Object.create(null):(delete F[B],F.removeListener&&this.emit("removeListener",B,S.listener||w));else if(typeof S!="function"){for(R=-1,D=S.length-1;D>=0;D--)if(S[D]===w||S[D].listener===w){H=S[D].listener,R=D;break}if(R<0)return this;R===0?S.shift():g(S,R),S.length===1&&(F[B]=S[0]),F.removeListener!==void 0&&this.emit("removeListener",B,H||w)}return this},r.prototype.off=r.prototype.removeListener,r.prototype.removeAllListeners=function(B){var w,S,F;if(S=this._events,S===void 0)return this;if(S.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):S[B]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete S[B]),this;if(arguments.length===0){var R=Object.keys(S),D;for(F=0;F<R.length;++F)D=R[F],D!=="removeListener"&&this.removeAllListeners(D);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(w=S[B],typeof w=="function")this.removeListener(B,w);else if(w!==void 0)for(F=w.length-1;F>=0;F--)this.removeListener(B,w[F]);return this};function d(v,B,w){var S=v._events;if(S===void 0)return[];var F=S[B];return F===void 0?[]:typeof F=="function"?w?[F.listener||F]:[F]:w?m(F):f(F,F.length)}r.prototype.listeners=function(B){return d(this,B,!0)},r.prototype.rawListeners=function(B){return d(this,B,!1)},r.listenerCount=function(v,B){return typeof v.listenerCount=="function"?v.listenerCount(B):h.call(v,B)},r.prototype.listenerCount=h;function h(v){var B=this._events;if(B!==void 0){var w=B[v];if(typeof w=="function")return 1;if(w!==void 0)return w.length}return 0}r.prototype.eventNames=function(){return this._eventsCount>0?A(this._events):[]};function f(v,B){for(var w=new Array(B),S=0;S<B;++S)w[S]=v[S];return w}function g(v,B){for(;B+1<v.length;B++)v[B]=v[B+1];v.pop()}function m(v){for(var B=new Array(v.length),w=0;w<B.length;++w)B[w]=v[w].listener||v[w];return B}function C(v,B){return new Promise(function(w,S){function F(D){v.removeListener(B,R),S(D)}function R(){typeof v.removeListener=="function"&&v.removeListener("error",F),w([].slice.call(arguments))}U(v,B,R,{once:!0}),B!=="error"&&y(v,F,{once:!0})})}function y(v,B,w){typeof v.on=="function"&&U(v,"error",B,w)}function U(v,B,w,S){if(typeof v.on=="function")S.once?v.once(B,w):v.on(B,w);else if(typeof v.addEventListener=="function")v.addEventListener(B,function F(R){S.once&&v.removeEventListener(B,F),w(R)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof v)}return hi.exports}var sA=lg();let yc=!0,bc=!0;function fi(n,e,A){const t=n.match(e);return t&&t.length>=A&&parseInt(t[A],10)}function at(n,e,A){if(!n.RTCPeerConnection)return;const t=n.RTCPeerConnection.prototype,i=t.addEventListener;t.addEventListener=function(s,o){if(s!==e)return i.apply(this,arguments);const a=c=>{const l=A(c);l&&(o.handleEvent?o.handleEvent(l):o(l))};return this._eventMap=this._eventMap||{},this._eventMap[e]||(this._eventMap[e]=new Map),this._eventMap[e].set(o,a),i.apply(this,[s,a])};const r=t.removeEventListener;t.removeEventListener=function(s,o){if(s!==e||!this._eventMap||!this._eventMap[e])return r.apply(this,arguments);if(!this._eventMap[e].has(o))return r.apply(this,arguments);const a=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,[s,a])},Object.defineProperty(t,"on"+e,{get(){return this["_on"+e]},set(s){this["_on"+e]&&(this.removeEventListener(e,this["_on"+e]),delete this["_on"+e]),s&&this.addEventListener(e,this["_on"+e]=s)},enumerable:!0,configurable:!0})}function ug(n){return typeof n!="boolean"?new Error("Argument type: "+typeof n+". Please use a boolean."):(yc=n,n?"adapter.js logging disabled":"adapter.js logging enabled")}function dg(n){return typeof n!="boolean"?new Error("Argument type: "+typeof n+". Please use a boolean."):(bc=!n,"adapter.js deprecation warnings "+(n?"disabled":"enabled"))}function Uc(){if(typeof window=="object"){if(yc)return;typeof console<"u"&&typeof console.log=="function"&&console.log.apply(console,arguments)}}function is(n,e){bc&&console.warn(n+" is deprecated, please use "+e+" instead.")}function hg(n){const e={browser:null,version:null};if(typeof n>"u"||!n.navigator||!n.navigator.userAgent)return e.browser="Not a browser.",e;const{navigator:A}=n;if(A.userAgentData&&A.userAgentData.brands){const t=A.userAgentData.brands.find(i=>i.brand==="Chromium");if(t)return{browser:"chrome",version:parseInt(t.version,10)}}if(A.mozGetUserMedia)e.browser="firefox",e.version=fi(A.userAgent,/Firefox\/(\d+)\./,1);else if(A.webkitGetUserMedia||n.isSecureContext===!1&&n.webkitRTCPeerConnection)e.browser="chrome",e.version=fi(A.userAgent,/Chrom(e|ium)\/(\d+)\./,2);else if(n.RTCPeerConnection&&A.userAgent.match(/AppleWebKit\/(\d+)\./))e.browser="safari",e.version=fi(A.userAgent,/AppleWebKit\/(\d+)\./,1),e.supportsUnifiedPlan=n.RTCRtpTransceiver&&"currentDirection"in n.RTCRtpTransceiver.prototype;else return e.browser="Not a supported browser.",e;return e}function Qc(n){return Object.prototype.toString.call(n)==="[object Object]"}function Ec(n){return Qc(n)?Object.keys(n).reduce(function(e,A){const t=Qc(n[A]),i=t?Ec(n[A]):n[A],r=t&&!Object.keys(i).length;return i===void 0||r?e:Object.assign(e,{[A]:i})},{}):n}function rs(n,e,A){!e||A.has(e.id)||(A.set(e.id,e),Object.keys(e).forEach(t=>{t.endsWith("Id")?rs(n,n.get(e[t]),A):t.endsWith("Ids")&&e[t].forEach(i=>{rs(n,n.get(i),A)})}))}function Sc(n,e,A){const t=A?"outbound-rtp":"inbound-rtp",i=new Map;if(e===null)return i;const r=[];return n.forEach(s=>{s.type==="track"&&s.trackIdentifier===e.id&&r.push(s)}),r.forEach(s=>{n.forEach(o=>{o.type===t&&o.trackId===s.id&&rs(n,o,i)})}),i}const Tc=Uc;function Fc(n,e){const A=n&&n.navigator;if(!A.mediaDevices)return;const t=function(o){if(typeof o!="object"||o.mandatory||o.optional)return o;const a={};return Object.keys(o).forEach(c=>{if(c==="require"||c==="advanced"||c==="mediaSource")return;const l=typeof o[c]=="object"?o[c]:{ideal:o[c]};l.exact!==void 0&&typeof l.exact=="number"&&(l.min=l.max=l.exact);const u=function(d,h){return d?d+h.charAt(0).toUpperCase()+h.slice(1):h==="deviceId"?"sourceId":h};if(l.ideal!==void 0){a.optional=a.optional||[];let d={};typeof l.ideal=="number"?(d[u("min",c)]=l.ideal,a.optional.push(d),d={},d[u("max",c)]=l.ideal,a.optional.push(d)):(d[u("",c)]=l.ideal,a.optional.push(d))}l.exact!==void 0&&typeof l.exact!="number"?(a.mandatory=a.mandatory||{},a.mandatory[u("",c)]=l.exact):["min","max"].forEach(d=>{l[d]!==void 0&&(a.mandatory=a.mandatory||{},a.mandatory[u(d,c)]=l[d])})}),o.advanced&&(a.optional=(a.optional||[]).concat(o.advanced)),a},i=function(o,a){if(e.version>=61)return a(o);if(o=JSON.parse(JSON.stringify(o)),o&&typeof o.audio=="object"){const c=function(l,u,d){u in l&&!(d in l)&&(l[d]=l[u],delete l[u])};o=JSON.parse(JSON.stringify(o)),c(o.audio,"autoGainControl","googAutoGainControl"),c(o.audio,"noiseSuppression","googNoiseSuppression"),o.audio=t(o.audio)}if(o&&typeof o.video=="object"){let c=o.video.facingMode;c=c&&(typeof c=="object"?c:{ideal:c});const l=e.version<66;if(c&&(c.exact==="user"||c.exact==="environment"||c.ideal==="user"||c.ideal==="environment")&&!(A.mediaDevices.getSupportedConstraints&&A.mediaDevices.getSupportedConstraints().facingMode&&!l)){delete o.video.facingMode;let u;if(c.exact==="environment"||c.ideal==="environment"?u=["back","rear"]:(c.exact==="user"||c.ideal==="user")&&(u=["front"]),u)return A.mediaDevices.enumerateDevices().then(d=>{d=d.filter(f=>f.kind==="videoinput");let h=d.find(f=>u.some(g=>f.label.toLowerCase().includes(g)));return!h&&d.length&&u.includes("back")&&(h=d[d.length-1]),h&&(o.video.deviceId=c.exact?{exact:h.deviceId}:{ideal:h.deviceId}),o.video=t(o.video),Tc("chrome: "+JSON.stringify(o)),a(o)})}o.video=t(o.video)}return Tc("chrome: "+JSON.stringify(o)),a(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}}},s=function(o,a,c){i(o,l=>{A.webkitGetUserMedia(l,a,u=>{c&&c(r(u))})})};if(A.getUserMedia=s.bind(A),A.mediaDevices.getUserMedia){const o=A.mediaDevices.getUserMedia.bind(A.mediaDevices);A.mediaDevices.getUserMedia=function(a){return i(a,c=>o(c).then(l=>{if(c.audio&&!l.getAudioTracks().length||c.video&&!l.getVideoTracks().length)throw l.getTracks().forEach(u=>{u.stop()}),new DOMException("","NotFoundError");return l},l=>Promise.reject(r(l))))}}}function kc(n){n.MediaStream=n.MediaStream||n.webkitMediaStream}function Ic(n){if(typeof n=="object"&&n.RTCPeerConnection&&!("ontrack"in n.RTCPeerConnection.prototype)){Object.defineProperty(n.RTCPeerConnection.prototype,"ontrack",{get(){return this._ontrack},set(A){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=A)},enumerable:!0,configurable:!0});const e=n.RTCPeerConnection.prototype.setRemoteDescription;n.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=t=>{t.stream.addEventListener("addtrack",i=>{let r;n.RTCPeerConnection.prototype.getReceivers?r=this.getReceivers().find(o=>o.track&&o.track.id===i.track.id):r={track:i.track};const s=new Event("track");s.track=i.track,s.receiver=r,s.transceiver={receiver:r},s.streams=[t.stream],this.dispatchEvent(s)}),t.stream.getTracks().forEach(i=>{let r;n.RTCPeerConnection.prototype.getReceivers?r=this.getReceivers().find(o=>o.track&&o.track.id===i.id):r={track:i};const s=new Event("track");s.track=i,s.receiver=r,s.transceiver={receiver:r},s.streams=[t.stream],this.dispatchEvent(s)})},this.addEventListener("addstream",this._ontrackpoly)),e.apply(this,arguments)}}else at(n,"track",e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e))}function Rc(n){if(typeof n=="object"&&n.RTCPeerConnection&&!("getSenders"in n.RTCPeerConnection.prototype)&&"createDTMFSender"in n.RTCPeerConnection.prototype){const e=function(i,r){return{track:r,get dtmf(){return this._dtmf===void 0&&(r.kind==="audio"?this._dtmf=i.createDTMFSender(r):this._dtmf=null),this._dtmf},_pc:i}};if(!n.RTCPeerConnection.prototype.getSenders){n.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};const i=n.RTCPeerConnection.prototype.addTrack;n.RTCPeerConnection.prototype.addTrack=function(o,a){let c=i.apply(this,arguments);return c||(c=e(this,o),this._senders.push(c)),c};const r=n.RTCPeerConnection.prototype.removeTrack;n.RTCPeerConnection.prototype.removeTrack=function(o){r.apply(this,arguments);const a=this._senders.indexOf(o);a!==-1&&this._senders.splice(a,1)}}const A=n.RTCPeerConnection.prototype.addStream;n.RTCPeerConnection.prototype.addStream=function(r){this._senders=this._senders||[],A.apply(this,[r]),r.getTracks().forEach(s=>{this._senders.push(e(this,s))})};const t=n.RTCPeerConnection.prototype.removeStream;n.RTCPeerConnection.prototype.removeStream=function(r){this._senders=this._senders||[],t.apply(this,[r]),r.getTracks().forEach(s=>{const o=this._senders.find(a=>a.track===s);o&&this._senders.splice(this._senders.indexOf(o),1)})}}else if(typeof n=="object"&&n.RTCPeerConnection&&"getSenders"in n.RTCPeerConnection.prototype&&"createDTMFSender"in n.RTCPeerConnection.prototype&&n.RTCRtpSender&&!("dtmf"in n.RTCRtpSender.prototype)){const e=n.RTCPeerConnection.prototype.getSenders;n.RTCPeerConnection.prototype.getSenders=function(){const t=e.apply(this,[]);return t.forEach(i=>i._pc=this),t},Object.defineProperty(n.RTCRtpSender.prototype,"dtmf",{get(){return this._dtmf===void 0&&(this.track.kind==="audio"?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}})}}function xc(n){if(!(typeof n=="object"&&n.RTCPeerConnection&&n.RTCRtpSender&&n.RTCRtpReceiver))return;if(!("getStats"in n.RTCRtpSender.prototype)){const A=n.RTCPeerConnection.prototype.getSenders;A&&(n.RTCPeerConnection.prototype.getSenders=function(){const r=A.apply(this,[]);return r.forEach(s=>s._pc=this),r});const t=n.RTCPeerConnection.prototype.addTrack;t&&(n.RTCPeerConnection.prototype.addTrack=function(){const r=t.apply(this,arguments);return r._pc=this,r}),n.RTCRtpSender.prototype.getStats=function(){const r=this;return this._pc.getStats().then(s=>Sc(s,r.track,!0))}}if(!("getStats"in n.RTCRtpReceiver.prototype)){const A=n.RTCPeerConnection.prototype.getReceivers;A&&(n.RTCPeerConnection.prototype.getReceivers=function(){const i=A.apply(this,[]);return i.forEach(r=>r._pc=this),i}),at(n,"track",t=>(t.receiver._pc=t.srcElement,t)),n.RTCRtpReceiver.prototype.getStats=function(){const i=this;return this._pc.getStats().then(r=>Sc(r,i.track,!1))}}if(!("getStats"in n.RTCRtpSender.prototype&&"getStats"in n.RTCRtpReceiver.prototype))return;const e=n.RTCPeerConnection.prototype.getStats;n.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof n.MediaStreamTrack){const t=arguments[0];let i,r,s;return this.getSenders().forEach(o=>{o.track===t&&(i?s=!0:i=o)}),this.getReceivers().forEach(o=>(o.track===t&&(r?s=!0:r=o),o.track===t)),s||i&&r?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):i?i.getStats():r?r.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return e.apply(this,arguments)}}function Pc(n){n.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map(s=>this._shimmedLocalStreams[s][0])};const e=n.RTCPeerConnection.prototype.addTrack;n.RTCPeerConnection.prototype.addTrack=function(s,o){if(!o)return e.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};const a=e.apply(this,arguments);return this._shimmedLocalStreams[o.id]?this._shimmedLocalStreams[o.id].indexOf(a)===-1&&this._shimmedLocalStreams[o.id].push(a):this._shimmedLocalStreams[o.id]=[o,a],a};const A=n.RTCPeerConnection.prototype.addStream;n.RTCPeerConnection.prototype.addStream=function(s){this._shimmedLocalStreams=this._shimmedLocalStreams||{},s.getTracks().forEach(c=>{if(this.getSenders().find(u=>u.track===c))throw new DOMException("Track already exists.","InvalidAccessError")});const o=this.getSenders();A.apply(this,arguments);const a=this.getSenders().filter(c=>o.indexOf(c)===-1);this._shimmedLocalStreams[s.id]=[s].concat(a)};const t=n.RTCPeerConnection.prototype.removeStream;n.RTCPeerConnection.prototype.removeStream=function(s){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[s.id],t.apply(this,arguments)};const i=n.RTCPeerConnection.prototype.removeTrack;n.RTCPeerConnection.prototype.removeTrack=function(s){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},s&&Object.keys(this._shimmedLocalStreams).forEach(o=>{const a=this._shimmedLocalStreams[o].indexOf(s);a!==-1&&this._shimmedLocalStreams[o].splice(a,1),this._shimmedLocalStreams[o].length===1&&delete this._shimmedLocalStreams[o]}),i.apply(this,arguments)}}function Lc(n,e){if(!n.RTCPeerConnection)return;if(n.RTCPeerConnection.prototype.addTrack&&e.version>=65)return Pc(n);const A=n.RTCPeerConnection.prototype.getLocalStreams;n.RTCPeerConnection.prototype.getLocalStreams=function(){const l=A.apply(this);return this._reverseStreams=this._reverseStreams||{},l.map(u=>this._reverseStreams[u.id])};const t=n.RTCPeerConnection.prototype.addStream;n.RTCPeerConnection.prototype.addStream=function(l){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},l.getTracks().forEach(u=>{if(this.getSenders().find(h=>h.track===u))throw new DOMException("Track already exists.","InvalidAccessError")}),!this._reverseStreams[l.id]){const u=new n.MediaStream(l.getTracks());this._streams[l.id]=u,this._reverseStreams[u.id]=l,l=u}t.apply(this,[l])};const i=n.RTCPeerConnection.prototype.removeStream;n.RTCPeerConnection.prototype.removeStream=function(l){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},i.apply(this,[this._streams[l.id]||l]),delete this._reverseStreams[this._streams[l.id]?this._streams[l.id].id:l.id],delete this._streams[l.id]},n.RTCPeerConnection.prototype.addTrack=function(l,u){if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");const d=[].slice.call(arguments,1);if(d.length!==1||!d[0].getTracks().find(g=>g===l))throw new DOMException("The adapter.js addTrack polyfill only supports a single stream which is associated with the specified track.","NotSupportedError");if(this.getSenders().find(g=>g.track===l))throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};const f=this._streams[u.id];if(f)f.addTrack(l),Promise.resolve().then(()=>{this.dispatchEvent(new Event("negotiationneeded"))});else{const g=new n.MediaStream([l]);this._streams[u.id]=g,this._reverseStreams[g.id]=u,this.addStream(g)}return this.getSenders().find(g=>g.track===l)};function r(c,l){let u=l.sdp;return Object.keys(c._reverseStreams||[]).forEach(d=>{const h=c._reverseStreams[d],f=c._streams[h.id];u=u.replace(new RegExp(f.id,"g"),h.id)}),new RTCSessionDescription({type:l.type,sdp:u})}function s(c,l){let u=l.sdp;return Object.keys(c._reverseStreams||[]).forEach(d=>{const h=c._reverseStreams[d],f=c._streams[h.id];u=u.replace(new RegExp(h.id,"g"),f.id)}),new RTCSessionDescription({type:l.type,sdp:u})}["createOffer","createAnswer"].forEach(function(c){const l=n.RTCPeerConnection.prototype[c],u={[c](){const d=arguments;return arguments.length&&typeof arguments[0]=="function"?l.apply(this,[f=>{const g=r(this,f);d[0].apply(null,[g])},f=>{d[1]&&d[1].apply(null,f)},arguments[2]]):l.apply(this,arguments).then(f=>r(this,f))}};n.RTCPeerConnection.prototype[c]=u[c]});const o=n.RTCPeerConnection.prototype.setLocalDescription;n.RTCPeerConnection.prototype.setLocalDescription=function(){return!arguments.length||!arguments[0].type?o.apply(this,arguments):(arguments[0]=s(this,arguments[0]),o.apply(this,arguments))};const a=Object.getOwnPropertyDescriptor(n.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(n.RTCPeerConnection.prototype,"localDescription",{get(){const c=a.get.apply(this);return c.type===""?c:r(this,c)}}),n.RTCPeerConnection.prototype.removeTrack=function(l){if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!l._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(!(l._pc===this))throw new DOMException("Sender was not created by this connection.","InvalidAccessError");this._streams=this._streams||{};let d;Object.keys(this._streams).forEach(h=>{this._streams[h].getTracks().find(g=>l.track===g)&&(d=this._streams[h])}),d&&(d.getTracks().length===1?this.removeStream(this._reverseStreams[d.id]):d.removeTrack(l.track),this.dispatchEvent(new Event("negotiationneeded")))}}function ss(n,e){!n.RTCPeerConnection&&n.webkitRTCPeerConnection&&(n.RTCPeerConnection=n.webkitRTCPeerConnection),n.RTCPeerConnection&&e.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(A){const t=n.RTCPeerConnection.prototype[A],i={[A](){return arguments[0]=new(A==="addIceCandidate"?n.RTCIceCandidate:n.RTCSessionDescription)(arguments[0]),t.apply(this,arguments)}};n.RTCPeerConnection.prototype[A]=i[A]})}function Dc(n,e){at(n,"negotiationneeded",A=>{const t=A.target;if(!((e.version<72||t.getConfiguration&&t.getConfiguration().sdpSemantics==="plan-b")&&t.signalingState!=="stable"))return A})}var _c=Object.freeze({__proto__:null,fixNegotiationNeeded:Dc,shimAddTrackRemoveTrack:Lc,shimAddTrackRemoveTrackWithNative:Pc,shimGetSendersWithDtmf:Rc,shimGetUserMedia:Fc,shimMediaStream:kc,shimOnTrack:Ic,shimPeerConnection:ss,shimSenderReceiverGetStats:xc});function Hc(n,e){const A=n&&n.navigator,t=n&&n.MediaStreamTrack;if(A.getUserMedia=function(i,r,s){is("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),A.mediaDevices.getUserMedia(i).then(r,s)},!(e.version>55&&"autoGainControl"in A.mediaDevices.getSupportedConstraints())){const i=function(s,o,a){o in s&&!(a in s)&&(s[a]=s[o],delete s[o])},r=A.mediaDevices.getUserMedia.bind(A.mediaDevices);if(A.mediaDevices.getUserMedia=function(s){return typeof s=="object"&&typeof s.audio=="object"&&(s=JSON.parse(JSON.stringify(s)),i(s.audio,"autoGainControl","mozAutoGainControl"),i(s.audio,"noiseSuppression","mozNoiseSuppression")),r(s)},t&&t.prototype.getSettings){const s=t.prototype.getSettings;t.prototype.getSettings=function(){const o=s.apply(this,arguments);return i(o,"mozAutoGainControl","autoGainControl"),i(o,"mozNoiseSuppression","noiseSuppression"),o}}if(t&&t.prototype.applyConstraints){const s=t.prototype.applyConstraints;t.prototype.applyConstraints=function(o){return this.kind==="audio"&&typeof o=="object"&&(o=JSON.parse(JSON.stringify(o)),i(o,"autoGainControl","mozAutoGainControl"),i(o,"noiseSuppression","mozNoiseSuppression")),s.apply(this,[o])}}}}function fg(n,e){n.navigator.mediaDevices&&"getDisplayMedia"in n.navigator.mediaDevices||n.navigator.mediaDevices&&(n.navigator.mediaDevices.getDisplayMedia=function(t){if(!(t&&t.video)){const i=new DOMException("getDisplayMedia without video constraints is undefined");return i.name="NotFoundError",i.code=8,Promise.reject(i)}return t.video===!0?t.video={mediaSource:e}:t.video.mediaSource=e,n.navigator.mediaDevices.getUserMedia(t)})}function Oc(n){typeof n=="object"&&n.RTCTrackEvent&&"receiver"in n.RTCTrackEvent.prototype&&!("transceiver"in n.RTCTrackEvent.prototype)&&Object.defineProperty(n.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function os(n,e){if(typeof n!="object"||!(n.RTCPeerConnection||n.mozRTCPeerConnection))return;!n.RTCPeerConnection&&n.mozRTCPeerConnection&&(n.RTCPeerConnection=n.mozRTCPeerConnection),e.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(i){const r=n.RTCPeerConnection.prototype[i],s={[i](){return arguments[0]=new(i==="addIceCandidate"?n.RTCIceCandidate:n.RTCSessionDescription)(arguments[0]),r.apply(this,arguments)}};n.RTCPeerConnection.prototype[i]=s[i]});const A={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},t=n.RTCPeerConnection.prototype.getStats;n.RTCPeerConnection.prototype.getStats=function(){const[r,s,o]=arguments;return t.apply(this,[r||null]).then(a=>{if(e.version<53&&!s)try{a.forEach(c=>{c.type=A[c.type]||c.type})}catch(c){if(c.name!=="TypeError")throw c;a.forEach((l,u)=>{a.set(u,Object.assign({},l,{type:A[l.type]||l.type}))})}return a}).then(s,o)}}function Mc(n){if(!(typeof n=="object"&&n.RTCPeerConnection&&n.RTCRtpSender)||n.RTCRtpSender&&"getStats"in n.RTCRtpSender.prototype)return;const e=n.RTCPeerConnection.prototype.getSenders;e&&(n.RTCPeerConnection.prototype.getSenders=function(){const i=e.apply(this,[]);return i.forEach(r=>r._pc=this),i});const A=n.RTCPeerConnection.prototype.addTrack;A&&(n.RTCPeerConnection.prototype.addTrack=function(){const i=A.apply(this,arguments);return i._pc=this,i}),n.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}function Nc(n){if(!(typeof n=="object"&&n.RTCPeerConnection&&n.RTCRtpSender)||n.RTCRtpSender&&"getStats"in n.RTCRtpReceiver.prototype)return;const e=n.RTCPeerConnection.prototype.getReceivers;e&&(n.RTCPeerConnection.prototype.getReceivers=function(){const t=e.apply(this,[]);return t.forEach(i=>i._pc=this),t}),at(n,"track",A=>(A.receiver._pc=A.srcElement,A)),n.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function Kc(n){!n.RTCPeerConnection||"removeStream"in n.RTCPeerConnection.prototype||(n.RTCPeerConnection.prototype.removeStream=function(A){is("removeStream","removeTrack"),this.getSenders().forEach(t=>{t.track&&A.getTracks().includes(t.track)&&this.removeTrack(t)})})}function Vc(n){n.DataChannel&&!n.RTCDataChannel&&(n.RTCDataChannel=n.DataChannel)}function Gc(n){if(!(typeof n=="object"&&n.RTCPeerConnection))return;const e=n.RTCPeerConnection.prototype.addTransceiver;e&&(n.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let t=arguments[1]&&arguments[1].sendEncodings;t===void 0&&(t=[]),t=[...t];const i=t.length>0;i&&t.forEach(s=>{if("rid"in s&&!/^[a-z0-9]{0,16}$/i.test(s.rid))throw new TypeError("Invalid RID value provided.");if("scaleResolutionDownBy"in s&&!(parseFloat(s.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in s&&!(parseFloat(s.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")});const r=e.apply(this,arguments);if(i){const{sender:s}=r,o=s.getParameters();(!("encodings"in o)||o.encodings.length===1&&Object.keys(o.encodings[0]).length===0)&&(o.encodings=t,s.sendEncodings=t,this.setParametersPromises.push(s.setParameters(o).then(()=>{delete s.sendEncodings}).catch(()=>{delete s.sendEncodings})))}return r})}function jc(n){if(!(typeof n=="object"&&n.RTCRtpSender))return;const e=n.RTCRtpSender.prototype.getParameters;e&&(n.RTCRtpSender.prototype.getParameters=function(){const t=e.apply(this,arguments);return"encodings"in t||(t.encodings=[].concat(this.sendEncodings||[{}])),t})}function Jc(n){if(!(typeof n=="object"&&n.RTCPeerConnection))return;const e=n.RTCPeerConnection.prototype.createOffer;n.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 Wc(n){if(!(typeof n=="object"&&n.RTCPeerConnection))return;const e=n.RTCPeerConnection.prototype.createAnswer;n.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 Xc=Object.freeze({__proto__:null,shimAddTransceiver:Gc,shimCreateAnswer:Wc,shimCreateOffer:Jc,shimGetDisplayMedia:fg,shimGetParameters:jc,shimGetUserMedia:Hc,shimOnTrack:Oc,shimPeerConnection:os,shimRTCDataChannel:Vc,shimReceiverGetStats:Nc,shimRemoveStream:Kc,shimSenderGetStats:Mc});function $c(n){if(!(typeof n!="object"||!n.RTCPeerConnection)){if("getLocalStreams"in n.RTCPeerConnection.prototype||(n.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in n.RTCPeerConnection.prototype)){const e=n.RTCPeerConnection.prototype.addTrack;n.RTCPeerConnection.prototype.addStream=function(t){this._localStreams||(this._localStreams=[]),this._localStreams.includes(t)||this._localStreams.push(t),t.getAudioTracks().forEach(i=>e.call(this,i,t)),t.getVideoTracks().forEach(i=>e.call(this,i,t))},n.RTCPeerConnection.prototype.addTrack=function(t){for(var i=arguments.length,r=new Array(i>1?i-1:0),s=1;s<i;s++)r[s-1]=arguments[s];return r&&r.forEach(o=>{this._localStreams?this._localStreams.includes(o)||this._localStreams.push(o):this._localStreams=[o]}),e.apply(this,arguments)}}"removeStream"in n.RTCPeerConnection.prototype||(n.RTCPeerConnection.prototype.removeStream=function(A){this._localStreams||(this._localStreams=[]);const t=this._localStreams.indexOf(A);if(t===-1)return;this._localStreams.splice(t,1);const i=A.getTracks();this.getSenders().forEach(r=>{i.includes(r.track)&&this.removeTrack(r)})})}}function Yc(n){if(!(typeof n!="object"||!n.RTCPeerConnection)&&("getRemoteStreams"in n.RTCPeerConnection.prototype||(n.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]}),!("onaddstream"in n.RTCPeerConnection.prototype))){Object.defineProperty(n.RTCPeerConnection.prototype,"onaddstream",{get(){return this._onaddstream},set(A){this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=A),this.addEventListener("track",this._onaddstreampoly=t=>{t.streams.forEach(i=>{if(this._remoteStreams||(this._remoteStreams=[]),this._remoteStreams.includes(i))return;this._remoteStreams.push(i);const r=new Event("addstream");r.stream=i,this.dispatchEvent(r)})})}});const e=n.RTCPeerConnection.prototype.setRemoteDescription;n.RTCPeerConnection.prototype.setRemoteDescription=function(){const t=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(i){i.streams.forEach(r=>{if(t._remoteStreams||(t._remoteStreams=[]),t._remoteStreams.indexOf(r)>=0)return;t._remoteStreams.push(r);const s=new Event("addstream");s.stream=r,t.dispatchEvent(s)})}),e.apply(t,arguments)}}}function qc(n){if(typeof n!="object"||!n.RTCPeerConnection)return;const e=n.RTCPeerConnection.prototype,A=e.createOffer,t=e.createAnswer,i=e.setLocalDescription,r=e.setRemoteDescription,s=e.addIceCandidate;e.createOffer=function(c,l){const u=arguments.length>=2?arguments[2]:arguments[0],d=A.apply(this,[u]);return l?(d.then(c,l),Promise.resolve()):d},e.createAnswer=function(c,l){const u=arguments.length>=2?arguments[2]:arguments[0],d=t.apply(this,[u]);return l?(d.then(c,l),Promise.resolve()):d};let o=function(a,c,l){const u=i.apply(this,[a]);return l?(u.then(c,l),Promise.resolve()):u};e.setLocalDescription=o,o=function(a,c,l){const u=r.apply(this,[a]);return l?(u.then(c,l),Promise.resolve()):u},e.setRemoteDescription=o,o=function(a,c,l){const u=s.apply(this,[a]);return l?(u.then(c,l),Promise.resolve()):u},e.addIceCandidate=o}function Zc(n){const e=n&&n.navigator;if(e.mediaDevices&&e.mediaDevices.getUserMedia){const A=e.mediaDevices,t=A.getUserMedia.bind(A);e.mediaDevices.getUserMedia=i=>t(zc(i))}!e.getUserMedia&&e.mediaDevices&&e.mediaDevices.getUserMedia&&(e.getUserMedia=(function(t,i,r){e.mediaDevices.getUserMedia(t).then(i,r)}).bind(e))}function zc(n){return n&&n.video!==void 0?Object.assign({},n,{video:Ec(n.video)}):n}function el(n){if(!n.RTCPeerConnection)return;const e=n.RTCPeerConnection;n.RTCPeerConnection=function(t,i){if(t&&t.iceServers){const r=[];for(let s=0;s<t.iceServers.length;s++){let o=t.iceServers[s];o.urls===void 0&&o.url?(is("RTCIceServer.url","RTCIceServer.urls"),o=JSON.parse(JSON.stringify(o)),o.urls=o.url,delete o.url,r.push(o)):r.push(t.iceServers[s])}t.iceServers=r}return new e(t,i)},n.RTCPeerConnection.prototype=e.prototype,"generateCertificate"in e&&Object.defineProperty(n.RTCPeerConnection,"generateCertificate",{get(){return e.generateCertificate}})}function Al(n){typeof n=="object"&&n.RTCTrackEvent&&"receiver"in n.RTCTrackEvent.prototype&&!("transceiver"in n.RTCTrackEvent.prototype)&&Object.defineProperty(n.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function tl(n){const e=n.RTCPeerConnection.prototype.createOffer;n.RTCPeerConnection.prototype.createOffer=function(t){if(t){typeof t.offerToReceiveAudio<"u"&&(t.offerToReceiveAudio=!!t.offerToReceiveAudio);const i=this.getTransceivers().find(s=>s.receiver.track.kind==="audio");t.offerToReceiveAudio===!1&&i?i.direction==="sendrecv"?i.setDirection?i.setDirection("sendonly"):i.direction="sendonly":i.direction==="recvonly"&&(i.setDirection?i.setDirection("inactive"):i.direction="inactive"):t.offerToReceiveAudio===!0&&!i&&this.addTransceiver("audio",{direction:"recvonly"}),typeof t.offerToReceiveVideo<"u"&&(t.offerToReceiveVideo=!!t.offerToReceiveVideo);const r=this.getTransceivers().find(s=>s.receiver.track.kind==="video");t.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"):t.offerToReceiveVideo===!0&&!r&&this.addTransceiver("video",{direction:"recvonly"})}return e.apply(this,arguments)}}function nl(n){typeof n!="object"||n.AudioContext||(n.AudioContext=n.webkitAudioContext)}var il=Object.freeze({__proto__:null,shimAudioContext:nl,shimCallbacksAPI:qc,shimConstraints:zc,shimCreateOfferLegacy:tl,shimGetUserMedia:Zc,shimLocalStreamsAPI:$c,shimRTCIceServerUrls:el,shimRemoteStreamsAPI:Yc,shimTrackEventTransceiver:Al}),as={exports:{}},rl;function gg(){return rl||(rl=1,function(n){const e={};e.generateIdentifier=function(){return Math.random().toString(36).substring(2,12)},e.localCName=e.generateIdentifier(),e.splitLines=function(A){return A.trim().split(`
3
+ `).map(t=>t.trim())},e.splitSections=function(A){return A.split(`
4
+ m=`).map((i,r)=>(r>0?"m="+i:i).trim()+`\r
5
+ `)},e.getDescription=function(A){const t=e.splitSections(A);return t&&t[0]},e.getMediaSections=function(A){const t=e.splitSections(A);return t.shift(),t},e.matchPrefix=function(A,t){return e.splitLines(A).filter(i=>i.indexOf(t)===0)},e.parseCandidate=function(A){let t;A.indexOf("a=candidate:")===0?t=A.substring(12).split(" "):t=A.substring(10).split(" ");const i={foundation:t[0],component:{1:"rtp",2:"rtcp"}[t[1]]||t[1],protocol:t[2].toLowerCase(),priority:parseInt(t[3],10),ip:t[4],address:t[4],port:parseInt(t[5],10),type:t[7]};for(let r=8;r<t.length;r+=2)switch(t[r]){case"raddr":i.relatedAddress=t[r+1];break;case"rport":i.relatedPort=parseInt(t[r+1],10);break;case"tcptype":i.tcpType=t[r+1];break;case"ufrag":i.ufrag=t[r+1],i.usernameFragment=t[r+1];break;default:i[t[r]]===void 0&&(i[t[r]]=t[r+1]);break}return i},e.writeCandidate=function(A){const t=[];t.push(A.foundation);const i=A.component;i==="rtp"?t.push(1):i==="rtcp"?t.push(2):t.push(i),t.push(A.protocol.toUpperCase()),t.push(A.priority),t.push(A.address||A.ip),t.push(A.port);const r=A.type;return t.push("typ"),t.push(r),r!=="host"&&A.relatedAddress&&A.relatedPort&&(t.push("raddr"),t.push(A.relatedAddress),t.push("rport"),t.push(A.relatedPort)),A.tcpType&&A.protocol.toLowerCase()==="tcp"&&(t.push("tcptype"),t.push(A.tcpType)),(A.usernameFragment||A.ufrag)&&(t.push("ufrag"),t.push(A.usernameFragment||A.ufrag)),"candidate:"+t.join(" ")},e.parseIceOptions=function(A){return A.substring(14).split(" ")},e.parseRtpMap=function(A){let t=A.substring(9).split(" ");const i={payloadType:parseInt(t.shift(),10)};return t=t[0].split("/"),i.name=t[0],i.clockRate=parseInt(t[1],10),i.channels=t.length===3?parseInt(t[2],10):1,i.numChannels=i.channels,i},e.writeRtpMap=function(A){let t=A.payloadType;A.preferredPayloadType!==void 0&&(t=A.preferredPayloadType);const i=A.channels||A.numChannels||1;return"a=rtpmap:"+t+" "+A.name+"/"+A.clockRate+(i!==1?"/"+i:"")+`\r
6
+ `},e.parseExtmap=function(A){const t=A.substring(9).split(" ");return{id:parseInt(t[0],10),direction:t[0].indexOf("/")>0?t[0].split("/")[1]:"sendrecv",uri:t[1],attributes:t.slice(2).join(" ")}},e.writeExtmap=function(A){return"a=extmap:"+(A.id||A.preferredId)+(A.direction&&A.direction!=="sendrecv"?"/"+A.direction:"")+" "+A.uri+(A.attributes?" "+A.attributes:"")+`\r
7
+ `},e.parseFmtp=function(A){const t={};let i;const r=A.substring(A.indexOf(" ")+1).split(";");for(let s=0;s<r.length;s++)i=r[s].trim().split("="),t[i[0].trim()]=i[1];return t},e.writeFmtp=function(A){let t="",i=A.payloadType;if(A.preferredPayloadType!==void 0&&(i=A.preferredPayloadType),A.parameters&&Object.keys(A.parameters).length){const r=[];Object.keys(A.parameters).forEach(s=>{A.parameters[s]!==void 0?r.push(s+"="+A.parameters[s]):r.push(s)}),t+="a=fmtp:"+i+" "+r.join(";")+`\r
8
+ `}return t},e.parseRtcpFb=function(A){const t=A.substring(A.indexOf(" ")+1).split(" ");return{type:t.shift(),parameter:t.join(" ")}},e.writeRtcpFb=function(A){let t="",i=A.payloadType;return A.preferredPayloadType!==void 0&&(i=A.preferredPayloadType),A.rtcpFeedback&&A.rtcpFeedback.length&&A.rtcpFeedback.forEach(r=>{t+="a=rtcp-fb:"+i+" "+r.type+(r.parameter&&r.parameter.length?" "+r.parameter:"")+`\r
9
+ `}),t},e.parseSsrcMedia=function(A){const t=A.indexOf(" "),i={ssrc:parseInt(A.substring(7,t),10)},r=A.indexOf(":",t);return r>-1?(i.attribute=A.substring(t+1,r),i.value=A.substring(r+1)):i.attribute=A.substring(t+1),i},e.parseSsrcGroup=function(A){const t=A.substring(13).split(" ");return{semantics:t.shift(),ssrcs:t.map(i=>parseInt(i,10))}},e.getMid=function(A){const t=e.matchPrefix(A,"a=mid:")[0];if(t)return t.substring(6)},e.parseFingerprint=function(A){const t=A.substring(14).split(" ");return{algorithm:t[0].toLowerCase(),value:t[1].toUpperCase()}},e.getDtlsParameters=function(A,t){return{role:"auto",fingerprints:e.matchPrefix(A+t,"a=fingerprint:").map(e.parseFingerprint)}},e.writeDtlsParameters=function(A,t){let i="a=setup:"+t+`\r
10
+ `;return A.fingerprints.forEach(r=>{i+="a=fingerprint:"+r.algorithm+" "+r.value+`\r
11
+ `}),i},e.parseCryptoLine=function(A){const t=A.substring(9).split(" ");return{tag:parseInt(t[0],10),cryptoSuite:t[1],keyParams:t[2],sessionParams:t.slice(3)}},e.writeCryptoLine=function(A){return"a=crypto:"+A.tag+" "+A.cryptoSuite+" "+(typeof A.keyParams=="object"?e.writeCryptoKeyParams(A.keyParams):A.keyParams)+(A.sessionParams?" "+A.sessionParams.join(" "):"")+`\r
12
+ `},e.parseCryptoKeyParams=function(A){if(A.indexOf("inline:")!==0)return null;const t=A.substring(7).split("|");return{keyMethod:"inline",keySalt:t[0],lifeTime:t[1],mkiValue:t[2]?t[2].split(":")[0]:void 0,mkiLength:t[2]?t[2].split(":")[1]:void 0}},e.writeCryptoKeyParams=function(A){return A.keyMethod+":"+A.keySalt+(A.lifeTime?"|"+A.lifeTime:"")+(A.mkiValue&&A.mkiLength?"|"+A.mkiValue+":"+A.mkiLength:"")},e.getCryptoParameters=function(A,t){return e.matchPrefix(A+t,"a=crypto:").map(e.parseCryptoLine)},e.getIceParameters=function(A,t){const i=e.matchPrefix(A+t,"a=ice-ufrag:")[0],r=e.matchPrefix(A+t,"a=ice-pwd:")[0];return i&&r?{usernameFragment:i.substring(12),password:r.substring(10)}:null},e.writeIceParameters=function(A){let t="a=ice-ufrag:"+A.usernameFragment+`\r
13
+ a=ice-pwd:`+A.password+`\r
14
+ `;return A.iceLite&&(t+=`a=ice-lite\r
15
+ `),t},e.parseRtpParameters=function(A){const t={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},r=e.splitLines(A)[0].split(" ");t.profile=r[2];for(let o=3;o<r.length;o++){const a=r[o],c=e.matchPrefix(A,"a=rtpmap:"+a+" ")[0];if(c){const l=e.parseRtpMap(c),u=e.matchPrefix(A,"a=fmtp:"+a+" ");switch(l.parameters=u.length?e.parseFmtp(u[0]):{},l.rtcpFeedback=e.matchPrefix(A,"a=rtcp-fb:"+a+" ").map(e.parseRtcpFb),t.codecs.push(l),l.name.toUpperCase()){case"RED":case"ULPFEC":t.fecMechanisms.push(l.name.toUpperCase());break}}}e.matchPrefix(A,"a=extmap:").forEach(o=>{t.headerExtensions.push(e.parseExtmap(o))});const s=e.matchPrefix(A,"a=rtcp-fb:* ").map(e.parseRtcpFb);return t.codecs.forEach(o=>{s.forEach(a=>{o.rtcpFeedback.find(l=>l.type===a.type&&l.parameter===a.parameter)||o.rtcpFeedback.push(a)})}),t},e.writeRtpDescription=function(A,t){let i="";i+="m="+A+" ",i+=t.codecs.length>0?"9":"0",i+=" "+(t.profile||"UDP/TLS/RTP/SAVPF")+" ",i+=t.codecs.map(s=>s.preferredPayloadType!==void 0?s.preferredPayloadType:s.payloadType).join(" ")+`\r
16
+ `,i+=`c=IN IP4 0.0.0.0\r
17
+ `,i+=`a=rtcp:9 IN IP4 0.0.0.0\r
18
+ `,t.codecs.forEach(s=>{i+=e.writeRtpMap(s),i+=e.writeFmtp(s),i+=e.writeRtcpFb(s)});let r=0;return t.codecs.forEach(s=>{s.maxptime>r&&(r=s.maxptime)}),r>0&&(i+="a=maxptime:"+r+`\r
19
+ `),t.headerExtensions&&t.headerExtensions.forEach(s=>{i+=e.writeExtmap(s)}),i},e.parseRtpEncodingParameters=function(A){const t=[],i=e.parseRtpParameters(A),r=i.fecMechanisms.indexOf("RED")!==-1,s=i.fecMechanisms.indexOf("ULPFEC")!==-1,o=e.matchPrefix(A,"a=ssrc:").map(d=>e.parseSsrcMedia(d)).filter(d=>d.attribute==="cname"),a=o.length>0&&o[0].ssrc;let c;const l=e.matchPrefix(A,"a=ssrc-group:FID").map(d=>d.substring(17).split(" ").map(f=>parseInt(f,10)));l.length>0&&l[0].length>1&&l[0][0]===a&&(c=l[0][1]),i.codecs.forEach(d=>{if(d.name.toUpperCase()==="RTX"&&d.parameters.apt){let h={ssrc:a,codecPayloadType:parseInt(d.parameters.apt,10)};a&&c&&(h.rtx={ssrc:c}),t.push(h),r&&(h=JSON.parse(JSON.stringify(h)),h.fec={ssrc:a,mechanism:s?"red+ulpfec":"red"},t.push(h))}}),t.length===0&&a&&t.push({ssrc:a});let u=e.matchPrefix(A,"b=");return u.length&&(u[0].indexOf("b=TIAS:")===0?u=parseInt(u[0].substring(7),10):u[0].indexOf("b=AS:")===0?u=parseInt(u[0].substring(5),10)*1e3*.95-50*40*8:u=void 0,t.forEach(d=>{d.maxBitrate=u})),t},e.parseRtcpParameters=function(A){const t={},i=e.matchPrefix(A,"a=ssrc:").map(o=>e.parseSsrcMedia(o)).filter(o=>o.attribute==="cname")[0];i&&(t.cname=i.value,t.ssrc=i.ssrc);const r=e.matchPrefix(A,"a=rtcp-rsize");t.reducedSize=r.length>0,t.compound=r.length===0;const s=e.matchPrefix(A,"a=rtcp-mux");return t.mux=s.length>0,t},e.writeRtcpParameters=function(A){let t="";return A.reducedSize&&(t+=`a=rtcp-rsize\r
20
+ `),A.mux&&(t+=`a=rtcp-mux\r
21
+ `),A.ssrc!==void 0&&A.cname&&(t+="a=ssrc:"+A.ssrc+" cname:"+A.cname+`\r
22
+ `),t},e.parseMsid=function(A){let t;const i=e.matchPrefix(A,"a=msid:");if(i.length===1)return t=i[0].substring(7).split(" "),{stream:t[0],track:t[1]};const r=e.matchPrefix(A,"a=ssrc:").map(s=>e.parseSsrcMedia(s)).filter(s=>s.attribute==="msid");if(r.length>0)return t=r[0].value.split(" "),{stream:t[0],track:t[1]}},e.parseSctpDescription=function(A){const t=e.parseMLine(A),i=e.matchPrefix(A,"a=max-message-size:");let r;i.length>0&&(r=parseInt(i[0].substring(19),10)),isNaN(r)&&(r=65536);const s=e.matchPrefix(A,"a=sctp-port:");if(s.length>0)return{port:parseInt(s[0].substring(12),10),protocol:t.fmt,maxMessageSize:r};const o=e.matchPrefix(A,"a=sctpmap:");if(o.length>0){const a=o[0].substring(10).split(" ");return{port:parseInt(a[0],10),protocol:a[1],maxMessageSize:r}}},e.writeSctpDescription=function(A,t){let i=[];return A.protocol!=="DTLS/SCTP"?i=["m="+A.kind+" 9 "+A.protocol+" "+t.protocol+`\r
23
+ `,`c=IN IP4 0.0.0.0\r
24
+ `,"a=sctp-port:"+t.port+`\r
25
+ `]:i=["m="+A.kind+" 9 "+A.protocol+" "+t.port+`\r
26
+ `,`c=IN IP4 0.0.0.0\r
27
+ `,"a=sctpmap:"+t.port+" "+t.protocol+` 65535\r
28
+ `],t.maxMessageSize!==void 0&&i.push("a=max-message-size:"+t.maxMessageSize+`\r
29
+ `),i.join("")},e.generateSessionId=function(){return Math.random().toString().substr(2,22)},e.writeSessionBoilerplate=function(A,t,i){let r;const s=t!==void 0?t:2;return A?r=A:r=e.generateSessionId(),`v=0\r
30
+ o=`+(i||"thisisadapterortc")+" "+r+" "+s+` IN IP4 127.0.0.1\r
31
+ s=-\r
32
+ t=0 0\r
33
+ `},e.getDirection=function(A,t){const i=e.splitLines(A);for(let r=0;r<i.length;r++)switch(i[r]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return i[r].substring(2)}return t?e.getDirection(t):"sendrecv"},e.getKind=function(A){return e.splitLines(A)[0].split(" ")[0].substring(2)},e.isRejected=function(A){return A.split(" ",2)[1]==="0"},e.parseMLine=function(A){const i=e.splitLines(A)[0].substring(2).split(" ");return{kind:i[0],port:parseInt(i[1],10),protocol:i[2],fmt:i.slice(3).join(" ")}},e.parseOLine=function(A){const i=e.matchPrefix(A,"o=")[0].substring(2).split(" ");return{username:i[0],sessionId:i[1],sessionVersion:parseInt(i[2],10),netType:i[3],addressType:i[4],address:i[5]}},e.isValidSDP=function(A){if(typeof A!="string"||A.length===0)return!1;const t=e.splitLines(A);for(let i=0;i<t.length;i++)if(t[i].length<2||t[i].charAt(1)!=="=")return!1;return!0},n.exports=e}(as)),as.exports}var sl=gg(),Pt=ng(sl),pg=Sh({__proto__:null,default:Pt},[sl]);function gi(n){if(!n.RTCIceCandidate||n.RTCIceCandidate&&"foundation"in n.RTCIceCandidate.prototype)return;const e=n.RTCIceCandidate;n.RTCIceCandidate=function(t){if(typeof t=="object"&&t.candidate&&t.candidate.indexOf("a=")===0&&(t=JSON.parse(JSON.stringify(t)),t.candidate=t.candidate.substring(2)),t.candidate&&t.candidate.length){const i=new e(t),r=Pt.parseCandidate(t.candidate);for(const s in r)s in i||Object.defineProperty(i,s,{value:r[s]});return i.toJSON=function(){return{candidate:i.candidate,sdpMid:i.sdpMid,sdpMLineIndex:i.sdpMLineIndex,usernameFragment:i.usernameFragment}},i}return new e(t)},n.RTCIceCandidate.prototype=e.prototype,at(n,"icecandidate",A=>(A.candidate&&Object.defineProperty(A,"candidate",{value:new n.RTCIceCandidate(A.candidate),writable:"false"}),A))}function cs(n){!n.RTCIceCandidate||n.RTCIceCandidate&&"relayProtocol"in n.RTCIceCandidate.prototype||at(n,"icecandidate",e=>{if(e.candidate){const A=Pt.parseCandidate(e.candidate.candidate);A.type==="relay"&&(e.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[A.priority>>24])}return e})}function pi(n,e){if(!n.RTCPeerConnection)return;"sctp"in n.RTCPeerConnection.prototype||Object.defineProperty(n.RTCPeerConnection.prototype,"sctp",{get(){return typeof this._sctp>"u"?null:this._sctp}});const A=function(o){if(!o||!o.sdp)return!1;const a=Pt.splitSections(o.sdp);return a.shift(),a.some(c=>{const l=Pt.parseMLine(c);return l&&l.kind==="application"&&l.protocol.indexOf("SCTP")!==-1})},t=function(o){const a=o.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(a===null||a.length<2)return-1;const c=parseInt(a[1],10);return c!==c?-1:c},i=function(o){let a=65536;return e.browser==="firefox"&&(e.version<57?o===-1?a=16384:a=2147483637:e.version<60?a=e.version===57?65535:65536:a=2147483637),a},r=function(o,a){let c=65536;e.browser==="firefox"&&e.version===57&&(c=65535);const l=Pt.matchPrefix(o.sdp,"a=max-message-size:");return l.length>0?c=parseInt(l[0].substring(19),10):e.browser==="firefox"&&a!==-1&&(c=2147483637),c},s=n.RTCPeerConnection.prototype.setRemoteDescription;n.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,e.browser==="chrome"&&e.version>=76){const{sdpSemantics:a}=this.getConfiguration();a==="plan-b"&&Object.defineProperty(this,"sctp",{get(){return typeof this._sctp>"u"?null:this._sctp},enumerable:!0,configurable:!0})}if(A(arguments[0])){const a=t(arguments[0]),c=i(a),l=r(arguments[0],a);let u;c===0&&l===0?u=Number.POSITIVE_INFINITY:c===0||l===0?u=Math.max(c,l):u=Math.min(c,l);const d={};Object.defineProperty(d,"maxMessageSize",{get(){return u}}),this._sctp=d}return s.apply(this,arguments)}}function mi(n){if(!(n.RTCPeerConnection&&"createDataChannel"in n.RTCPeerConnection.prototype))return;function e(t,i){const r=t.send;t.send=function(){const o=arguments[0],a=o.length||o.size||o.byteLength;if(t.readyState==="open"&&i.sctp&&a>i.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+i.sctp.maxMessageSize+" bytes)");return r.apply(t,arguments)}}const A=n.RTCPeerConnection.prototype.createDataChannel;n.RTCPeerConnection.prototype.createDataChannel=function(){const i=A.apply(this,arguments);return e(i,this),i},at(n,"datachannel",t=>(e(t.channel,t.target),t))}function ls(n){if(!n.RTCPeerConnection||"connectionState"in n.RTCPeerConnection.prototype)return;const e=n.RTCPeerConnection.prototype;Object.defineProperty(e,"connectionState",{get(){return{completed:"connected",checking:"connecting"}[this.iceConnectionState]||this.iceConnectionState},enumerable:!0,configurable:!0}),Object.defineProperty(e,"onconnectionstatechange",{get(){return this._onconnectionstatechange||null},set(A){this._onconnectionstatechange&&(this.removeEventListener("connectionstatechange",this._onconnectionstatechange),delete this._onconnectionstatechange),A&&this.addEventListener("connectionstatechange",this._onconnectionstatechange=A)},enumerable:!0,configurable:!0}),["setLocalDescription","setRemoteDescription"].forEach(A=>{const t=e[A];e[A]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=i=>{const r=i.target;if(r._lastConnectionState!==r.connectionState){r._lastConnectionState=r.connectionState;const s=new Event("connectionstatechange",i);r.dispatchEvent(s)}return i},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),t.apply(this,arguments)}})}function us(n,e){if(!n.RTCPeerConnection||e.browser==="chrome"&&e.version>=71||e.browser==="safari"&&e.version>=605)return;const A=n.RTCPeerConnection.prototype.setRemoteDescription;n.RTCPeerConnection.prototype.setRemoteDescription=function(i){if(i&&i.sdp&&i.sdp.indexOf(`
34
+ a=extmap-allow-mixed`)!==-1){const r=i.sdp.split(`
35
+ `).filter(s=>s.trim()!=="a=extmap-allow-mixed").join(`
36
+ `);n.RTCSessionDescription&&i instanceof n.RTCSessionDescription?arguments[0]=new n.RTCSessionDescription({type:i.type,sdp:r}):i.sdp=r}return A.apply(this,arguments)}}function Bi(n,e){if(!(n.RTCPeerConnection&&n.RTCPeerConnection.prototype))return;const A=n.RTCPeerConnection.prototype.addIceCandidate;!A||A.length===0||(n.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?(e.browser==="chrome"&&e.version<78||e.browser==="firefox"&&e.version<68||e.browser==="safari")&&arguments[0]&&arguments[0].candidate===""?Promise.resolve():A.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}function vi(n,e){if(!(n.RTCPeerConnection&&n.RTCPeerConnection.prototype))return;const A=n.RTCPeerConnection.prototype.setLocalDescription;!A||A.length===0||(n.RTCPeerConnection.prototype.setLocalDescription=function(){let i=arguments[0]||{};if(typeof i!="object"||i.type&&i.sdp)return A.apply(this,arguments);if(i={type:i.type,sdp:i.sdp},!i.type)switch(this.signalingState){case"stable":case"have-local-offer":case"have-remote-pranswer":i.type="offer";break;default:i.type="answer";break}return i.sdp||i.type!=="offer"&&i.type!=="answer"?A.apply(this,[i]):(i.type==="offer"?this.createOffer:this.createAnswer).apply(this).then(s=>A.apply(this,[s]))})}var mg=Object.freeze({__proto__:null,removeExtmapAllowMixed:us,shimAddIceCandidateNullOrEmpty:Bi,shimConnectionState:ls,shimMaxMessageSize:pi,shimParameterlessSetLocalDescription:vi,shimRTCIceCandidate:gi,shimRTCIceCandidateRelayProtocol:cs,shimSendThrowTypeError:mi});function Bg(){let{window:n}=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 A=Uc,t=hg(n),i={browserDetails:t,commonShim:mg,extractVersion:fi,disableLog:ug,disableWarnings:dg,sdp:pg};switch(t.browser){case"chrome":if(!_c||!ss||!e.shimChrome)return A("Chrome shim is not included in this adapter release."),i;if(t.version===null)return A("Chrome shim can not determine version, not shimming."),i;A("adapter.js shimming chrome."),i.browserShim=_c,Bi(n,t),vi(n),Fc(n,t),kc(n),ss(n,t),Ic(n),Lc(n,t),Rc(n),xc(n),Dc(n,t),gi(n),cs(n),ls(n),pi(n,t),mi(n),us(n,t);break;case"firefox":if(!Xc||!os||!e.shimFirefox)return A("Firefox shim is not included in this adapter release."),i;A("adapter.js shimming firefox."),i.browserShim=Xc,Bi(n,t),vi(n),Hc(n,t),os(n,t),Oc(n),Kc(n),Mc(n),Nc(n),Vc(n),Gc(n),jc(n),Jc(n),Wc(n),gi(n),ls(n),pi(n,t),mi(n);break;case"safari":if(!il||!e.shimSafari)return A("Safari shim is not included in this adapter release."),i;A("adapter.js shimming safari."),i.browserShim=il,Bi(n,t),vi(n),el(n),tl(n),qc(n),$c(n),Yc(n),Al(n),Zc(n),nl(n),gi(n),cs(n),pi(n,t),mi(n),us(n,t);break;default:A("Unsupported browser!");break}return i}Bg({window:typeof window>"u"?void 0:window});const vg=10,Ci="lk_e2ee",Cg={sharedKey:!1,ratchetSalt:"LKFrameEncryptionKey",ratchetWindowSize:8,failureTolerance:vg,keyringSize:16};var IA;(function(n){n.SetKey="setKey",n.RatchetRequest="ratchetRequest",n.KeyRatcheted="keyRatcheted"})(IA||(IA={}));var ol;(function(n){n.KeyRatcheted="keyRatcheted"})(ol||(ol={}));var RA;(function(n){n.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",n.EncryptionError="encryptionError"})(RA||(RA={}));var al;(function(n){n.Error="cryptorError"})(al||(al={}));function wg(){return yg()||ds()}function ds(){return typeof window.RTCRtpScriptTransform<"u"}function yg(){return typeof window.RTCRtpSender<"u"&&typeof window.RTCRtpSender.prototype.createEncodedStreams<"u"}class Zy extends sA.EventEmitter{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};super(),this.onKeyRatcheted=(A,t,i)=>{V.debug("key ratcheted event received",{ratchetResult:A,participantId:t,keyIndex:i})},this.keyInfoMap=new Map,this.options=Object.assign(Object.assign({},Cg),e),this.on(IA.KeyRatcheted,this.onKeyRatcheted)}onSetEncryptionKey(e,A,t){const i={key:e,participantIdentity:A,keyIndex:t};if(!this.options.sharedKey&&!A)throw new Error("participant identity needs to be passed for encryption key if sharedKey option is false");this.keyInfoMap.set("".concat(A??"shared","-").concat(t??0),i),this.emit(IA.SetKey,i)}getKeys(){return Array.from(this.keyInfoMap.values())}getOptions(){return this.options}ratchetKey(e,A){this.emit(IA.RatchetRequest,e,A)}}class xA extends Error{constructor(e,A){super(A||"an error has occured"),this.name="LiveKitError",this.code=e}}var G;(function(n){n[n.NotAllowed=0]="NotAllowed",n[n.ServerUnreachable=1]="ServerUnreachable",n[n.InternalError=2]="InternalError",n[n.Cancelled=3]="Cancelled",n[n.LeaveRequest=4]="LeaveRequest"})(G||(G={}));class Z extends xA{constructor(e,A,t,i){super(1,e),this.name="ConnectionError",this.status=t,this.reason=A,this.context=i,this.reasonName=G[A]}}class hs extends xA{constructor(e){super(21,e??"device is unsupported"),this.name="DeviceUnsupportedError"}}class mA extends xA{constructor(e){super(20,e??"track is invalid"),this.name="TrackInvalidError"}}class bg extends xA{constructor(e){super(10,e??"unsupported server"),this.name="UnsupportedServer"}}class ge extends xA{constructor(e){super(12,e??"unexpected connection state"),this.name="UnexpectedConnectionState"}}class fs extends xA{constructor(e){super(13,e??"unable to negotiate"),this.name="NegotiationError"}}class gs extends xA{constructor(e,A){super(15,e),this.name="PublishTrackError",this.status=A}}class cl extends xA{constructor(e,A){super(15,e),this.reason=A,this.reasonName=typeof A=="string"?A:ts[A]}}var wi;(function(n){n.PermissionDenied="PermissionDenied",n.NotFound="NotFound",n.DeviceInUse="DeviceInUse",n.Other="Other"})(wi||(wi={})),function(n){function e(A){if(A&&"name"in A)return A.name==="NotFoundError"||A.name==="DevicesNotFoundError"?n.NotFound:A.name==="NotAllowedError"||A.name==="PermissionDeniedError"?n.PermissionDenied:A.name==="NotReadableError"||A.name==="TrackStartError"?n.DeviceInUse:n.Other}n.getFailure=e}(wi||(wi={}));var ll;(function(n){n[n.InvalidKey=0]="InvalidKey",n[n.MissingKey=1]="MissingKey",n[n.InternalError=2]="InternalError"})(ll||(ll={}));var T;(function(n){n.Connected="connected",n.Reconnecting="reconnecting",n.SignalReconnecting="signalReconnecting",n.Reconnected="reconnected",n.Disconnected="disconnected",n.ConnectionStateChanged="connectionStateChanged",n.Moved="moved",n.MediaDevicesChanged="mediaDevicesChanged",n.ParticipantConnected="participantConnected",n.ParticipantDisconnected="participantDisconnected",n.TrackPublished="trackPublished",n.TrackSubscribed="trackSubscribed",n.TrackSubscriptionFailed="trackSubscriptionFailed",n.TrackUnpublished="trackUnpublished",n.TrackUnsubscribed="trackUnsubscribed",n.TrackMuted="trackMuted",n.TrackUnmuted="trackUnmuted",n.LocalTrackPublished="localTrackPublished",n.LocalTrackUnpublished="localTrackUnpublished",n.LocalAudioSilenceDetected="localAudioSilenceDetected",n.ActiveSpeakersChanged="activeSpeakersChanged",n.ParticipantMetadataChanged="participantMetadataChanged",n.ParticipantNameChanged="participantNameChanged",n.ParticipantAttributesChanged="participantAttributesChanged",n.ParticipantActive="participantActive",n.RoomMetadataChanged="roomMetadataChanged",n.DataReceived="dataReceived",n.SipDTMFReceived="sipDTMFReceived",n.TranscriptionReceived="transcriptionReceived",n.ConnectionQualityChanged="connectionQualityChanged",n.TrackStreamStateChanged="trackStreamStateChanged",n.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",n.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",n.AudioPlaybackStatusChanged="audioPlaybackChanged",n.VideoPlaybackStatusChanged="videoPlaybackChanged",n.MediaDevicesError="mediaDevicesError",n.ParticipantPermissionsChanged="participantPermissionsChanged",n.SignalConnected="signalConnected",n.RecordingStatusChanged="recordingStatusChanged",n.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",n.EncryptionError="encryptionError",n.DCBufferStatusChanged="dcBufferStatusChanged",n.ActiveDeviceChanged="activeDeviceChanged",n.ChatMessage="chatMessage",n.LocalTrackSubscribed="localTrackSubscribed",n.MetricsReceived="metricsReceived"})(T||(T={}));var x;(function(n){n.TrackPublished="trackPublished",n.TrackSubscribed="trackSubscribed",n.TrackSubscriptionFailed="trackSubscriptionFailed",n.TrackUnpublished="trackUnpublished",n.TrackUnsubscribed="trackUnsubscribed",n.TrackMuted="trackMuted",n.TrackUnmuted="trackUnmuted",n.LocalTrackPublished="localTrackPublished",n.LocalTrackUnpublished="localTrackUnpublished",n.ParticipantMetadataChanged="participantMetadataChanged",n.ParticipantNameChanged="participantNameChanged",n.DataReceived="dataReceived",n.SipDTMFReceived="sipDTMFReceived",n.TranscriptionReceived="transcriptionReceived",n.IsSpeakingChanged="isSpeakingChanged",n.ConnectionQualityChanged="connectionQualityChanged",n.TrackStreamStateChanged="trackStreamStateChanged",n.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",n.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",n.MediaDevicesError="mediaDevicesError",n.AudioStreamAcquired="audioStreamAcquired",n.ParticipantPermissionsChanged="participantPermissionsChanged",n.PCTrackAdded="pcTrackAdded",n.AttributesChanged="attributesChanged",n.LocalTrackSubscribed="localTrackSubscribed",n.ChatMessage="chatMessage",n.Active="active"})(x||(x={}));var I;(function(n){n.TransportsCreated="transportsCreated",n.Connected="connected",n.Disconnected="disconnected",n.Resuming="resuming",n.Resumed="resumed",n.Restarting="restarting",n.Restarted="restarted",n.SignalResumed="signalResumed",n.SignalRestarted="signalRestarted",n.Closing="closing",n.MediaTrackAdded="mediaTrackAdded",n.ActiveSpeakersUpdate="activeSpeakersUpdate",n.DataPacketReceived="dataPacketReceived",n.RTPVideoMapUpdate="rtpVideoMapUpdate",n.DCBufferStatusChanged="dcBufferStatusChanged",n.ParticipantUpdate="participantUpdate",n.RoomUpdate="roomUpdate",n.SpeakersChanged="speakersChanged",n.StreamStateChanged="streamStateChanged",n.ConnectionQualityUpdate="connectionQualityUpdate",n.SubscriptionError="subscriptionError",n.SubscriptionPermissionUpdate="subscriptionPermissionUpdate",n.RemoteMute="remoteMute",n.SubscribedQualityUpdate="subscribedQualityUpdate",n.LocalTrackUnpublished="localTrackUnpublished",n.LocalTrackSubscribed="localTrackSubscribed",n.Offline="offline",n.SignalRequestResponse="signalRequestResponse",n.SignalConnected="signalConnected",n.RoomMoved="roomMoved"})(I||(I={}));var k;(function(n){n.Message="message",n.Muted="muted",n.Unmuted="unmuted",n.Restarted="restarted",n.Ended="ended",n.Subscribed="subscribed",n.Unsubscribed="unsubscribed",n.UpdateSettings="updateSettings",n.UpdateSubscription="updateSubscription",n.AudioPlaybackStarted="audioPlaybackStarted",n.AudioPlaybackFailed="audioPlaybackFailed",n.AudioSilenceDetected="audioSilenceDetected",n.VisibilityChanged="visibilityChanged",n.VideoDimensionsChanged="videoDimensionsChanged",n.VideoPlaybackStarted="videoPlaybackStarted",n.VideoPlaybackFailed="videoPlaybackFailed",n.ElementAttached="elementAttached",n.ElementDetached="elementDetached",n.UpstreamPaused="upstreamPaused",n.UpstreamResumed="upstreamResumed",n.SubscriptionPermissionChanged="subscriptionPermissionChanged",n.SubscriptionStatusChanged="subscriptionStatusChanged",n.SubscriptionFailed="subscriptionFailed",n.TrackProcessorUpdate="trackProcessorUpdate",n.AudioTrackFeatureUpdate="audioTrackFeatureUpdate",n.TranscriptionReceived="transcriptionReceived",n.TimeSyncUpdate="timeSyncUpdate"})(k||(k={}));function Ug(n){return typeof n>"u"?n:typeof structuredClone=="function"?structuredClone(n):JSON.parse(JSON.stringify(n))}const Qg=/version\/(\d+(\.?_?\d+)+)/i;let ps;function qe(n){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;if(typeof n>"u"&&typeof navigator>"u")return;const A=(n??navigator.userAgent).toLowerCase();if(ps===void 0||e){const t=Eg.find(i=>{let{test:r}=i;return r.test(A)});ps=t==null?void 0:t.describe(A)}return ps}const Eg=[{test:/firefox|iceweasel|fxios/i,describe(n){return{name:"Firefox",version:yi(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,n),os:n.toLowerCase().includes("fxios")?"iOS":void 0,osVersion:ms(n)}}},{test:/chrom|crios|crmo/i,describe(n){return{name:"Chrome",version:yi(/(?:chrome|chromium|crios|crmo)\/(\d+(\.?_?\d+)+)/i,n),os:n.toLowerCase().includes("crios")?"iOS":void 0,osVersion:ms(n)}}},{test:/safari|applewebkit/i,describe(n){return{name:"Safari",version:yi(Qg,n),os:n.includes("mobile/")?"iOS":"macOS",osVersion:ms(n)}}}];function yi(n,e){let A=arguments.length>2&&arguments[2]!==void 0?arguments[2]:1;const t=e.match(n);return t&&t.length>=A&&t[A]||""}function ms(n){return n.includes("mac os")?yi(/\(.+?(\d+_\d+(:?_\d+)?)/,n,1).replace(/_/g,"."):void 0}var Sg="2.13.0";const Tg=Sg,Fg=16;class ve{}ve.setTimeout=function(){return setTimeout(...arguments)},ve.setInterval=function(){return setInterval(...arguments)},ve.clearTimeout=function(){return clearTimeout(...arguments)},ve.clearInterval=function(){return clearInterval(...arguments)};const kg=5e3,dn=[];var Ne;(function(n){n[n.LOW=0]="LOW",n[n.MEDIUM=1]="MEDIUM",n[n.HIGH=2]="HIGH"})(Ne||(Ne={}));class Q extends sA.EventEmitter{constructor(e,A){let t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};var i;super(),this.attachedElements=[],this.isMuted=!1,this.streamState=Q.StreamState.Active,this.isInBackground=!1,this._currentBitrate=0,this.log=V,this.appVisibilityChangedListener=()=>{this.backgroundTimeout&&clearTimeout(this.backgroundTimeout),document.visibilityState==="hidden"?this.backgroundTimeout=setTimeout(()=>this.handleAppVisibilityChanged(),kg):this.handleAppVisibilityChanged()},this.log=pA((i=t.loggerName)!==null&&i!==void 0?i:Ye.Track),this.loggerContextCb=t.loggerContextCb,this.setMaxListeners(100),this.kind=A,this._mediaStreamTrack=e,this._mediaStreamID=e.id,this.source=Q.Source.Unknown}get logContext(){var e;return Object.assign(Object.assign({},(e=this.loggerContextCb)===null||e===void 0?void 0:e.call(this)),X(this))}get currentBitrate(){return this._currentBitrate}get mediaStreamTrack(){return this._mediaStreamTrack}get mediaStreamID(){return this._mediaStreamID}attach(e){let A="audio";this.kind===Q.Kind.Video&&(A="video"),this.attachedElements.length===0&&this.kind===Q.Kind.Video&&this.addAppVisibilityListener(),e||(A==="audio"&&(dn.forEach(r=>{r.parentElement===null&&!e&&(e=r)}),e&&dn.splice(dn.indexOf(e),1)),e||(e=document.createElement(A))),this.attachedElements.includes(e)||this.attachedElements.push(e),Lt(this.mediaStreamTrack,e);const t=e.srcObject.getTracks(),i=t.some(r=>r.kind==="audio");return e.play().then(()=>{this.emit(i?k.AudioPlaybackStarted:k.VideoPlaybackStarted)}).catch(r=>{r.name==="NotAllowedError"?this.emit(i?k.AudioPlaybackFailed:k.VideoPlaybackFailed,r):r.name==="AbortError"?V.debug("".concat(i?"audio":"video"," playback aborted, likely due to new play request")):V.warn("could not playback ".concat(i?"audio":"video"),r),i&&e&&t.some(s=>s.kind==="video")&&r.name==="NotAllowedError"&&(e.muted=!0,e.play().catch(()=>{}))}),this.emit(k.ElementAttached,e),e}detach(e){try{if(e){Dt(this.mediaStreamTrack,e);const t=this.attachedElements.indexOf(e);return t>=0&&(this.attachedElements.splice(t,1),this.recycleElement(e),this.emit(k.ElementDetached,e)),e}const A=[];return this.attachedElements.forEach(t=>{Dt(this.mediaStreamTrack,t),A.push(t),this.recycleElement(t),this.emit(k.ElementDetached,t)}),this.attachedElements=[],A}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=pA(e.loggerName)),e.loggerContextCb&&(this.loggerContextCb=e.loggerContextCb)}recycleElement(e){if(e instanceof HTMLAudioElement){let A=!0;e.pause(),dn.forEach(t=>{t.parentElement||(A=!1)}),A&&dn.push(e)}}handleAppVisibilityChanged(){return p(this,void 0,void 0,function*(){this.isInBackground=document.visibilityState==="hidden",!this.isInBackground&&this.kind===Q.Kind.Video&&setTimeout(()=>this.attachedElements.forEach(e=>e.play().catch(()=>{})),0)})}addAppVisibilityListener(){Re()?(this.isInBackground=document.visibilityState==="hidden",document.addEventListener("visibilitychange",this.appVisibilityChangedListener)):this.isInBackground=!1}removeAppVisibilityListener(){Re()&&document.removeEventListener("visibilitychange",this.appVisibilityChangedListener)}}function Lt(n,e){let A;e.srcObject instanceof MediaStream?A=e.srcObject:A=new MediaStream;let t;n.kind==="audio"?t=A.getAudioTracks():t=A.getVideoTracks(),t.includes(n)||(t.forEach(i=>{A.removeTrack(i)}),A.addTrack(n)),(!PA()||!(e instanceof HTMLVideoElement))&&(e.autoplay=!0),e.muted=A.getAudioTracks().length===0,e instanceof HTMLVideoElement&&(e.playsInline=!0),e.srcObject!==A&&(e.srcObject=A,(PA()||_t())&&e instanceof HTMLVideoElement&&setTimeout(()=>{e.srcObject=A,e.play().catch(()=>{})},0))}function Dt(n,e){if(e.srcObject instanceof MediaStream){const A=e.srcObject;A.removeTrack(n),A.getTracks().length>0?e.srcObject=A:e.srcObject=null}}(function(n){let e;(function(c){c.Audio="audio",c.Video="video",c.Unknown="unknown"})(e=n.Kind||(n.Kind={}));let A;(function(c){c.Camera="camera",c.Microphone="microphone",c.ScreenShare="screen_share",c.ScreenShareAudio="screen_share_audio",c.Unknown="unknown"})(A=n.Source||(n.Source={}));let t;(function(c){c.Active="active",c.Paused="paused",c.Unknown="unknown"})(t=n.StreamState||(n.StreamState={}));function i(c){switch(c){case e.Audio:return Je.AUDIO;case e.Video:return Je.VIDEO;default:return Je.DATA}}n.kindToProto=i;function r(c){switch(c){case Je.AUDIO:return e.Audio;case Je.VIDEO:return e.Video;default:return e.Unknown}}n.kindFromProto=r;function s(c){switch(c){case A.Camera:return de.CAMERA;case A.Microphone:return de.MICROPHONE;case A.ScreenShare:return de.SCREEN_SHARE;case A.ScreenShareAudio:return de.SCREEN_SHARE_AUDIO;default:return de.UNKNOWN}}n.sourceToProto=s;function o(c){switch(c){case de.CAMERA:return A.Camera;case de.MICROPHONE:return A.Microphone;case de.SCREEN_SHARE:return A.ScreenShare;case de.SCREEN_SHARE_AUDIO:return A.ScreenShareAudio;default:return A.Unknown}}n.sourceFromProto=o;function a(c){switch(c){case $r.ACTIVE:return t.Active;case $r.PAUSED:return t.Paused;default:return t.Unknown}}n.streamStateFromProto=a})(Q||(Q={}));class Y{constructor(e,A,t,i,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(A!==void 0&&t!==void 0)this.width=e,this.height=A,this.aspectRatio=e/A,this.encoding={maxBitrate:t,maxFramerate:i,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 Ig=["vp8","h264"],Rg=["vp8","h264","vp9","av1"];function xg(n){return!!Ig.find(e=>e===n)}var ul;(function(n){n[n.PREFER_REGRESSION=0]="PREFER_REGRESSION",n[n.SIMULCAST=1]="SIMULCAST",n[n.REGRESSION=2]="REGRESSION"})(ul||(ul={}));var Bs;(function(n){n.telephone={maxBitrate:12e3},n.speech={maxBitrate:24e3},n.music={maxBitrate:48e3},n.musicStereo={maxBitrate:64e3},n.musicHighQuality={maxBitrate:96e3},n.musicHighQualityStereo={maxBitrate:128e3}})(Bs||(Bs={}));const hn={h90:new Y(160,90,9e4,20),h180:new Y(320,180,16e4,20),h216:new Y(384,216,18e4,20),h360:new Y(640,360,45e4,20),h540:new Y(960,540,8e5,25),h720:new Y(1280,720,17e5,30),h1080:new Y(1920,1080,3e6,30),h1440:new Y(2560,1440,5e6,30),h2160:new Y(3840,2160,8e6,30)},vs={h120:new Y(160,120,7e4,20),h180:new Y(240,180,125e3,20),h240:new Y(320,240,14e4,20),h360:new Y(480,360,33e4,20),h480:new Y(640,480,5e5,20),h540:new Y(720,540,6e5,25),h720:new Y(960,720,13e5,30),h1080:new Y(1440,1080,23e5,30),h1440:new Y(1920,1440,38e5,30)},Cs={h360fps3:new Y(640,360,2e5,3,"medium"),h360fps15:new Y(640,360,4e5,15,"medium"),h720fps5:new Y(1280,720,8e5,5,"medium"),h720fps15:new Y(1280,720,15e5,15,"medium"),h720fps30:new Y(1280,720,2e6,30,"medium"),h1080fps15:new Y(1920,1080,25e5,15,"medium"),h1080fps30:new Y(1920,1080,5e6,30,"medium"),original:new Y(0,0,7e6,30,"medium")},Pg="|",dl="https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension";function Lg(n){const e=n.split(Pg);return e.length>1?[e[0],n.substr(e[0].length+1)]:[n,""]}function Ie(n){return p(this,void 0,void 0,function*(){return new Promise(e=>ve.setTimeout(e,n))})}function ws(){return"addTransceiver"in RTCPeerConnection.prototype}function ys(){return"addTrack"in RTCPeerConnection.prototype}function Dg(){if(!("getCapabilities"in RTCRtpSender)||PA())return!1;const n=RTCRtpSender.getCapabilities("video");let e=!1;if(n){for(const A of n.codecs)if(A.mimeType==="video/AV1"){e=!0;break}}return e}function _g(){if(!("getCapabilities"in RTCRtpSender)||_t())return!1;if(PA()){const A=qe();if(A!=null&&A.version&&ct(A.version,"16")<0)return!1}const n=RTCRtpSender.getCapabilities("video");let e=!1;if(n){for(const A of n.codecs)if(A.mimeType==="video/VP9"){e=!0;break}}return e}function fn(n){return n==="av1"||n==="vp9"}function bs(n){return document?(n||(n=document.createElement("audio")),"setSinkId"in n):!1}function Hg(){return typeof RTCPeerConnection>"u"?!1:ws()||ys()}function _t(){var n;return((n=qe())===null||n===void 0?void 0:n.name)==="Firefox"}function PA(){var n;return((n=qe())===null||n===void 0?void 0:n.name)==="Safari"}function Og(){const n=qe();return(n==null?void 0:n.name)==="Safari"&&n.version.startsWith("17.")}function hl(){var n,e;return Re()?(e=(n=navigator.userAgentData)===null||n===void 0?void 0:n.mobile)!==null&&e!==void 0?e:/Tablet|iPad|Mobile|Android|BlackBerry/.test(navigator.userAgent):!1}function Mg(){const n=qe(),e="17.2";if(n)return n.name!=="Safari"&&n.os!=="iOS"||n.os==="iOS"&&n.osVersion&&ct(e,n.osVersion)>=0?!0:n.name==="Safari"&&ct(e,n.version)>=0}function Re(){return typeof document<"u"}function oA(){return navigator.product=="ReactNative"}function Us(n){return n.hostname.endsWith(".livekit.cloud")||n.hostname.endsWith(".livekit.run")}function fl(){if(global&&global.LiveKitReactNativeGlobal)return global.LiveKitReactNativeGlobal}function gl(){if(!oA())return;let n=fl();if(n)return n.platform}function pl(){if(Re())return window.devicePixelRatio;if(oA()){let n=fl();if(n)return n.devicePixelRatio}return 1}function ct(n,e){const A=n.split("."),t=e.split("."),i=Math.min(A.length,t.length);for(let r=0;r<i;++r){const s=parseInt(A[r],10),o=parseInt(t[r],10);if(s>o)return 1;if(s<o)return-1;if(r===i-1&&s===o)return 0}return n===""&&e!==""?-1:e===""?1:A.length==t.length?0:A.length<t.length?-1:1}function Ng(n){for(const e of n)e.target.handleResize(e)}function Kg(n){for(const e of n)e.target.handleVisibilityChanged(e)}let Qs=null;const ml=()=>(Qs||(Qs=new ResizeObserver(Ng)),Qs);let Es=null;const Bl=()=>(Es||(Es=new IntersectionObserver(Kg,{root:null,rootMargin:"0px"})),Es);function Vg(){var n;const e=new Rf({sdk:tc.JS,protocol:Fg,version:Tg});return oA()&&(e.os=(n=gl())!==null&&n!==void 0?n:""),e}function vl(){let n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:16,e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:16,A=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1,t=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1;const i=document.createElement("canvas");i.width=n,i.height=e;const r=i.getContext("2d");r==null||r.fillRect(0,0,i.width,i.height),t&&r&&(r.beginPath(),r.arc(n/2,e/2,50,0,Math.PI*2,!0),r.closePath(),r.fillStyle="grey",r.fill());const s=i.captureStream(),[o]=s.getTracks();if(!o)throw Error("Could not get empty media stream video track");return o.enabled=A,o}let gn;function Ss(){if(!gn){const n=new AudioContext,e=n.createOscillator(),A=n.createGain();A.gain.setValueAtTime(0,0);const t=n.createMediaStreamDestination();if(e.connect(A),A.connect(t),e.start(),[gn]=t.stream.getAudioTracks(),!gn)throw Error("Could not get empty media stream audio track");gn.enabled=!1}return gn.clone()}class Ts{constructor(e,A){this.onFinally=A,this.promise=new Promise((t,i)=>p(this,void 0,void 0,function*(){this.resolve=t,this.reject=i,e&&(yield e(t,i))})).finally(()=>{var t;return(t=this.onFinally)===null||t===void 0?void 0:t.call(this)})}}function Gg(n){return Rg.includes(n)}function LA(n){if(typeof n=="string"||typeof n=="number")return n;if(Array.isArray(n))return n[0];if(n.exact)return Array.isArray(n.exact)?n.exact[0]:n.exact;if(n.ideal)return Array.isArray(n.ideal)?n.ideal[0]:n.ideal;throw Error("could not unwrap constraint")}function jg(n){return n.startsWith("http")?n.replace(/^(http)/,"ws"):n}function Fs(n){return n.startsWith("ws")?n.replace(/^(ws)/,"http"):n}function Jg(n,e){return n.segments.map(A=>{let{id:t,text:i,language:r,startTime:s,endTime:o,final:a}=A;var c;const l=(c=e.get(t))!==null&&c!==void 0?c:Date.now(),u=Date.now();return a?e.delete(t):e.set(t,l),{id:t,text:i,startTime:Number.parseInt(s.toString()),endTime:Number.parseInt(o.toString()),final:a,language:r,firstReceivedTime:l,lastReceivedTime:u}})}function Wg(n){const{id:e,timestamp:A,message:t,editTimestamp:i}=n;return{id:e,timestamp:Number.parseInt(A.toString()),editTimestamp:i?Number.parseInt(i.toString()):void 0,message:t}}function Cl(n){switch(n.reason){case G.LeaveRequest:return n.context;case G.Cancelled:return We.CLIENT_INITIATED;case G.NotAllowed:return We.USER_REJECTED;case G.ServerUnreachable:return We.JOIN_FAILURE;default:return We.UNKNOWN_REASON}}function bi(n){return n!==void 0?Number(n):void 0}function lt(n){return n!==void 0?BigInt(n):void 0}function Ht(n){return!!n&&!(n instanceof MediaStreamTrack)&&n.isLocal}function BA(n){return!!n&&n.kind==Q.Kind.Audio}function Ot(n){return!!n&&n.kind==Q.Kind.Video}function DA(n){return Ht(n)&&Ot(n)}function ut(n){return Ht(n)&&BA(n)}function ks(n){return!!n&&!n.isLocal}function Xg(n){return!!n&&!n.isLocal}function Is(n){return ks(n)&&Ot(n)}function $g(n){return n.isLocal}function Yg(n,e){const A=[];let t=new TextEncoder().encode(n);for(;t.length>e;){let i=e;for(;i>0;){const r=t[i];if(r!==void 0&&(r&192)!==128)break;i--}A.push(t.slice(0,i)),t=t.slice(i)}return t.length>0&&A.push(t),A}function wl(n,e,A){var t,i,r,s;const{optionsWithoutProcessor:o,audioProcessor:a,videoProcessor:c}=Ql(n??{}),l=e==null?void 0:e.processor,u=A==null?void 0:A.processor,d=o??{};return d.audio===!0&&(d.audio={}),d.video===!0&&(d.video={}),d.audio&&(Rs(d.audio,e),(t=(r=d.audio).deviceId)!==null&&t!==void 0||(r.deviceId={ideal:"default"}),(a||l)&&(d.audio.processor=a??l)),d.video&&(Rs(d.video,A),(i=(s=d.video).deviceId)!==null&&i!==void 0||(s.deviceId={ideal:"default"}),(c||u)&&(d.video.processor=c??u)),d}function Rs(n,e){return Object.keys(e).forEach(A=>{n[A]===void 0&&(n[A]=e[A])}),n}function xs(n){var e,A,t,i;const r={};if(n.video)if(typeof n.video=="object"){const s={},o=s,a=n.video;Object.keys(a).forEach(c=>{switch(c){case"resolution":Rs(o,a.resolution);break;default:o[c]=a[c]}}),r.video=s,(e=(t=r.video).deviceId)!==null&&e!==void 0||(t.deviceId={ideal:"default"})}else r.video=n.video?{deviceId:{ideal:"default"}}:!1;else r.video=!1;return n.audio?typeof n.audio=="object"?(r.audio=n.audio,(A=(i=r.audio).deviceId)!==null&&A!==void 0||(i.deviceId={ideal:"default"})):r.audio={deviceId:{ideal:"default"}}:r.audio=!1,r}function yl(n){return p(this,arguments,void 0,function(e){let A=arguments.length>1&&arguments[1]!==void 0?arguments[1]:200;return function*(){const t=bl();if(t){const i=t.createAnalyser();i.fftSize=2048;const r=i.frequencyBinCount,s=new Uint8Array(r);t.createMediaStreamSource(new MediaStream([e.mediaStreamTrack])).connect(i),yield Ie(A),i.getByteTimeDomainData(s);const a=s.some(c=>c!==128&&c!==0);return t.close(),!a}return!1}()})}function bl(){var n;const e=typeof window<"u"&&(window.AudioContext||window.webkitAudioContext);if(e){const A=new e({latencyHint:"interactive"});if(A.state==="suspended"&&typeof window<"u"&&(!((n=window.document)===null||n===void 0)&&n.body)){const t=()=>p(this,void 0,void 0,function*(){var i;try{A.state==="suspended"&&(yield A.resume())}catch(r){console.warn("Error trying to auto-resume audio context",r)}(i=window.document.body)===null||i===void 0||i.removeEventListener("click",t)});window.document.body.addEventListener("click",t)}return A}}function qg(n){return n==="audioinput"?Q.Source.Microphone:n==="videoinput"?Q.Source.Camera:Q.Source.Unknown}function Ul(n){return n===Q.Source.Microphone?"audioinput":n===Q.Source.Camera?"videoinput":void 0}function Zg(n){var e,A;let t=(e=n.video)!==null&&e!==void 0?e:!0;return n.resolution&&n.resolution.width>0&&n.resolution.height>0&&(t=typeof t=="boolean"?{}:t,PA()?t=Object.assign(Object.assign({},t),{width:{max:n.resolution.width},height:{max:n.resolution.height},frameRate:n.resolution.frameRate}):t=Object.assign(Object.assign({},t),{width:{ideal:n.resolution.width},height:{ideal:n.resolution.height},frameRate:n.resolution.frameRate})),{audio:(A=n.audio)!==null&&A!==void 0?A:!1,video:t,controller:n.controller,selfBrowserSurface:n.selfBrowserSurface,surfaceSwitching:n.surfaceSwitching,systemAudio:n.systemAudio,preferCurrentTab:n.preferCurrentTab}}function Ui(n){return n.split("/")[1].toLowerCase()}function zg(n){const e=[];return n.forEach(A=>{A.track!==void 0&&e.push(new es({cid:A.track.mediaStreamID,track:A.trackInfo}))}),e}function X(n){return"mediaStreamTrack"in n?{trackID:n.sid,source:n.source,muted:n.isMuted,enabled:n.mediaStreamTrack.enabled,kind:n.kind,streamID:n.mediaStreamID,streamTrackID:n.mediaStreamTrack.id}:{trackID:n.trackSid,enabled:n.isEnabled,muted:n.isMuted,trackInfo:Object.assign({mimeType:n.mimeType,name:n.trackName,encrypted:n.isEncrypted,kind:n.kind,source:n.source},n.track?X(n.track):{})}}function ep(){return typeof RTCRtpReceiver<"u"&&"getSynchronizationSources"in RTCRtpReceiver}function Ap(n,e){var A;n===void 0&&(n={}),e===void 0&&(e={});const t=[...Object.keys(e),...Object.keys(n)],i={};for(const r of t)n[r]!==e[r]&&(i[r]=(A=e[r])!==null&&A!==void 0?A:"");return i}function Ql(n){const e=Object.assign({},n);let A,t;return typeof e.audio=="object"&&e.audio.processor&&(A=e.audio.processor,e.audio=Object.assign(Object.assign({},e.audio),{processor:void 0})),typeof e.video=="object"&&e.video.processor&&(t=e.video.processor,e.video=Object.assign(Object.assign({},e.video),{processor:void 0})),{audioProcessor:A,videoProcessor:t,optionsWithoutProcessor:Ug(e)}}function tp(n){switch(n){case de.CAMERA:return Q.Source.Camera;case de.MICROPHONE:return Q.Source.Microphone;case de.SCREEN_SHARE:return Q.Source.ScreenShare;case de.SCREEN_SHARE_AUDIO:return Q.Source.ScreenShareAudio;default:return Q.Source.Unknown}}class np extends sA.EventEmitter{constructor(e){super(),this.onWorkerMessage=A=>{var t,i;const{kind:r,data:s}=A.data;switch(r){case"error":V.error(s.error.message),this.emit(RA.EncryptionError,s.error);break;case"initAck":s.enabled&&this.keyProvider.getKeys().forEach(o=>{this.postKey(o)});break;case"enable":if(s.enabled&&this.keyProvider.getKeys().forEach(o=>{this.postKey(o)}),this.encryptionEnabled!==s.enabled&&s.participantIdentity===((t=this.room)===null||t===void 0?void 0:t.localParticipant.identity))this.emit(RA.ParticipantEncryptionStatusChanged,s.enabled,this.room.localParticipant),this.encryptionEnabled=s.enabled;else if(s.participantIdentity){const o=(i=this.room)===null||i===void 0?void 0:i.getParticipantByIdentity(s.participantIdentity);if(!o)throw TypeError("couldn't set encryption status, participant not found".concat(s.participantIdentity));this.emit(RA.ParticipantEncryptionStatusChanged,s.enabled,o)}break;case"ratchetKey":this.keyProvider.emit(IA.KeyRatcheted,s.ratchetResult,s.participantIdentity,s.keyIndex);break}},this.onWorkerError=A=>{V.error("e2ee worker encountered an error:",{error:A.error}),this.emit(RA.EncryptionError,A.error)},this.keyProvider=e.keyProvider,this.worker=e.worker,this.encryptionEnabled=!1}setup(e){if(!wg())throw new hs("tried to setup end-to-end encryption on an unsupported browser");if(V.info("setting up e2ee"),e!==this.room){this.room=e,this.setupEventListeners(e,this.keyProvider);const A={kind:"init",data:{keyProviderOptions:this.keyProvider.getOptions(),loglevel:sg.getLevel()}};this.worker&&(V.info("initializing worker",{worker:this.worker}),this.worker.onmessage=this.onWorkerMessage,this.worker.onerror=this.onWorkerError,this.worker.postMessage(A))}}setParticipantCryptorEnabled(e,A){V.debug("set e2ee to ".concat(e," for participant ").concat(A)),this.postEnable(e,A)}setSifTrailer(e){!e||e.length===0?V.warn("ignoring server sent trailer as it's empty"):this.postSifTrailer(e)}setupEngine(e){e.on(I.RTPVideoMapUpdate,A=>{this.postRTPMap(A)})}setupEventListeners(e,A){e.on(T.TrackPublished,(t,i)=>this.setParticipantCryptorEnabled(t.trackInfo.encryption!==He.NONE,i.identity)),e.on(T.ConnectionStateChanged,t=>{t===W.Connected&&e.remoteParticipants.forEach(i=>{i.trackPublications.forEach(r=>{this.setParticipantCryptorEnabled(r.trackInfo.encryption!==He.NONE,i.identity)})})}).on(T.TrackUnsubscribed,(t,i,r)=>{var s;const o={kind:"removeTransform",data:{participantIdentity:r.identity,trackId:t.mediaStreamID}};(s=this.worker)===null||s===void 0||s.postMessage(o)}).on(T.TrackSubscribed,(t,i,r)=>{this.setupE2EEReceiver(t,r.identity,i.trackInfo)}).on(T.SignalConnected,()=>{if(!this.room)throw new TypeError("expected room to be present on signal connect");A.getKeys().forEach(t=>{this.postKey(t)}),this.setParticipantCryptorEnabled(this.room.localParticipant.isE2EEEnabled,this.room.localParticipant.identity)}),e.localParticipant.on(x.LocalTrackPublished,t=>p(this,void 0,void 0,function*(){this.setupE2EESender(t.track,t.track.sender)})),A.on(IA.SetKey,t=>this.postKey(t)).on(IA.RatchetRequest,(t,i)=>this.postRatchetRequest(t,i))}postRatchetRequest(e,A){if(!this.worker)throw Error("could not ratchet key, worker is missing");const t={kind:"ratchetRequest",data:{participantIdentity:e,keyIndex:A}};this.worker.postMessage(t)}postKey(e){let{key:A,participantIdentity:t,keyIndex:i}=e;var r;if(!this.worker)throw Error("could not set key, worker is missing");const s={kind:"setKey",data:{participantIdentity:t,isPublisher:t===((r=this.room)===null||r===void 0?void 0:r.localParticipant.identity),key:A,keyIndex:i}};this.worker.postMessage(s)}postEnable(e,A){if(this.worker){const t={kind:"enable",data:{enabled:e,participantIdentity:A}};this.worker.postMessage(t)}else throw new ReferenceError("failed to enable e2ee, worker is not ready")}postRTPMap(e){var A;if(!this.worker)throw TypeError("could not post rtp map, worker is missing");if(!(!((A=this.room)===null||A===void 0)&&A.localParticipant.identity))throw TypeError("could not post rtp map, local participant identity is missing");const t={kind:"setRTPMap",data:{map:e,participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(t)}postSifTrailer(e){if(!this.worker)throw Error("could not post SIF trailer, worker is missing");const A={kind:"setSifTrailer",data:{trailer:e}};this.worker.postMessage(A)}setupE2EEReceiver(e,A,t){if(e.receiver){if(!(t!=null&&t.mimeType)||t.mimeType==="")throw new TypeError("MimeType missing from trackInfo, cannot set up E2EE cryptor");this.handleReceiver(e.receiver,e.mediaStreamID,A,e.kind==="video"?Ui(t.mimeType):void 0)}}setupE2EESender(e,A){if(!Ht(e)||!A){A||V.warn("early return because sender is not ready");return}this.handleSender(A,e.mediaStreamID,void 0)}handleReceiver(e,A,t,i){return p(this,void 0,void 0,function*(){if(this.worker){if(ds()){const r={kind:"decode",participantIdentity:t,trackId:A,codec:i};e.transform=new RTCRtpScriptTransform(this.worker,r)}else{if(Ci in e&&i){const a={kind:"updateCodec",data:{trackId:A,codec:i,participantIdentity:t}};this.worker.postMessage(a);return}let r=e.writableStream,s=e.readableStream;if(!r||!s){const a=e.createEncodedStreams();e.writableStream=a.writable,r=a.writable,e.readableStream=a.readable,s=a.readable}const o={kind:"decode",data:{readableStream:s,writableStream:r,trackId:A,codec:i,participantIdentity:t}};this.worker.postMessage(o,[s,r])}e[Ci]=!0}})}handleSender(e,A,t){var i;if(!(Ci in e||!this.worker)){if(!(!((i=this.room)===null||i===void 0)&&i.localParticipant.identity)||this.room.localParticipant.identity==="")throw TypeError("local identity needs to be known in order to set up encrypted sender");if(ds()){V.info("initialize script transform");const r={kind:"encode",participantIdentity:this.room.localParticipant.identity,trackId:A,codec:t};e.transform=new RTCRtpScriptTransform(this.worker,r)}else{V.info("initialize encoded streams");const r=e.createEncodedStreams(),s={kind:"encode",data:{readableStream:r.readable,writableStream:r.writable,codec:t,trackId:A,participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(s,[r.readable,r.writable])}e[Ci]=!0}}}const Ps="default";class me{constructor(){this._previousDevices=[]}static getInstance(){return this.instance===void 0&&(this.instance=new me),this.instance}get previousDevices(){return this._previousDevices}getDevices(e){return p(this,arguments,void 0,function(A){var t=this;let i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){var r;if(((r=me.userMediaPromiseMap)===null||r===void 0?void 0:r.size)>0){V.debug("awaiting getUserMedia promise");try{A?yield me.userMediaPromiseMap.get(A):yield Promise.all(me.userMediaPromiseMap.values())}catch{V.warn("error waiting for media permissons")}}let s=yield navigator.mediaDevices.enumerateDevices();if(i&&!(PA()&&t.hasDeviceInUse(A))&&(s.filter(a=>a.kind===A).length===0||s.some(a=>{const c=a.label==="",l=A?a.kind===A:!0;return c&&l}))){const a={video:A!=="audioinput"&&A!=="audiooutput",audio:A!=="videoinput"&&{deviceId:{ideal:"default"}}},c=yield navigator.mediaDevices.getUserMedia(a);s=yield navigator.mediaDevices.enumerateDevices(),c.getTracks().forEach(l=>{l.stop()})}return t._previousDevices=s,A&&(s=s.filter(o=>o.kind===A)),s}()})}normalizeDeviceId(e,A,t){return p(this,void 0,void 0,function*(){if(A!==Ps)return A;const i=yield this.getDevices(e),r=i.find(o=>o.deviceId===Ps);if(!r){V.warn("could not reliably determine default device");return}const s=i.find(o=>o.deviceId!==Ps&&o.groupId===(t??r.groupId));if(!s){V.warn("could not reliably determine default device");return}return s==null?void 0:s.deviceId})}hasDeviceInUse(e){return e?me.userMediaPromiseMap.has(e):me.userMediaPromiseMap.size>0}}me.mediaDeviceKinds=["audioinput","audiooutput","videoinput"],me.userMediaPromiseMap=new Map;var pn;(function(n){n[n.WAITING=0]="WAITING",n[n.RUNNING=1]="RUNNING",n[n.COMPLETED=2]="COMPLETED"})(pn||(pn={}));class ip{constructor(){this.pendingTasks=new Map,this.taskMutex=new Te,this.nextTaskIndex=0}run(e){return p(this,void 0,void 0,function*(){const A={id:this.nextTaskIndex++,enqueuedAt:Date.now(),status:pn.WAITING};this.pendingTasks.set(A.id,A);const t=yield this.taskMutex.lock();try{return A.executedAt=Date.now(),A.status=pn.RUNNING,yield e()}finally{A.status=pn.COMPLETED,this.pendingTasks.delete(A.id),t()}})}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 rp(n,e){const A=new URL(jg(n));return e.forEach((t,i)=>{A.searchParams.set(i,t)}),El(A,"rtc")}function sp(n){const e=new URL(Fs(n));return El(e,"validate")}function op(n){return n.endsWith("/")?n:"".concat(n,"/")}function El(n,e){return n.pathname="".concat(op(n.pathname)).concat(e),n.toString()}const ap=["syncState","trickle","offer","answer","simulate","leave"];function cp(n){const e=ap.indexOf(n.case)>=0;return V.trace("request allowed to bypass queue:",{canPass:e,req:n}),e}var Ae;(function(n){n[n.CONNECTING=0]="CONNECTING",n[n.CONNECTED=1]="CONNECTED",n[n.RECONNECTING=2]="RECONNECTING",n[n.DISCONNECTING=3]="DISCONNECTING",n[n.DISCONNECTED=4]="DISCONNECTED"})(Ae||(Ae={}));class Ls{get currentState(){return this.state}get isDisconnected(){return this.state===Ae.DISCONNECTING||this.state===Ae.DISCONNECTED}get isEstablishingConnection(){return this.state===Ae.CONNECTING||this.state===Ae.RECONNECTING}getNextRequestId(){return this._requestId+=1,this._requestId}constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1,A=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};var t;this.rtt=0,this.state=Ae.DISCONNECTED,this.log=V,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=pA((t=A.loggerName)!==null&&t!==void 0?t:Ye.Signal),this.loggerContextCb=A.loggerContextCb,this.useJSON=e,this.requestQueue=new ip,this.queuedRequests=[],this.closingLock=new Te,this.connectionLock=new Te,this.state=Ae.DISCONNECTED}get logContext(){var e,A;return(A=(e=this.loggerContextCb)===null||e===void 0?void 0:e.call(this))!==null&&A!==void 0?A:{}}join(e,A,t,i){return p(this,void 0,void 0,function*(){return this.state=Ae.CONNECTING,this.options=t,yield this.connect(e,A,t,i)})}reconnect(e,A,t,i){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=Ae.RECONNECTING,this.clearPingInterval(),yield this.connect(e,A,Object.assign(Object.assign({},this.options),{reconnect:!0,sid:t,reconnectReason:i}))})}connect(e,A,t,i){this.connectOptions=t;const r=Vg(),s=lp(A,r,t),o=rp(e,s),a=sp(o);return new Promise((c,l)=>p(this,void 0,void 0,function*(){const u=yield this.connectionLock.lock();try{const d=()=>p(this,void 0,void 0,function*(){this.close(),clearTimeout(h),l(new Z("room connection has been cancelled (signal)",G.Cancelled))}),h=setTimeout(()=>{this.close(),l(new Z("room connection has timed out (signal)",G.ServerUnreachable))},t.websocketTimeout);i!=null&&i.aborted&&d(),i==null||i.addEventListener("abort",d);const f=new URL(o);f.searchParams.has("access_token")&&f.searchParams.set("access_token","<redacted>"),this.log.debug("connecting to ".concat(f),Object.assign({reconnect:t.reconnect,reconnectReason:t.reconnectReason},this.logContext)),this.ws&&(yield this.close(!1)),this.ws=new WebSocket(o),this.ws.binaryType="arraybuffer",this.ws.onopen=()=>{clearTimeout(h)},this.ws.onerror=g=>p(this,void 0,void 0,function*(){if(this.state!==Ae.CONNECTED){this.state=Ae.DISCONNECTED,clearTimeout(h);try{const m=yield fetch(a);if(m.status.toFixed(0).startsWith("4")){const C=yield m.text();l(new Z(C,G.NotAllowed,m.status))}else l(new Z("Encountered unknown websocket error during connection: ".concat(g.toString()),G.InternalError,m.status))}catch(m){l(new Z(m instanceof Error?m.message:"server was not reachable",G.ServerUnreachable))}return}this.handleWSError(g)}),this.ws.onmessage=g=>p(this,void 0,void 0,function*(){var m,C,y;let U;if(typeof g.data=="string"){const v=JSON.parse(g.data);U=ac.fromJson(v,{ignoreUnknownFields:!0})}else if(g.data instanceof ArrayBuffer)U=ac.fromBinary(new Uint8Array(g.data));else{this.log.error("could not decode websocket message: ".concat(typeof g.data),this.logContext);return}if(this.state!==Ae.CONNECTED){let v=!1;if(((m=U.message)===null||m===void 0?void 0:m.case)==="join"?(this.state=Ae.CONNECTED,i==null||i.removeEventListener("abort",d),this.pingTimeoutDuration=U.message.value.pingTimeout,this.pingIntervalDuration=U.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()),c(U.message.value)):this.state===Ae.RECONNECTING&&U.message.case!=="leave"?(this.state=Ae.CONNECTED,i==null||i.removeEventListener("abort",d),this.startPingInterval(),((C=U.message)===null||C===void 0?void 0:C.case)==="reconnect"?c(U.message.value):(this.log.debug("declaring signal reconnected without reconnect response received",this.logContext),c(void 0),v=!0)):this.isEstablishingConnection&&U.message.case==="leave"?l(new Z("Received leave request while trying to (re)connect",G.LeaveRequest,void 0,U.message.value.reason)):t.reconnect||l(new Z("did not receive join response, got ".concat((y=U.message)===null||y===void 0?void 0:y.case," instead"),G.InternalError)),!v)return}this.signalLatency&&(yield Ie(this.signalLatency)),this.handleSignalResponse(U)}),this.ws.onclose=g=>{this.isEstablishingConnection&&l(new Z("Websocket got closed during a (re)connection attempt",G.InternalError)),this.log.warn("websocket closed",Object.assign(Object.assign({},this.logContext),{reason:g.reason,code:g.code,wasClean:g.wasClean,state:this.state})),this.handleOnClose(g.reason)}}finally{u()}}))}close(){return p(this,arguments,void 0,function(){var e=this;let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){const t=yield e.closingLock.lock();try{if(e.clearPingInterval(),A&&(e.state=Ae.DISCONNECTING),e.ws){e.ws.onmessage=null,e.ws.onopen=null,e.ws.onclose=null;const i=new Promise(r=>{e.ws?e.ws.onclose=()=>{r()}:r()});e.ws.readyState<e.ws.CLOSING&&(e.ws.close(),yield Promise.race([i,Ie(250)])),e.ws=void 0}}finally{A&&(e.state=Ae.DISCONNECTED),t()}}()})}sendOffer(e){this.log.debug("sending offer",Object.assign(Object.assign({},this.logContext),{offerSdp:e.sdp})),this.sendRequest({case:"offer",value:Qi(e)})}sendAnswer(e){return this.log.debug("sending answer",Object.assign(Object.assign({},this.logContext),{answerSdp:e.sdp})),this.sendRequest({case:"answer",value:Qi(e)})}sendIceCandidate(e,A){return this.log.debug("sending ice candidate",Object.assign(Object.assign({},this.logContext),{candidate:e})),this.sendRequest({case:"trickle",value:new Zr({candidateInit:JSON.stringify(e),target:A})})}sendMuteTrack(e,A){return this.sendRequest({case:"mute",value:new zr({sid:e,muted:A})})}sendAddTrack(e){return this.sendRequest({case:"addTrack",value:e})}sendUpdateLocalMetadata(e,A){return p(this,arguments,void 0,function(t,i){var r=this;let s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return function*(){const o=r.getNextRequestId();return yield r.sendRequest({case:"updateMetadata",value:new dc({requestId:o,metadata:t,name:i,attributes:s})}),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,A){return this.sendRequest({case:"updateLayers",value:new uc({trackSid:e,layers:A})})}sendUpdateSubscriptionPermissions(e,A){return this.sendRequest({case:"subscriptionPermission",value:new gc({allParticipants:e,trackPermissions:A})})}sendSimulateScenario(e){return this.sendRequest({case:"simulate",value:e})}sendPing(){return Promise.all([this.sendRequest({case:"ping",value:ne.parse(Date.now())}),this.sendRequest({case:"pingReq",value:new Bc({timestamp:ne.parse(Date.now()),rtt:ne.parse(this.rtt)})})])}sendUpdateLocalAudioTrack(e,A){return this.sendRequest({case:"updateAudioTrack",value:new lc({trackSid:e,features:A})})}sendLeave(){return this.sendRequest({case:"leave",value:new li({reason:We.CLIENT_INITIATED,action:xt.DISCONNECT})})}sendRequest(e){return p(this,arguments,void 0,function(A){var t=this;let i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1;return function*(){if(!i&&!cp(A)&&t.state===Ae.RECONNECTING){t.queuedRequests.push(()=>p(t,void 0,void 0,function*(){yield this.sendRequest(A,!0)}));return}if(i||(yield t.requestQueue.flush()),t.signalLatency&&(yield Ie(t.signalLatency)),!t.ws||t.ws.readyState!==t.ws.OPEN){t.log.error("cannot send signal request before connected, type: ".concat(A==null?void 0:A.case),t.logContext);return}const s=new Lf({message:A});try{t.useJSON?t.ws.send(s.toJsonString()):t.ws.send(s.toBinary())}catch(o){t.log.error("error sending signal message",Object.assign(Object.assign({},t.logContext),{error:o}))}}()})}handleSignalResponse(e){var A,t;const i=e.message;if(i==null){this.log.debug("received unsupported message",this.logContext);return}let r=!1;if(i.case==="answer"){const s=Sl(i.value);this.onAnswer&&this.onAnswer(s)}else if(i.case==="offer"){const s=Sl(i.value);this.onOffer&&this.onOffer(s)}else if(i.case==="trickle"){const s=JSON.parse(i.value.candidateInit);this.onTrickle&&this.onTrickle(s,i.value.target)}else i.case==="update"?this.onParticipantUpdate&&this.onParticipantUpdate((A=i.value.participants)!==null&&A!==void 0?A:[]):i.case==="trackPublished"?this.onLocalTrackPublished&&this.onLocalTrackPublished(i.value):i.case==="speakersChanged"?this.onSpeakersChanged&&this.onSpeakersChanged((t=i.value.speakers)!==null&&t!==void 0?t:[]):i.case==="leave"?this.onLeave&&this.onLeave(i.value):i.case==="mute"?this.onRemoteMuteChanged&&this.onRemoteMuteChanged(i.value.sid,i.value.muted):i.case==="roomUpdate"?this.onRoomUpdate&&i.value.room&&this.onRoomUpdate(i.value.room):i.case==="connectionQuality"?this.onConnectionQuality&&this.onConnectionQuality(i.value):i.case==="streamStateUpdate"?this.onStreamStateUpdate&&this.onStreamStateUpdate(i.value):i.case==="subscribedQualityUpdate"?this.onSubscribedQualityUpdate&&this.onSubscribedQualityUpdate(i.value):i.case==="subscriptionPermissionUpdate"?this.onSubscriptionPermissionUpdate&&this.onSubscriptionPermissionUpdate(i.value):i.case==="refreshToken"?this.onTokenRefresh&&this.onTokenRefresh(i.value):i.case==="trackUnpublished"?this.onLocalTrackUnpublished&&this.onLocalTrackUnpublished(i.value):i.case==="subscriptionResponse"?this.onSubscriptionError&&this.onSubscriptionError(i.value):i.case==="pong"||(i.case==="pongResp"?(this.rtt=Date.now()-Number.parseInt(i.value.lastPingTimestamp.toString()),this.resetPingTimeout(),r=!0):i.case==="requestResponse"?this.onRequestResponse&&this.onRequestResponse(i.value):i.case==="trackSubscribed"?this.onLocalTrackSubscribed&&this.onLocalTrackSubscribed(i.value.trackSid):i.case==="roomMoved"?(this.onTokenRefresh&&this.onTokenRefresh(i.value.token),this.onRoomMoved&&this.onRoomMoved(i.value)):this.log.debug("unsupported message",Object.assign(Object.assign({},this.logContext),{msgCase:i.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===Ae.DISCONNECTED)return;const A=this.onClose;yield this.close(),this.log.debug("websocket connection closed: ".concat(e),Object.assign(Object.assign({},this.logContext),{reason:e})),A&&A(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=ve.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&&ve.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=ve.setInterval(()=>{this.sendPing()},this.pingIntervalDuration*1e3)}clearPingInterval(){this.log.debug("clearing ping interval",this.logContext),this.clearPingTimeout(),this.pingInterval&&ve.clearInterval(this.pingInterval)}}function Sl(n){const e={type:"offer",sdp:n.sdp};switch(n.type){case"answer":case"offer":case"pranswer":case"rollback":e.type=n.type;break}return e}function Qi(n){return new ot({sdp:n.sdp,type:n.type})}function lp(n,e,A){var t;const i=new URLSearchParams;return i.set("access_token",n),A.reconnect&&(i.set("reconnect","1"),A.sid&&i.set("sid",A.sid)),i.set("auto_subscribe",A.autoSubscribe?"1":"0"),i.set("sdk",oA()?"reactnative":"js"),i.set("version",e.version),i.set("protocol",e.protocol.toString()),e.deviceModel&&i.set("device_model",e.deviceModel),e.os&&i.set("os",e.os),e.osVersion&&i.set("os_version",e.osVersion),e.browser&&i.set("browser",e.browser),e.browserVersion&&i.set("browser_version",e.browserVersion),A.adaptiveStream&&i.set("adaptive_stream","1"),A.reconnectReason&&i.set("reconnect_reason",A.reconnectReason.toString()),!((t=navigator.connection)===null||t===void 0)&&t.type&&i.set("network",navigator.connection.type),i}var Ze={},Ds={},_s={exports:{}},Tl;function Hs(){if(Tl)return _s.exports;Tl=1;var n=_s.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 A="candidate:%s %d %s %d %s %d typ %s";return A+=e.raddr!=null?" raddr %s rport %d":"%v%v",A+=e.tcptype!=null?" tcptype %s":"%v",e.generation!=null&&(A+=" generation %d"),A+=e["network-id"]!=null?" network-id %d":"%v",A+=e["network-cost"]!=null?" network-cost %d":"%v",A}},{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 A="ssrc:%d";return e.attribute!=null&&(A+=" %s",e.value!=null&&(A+=":%s")),A}},{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 A="mediaclk:";return A+=e.id!=null?"id=%s %s":"%v%s",A+=e.mediaClockValue!=null?"=%s":"",A+=e.rateNumerator!=null?" rate=%s":"",A+=e.rateDenominator!=null?"/%s":"",A}},{name:"keywords",reg:/^keywds:(.+)$/,format:"keywds:%s"},{name:"content",reg:/^content:(.+)/,format:"content:%s"},{name:"bfcpFloorCtrl",reg:/^floorctrl:(c-only|s-only|c-s)/,format:"floorctrl:%s"},{name:"bfcpConfId",reg:/^confid:(\d+)/,format:"confid:%s"},{name:"bfcpUserId",reg:/^userid:(\d+)/,format:"userid:%s"},{name:"bfcpFloorId",reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:["id","mStream"],format:"floorid:%s mstrm:%s"},{push:"invalid",names:["value"]}]};return Object.keys(n).forEach(function(e){var A=n[e];A.forEach(function(t){t.reg||(t.reg=/(.*)/),t.format||(t.format="%s")})}),_s.exports}var Fl;function up(){return Fl||(Fl=1,function(n){var e=function(o){return String(Number(o))===o?Number(o):o},A=function(o,a,c,l){if(l&&!c)a[l]=e(o[1]);else for(var u=0;u<c.length;u+=1)o[u+1]!=null&&(a[c[u]]=e(o[u+1]))},t=function(o,a,c){var l=o.name&&o.names;o.push&&!a[o.push]?a[o.push]=[]:l&&!a[o.name]&&(a[o.name]={});var u=o.push?{}:l?a[o.name]:a;A(c.match(o.reg),u,o.names,o.name),o.push&&a[o.push].push(u)},i=Hs(),r=RegExp.prototype.test.bind(/^([a-z])=(.*)/);n.parse=function(o){var a={},c=[],l=a;return o.split(/(\r\n|\r|\n)/).filter(r).forEach(function(u){var d=u[0],h=u.slice(2);d==="m"&&(c.push({rtp:[],fmtp:[]}),l=c[c.length-1]);for(var f=0;f<(i[d]||[]).length;f+=1){var g=i[d][f];if(g.reg.test(h))return t(g,l,h)}}),a.media=c,a};var s=function(o,a){var c=a.split(/=(.+)/,2);return c.length===2?o[c[0]]=e(c[1]):c.length===1&&a.length>1&&(o[c[0]]=void 0),o};n.parseParams=function(o){return o.split(/;\s?/).reduce(s,{})},n.parseFmtpConfig=n.parseParams,n.parsePayloads=function(o){return o.toString().split(" ").map(Number)},n.parseRemoteCandidates=function(o){for(var a=[],c=o.split(" ").map(e),l=0;l<c.length;l+=3)a.push({component:c[l],ip:c[l+1],port:c[l+2]});return a},n.parseImageAttributes=function(o){return o.split(" ").map(function(a){return a.substring(1,a.length-1).split(",").reduce(s,{})})},n.parseSimulcastStreamList=function(o){return o.split(";").map(function(a){return a.split(",").map(function(c){var l,u=!1;return c[0]!=="~"?l=e(c):(l=e(c.substring(1,c.length)),u=!0),{scid:l,paused:u}})})}}(Ds)),Ds}var Os,kl;function dp(){if(kl)return Os;kl=1;var n=Hs(),e=/%[sdv%]/g,A=function(s){var o=1,a=arguments,c=a.length;return s.replace(e,function(l){if(o>=c)return l;var u=a[o];switch(o+=1,l){case"%%":return"%";case"%s":return String(u);case"%d":return Number(u);case"%v":return""}})},t=function(s,o,a){var c=o.format instanceof Function?o.format(o.push?a:a[o.name]):o.format,l=[s+"="+c];if(o.names)for(var u=0;u<o.names.length;u+=1){var d=o.names[u];o.name?l.push(a[o.name][d]):l.push(a[o.names[u]])}else l.push(a[o.name]);return A.apply(null,l)},i=["v","o","s","i","u","e","p","c","b","t","r","z","a"],r=["i","c","b","a"];return Os=function(s,o){o=o||{},s.version==null&&(s.version=0),s.name==null&&(s.name=" "),s.media.forEach(function(u){u.payloads==null&&(u.payloads="")});var a=o.outerOrder||i,c=o.innerOrder||r,l=[];return a.forEach(function(u){n[u].forEach(function(d){d.name in s&&s[d.name]!=null?l.push(t(u,d,s)):d.push in s&&s[d.push]!=null&&s[d.push].forEach(function(h){l.push(t(u,d,h))})})}),s.media.forEach(function(u){l.push(t("m",n.m[0],u)),c.forEach(function(d){n[d].forEach(function(h){h.name in u&&u[h.name]!=null?l.push(t(d,h,u)):h.push in u&&u[h.push]!=null&&u[h.push].forEach(function(f){l.push(t(d,h,f))})})})}),l.join(`\r
37
+ `)+`\r
38
+ `},Os}var Il;function hp(){if(Il)return Ze;Il=1;var n=up(),e=dp(),A=Hs();return Ze.grammar=A,Ze.write=e,Ze.parse=n.parse,Ze.parseParams=n.parseParams,Ze.parseFmtpConfig=n.parseFmtpConfig,Ze.parsePayloads=n.parsePayloads,Ze.parseRemoteCandidates=n.parseRemoteCandidates,Ze.parseImageAttributes=n.parseImageAttributes,Ze.parseSimulcastStreamList=n.parseSimulcastStreamList,Ze}var _A=hp();function Ms(n,e,A){var t,i,r;e===void 0&&(e=50),A===void 0&&(A={});var s=(t=A.isImmediate)!=null&&t,o=(i=A.callback)!=null&&i,a=A.maxWait,c=Date.now(),l=[];function u(){if(a!==void 0){var h=Date.now()-c;if(h+e>=a)return a-h}return e}var d=function(){var h=[].slice.call(arguments),f=this;return new Promise(function(g,m){var C=s&&r===void 0;if(r!==void 0&&clearTimeout(r),r=setTimeout(function(){if(r=void 0,c=Date.now(),!s){var U=n.apply(f,h);o&&o(U),l.forEach(function(v){return(0,v.resolve)(U)}),l=[]}},u()),C){var y=n.apply(f,h);return o&&o(y),g(y)}l.push({resolve:g,reject:m})})};return d.cancel=function(h){r!==void 0&&clearTimeout(r),l.forEach(function(f){return(0,f.reject)(h)}),l=[]},d}const fp=.7,gp=20,Mt={NegotiationStarted:"negotiationStarted",NegotiationComplete:"negotiationComplete",RTPVideoPayloadTypes:"rtpVideoPayloadTypes"};class Rl extends sA.EventEmitter{get pc(){return this._pc||(this._pc=this.createPC()),this._pc}constructor(e){let A=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};var t;super(),this.log=V,this.ddExtID=0,this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate=!1,this.trackBitrates=[],this.remoteStereoMids=[],this.remoteNackMids=[],this.negotiate=Ms(i=>p(this,void 0,void 0,function*(){this.emit(Mt.NegotiationStarted);try{yield this.createAndSendOffer()}catch(r){if(i)i(r);else throw r}}),gp),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=pA((t=A.loggerName)!==null&&t!==void 0?t:Ye.PCTransport),this.loggerOptions=A,this.config=e,this._pc=this.createPC()}createPC(){const e=new RTCPeerConnection(this.config);return e.onicecandidate=A=>{var t;A.candidate&&((t=this.onIceCandidate)===null||t===void 0||t.call(this,A.candidate))},e.onicecandidateerror=A=>{var t;(t=this.onIceCandidateError)===null||t===void 0||t.call(this,A)},e.oniceconnectionstatechange=()=>{var A;(A=this.onIceConnectionStateChange)===null||A===void 0||A.call(this,e.iceConnectionState)},e.onsignalingstatechange=()=>{var A;(A=this.onSignalingStatechange)===null||A===void 0||A.call(this,e.signalingState)},e.onconnectionstatechange=()=>{var A;(A=this.onConnectionStateChange)===null||A===void 0||A.call(this,e.connectionState)},e.ondatachannel=A=>{var t;(t=this.onDataChannel)===null||t===void 0||t.call(this,A)},e.ontrack=A=>{var t;(t=this.onTrack)===null||t===void 0||t.call(this,A)},e}get logContext(){var e,A;return Object.assign({},(A=(e=this.loggerOptions).loggerContextCb)===null||A===void 0?void 0:A.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){return p(this,void 0,void 0,function*(){var A;let t;if(e.type==="offer"){let{stereoMids:i,nackMids:r}=pp(e);this.remoteStereoMids=i,this.remoteNackMids=r}else if(e.type==="answer"){const i=_A.parse((A=e.sdp)!==null&&A!==void 0?A:"");i.media.forEach(r=>{r.type==="audio"&&this.trackBitrates.some(s=>{if(!s.transceiver||r.mid!=s.transceiver.mid)return!1;let o=0;if(r.rtp.some(c=>c.codec.toUpperCase()===s.codec.toUpperCase()?(o=c.payload,!0):!1),o===0)return!0;let a=!1;for(const c of r.fmtp)if(c.payload===o){c.config=c.config.split(";").filter(l=>!l.includes("maxaveragebitrate")).join(";"),s.maxbr>0&&(c.config+=";maxaveragebitrate=".concat(s.maxbr*1e3)),a=!0;break}return a||s.maxbr>0&&r.fmtp.push({payload:o,config:"maxaveragebitrate=".concat(s.maxbr*1e3)}),!0})}),t=_A.write(i)}yield this.setMungedSDP(e,t,!0),this.pendingCandidates.forEach(i=>{this.pc.addIceCandidate(i)}),this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate?(this.renegotiate=!1,yield this.createAndSendOffer()):e.type==="answer"&&(this.emit(Mt.NegotiationComplete),e.sdp&&_A.parse(e.sdp).media.forEach(r=>{r.type==="video"&&this.emit(Mt.RTPVideoPayloadTypes,r.rtp)}))})}createAndSendOffer(e){return p(this,void 0,void 0,function*(){var A;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 r=this._pc.remoteDescription;if(e!=null&&e.iceRestart&&r)yield this._pc.setRemoteDescription(r);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 t=yield this.pc.createOffer(e);this.log.debug("original offer",Object.assign({sdp:t.sdp},this.logContext));const i=_A.parse((A=t.sdp)!==null&&A!==void 0?A:"");i.media.forEach(r=>{Pl(r),r.type==="audio"?xl(r,[],[]):r.type==="video"&&this.trackBitrates.some(s=>{if(!r.msid||!s.cid||!r.msid.includes(s.cid))return!1;let o=0;if(r.rtp.some(c=>c.codec.toUpperCase()===s.codec.toUpperCase()?(o=c.payload,!0):!1),o===0||(fn(s.codec)&&this.ensureVideoDDExtensionForSVC(r,i),s.codec!=="av1"))return!0;const a=Math.round(s.maxbr*fp);for(const c of r.fmtp)if(c.payload===o){c.config.includes("x-google-start-bitrate")||(c.config+=";x-google-start-bitrate=".concat(a));break}return!0})}),yield this.setMungedSDP(t,_A.write(i)),this.onOffer(t)})}createAndSetAnswer(){return p(this,void 0,void 0,function*(){var e;const A=yield this.pc.createAnswer(),t=_A.parse((e=A.sdp)!==null&&e!==void 0?e:"");return t.media.forEach(i=>{Pl(i),i.type==="audio"&&xl(i,this.remoteStereoMids,this.remoteNackMids)}),yield this.setMungedSDP(A,_A.write(t)),A})}createDataChannel(e,A){return this.pc.createDataChannel(e,A)}addTransceiver(e,A){return this.pc.addTransceiver(e,A)}addTrack(e){if(!this._pc)throw new ge("PC closed, cannot add track");return this._pc.addTrack(e)}setTrackCodecBitrate(e){this.trackBitrates.push(e)}setConfiguration(e){var A;if(!this._pc)throw new ge("PC closed, cannot configure");return(A=this._pc)===null||A===void 0?void 0:A.setConfiguration(e)}canRemoveTrack(){var e;return!!(!((e=this._pc)===null||e===void 0)&&e.removeTrack)}removeTrack(e){var A;return(A=this._pc)===null||A===void 0?void 0:A.removeTrack(e)}getConnectionState(){var e,A;return(A=(e=this._pc)===null||e===void 0?void 0:e.connectionState)!==null&&A!==void 0?A:"closed"}getICEConnectionState(){var e,A;return(A=(e=this._pc)===null||e===void 0?void 0:e.iceConnectionState)!==null&&A!==void 0?A:"closed"}getSignallingState(){var e,A;return(A=(e=this._pc)===null||e===void 0?void 0:e.signalingState)!==null&&A!==void 0?A:"closed"}getTransceivers(){var e,A;return(A=(e=this._pc)===null||e===void 0?void 0:e.getTransceivers())!==null&&A!==void 0?A:[]}getSenders(){var e,A;return(A=(e=this._pc)===null||e===void 0?void 0:e.getSenders())!==null&&A!==void 0?A:[]}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 A="";const t=new Map,i=new Map;if((yield this._pc.getStats()).forEach(o=>{switch(o.type){case"transport":A=o.selectedCandidatePairId;break;case"candidate-pair":A===""&&o.selected&&(A=o.id),t.set(o.id,o);break;case"remote-candidate":i.set(o.id,"".concat(o.address,":").concat(o.port));break}}),A==="")return;const s=(e=t.get(A))===null||e===void 0?void 0:e.remoteCandidateId;if(s!==void 0)return i.get(s)})}setMungedSDP(e,A,t){return p(this,void 0,void 0,function*(){if(A){const i=e.sdp;e.sdp=A;try{this.log.debug("setting munged ".concat(t?"remote":"local"," description"),this.logContext),t?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:A})),e.sdp=i}}try{t?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e)}catch(i){let r="unknown error";i instanceof Error?r=i.message:typeof i=="string"&&(r=i);const s={error:r,sdp:e.sdp};throw!t&&this.pc.remoteDescription&&(s.remoteSdp=this.pc.remoteDescription),this.log.error("unable to set ".concat(e.type),Object.assign(Object.assign({},this.logContext),{fields:s})),new fs(r)}})}ensureVideoDDExtensionForSVC(e,A){var t,i;if(!((t=e.ext)===null||t===void 0?void 0:t.some(s=>s.uri===dl))){if(this.ddExtID===0){let s=0;A.media.forEach(o=>{var a;o.type==="video"&&((a=o.ext)===null||a===void 0||a.forEach(c=>{c.value>s&&(s=c.value)}))}),this.ddExtID=s+1}(i=e.ext)===null||i===void 0||i.push({value:this.ddExtID,uri:dl})}}}function xl(n,e,A){let t=0;n.rtp.some(i=>i.codec==="opus"?(t=i.payload,!0):!1),t>0&&(n.rtcpFb||(n.rtcpFb=[]),A.includes(n.mid)&&!n.rtcpFb.some(i=>i.payload===t&&i.type==="nack")&&n.rtcpFb.push({payload:t,type:"nack"}),e.includes(n.mid)&&n.fmtp.some(i=>i.payload===t?(i.config.includes("stereo=1")||(i.config+=";stereo=1"),!0):!1))}function pp(n){var e;const A=[],t=[],i=_A.parse((e=n.sdp)!==null&&e!==void 0?e:"");let r=0;return i.media.forEach(s=>{var o;s.type==="audio"&&(s.rtp.some(a=>a.codec==="opus"?(r=a.payload,!0):!1),!((o=s.rtcpFb)===null||o===void 0)&&o.some(a=>a.payload===r&&a.type==="nack")&&t.push(s.mid),s.fmtp.some(a=>a.payload===r?(a.config.includes("sprop-stereo=1")&&A.push(s.mid),!0):!1))}),{stereoMids:A,nackMids:t}}function Pl(n){if(n.connection){const e=n.connection.ip.indexOf(":")>=0;(n.connection.version===4&&e||n.connection.version===6&&!e)&&(n.connection.ip="0.0.0.0",n.connection.version=4)}}const Ns="vp8",mp={audioPreset:Bs.music,dtx:!0,red:!0,forceStereo:!1,simulcast:!0,screenShareEncoding:Cs.h1080fps15.encoding,stopMicTrackOnMute:!1,videoCodec:Ns,backupCodec:!0},Ll={deviceId:{ideal:"default"},autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0,voiceIsolation:!0},Dl={deviceId:{ideal:"default"},resolution:hn.h720.resolution},Bp={adaptiveStream:!1,dynacast:!1,stopLocalTrackOnUnpublish:!0,reconnectPolicy:new ag,disconnectOnPageLeave:!0,webAudioMix:!1},Ks={autoSubscribe:!0,maxRetries:1,peerConnectionTimeout:15e3,websocketTimeout:15e3};var se;(function(n){n[n.NEW=0]="NEW",n[n.CONNECTING=1]="CONNECTING",n[n.CONNECTED=2]="CONNECTED",n[n.FAILED=3]="FAILED",n[n.CLOSING=4]="CLOSING",n[n.CLOSED=5]="CLOSED"})(se||(se={}));class vp{get needsPublisher(){return this.isPublisherConnectionRequired}get needsSubscriber(){return this.isSubscriberConnectionRequired}get currentState(){return this.state}constructor(e,A,t){var i;this.peerConnectionTimeout=Ks.peerConnectionTimeout,this.log=V,this.updateState=()=>{var r;const s=this.state,o=this.requiredTransports.map(a=>a.getConnectionState());o.every(a=>a==="connected")?this.state=se.CONNECTED:o.some(a=>a==="failed")?this.state=se.FAILED:o.some(a=>a==="connecting")?this.state=se.CONNECTING:o.every(a=>a==="closed")?this.state=se.CLOSED:o.some(a=>a==="closed")?this.state=se.CLOSING:o.every(a=>a==="new")&&(this.state=se.NEW),s!==this.state&&(this.log.debug("pc state change: from ".concat(se[s]," to ").concat(se[this.state]),this.logContext),(r=this.onStateChange)===null||r===void 0||r.call(this,this.state,this.publisher.getConnectionState(),this.subscriber.getConnectionState()))},this.log=pA((i=t.loggerName)!==null&&i!==void 0?i:Ye.PCManager),this.loggerOptions=t,this.isPublisherConnectionRequired=!A,this.isSubscriberConnectionRequired=A,this.publisher=new Rl(e,t),this.subscriber=new Rl(e,t),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 s;(s=this.onIceCandidate)===null||s===void 0||s.call(this,r,$e.PUBLISHER)},this.subscriber.onIceCandidate=r=>{var s;(s=this.onIceCandidate)===null||s===void 0||s.call(this,r,$e.SUBSCRIBER)},this.subscriber.onDataChannel=r=>{var s;(s=this.onDataChannel)===null||s===void 0||s.call(this,r)},this.subscriber.onTrack=r=>{var s;(s=this.onTrack)===null||s===void 0||s.call(this,r)},this.publisher.onOffer=r=>{var s;(s=this.onPublisherOffer)===null||s===void 0||s.call(this,r)},this.state=se.NEW,this.connectionLock=new Te,this.remoteOfferLock=new Te}get logContext(){var e,A;return Object.assign({},(A=(e=this.loggerOptions).loggerContextCb)===null||A===void 0?void 0:A.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){return this.publisher.setRemoteDescription(e)}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 A of e.getSenders())try{e.canRemoveTrack()&&e.removeTrack(A)}catch(t){this.log.warn("could not removeTrack",Object.assign(Object.assign({},this.logContext),{error:t}))}}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,A){return p(this,void 0,void 0,function*(){A===$e.PUBLISHER?yield this.publisher.addIceCandidate(e):yield this.subscriber.addIceCandidate(e)})}createSubscriberAnswerFromOffer(e){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 A=yield this.remoteOfferLock.lock();try{return yield this.subscriber.setRemoteDescription(e),yield this.subscriber.createAndSetAnswer()}finally{A()}})}updateConfiguration(e,A){this.publisher.setConfiguration(e),this.subscriber.setConfiguration(e),A&&this.triggerIceRestart()}ensurePCTransportConnection(e,A){return p(this,void 0,void 0,function*(){var t;const i=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((t=this.requiredTransports)===null||t===void 0?void 0:t.map(r=>this.ensureTransportConnected(r,e,A)))}finally{i()}})}negotiate(e){return p(this,void 0,void 0,function*(){return new Promise((A,t)=>p(this,void 0,void 0,function*(){const i=setTimeout(()=>{t("negotiation timed out")},this.peerConnectionTimeout),r=()=>{clearTimeout(i),t("negotiation aborted")};e.signal.addEventListener("abort",r),this.publisher.once(Mt.NegotiationStarted,()=>{e.signal.aborted||this.publisher.once(Mt.NegotiationComplete,()=>{clearTimeout(i),A()})}),yield this.publisher.negotiate(s=>{clearTimeout(i),t(s)})}))})}addPublisherTransceiver(e,A){return this.publisher.addTransceiver(e,A)}addPublisherTrack(e){return this.publisher.addTrack(e)}createPublisherDataChannel(e,A){return this.publisher.createDataChannel(e,A)}getConnectedAddress(e){return e===$e.PUBLISHER?this.publisher.getConnectedAddress():e===$e.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,A){return p(this,arguments,void 0,function(t,i){var r=this;let s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:this.peerConnectionTimeout;return function*(){if(t.getConnectionState()!=="connected")return new Promise((a,c)=>p(r,void 0,void 0,function*(){const l=()=>{this.log.warn("abort transport connection",this.logContext),ve.clearTimeout(u),c(new Z("room connection has been cancelled",G.Cancelled))};i!=null&&i.signal.aborted&&l(),i==null||i.signal.addEventListener("abort",l);const u=ve.setTimeout(()=>{i==null||i.signal.removeEventListener("abort",l),c(new Z("could not establish pc connection",G.InternalError))},s);for(;this.state!==se.CONNECTED;)if(yield Ie(50),i!=null&&i.signal.aborted){c(new Z("room connection has been cancelled",G.Cancelled));return}ve.clearTimeout(u),i==null||i.signal.removeEventListener("abort",l),a()}))}()})}}class oe extends Error{constructor(e,A,t){super(A),this.code=e,this.message=Hl(A,oe.MAX_MESSAGE_BYTES),this.data=t?Hl(t,oe.MAX_DATA_BYTES):void 0}static fromProto(e){return new oe(e.code,e.message,e.data)}toProto(){return new za({code:this.code,message:this.message,data:this.data})}static builtIn(e,A){return new oe(oe.ErrorCode[e],oe.ErrorMessage[e],A)}}oe.MAX_MESSAGE_BYTES=256,oe.MAX_DATA_BYTES=15360,oe.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},oe.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 _l=15360;function Vs(n){return new TextEncoder().encode(n).length}function Hl(n,e){if(Vs(n)<=e)return n;let A=0,t=n.length;const i=new TextEncoder;for(;A<t;){const r=Math.floor((A+t+1)/2);i.encode(n.slice(0,r)).length<=e?A=r:t=r-1}return n.slice(0,A)}const Gs=2e3;function Ei(n,e){if(!e)return 0;let A,t;return"bytesReceived"in n?(A=n.bytesReceived,t=e.bytesReceived):"bytesSent"in n&&(A=n.bytesSent,t=e.bytesSent),A===void 0||t===void 0||n.timestamp===void 0||e.timestamp===void 0?0:(A-t)*8*1e3/(n.timestamp-e.timestamp)}const Cp=1e3;class Ol extends Q{get sender(){return this._sender}set sender(e){this._sender=e}get constraints(){return this._constraints}constructor(e,A,t){let i=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1,r=arguments.length>4?arguments[4]:void 0;super(e,A,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=Ms(()=>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(k.Ended,this)},this.reacquireTrack=!1,this.providedByUser=i,this.muteLock=new Te,this.pauseUpstreamLock=new Te,this.processorLock=new Te,this.restartLock=new Te,this.setMediaStreamTrack(e,!0),this._constraints=e.getConstraints(),t&&(this._constraints=t)}get id(){return this._mediaStreamTrack.id}get dimensions(){if(this.kind!==Q.Kind.Video)return;const{width:e,height:A}=this._mediaStreamTrack.getSettings();if(e&&A)return{width:e,height:A}}get isUpstreamPaused(){return this._isUpstreamPaused}get isUserProvided(){return this.providedByUser}get mediaStreamTrack(){var e,A;return(A=(e=this.processor)===null||e===void 0?void 0:e.processedTrack)!==null&&A!==void 0?A:this._mediaStreamTrack}get isLocal(){return!0}getSourceTrackSettings(){return this._mediaStreamTrack.getSettings()}setMediaStreamTrack(e,A){return p(this,void 0,void 0,function*(){var t;if(e===this._mediaStreamTrack&&!A)return;this._mediaStreamTrack&&(this.attachedElements.forEach(r=>{Dt(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 i;if(this.processor&&e){const r=yield this.processorLock.lock();try{if(this.log.debug("restarting processor",this.logContext),this.kind==="unknown")throw TypeError("cannot set processor on track of unknown kind");this.processorElement&&(Lt(e,this.processorElement),this.processorElement.muted=!0),yield this.processor.restart({track:e,kind:this.kind,element:this.processorElement}),i=this.processor.processedTrack}finally{r()}}this.sender&&((t=this.sender.transport)===null||t===void 0?void 0:t.state)!=="closed"&&(yield this.sender.replaceTrack(i??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=>{Lt(i??e,r)}))})}waitForDimensions(){return p(this,arguments,void 0,function(){var e=this;let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:Cp;return function*(){var t;if(e.kind===Q.Kind.Audio)throw new Error("cannot get dimensions for audio tracks");((t=qe())===null||t===void 0?void 0:t.os)==="iOS"&&(yield Ie(10));const i=Date.now();for(;Date.now()-i<A;){const r=e.dimensions;if(r)return r;yield Ie(50)}throw new mA("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===LA(e)||(this._constraints.deviceId=e,this.isMuted)?!0:(yield this.restartTrack(),LA(e)===this._mediaStreamTrack.getSettings().deviceId)})}getDeviceId(){return p(this,arguments,void 0,function(){var e=this;let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){if(e.source===Q.Source.ScreenShare)return;const{deviceId:t,groupId:i}=e._mediaStreamTrack.getSettings(),r=e.kind===Q.Kind.Audio?"audioinput":"videoinput";return A?me.getInstance().normalizeDeviceId(r,t,i):t}()})}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,A){return p(this,void 0,void 0,function*(){if(!this.sender)throw new mA("unable to replace an unpublished track");let t,i;return typeof A=="boolean"?t=A:A!==void 0&&(t=A.userProvidedTrack,i=A.stopProcessor),this.providedByUser=t??!0,this.log.debug("replace MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(e),i&&this.processor&&(yield this.stopProcessor()),this})}restart(e){return p(this,void 0,void 0,function*(){this.manuallyStopped=!1;const A=yield this.restartLock.lock();try{e||(e=this._constraints);const{deviceId:t,facingMode:i}=e,r=cg(e,["deviceId","facingMode"]);this.log.debug("restarting track with constraints",Object.assign(Object.assign({},this.logContext),{constraints:e}));const s={audio:!1,video:!1};this.kind===Q.Kind.Video?s.video=t||i?{deviceId:t,facingMode:i}:!0:s.audio=t?{deviceId:t}:!0,this.attachedElements.forEach(c=>{Dt(this.mediaStreamTrack,c)}),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.stop();const a=(yield navigator.mediaDevices.getUserMedia(s)).getTracks()[0];return yield a.applyConstraints(r),a.addEventListener("ended",this.handleEnded),this.log.debug("re-acquired MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(a),this._constraints=e,this.emit(k.Restarted,this),this.manuallyStopped&&(this.log.warn("track was stopped during a restart, stopping restarted track",this.logContext),this.stop()),this}finally{A()}})}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?k.Muted:k.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),hl()&&(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 A=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(k.UpstreamPaused,this);const t=qe();if((t==null?void 0:t.name)==="Safari"&&ct(t.version,"12.0")<0)throw new hs("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{A()}})}resumeUpstream(){return p(this,void 0,void 0,function*(){var e;const A=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(k.UpstreamResumed,this),((e=this.sender.transport)===null||e===void 0?void 0:e.state)!=="closed"&&(yield this.sender.replaceTrack(this.mediaStreamTrack))}finally{A()}})}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(A){var t=this;let i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){var r;const s=yield t.processorLock.lock();try{t.log.debug("setting up processor",t.logContext);const o=document.createElement(t.kind),a={kind:t.kind,track:t._mediaStreamTrack,element:o,audioContext:t.audioContext};if(yield A.init(a),t.log.debug("processor initialized",t.logContext),t.processor&&(yield t.stopProcessor()),t.kind==="unknown")throw TypeError("cannot set processor on track of unknown kind");if(Lt(t._mediaStreamTrack,o),o.muted=!0,o.play().catch(c=>t.log.error("failed to play processor element",Object.assign(Object.assign({},t.logContext),{error:c}))),t.processor=A,t.processorElement=o,t.processor.processedTrack){for(const c of t.attachedElements)c!==t.processorElement&&i&&(Dt(t._mediaStreamTrack,c),Lt(t.processor.processedTrack,c));yield(r=t.sender)===null||r===void 0?void 0:r.replaceTrack(t.processor.processedTrack)}t.emit(k.TrackProcessorUpdate,t.processor)}finally{s()}}()})}getProcessor(){return this.processor}stopProcessor(){return p(this,arguments,void 0,function(){var e=this;let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){var t,i;e.processor&&(e.log.debug("stopping processor",e.logContext),(t=e.processor.processedTrack)===null||t===void 0||t.stop(),yield e.processor.destroy(),e.processor=void 0,A||((i=e.processorElement)===null||i===void 0||i.remove(),e.processorElement=void 0),yield e._mediaStreamTrack.applyConstraints(e._constraints),yield e.setMediaStreamTrack(e._mediaStreamTrack,!0),e.emit(k.TrackProcessorUpdate))}()})}}class Si extends Ol{get enhancedNoiseCancellation(){return this.isKrispNoiseFilterEnabled}constructor(e,A){let t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,i=arguments.length>3?arguments[3]:void 0,r=arguments.length>4?arguments[4]:void 0;super(e,Q.Kind.Audio,A,t,r),this.stopOnMute=!1,this.isKrispNoiseFilterEnabled=!1,this.monitorSender=()=>p(this,void 0,void 0,function*(){if(!this.sender){this._currentBitrate=0;return}let s;try{s=yield this.getSenderStats()}catch(o){this.log.error("could not get audio sender stats",Object.assign(Object.assign({},this.logContext),{error:o}));return}s&&this.prevStats&&(this._currentBitrate=Ei(s,this.prevStats)),this.prevStats=s}),this.handleKrispNoiseFilterEnable=()=>{this.isKrispNoiseFilterEnabled=!0,this.log.debug("Krisp noise filter enabled",this.logContext),this.emit(k.AudioTrackFeatureUpdate,this,Xe.TF_ENHANCED_NOISE_CANCELLATION,!0)},this.handleKrispNoiseFilterDisable=()=>{this.isKrispNoiseFilterEnabled=!1,this.log.debug("Krisp noise filter disabled",this.logContext),this.emit(k.AudioTrackFeatureUpdate,this,Xe.TF_ENHANCED_NOISE_CANCELLATION,!1)},this.audioContext=i,this.checkForSilence()}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return p(this,void 0,void 0,function*(){const A=yield this.muteLock.lock();try{return this.isMuted?(this.log.debug("Track already muted",this.logContext),this):(this.source===Q.Source.Microphone&&this.stopOnMute&&!this.isUserProvided&&(this.log.debug("stopping mic track",this.logContext),this._mediaStreamTrack.stop()),yield e.mute.call(this),this)}finally{A()}})}unmute(){const e=Object.create(null,{unmute:{get:()=>super.unmute}});return p(this,void 0,void 0,function*(){const A=yield this.muteLock.lock();try{if(!this.isMuted)return this.log.debug("Track already unmuted",this.logContext),this;const t=this._constraints.deviceId&&this._mediaStreamTrack.getSettings().deviceId!==LA(this._constraints.deviceId);return this.source===Q.Source.Microphone&&(this.stopOnMute||this._mediaStreamTrack.readyState==="ended"||t)&&!this.isUserProvided&&(this.log.debug("reacquiring mic track",this.logContext),yield this.restartTrack()),yield e.unmute.call(this),this}finally{A()}})}restartTrack(e){return p(this,void 0,void 0,function*(){let A;if(e){const t=xs({audio:e});typeof t.audio!="boolean"&&(A=t.audio)}yield this.restart(A)})}restart(e){const A=Object.create(null,{restart:{get:()=>super.restart}});return p(this,void 0,void 0,function*(){const t=yield A.restart.call(this,e);return this.checkForSilence(),t})}startMonitor(){Re()&&(this.monitorInterval||(this.monitorInterval=setInterval(()=>{this.monitorSender()},Gs)))}setProcessor(e){return p(this,void 0,void 0,function*(){var A;const t=yield this.processorLock.lock();try{if(!oA()&&!this.audioContext)throw Error("Audio context needs to be set on LocalAudioTrack in order to enable processors");this.processor&&(yield this.stopProcessor());const i={kind:this.kind,track:this._mediaStreamTrack,audioContext:this.audioContext};this.log.debug("setting up audio processor ".concat(e.name),this.logContext),yield e.init(i),this.processor=e,this.processor.processedTrack&&(yield(A=this.sender)===null||A===void 0?void 0:A.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(k.TrackProcessorUpdate,this.processor)}finally{t()}})}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 A=yield this.sender.getStats();let t;return A.forEach(i=>{i.type==="outbound-rtp"&&(t={type:"audio",streamId:i.id,packetsSent:i.packetsSent,packetsLost:i.packetsLost,bytesSent:i.bytesSent,timestamp:i.timestamp,roundTripTime:i.roundTripTime,jitter:i.jitter})}),t})}checkForSilence(){return p(this,void 0,void 0,function*(){const e=yield yl(this);return e&&(this.isMuted||this.log.warn("silence detected on local audio track",this.logContext),this.emit(k.AudioSilenceDetected)),e})}}function wp(n,e,A){switch(n.kind){case"audio":return new Si(n,e,!1,void 0,A);case"video":return new Fi(n,e,!1,A);default:throw new mA("unsupported track type: ".concat(n.kind))}}const yp=Object.values(hn),bp=Object.values(vs),Up=Object.values(Cs),Qp=[hn.h180,hn.h360],Ep=[vs.h180,vs.h360],Sp=n=>[{scaleResolutionDownBy:2,fps:n.encoding.maxFramerate}].map(A=>{var t,i;return new Y(Math.floor(n.width/A.scaleResolutionDownBy),Math.floor(n.height/A.scaleResolutionDownBy),Math.max(15e4,Math.floor(n.encoding.maxBitrate/(Math.pow(A.scaleResolutionDownBy,2)*(((t=n.encoding.maxFramerate)!==null&&t!==void 0?t:30)/((i=A.fps)!==null&&i!==void 0?i:30))))),A.fps,n.encoding.priority)}),js=["q","h","f"];function Js(n,e,A,t){var i,r;let s=t==null?void 0:t.videoEncoding;n&&(s=t==null?void 0:t.screenShareEncoding);const o=t==null?void 0:t.simulcast,a=t==null?void 0:t.scalabilityMode,c=t==null?void 0:t.videoCodec;if(!s&&!o&&!a||!e||!A)return[{}];s||(s=Fp(n,e,A,c),V.debug("using video encoding",s));const l=s.maxFramerate,u=new Y(e,A,s.maxBitrate,s.maxFramerate,s.priority);if(a&&fn(c)){const f=new Ti(a),g=[];if(f.spatial>3)throw new Error("unsupported scalabilityMode: ".concat(a));const m=qe();if(PA()||oA()||(m==null?void 0:m.name)==="Chrome"&&ct(m==null?void 0:m.version,"113")<0){const C=f.suffix=="h"?2:3;for(let y=0;y<f.spatial;y+=1)g.push({rid:js[2-y],maxBitrate:s.maxBitrate/Math.pow(C,y),maxFramerate:u.encoding.maxFramerate});g[0].scalabilityMode=a}else g.push({maxBitrate:s.maxBitrate,maxFramerate:u.encoding.maxFramerate,scalabilityMode:a});return u.encoding.priority&&(g[0].priority=u.encoding.priority,g[0].networkPriority=u.encoding.priority),V.debug("using svc encoding",{encodings:g}),g}if(!o)return[s];let d=[];n?d=(i=Nl(t==null?void 0:t.screenShareSimulcastLayers))!==null&&i!==void 0?i:Ml(n,u):d=(r=Nl(t==null?void 0:t.videoSimulcastLayers))!==null&&r!==void 0?r:Ml(n,u);let h;if(d.length>0){const f=d[0];d.length>1&&([,h]=d);const g=Math.max(e,A);if(g>=960&&h)return Ws(e,A,[f,h,u],l);if(g>=480)return Ws(e,A,[f,u],l)}return Ws(e,A,[u])}function Tp(n,e,A){var t,i,r,s;if(!A.backupCodec||A.backupCodec===!0||A.backupCodec.codec===A.videoCodec)return;e!==A.backupCodec.codec&&V.warn("requested a different codec than specified as backup",{serverRequested:e,backup:A.backupCodec.codec}),A.videoCodec=e,A.videoEncoding=A.backupCodec.encoding;const o=n.mediaStreamTrack.getSettings(),a=(t=o.width)!==null&&t!==void 0?t:(i=n.dimensions)===null||i===void 0?void 0:i.width,c=(r=o.height)!==null&&r!==void 0?r:(s=n.dimensions)===null||s===void 0?void 0:s.height;return n.source===Q.Source.ScreenShare&&A.simulcast&&(A.simulcast=!1),Js(n.source===Q.Source.ScreenShare,a,c,A)}function Fp(n,e,A,t){const i=kp(n,e,A);let{encoding:r}=i[0];const s=Math.max(e,A);for(let o=0;o<i.length;o+=1){const a=i[o];if(r=a.encoding,a.width>=s)break}if(t)switch(t){case"av1":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 kp(n,e,A){if(n)return Up;const t=e>A?e/A:A/e;return Math.abs(t-16/9)<Math.abs(t-4/3)?yp:bp}function Ml(n,e){if(n)return Sp(e);const{width:A,height:t}=e,i=A>t?A/t:t/A;return Math.abs(i-16/9)<Math.abs(i-4/3)?Qp:Ep}function Ws(n,e,A,t){const i=[];if(A.forEach((r,s)=>{if(s>=js.length)return;const o=Math.min(n,e),c={rid:js[s],scaleResolutionDownBy:Math.max(1,o/Math.min(r.width,r.height)),maxBitrate:r.encoding.maxBitrate},l=t&&r.encoding.maxFramerate?Math.min(t,r.encoding.maxFramerate):r.encoding.maxFramerate;l&&(c.maxFramerate=l);const u=_t()||s===0;r.encoding.priority&&u&&(c.priority=r.encoding.priority,c.networkPriority=r.encoding.priority),i.push(c)}),oA()&&gl()==="ios"){let r;i.forEach(o=>{r?o.maxFramerate&&o.maxFramerate>r&&(r=o.maxFramerate):r=o.maxFramerate});let s=!0;i.forEach(o=>{var a;o.maxFramerate!=r&&(s&&(s=!1,V.info("Simulcast on iOS React-Native requires all encodings to share the same framerate.")),V.info('Setting framerate of encoding "'.concat((a=o.rid)!==null&&a!==void 0?a:"",'" to ').concat(r)),o.maxFramerate=r)})}return i}function Nl(n){if(n)return n.sort((e,A)=>{const{encoding:t}=e,{encoding:i}=A;return t.maxBitrate>i.maxBitrate?1:t.maxBitrate<i.maxBitrate?-1:t.maxBitrate===i.maxBitrate&&t.maxFramerate&&i.maxFramerate?t.maxFramerate>i.maxFramerate?1:-1:0})}class Ti{constructor(e){const A=e.match(/^L(\d)T(\d)(h|_KEY|_KEY_SHIFT){0,1}$/);if(!A)throw new Error("invalid scalability mode");if(this.spatial=parseInt(A[1]),this.temporal=parseInt(A[2]),A.length>3)switch(A[3]){case"h":case"_KEY":case"_KEY_SHIFT":this.suffix=A[3]}}toString(){var e;return"L".concat(this.spatial,"T").concat(this.temporal).concat((e=this.suffix)!==null&&e!==void 0?e:"")}}function Ip(n){return n.source===Q.Source.ScreenShare||n.constraints.height&&LA(n.constraints.height)>=1080?"maintain-resolution":"balanced"}const Rp=5e3;class Fi extends Ol{get sender(){return this._sender}set sender(e){this._sender=e,this.degradationPreference&&this.setDegradationPreference(this.degradationPreference)}constructor(e,A){let t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,i=arguments.length>3?arguments[3]:void 0;super(e,Q.Kind.Video,A,t,i),this.simulcastCodecs=new Map,this.degradationPreference="balanced",this.monitorSender=()=>p(this,void 0,void 0,function*(){if(!this.sender){this._currentBitrate=0;return}let r;try{r=yield this.getSenderStats()}catch(o){this.log.error("could not get audio sender stats",Object.assign(Object.assign({},this.logContext),{error:o}));return}const s=new Map(r.map(o=>[o.rid,o]));if(this.prevStats){let o=0;s.forEach((a,c)=>{var l;const u=(l=this.prevStats)===null||l===void 0?void 0:l.get(c);o+=Ei(a,u)}),this._currentBitrate=o}this.prevStats=s}),this.senderLock=new Te}get isSimulcast(){return!!(this.sender&&this.sender.getParameters().encodings.length>1)}startMonitor(e){var A;if(this.signalClient=e,!Re())return;const t=(A=this.sender)===null||A===void 0?void 0:A.getParameters();t&&(this.encodings=t.encodings),!this.monitorInterval&&(this.monitorInterval=setInterval(()=>{this.monitorSender()},Gs))}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 A,t,i,r,s;yield e.pauseUpstream.call(this);try{for(var o=!0,a=kA(this.simulcastCodecs.values()),c;c=yield a.next(),A=c.done,!A;o=!0)r=c.value,o=!1,yield(s=r.sender)===null||s===void 0?void 0:s.replaceTrack(null)}catch(l){t={error:l}}finally{try{!o&&!A&&(i=a.return)&&(yield i.call(a))}finally{if(t)throw t.error}}})}resumeUpstream(){const e=Object.create(null,{resumeUpstream:{get:()=>super.resumeUpstream}});return p(this,void 0,void 0,function*(){var A,t,i,r,s;yield e.resumeUpstream.call(this);try{for(var o=!0,a=kA(this.simulcastCodecs.values()),c;c=yield a.next(),A=c.done,!A;o=!0){r=c.value,o=!1;const l=r;yield(s=l.sender)===null||s===void 0?void 0:s.replaceTrack(l.mediaStreamTrack)}}catch(l){t={error:l}}finally{try{!o&&!A&&(i=a.return)&&(yield i.call(a))}finally{if(t)throw t.error}}})}mute(){const e=Object.create(null,{mute:{get:()=>super.mute}});return p(this,void 0,void 0,function*(){const A=yield this.muteLock.lock();try{return this.isMuted?(this.log.debug("Track already muted",this.logContext),this):(this.source===Q.Source.Camera&&!this.isUserProvided&&(this.log.debug("stopping camera track",this.logContext),this._mediaStreamTrack.stop()),yield e.mute.call(this),this)}finally{A()}})}unmute(){const e=Object.create(null,{unmute:{get:()=>super.unmute}});return p(this,void 0,void 0,function*(){const A=yield this.muteLock.lock();try{return this.isMuted?(this.source===Q.Source.Camera&&!this.isUserProvided&&(this.log.debug("reacquiring camera track",this.logContext),yield this.restartTrack()),yield e.unmute.call(this),this):(this.log.debug("Track already unmuted",this.logContext),this)}finally{A()}})}setTrackMuted(e){super.setTrackMuted(e);for(const A of this.simulcastCodecs.values())A.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 A=[],t=yield this.sender.getStats();return t.forEach(i=>{var r;if(i.type==="outbound-rtp"){const s={type:"video",streamId:i.id,frameHeight:i.frameHeight,frameWidth:i.frameWidth,framesPerSecond:i.framesPerSecond,framesSent:i.framesSent,firCount:i.firCount,pliCount:i.pliCount,nackCount:i.nackCount,packetsSent:i.packetsSent,bytesSent:i.bytesSent,qualityLimitationReason:i.qualityLimitationReason,qualityLimitationDurations:i.qualityLimitationDurations,qualityLimitationResolutionChanges:i.qualityLimitationResolutionChanges,rid:(r=i.rid)!==null&&r!==void 0?r:i.id,retransmittedPacketsSent:i.retransmittedPacketsSent,targetBitrate:i.targetBitrate,timestamp:i.timestamp},o=t.get(i.remoteId);o&&(s.jitter=o.jitter,s.packetsLost=o.packetsLost,s.roundTripTime=o.roundTripTime),A.push(s)}}),A.sort((i,r)=>{var s,o;return((s=r.frameWidth)!==null&&s!==void 0?s:0)-((o=i.frameWidth)!==null&&o!==void 0?o:0)}),A})}setPublishingQuality(e){const A=[];for(let t=Ne.LOW;t<=Ne.HIGH;t+=1)A.push(new As({quality:t,enabled:t<=e}));this.log.debug("setting publishing quality. max quality ".concat(e),this.logContext),this.setPublishingLayers(A)}restartTrack(e){return p(this,void 0,void 0,function*(){var A,t,i,r,s;let o;if(e){const u=xs({video:e});typeof u.video!="boolean"&&(o=u.video)}yield this.restart(o);try{for(var a=!0,c=kA(this.simulcastCodecs.values()),l;l=yield c.next(),A=l.done,!A;a=!0){r=l.value,a=!1;const u=r;u.sender&&((s=u.sender.transport)===null||s===void 0?void 0:s.state)!=="closed"&&(u.mediaStreamTrack=this.mediaStreamTrack.clone(),yield u.sender.replaceTrack(u.mediaStreamTrack))}}catch(u){t={error:u}}finally{try{!a&&!A&&(i=c.return)&&(yield i.call(c))}finally{if(t)throw t.error}}})}setProcessor(e){const A=Object.create(null,{setProcessor:{get:()=>super.setProcessor}});return p(this,arguments,void 0,function(t){var i=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){var s,o,a,c,l,u;if(yield A.setProcessor.call(i,t,r),!((l=i.processor)===null||l===void 0)&&l.processedTrack)try{for(var d=!0,h=kA(i.simulcastCodecs.values()),f;f=yield h.next(),s=f.done,!s;d=!0)c=f.value,d=!1,yield(u=c.sender)===null||u===void 0?void 0:u.replaceTrack(i.processor.processedTrack)}catch(g){o={error:g}}finally{try{!d&&!s&&(a=h.return)&&(yield a.call(h))}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 A=this.sender.getParameters();A.degradationPreference=e,this.sender.setParameters(A)}catch(A){this.log.warn("failed to set degradationPreference",Object.assign({error:A},this.logContext))}})}addSimulcastTrack(e,A){if(this.simulcastCodecs.has(e)){this.log.error("".concat(e," already added, skipping adding simulcast codec"),this.logContext);return}const t={codec:e,mediaStreamTrack:this.mediaStreamTrack.clone(),sender:void 0,encodings:A};return this.simulcastCodecs.set(e,t),t}setSimulcastTrackSender(e,A){const t=this.simulcastCodecs.get(e);t&&(t.sender=A,setTimeout(()=>{this.subscribedCodecs&&this.setPublishingCodecs(this.subscribedCodecs)},Rp))}setPublishingCodecs(e){return p(this,void 0,void 0,function*(){var A,t,i,r,s,o,a;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(e[0].qualities),[];this.subscribedCodecs=e;const c=[];try{for(A=!0,t=kA(e);i=yield t.next(),r=i.done,!r;A=!0){a=i.value,A=!1;const l=a;if(!this.codec||this.codec===l.codec)yield this.setPublishingLayers(l.qualities);else{const u=this.simulcastCodecs.get(l.codec);if(this.log.debug("try setPublishingCodec for ".concat(l.codec),Object.assign(Object.assign({},this.logContext),{simulcastCodecInfo:u})),!u||!u.sender){for(const d of l.qualities)if(d.enabled){c.push(l.codec);break}}else u.encodings&&(this.log.debug("try setPublishingLayersForSender ".concat(l.codec),this.logContext),yield Kl(u.sender,u.encodings,l.qualities,this.senderLock,this.log,this.logContext))}}}catch(l){s={error:l}}finally{try{!A&&!r&&(o=t.return)&&(yield o.call(t))}finally{if(s)throw s.error}}return c})}setPublishingLayers(e){return p(this,void 0,void 0,function*(){this.log.debug("setting publishing layers",Object.assign(Object.assign({},this.logContext),{qualities:e})),!(!this.sender||!this.encodings)&&(yield Kl(this.sender,this.encodings,e,this.senderLock,this.log,this.logContext))})}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return p(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),hl()&&this.isInBackground&&this.source===Q.Source.Camera&&(this._mediaStreamTrack.enabled=!1)})}}function Kl(n,e,A,t,i,r){return p(this,void 0,void 0,function*(){const s=yield t.lock();i.debug("setPublishingLayersForSender",Object.assign(Object.assign({},r),{sender:n,qualities:A,senderEncodings:e}));try{const o=n.getParameters(),{encodings:a}=o;if(!a)return;if(a.length!==e.length){i.warn("cannot set publishing layers, encodings mismatch",Object.assign(Object.assign({},r),{encodings:a,senderEncodings:e}));return}let c=!1;const l=qe();if((l==null?void 0:l.name)==="Chrome"&&ct(l==null?void 0:l.version,"133")>0&&a[0].scalabilityMode){const d=a[0],h=new Ti(d.scalabilityMode);let f=Ft.OFF;if(A.forEach(g=>{g.enabled&&(f===Ft.OFF||g.quality>f)&&(f=g.quality)}),f===Ft.OFF)d.active&&(d.active=!1,c=!0);else if(!d.active||h.spatial!==f+1){c=!0,d.active=!0;const g=new Ti(e[0].scalabilityMode);h.spatial=f+1,h.suffix=g.suffix,h.spatial===1&&(h.suffix=void 0),d.scalabilityMode=h.toString(),d.scaleResolutionDownBy=Math.pow(2,2-f),e[0].maxBitrate&&(d.maxBitrate=e[0].maxBitrate/(d.scaleResolutionDownBy*d.scaleResolutionDownBy))}}else a.forEach((d,h)=>{var f;let g=(f=d.rid)!==null&&f!==void 0?f:"";g===""&&(g="q");const m=Vl(g),C=A.find(y=>y.quality===m);C&&d.active!==C.enabled&&(c=!0,d.active=C.enabled,i.debug("setting layer ".concat(C.quality," to ").concat(d.active?"enabled":"disabled"),r),_t()&&(C.enabled?(d.scaleResolutionDownBy=e[h].scaleResolutionDownBy,d.maxBitrate=e[h].maxBitrate,d.maxFrameRate=e[h].maxFrameRate):(d.scaleResolutionDownBy=4,d.maxBitrate=10,d.maxFrameRate=2)))});c&&(o.encodings=a,i.debug("setting encodings",Object.assign(Object.assign({},r),{encodings:o.encodings})),yield n.setParameters(o))}finally{s()}})}function Vl(n){switch(n){case"f":return Ne.HIGH;case"h":return Ne.MEDIUM;case"q":return Ne.LOW;default:return Ne.HIGH}}function Gl(n,e,A,t){if(!A)return[new st({quality:Ne.HIGH,width:n,height:e,bitrate:0,ssrc:0})];if(t){const i=A[0].scalabilityMode,r=new Ti(i),s=[],o=r.suffix=="h"?1.5:2,a=r.suffix=="h"?2:3;for(let c=0;c<r.spatial;c+=1)s.push(new st({quality:Math.min(Ne.HIGH,r.spatial-1)-c,width:Math.ceil(n/Math.pow(o,c)),height:Math.ceil(e/Math.pow(o,c)),bitrate:A[0].maxBitrate?Math.ceil(A[0].maxBitrate/Math.pow(a,c)):0,ssrc:0}));return s}return A.map(i=>{var r,s,o;const a=(r=i.scaleResolutionDownBy)!==null&&r!==void 0?r:1;let c=Vl((s=i.rid)!==null&&s!==void 0?s:"");return new st({quality:c,width:Math.ceil(n/a),height:Math.ceil(e/a),bitrate:(o=i.maxBitrate)!==null&&o!==void 0?o:0,ssrc:0})})}const jl="_lossy",Jl="_reliable",xp=2*1e3,Xs="leave-reconnect";var ze;(function(n){n[n.New=0]="New",n[n.Connected=1]="Connected",n[n.Disconnected=2]="Disconnected",n[n.Reconnecting=3]="Reconnecting",n[n.Closed=4]="Closed"})(ze||(ze={}));class Pp extends sA.EventEmitter{get isClosed(){return this._isClosed}get pendingReconnect(){return!!this.reconnectTimeout}constructor(e){var A;super(),this.options=e,this.rtcConfig={},this.peerConnectionTimeout=Ks.peerConnectionTimeout,this.fullReconnectOnNext=!1,this.subscriberPrimary=!1,this.pcState=ze.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=V,this.handleDataChannel=t=>p(this,[t],void 0,function(i){var r=this;let{channel:s}=i;return function*(){if(s){if(s.label===Jl)r.reliableDCSub=s;else if(s.label===jl)r.lossyDCSub=s;else return;r.log.debug("on data channel ".concat(s.id,", ").concat(s.label),r.logContext),s.onmessage=r.handleDataMessage}}()}),this.handleDataMessage=t=>p(this,void 0,void 0,function*(){var i,r;const s=yield this.dataProcessLock.lock();try{let o;if(t.data instanceof ArrayBuffer)o=t.data;else if(t.data instanceof Blob)o=yield t.data.arrayBuffer();else{this.log.error("unsupported data type",Object.assign(Object.assign({},this.logContext),{data:t.data}));return}const a=ke.fromBinary(new Uint8Array(o));((i=a.value)===null||i===void 0?void 0:i.case)==="speaker"?this.emit(I.ActiveSpeakersUpdate,a.value.value.speakers):(((r=a.value)===null||r===void 0?void 0:r.case)==="user"&&Dp(a,a.value.value),this.emit(I.DataPacketReceived,a))}finally{s()}}),this.handleDataError=t=>{const r=t.currentTarget.maxRetransmits===0?"lossy":"reliable";if(t instanceof ErrorEvent&&t.error){const{error:s}=t.error;this.log.error("DataChannel error on ".concat(r,": ").concat(t.message),Object.assign(Object.assign({},this.logContext),{error:s}))}else this.log.error("Unknown DataChannel error on ".concat(r),Object.assign(Object.assign({},this.logContext),{event:t}))},this.handleBufferedAmountLow=t=>{const r=t.currentTarget.maxRetransmits===0?J.LOSSY:J.RELIABLE;this.updateAndEmitDCBufferStatus(r)},this.handleDisconnect=(t,i)=>{if(this._isClosed)return;this.log.warn("".concat(t," disconnected"),this.logContext),this.reconnectAttempts===0&&(this.reconnectStart=Date.now());const r=a=>{this.log.warn("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(a,"ms. giving up"),this.logContext),this.emit(I.Disconnected),this.close()},s=Date.now()-this.reconnectStart;let o=this.getNextRetryDelay({elapsedMs:s,retryCount:this.reconnectAttempts});if(o===null){r(s);return}t===Xs&&(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=ve.setTimeout(()=>this.attemptReconnect(i).finally(()=>this.reconnectTimeout=void 0),o)},this.waitForRestarted=()=>new Promise((t,i)=>{this.pcState===ze.Connected&&t();const r=()=>{this.off(I.Disconnected,s),t()},s=()=>{this.off(I.Restarted,r),i()};this.once(I.Restarted,r),this.once(I.Disconnected,s)}),this.updateAndEmitDCBufferStatus=t=>{const i=this.isBufferStatusLow(t);typeof i<"u"&&i!==this.dcBufferStatus.get(t)&&(this.dcBufferStatus.set(t,i),this.emit(I.DCBufferStatusChanged,i,t))},this.isBufferStatusLow=t=>{const i=this.dataChannelForKind(t);if(i)return i.bufferedAmount<=i.bufferedAmountLowThreshold},this.handleBrowserOnLine=()=>{this.client.currentState===Ae.RECONNECTING&&(this.clearReconnectTimeout(),this.attemptReconnect(kt.RR_SIGNAL_DISCONNECTED))},this.log=pA((A=e.loggerName)!==null&&A!==void 0?A:Ye.Engine),this.loggerOptions={loggerName:e.loggerName,loggerContextCb:()=>this.logContext},this.client=new Ls(void 0,this.loggerOptions),this.client.signalLatency=this.options.expSignalLatency,this.reconnectPolicy=this.options.reconnectPolicy,this.registerOnLineListener(),this.closingLock=new Te,this.dataProcessLock=new Te,this.dcBufferStatus=new Map([[J.LOSSY,!0],[J.RELIABLE,!0]]),this.client.onParticipantUpdate=t=>this.emit(I.ParticipantUpdate,t),this.client.onConnectionQuality=t=>this.emit(I.ConnectionQualityUpdate,t),this.client.onRoomUpdate=t=>this.emit(I.RoomUpdate,t),this.client.onSubscriptionError=t=>this.emit(I.SubscriptionError,t),this.client.onSubscriptionPermissionUpdate=t=>this.emit(I.SubscriptionPermissionUpdate,t),this.client.onSpeakersChanged=t=>this.emit(I.SpeakersChanged,t),this.client.onStreamStateUpdate=t=>this.emit(I.StreamStateChanged,t),this.client.onRequestResponse=t=>this.emit(I.SignalRequestResponse,t)}get logContext(){var e,A,t,i,r,s,o,a;return{room:(A=(e=this.latestJoinResponse)===null||e===void 0?void 0:e.room)===null||A===void 0?void 0:A.name,roomID:(i=(t=this.latestJoinResponse)===null||t===void 0?void 0:t.room)===null||i===void 0?void 0:i.sid,participant:(s=(r=this.latestJoinResponse)===null||r===void 0?void 0:r.participant)===null||s===void 0?void 0:s.identity,pID:(a=(o=this.latestJoinResponse)===null||o===void 0?void 0:o.participant)===null||a===void 0?void 0:a.sid}}join(e,A,t,i){return p(this,void 0,void 0,function*(){this.url=e,this.token=A,this.signalOpts=t,this.maxJoinAttempts=t.maxRetries;try{this.joinAttempts+=1,this.setupSignalClientCallbacks();const r=yield this.client.join(e,A,t,i);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,setTimeout(()=>{this.emit(I.SignalConnected)},10),r}catch(r){if(r instanceof Z&&r.reason===G.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,A,t,i);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(I.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 A=t=>{t&&(t.close(),t.onbufferedamountlow=null,t.onclose=null,t.onclosing=null,t.onerror=null,t.onmessage=null,t.onopen=null)};A(this.lossyDC),A(this.lossyDCSub),A(this.reliableDC),A(this.reliableDCSub),this.lossyDC=void 0,this.lossyDCSub=void 0,this.reliableDC=void 0,this.reliableDCSub=void 0})}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 mA("a track with the same ID has already been published");return new Promise((A,t)=>{const i=setTimeout(()=>{delete this.pendingTrackResolvers[e.cid],t(new Z("publication of local track timed out, no response from server",G.InternalError))},1e4);this.pendingTrackResolvers[e.cid]={resolve:r=>{clearTimeout(i),A(r)},reject:()=>{clearTimeout(i),t(new Error("Cancelled publication by calling unpublish"))}},this.client.sendAddTrack(e)})}removeTrack(e){if(e.track&&this.pendingTrackResolvers[e.track.id]){const{reject:A}=this.pendingTrackResolvers[e.track.id];A&&A(),delete this.pendingTrackResolvers[e.track.id]}try{return this.pcManager.removeTrack(e),!0}catch(A){this.log.warn("failed to remove track",Object.assign(Object.assign({},this.logContext),{error:A}))}return!1}updateMuteStatus(e,A){this.client.sendMuteTrack(e,A)}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 A,t;if(this.pcManager&&this.pcManager.currentState!==se.NEW)return;this.participantSid=(A=e.participant)===null||A===void 0?void 0:A.sid;const i=this.makeRTCConfiguration(e);this.pcManager=new vp(i,e.subscriberPrimary,this.loggerOptions),this.emit(I.TransportsCreated,this.pcManager.publisher,this.pcManager.subscriber),this.pcManager.onIceCandidate=(r,s)=>{this.client.sendIceCandidate(r,s)},this.pcManager.onPublisherOffer=r=>{this.client.sendOffer(r)},this.pcManager.onDataChannel=this.handleDataChannel,this.pcManager.onStateChange=(r,s,o)=>p(this,void 0,void 0,function*(){if(this.log.debug("primary PC state changed ".concat(r),this.logContext),["closed","disconnected","failed"].includes(s)&&(this.publisherConnectionPromise=void 0),r===se.CONNECTED){const l=this.pcState===ze.New;this.pcState=ze.Connected,l&&this.emit(I.Connected,e)}else r===se.FAILED&&this.pcState===ze.Connected&&(this.pcState=ze.Disconnected,this.handleDisconnect("peerconnection failed",o==="failed"?kt.RR_SUBSCRIBER_FAILED:kt.RR_PUBLISHER_FAILED));const a=this.client.isDisconnected||this.client.currentState===Ae.RECONNECTING,c=[se.FAILED,se.CLOSING,se.CLOSED].includes(r);a&&c&&!this._isClosed&&this.emit(I.Offline)}),this.pcManager.onTrack=r=>{this.emit(I.MediaTrackAdded,r.track,r.streams[0],r.receiver)},Lp((t=e.serverInfo)===null||t===void 0?void 0:t.protocol)||this.createDataChannels()})}setupSignalClientCallbacks(){this.client.onAnswer=e=>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))}),this.client.onTrickle=(e,A)=>{this.pcManager&&(this.log.debug("got ICE candidate from peer",Object.assign(Object.assign({},this.logContext),{candidate:e,target:A})),this.pcManager.addIceCandidate(e,A))},this.client.onOffer=e=>p(this,void 0,void 0,function*(){if(!this.pcManager)return;const A=yield this.pcManager.createSubscriberAnswerFromOffer(e);this.client.sendAnswer(A)}),this.client.onLocalTrackPublished=e=>{var A;if(this.log.debug("received trackPublishedResponse",Object.assign(Object.assign({},this.logContext),{cid:e.cid,track:(A=e.track)===null||A===void 0?void 0:A.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:t}=this.pendingTrackResolvers[e.cid];delete this.pendingTrackResolvers[e.cid],t(e.track)},this.client.onLocalTrackUnpublished=e=>{this.emit(I.LocalTrackUnpublished,e)},this.client.onLocalTrackSubscribed=e=>{this.emit(I.LocalTrackSubscribed,e)},this.client.onTokenRefresh=e=>{this.token=e},this.client.onRemoteMuteChanged=(e,A)=>{this.emit(I.RemoteMute,e,A)},this.client.onSubscribedQualityUpdate=e=>{this.emit(I.SubscribedQualityUpdate,e)},this.client.onRoomMoved=e=>{var A;this.participantSid=(A=e.participant)===null||A===void 0?void 0:A.sid,this.emit(I.RoomMoved,e)},this.client.onClose=()=>{this.handleDisconnect("signal",kt.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 xt.DISCONNECT:this.emit(I.Disconnected,e==null?void 0:e.reason),this.close();break;case xt.RECONNECT:this.fullReconnectOnNext=!0,this.handleDisconnect(Xs);break;case xt.RESUME:this.handleDisconnect(Xs)}}}makeRTCConfiguration(e){var A;const t=Object.assign({},this.rtcConfig);if(!((A=this.signalOpts)===null||A===void 0)&&A.e2eeEnabled&&(this.log.debug("E2EE - setting up transports with insertable streams",this.logContext),t.encodedInsertableStreams=!0),e.iceServers&&!t.iceServers){const i=[];e.iceServers.forEach(r=>{const s={urls:r.urls};r.username&&(s.username=r.username),r.credential&&(s.credential=r.credential),i.push(s)}),t.iceServers=i}return e.clientConfiguration&&e.clientConfiguration.forceRelay===ln.ENABLED&&(t.iceTransportPolicy="relay"),t.sdpSemantics="unified-plan",t.continualGatheringPolicy="gather_continually",t}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(jl,{ordered:!1,maxRetransmits:0}),this.reliableDC=this.pcManager.createPublisherDataChannel(Jl,{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,A,t){return p(this,void 0,void 0,function*(){if(ws())return yield this.createTransceiverRTCRtpSender(e,A,t);if(ys())return this.log.warn("using add-track fallback",this.logContext),yield this.createRTCRtpSender(e.mediaStreamTrack);throw new ge("Required webRTC APIs not supported on this device")})}createSimulcastSender(e,A,t,i){return p(this,void 0,void 0,function*(){if(ws())return this.createSimulcastTransceiverSender(e,A,t,i);if(ys())return this.log.debug("using add-track fallback",this.logContext),this.createRTCRtpSender(e.mediaStreamTrack);throw new ge("Cannot stream on this device")})}createTransceiverRTCRtpSender(e,A,t){return p(this,void 0,void 0,function*(){if(!this.pcManager)throw new ge("publisher is closed");const i=[];e.mediaStream&&i.push(e.mediaStream),Ot(e)&&(e.codec=A.videoCodec);const r={direction:"sendonly",streams:i};return t&&(r.sendEncodings=t),(yield this.pcManager.addPublisherTransceiver(e.mediaStreamTrack,r)).sender})}createSimulcastTransceiverSender(e,A,t,i){return p(this,void 0,void 0,function*(){if(!this.pcManager)throw new ge("publisher is closed");const r={direction:"sendonly"};i&&(r.sendEncodings=i);const s=yield this.pcManager.addPublisherTransceiver(A.mediaStreamTrack,r);if(t.videoCodec)return e.setSimulcastTrackSender(t.videoCodec,s.sender),s.sender})}createRTCRtpSender(e){return p(this,void 0,void 0,function*(){if(!this.pcManager)throw new ge("publisher is closed");return this.pcManager.addPublisherTrack(e)})}attemptReconnect(e){return p(this,void 0,void 0,function*(){var A,t,i;if(!this._isClosed){if(this.attemptingReconnect){V.warn("already attempting reconnect, returning early",this.logContext);return}(((A=this.clientConfiguration)===null||A===void 0?void 0:A.resumeConnection)===ln.DISABLED||((i=(t=this.pcManager)===null||t===void 0?void 0:t.currentState)!==null&&i!==void 0?i:se.NEW)===se.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 s=!0;r instanceof ge?(this.log.debug("received unrecoverable error",Object.assign(Object.assign({},this.logContext),{error:r})),s=!1):r instanceof Nt||(this.fullReconnectOnNext=!0),s?this.handleDisconnect("reconnect",kt.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(I.Disconnected),yield this.close())}finally{this.attemptingReconnect=!1}}})}getNextRetryDelay(e){try{return this.reconnectPolicy.nextRetryDelayInMs(e)}catch(A){this.log.warn("encountered error in reconnect policy",Object.assign(Object.assign({},this.logContext),{error:A}))}return null}restartConnection(e){return p(this,void 0,void 0,function*(){var A,t,i;try{if(!this.url||!this.token)throw new ge("could not reconnect, url or token not saved");this.log.info("reconnecting, attempt: ".concat(this.reconnectAttempts),this.logContext),this.emit(I.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 Nt;r=yield this.join(e??this.url,this.token,this.signalOpts)}catch(s){throw s instanceof Z&&s.reason===G.NotAllowed?new ge("could not reconnect, token might be expired"):new Nt}if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(this.client.setReconnected(),this.emit(I.SignalRestarted,r),yield this.waitForPCReconnected(),this.client.currentState!==Ae.CONNECTED)throw new Nt("Signal connection got severed during reconnect");(A=this.regionUrlProvider)===null||A===void 0||A.resetAttempts(),this.emit(I.Restarted)}catch(r){const s=yield(t=this.regionUrlProvider)===null||t===void 0?void 0:t.getNextBestRegionUrl();if(s){yield this.restartConnection(s);return}else throw(i=this.regionUrlProvider)===null||i===void 0||i.resetAttempts(),r}})}resumeConnection(e){return p(this,void 0,void 0,function*(){var A;if(!this.url||!this.token)throw new ge("could not reconnect, url or token not saved");if(!this.pcManager)throw new ge("publisher and subscriber connections unset");this.log.info("resuming signal connection, attempt ".concat(this.reconnectAttempts),this.logContext),this.emit(I.Resuming);let t;try{this.setupSignalClientCallbacks(),t=yield this.client.reconnect(this.url,this.token,this.participantSid,e)}catch(i){let r="";throw i instanceof Error&&(r=i.message,this.log.error(i.message,Object.assign(Object.assign({},this.logContext),{error:i}))),i instanceof Z&&i.reason===G.NotAllowed?new ge("could not reconnect, token might be expired"):i instanceof Z&&i.reason===G.LeaveRequest?i:new Nt(r)}if(this.emit(I.SignalResumed),t){const i=this.makeRTCConfiguration(t);this.pcManager.updateConfiguration(i)}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!==Ae.CONNECTED)throw new Nt("Signal connection got severed during reconnect");this.client.setReconnected(),((A=this.reliableDC)===null||A===void 0?void 0:A.readyState)==="open"&&this.reliableDC.id===null&&this.createDataChannels(),this.emit(I.Resumed)})}waitForPCInitialConnection(e,A){return p(this,void 0,void 0,function*(){if(!this.pcManager)throw new ge("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(A,e)})}waitForPCReconnected(){return p(this,void 0,void 0,function*(){this.pcState=ze.Reconnecting,this.log.debug("waiting for peer connection to reconnect",this.logContext);try{if(yield Ie(xp),!this.pcManager)throw new ge("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(void 0,this.peerConnectionTimeout),this.pcState=ze.Connected}catch(e){throw this.pcState=ze.Disconnected,new Z("could not establish PC connection, ".concat(e.message),G.InternalError)}})}publishRpcResponse(e,A,t,i){return p(this,void 0,void 0,function*(){const r=new ke({destinationIdentities:[e],kind:J.RELIABLE,value:{case:"rpcResponse",value:new Za({requestId:A,value:i?{case:"error",value:i.toProto()}:{case:"payload",value:t??""}})}});yield this.sendDataPacket(r,J.RELIABLE)})}publishRpcAck(e,A){return p(this,void 0,void 0,function*(){const t=new ke({destinationIdentities:[e],kind:J.RELIABLE,value:{case:"rpcAck",value:new qa({requestId:A})}});yield this.sendDataPacket(t,J.RELIABLE)})}sendDataPacket(e,A){return p(this,void 0,void 0,function*(){const t=e.toBinary();yield this.ensurePublisherConnected(A);const i=this.dataChannelForKind(A);i&&i.send(t),this.updateAndEmitDCBufferStatus(A)})}waitForBufferStatusLow(e){return new Promise((A,t)=>p(this,void 0,void 0,function*(){if(this.isBufferStatusLow(e))A();else{const i=()=>t("Engine closed");for(this.once(I.Closing,i);!this.dcBufferStatus.get(e);)yield Ie(10);this.off(I.Closing,i),A()}}))}ensureDataTransportConnected(e){return p(this,arguments,void 0,function(A){var t=this;let i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.subscriberPrimary;return function*(){var r;if(!t.pcManager)throw new ge("PC manager is closed");const s=i?t.pcManager.subscriber:t.pcManager.publisher,o=i?"Subscriber":"Publisher";if(!s)throw new Z("".concat(o," connection not set"),G.InternalError);let a=!1;!i&&!t.dataChannelForKind(A,i)&&(t.createDataChannels(),a=!0),!a&&!i&&!t.pcManager.publisher.isICEConnected&&t.pcManager.publisher.getICEConnectionState()!=="checking"&&(a=!0),a&&t.negotiate();const c=t.dataChannelForKind(A,i);if((c==null?void 0:c.readyState)==="open")return;const l=new Date().getTime()+t.peerConnectionTimeout;for(;new Date().getTime()<l;){if(s.isICEConnected&&((r=t.dataChannelForKind(A,i))===null||r===void 0?void 0:r.readyState)==="open")return;yield Ie(50)}throw new Z("could not establish ".concat(o," connection, state: ").concat(s.getICEConnectionState()),G.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!==se.CONNECTED||!this.client.ws||this.client.ws.readyState===WebSocket.CLOSED)}negotiate(){return p(this,void 0,void 0,function*(){return new Promise((e,A)=>p(this,void 0,void 0,function*(){if(!this.pcManager){A(new fs("PC manager is closed"));return}this.pcManager.requirePublisher(),this.pcManager.publisher.getTransceivers().length==0&&!this.lossyDC&&!this.reliableDC&&this.createDataChannels();const t=new AbortController,i=()=>{t.abort(),this.log.debug("engine disconnected while negotiation was ongoing",this.logContext),e()};this.isClosed&&A("cannot negotiate on closed engine"),this.on(I.Closing,i),this.pcManager.publisher.once(Mt.RTPVideoPayloadTypes,r=>{const s=new Map;r.forEach(o=>{const a=o.codec.toLowerCase();Gg(a)&&s.set(o.payload,a)}),this.emit(I.RTPVideoMapUpdate,s)});try{yield this.pcManager.negotiate(t),e()}catch(r){r instanceof fs&&(this.fullReconnectOnNext=!0),this.handleDisconnect("negotiation",kt.RR_UNKNOWN),A(r)}finally{this.off(I.Closing,i)}}))})}dataChannelForKind(e,A){if(A){if(e===J.LOSSY)return this.lossyDCSub;if(e===J.RELIABLE)return this.reliableDCSub}else{if(e===J.LOSSY)return this.lossyDC;if(e===J.RELIABLE)return this.reliableDC}}sendSyncState(e,A){var t,i;if(!this.pcManager){this.log.warn("sync state cannot be sent without peer connection setup",this.logContext);return}const r=this.pcManager.subscriber.getLocalDescription(),s=this.pcManager.subscriber.getRemoteDescription(),o=(i=(t=this.signalOpts)===null||t===void 0?void 0:t.autoSubscribe)!==null&&i!==void 0?i:!0,a=new Array,c=new Array;e.forEach(l=>{l.isDesired!==o&&a.push(l.trackSid),l.isEnabled||c.push(l.trackSid)}),this.client.sendSyncState(new pc({answer:r?Qi({sdp:r.sdp,type:r.type}):void 0,offer:s?Qi({sdp:s.sdp,type:s.type}):void 0,subscription:new ci({trackSids:a,subscribe:!o,participantTracks:[]}),publishTracks:zg(A),dataChannels:this.dataChannelsInfo(),trackSidsDisabled:c}))}failNext(){this.shouldFailNext=!0}dataChannelsInfo(){const e=[],A=(t,i)=>{(t==null?void 0:t.id)!==void 0&&t.id!==null&&e.push(new mc({label:t.label,id:t.id,target:i}))};return A(this.dataChannelForKind(J.LOSSY),$e.PUBLISHER),A(this.dataChannelForKind(J.RELIABLE),$e.PUBLISHER),A(this.dataChannelForKind(J.LOSSY,!0),$e.SUBSCRIBER),A(this.dataChannelForKind(J.RELIABLE,!0),$e.SUBSCRIBER),e}clearReconnectTimeout(){this.reconnectTimeout&&ve.clearTimeout(this.reconnectTimeout)}clearPendingReconnect(){this.clearReconnectTimeout(),this.reconnectAttempts=0}registerOnLineListener(){Re()&&window.addEventListener("online",this.handleBrowserOnLine)}deregisterOnLineListener(){Re()&&window.removeEventListener("online",this.handleBrowserOnLine)}}class Nt extends Error{}function Lp(n){return n!==void 0&&n>13}function Dp(n,e){const A=n.participantIdentity?n.participantIdentity:e.participantIdentity;n.participantIdentity=A,e.participantIdentity=A;const t=n.destinationIdentities.length!==0?n.destinationIdentities:e.destinationIdentities;n.destinationIdentities=t,e.destinationIdentities=t}class $s{constructor(e,A){this.lastUpdateAt=0,this.settingsCacheTime=3e3,this.attemptedRegions=[],this.serverUrl=new URL(e),this.token=A}updateToken(e){this.token=e}isCloud(){return Us(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 A=this.regionSettings.regions.filter(t=>!this.attemptedRegions.find(i=>i.url===t.url));if(A.length>0){const t=A[0];return this.attemptedRegions.push(t),V.debug("next region: ".concat(t.region)),t.url}else return null})}resetAttempts(){this.attemptedRegions=[]}fetchRegionSettings(e){return p(this,void 0,void 0,function*(){const A=yield fetch("".concat(_p(this.serverUrl),"/regions"),{headers:{authorization:"Bearer ".concat(this.token)},signal:e});if(A.ok){const t=yield A.json();return this.lastUpdateAt=Date.now(),t}else throw new Z("Could not fetch region settings: ".concat(A.statusText),A.status===401?G.NotAllowed:G.InternalError,A.status)})}setServerReportedRegions(e){this.regionSettings=e,this.lastUpdateAt=Date.now()}}function _p(n){return"".concat(n.protocol.replace("ws","http"),"//").concat(n.host,"/settings")}class Wl{get info(){return this._info}constructor(e,A,t){this.reader=A,this.totalByteSize=t,this._info=e,this.bytesReceived=0}}class Hp extends Wl{handleChunkReceived(e){var A;this.bytesReceived+=e.content.byteLength;const t=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;(A=this.onProgress)===null||A===void 0||A.call(this,t)}[Symbol.asyncIterator](){const e=this.reader.getReader();return{next:()=>p(this,void 0,void 0,function*(){try{const{done:A,value:t}=yield e.read();return A?{done:!0,value:void 0}:(this.handleChunkReceived(t),{done:!1,value:t.content})}catch{return{done:!0,value:void 0}}}),return(){return p(this,void 0,void 0,function*(){return e.releaseLock(),{done:!0,value:void 0}})}}}readAll(){return p(this,void 0,void 0,function*(){var e,A,t,i;let r=new Set;try{for(var s=!0,o=kA(this),a;a=yield o.next(),e=a.done,!e;s=!0){i=a.value,s=!1;const c=i;r.add(c)}}catch(c){A={error:c}}finally{try{!s&&!e&&(t=o.return)&&(yield t.call(o))}finally{if(A)throw A.error}}return Array.from(r)})}}class Op extends Wl{constructor(e,A,t){super(e,A,t),this.receivedChunks=new Map}handleChunkReceived(e){var A;const t=bi(e.chunkIndex),i=this.receivedChunks.get(t);if(i&&i.version>e.version)return;this.receivedChunks.set(t,e),this.bytesReceived+=e.content.byteLength;const r=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;(A=this.onProgress)===null||A===void 0||A.call(this,r)}[Symbol.asyncIterator](){const e=this.reader.getReader(),A=new TextDecoder;return{next:()=>p(this,void 0,void 0,function*(){try{const{done:t,value:i}=yield e.read();return t?{done:!0,value:void 0}:(this.handleChunkReceived(i),{done:!1,value:A.decode(i.content)})}catch{return{done:!0,value:void 0}}}),return(){return p(this,void 0,void 0,function*(){return e.releaseLock(),{done:!0,value:void 0}})}}}readAll(){return p(this,void 0,void 0,function*(){var e,A,t,i;let r="";try{for(var s=!0,o=kA(this),a;a=yield o.next(),e=a.done,!e;s=!0)i=a.value,s=!1,r+=i}catch(c){A={error:c}}finally{try{!s&&!e&&(t=o.return)&&(yield t.call(o))}finally{if(A)throw A.error}}return r})}}class Xl{constructor(e,A,t){this.writableStream=e,this.defaultWriter=e.getWriter(),this.onClose=t,this.info=A}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 Mp extends Xl{}class Np extends Xl{}class $l extends Q{constructor(e,A,t,i,r){super(e,t,r),this.sid=A,this.receiver=i}get isLocal(){return!1}setMuted(e){this.isMuted!==e&&(this.isMuted=e,this._mediaStreamTrack.enabled=!e,this.emit(e?k.Muted:k.Unmuted,this))}setMediaStream(e){this.mediaStream=e;const A=t=>{t.track===this._mediaStreamTrack&&(e.removeEventListener("removetrack",A),this.receiver&&"playoutDelayHint"in this.receiver&&(this.receiver.playoutDelayHint=void 0),this.receiver=void 0,this._currentBitrate=0,this.emit(k.Ended,this))};e.addEventListener("removetrack",A)}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(),Gs)),ep()&&this.registerTimeSyncUpdate()}registerTimeSyncUpdate(){const e=()=>{var A;this.timeSyncHandle=requestAnimationFrame(()=>e());const t=(A=this.receiver)===null||A===void 0?void 0:A.getSynchronizationSources()[0];if(t){const{timestamp:i,rtpTimestamp:r}=t;r&&this.rtpTimestamp!==r&&(this.emit(k.TimeSyncUpdate,{timestamp:i,rtpTimestamp:r}),this.rtpTimestamp=r)}};e()}}class Kp extends $l{constructor(e,A,t,i,r,s){super(e,A,Q.Kind.Audio,t,s),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=Ei(o,this.prevStats)),this.prevStats=o}),this.audioContext=i,this.webAudioPluginNodes=[],r&&(this.sinkId=r.deviceId)}setVolume(e){var A;for(const t of this.attachedElements)this.audioContext?(A=this.gainNode)===null||A===void 0||A.gain.setTargetAtTime(e,0,.1):t.volume=e;oA()&&this._mediaStreamTrack._setVolume(e),this.elementVolume=e}getVolume(){if(this.elementVolume)return this.elementVolume;if(oA())return 1;let e=0;return this.attachedElements.forEach(A=>{A.volume>e&&(e=A.volume)}),e}setSinkId(e){return p(this,void 0,void 0,function*(){this.sinkId=e,yield Promise.all(this.attachedElements.map(A=>{if(bs(A))return A.setSinkId(e)}))})}attach(e){const A=this.attachedElements.length===0;return e?super.attach(e):e=super.attach(),this.sinkId&&bs(e)&&e.setSinkId(this.sinkId).catch(t=>{this.log.error("Failed to set sink id on remote audio track",t,this.logContext)}),this.audioContext&&A&&(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 A;return e?(A=super.detach(e),this.audioContext&&(this.attachedElements.length>0?this.connectWebAudio(this.audioContext,this.attachedElements[0]):this.disconnectWebAudio())):(A=super.detach(),this.disconnectWebAudio()),A}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,A){this.disconnectWebAudio(),this.sourceNode=e.createMediaStreamSource(A.srcObject);let t=this.sourceNode;this.webAudioPluginNodes.forEach(i=>{t.connect(i),t=i}),this.gainNode=e.createGain(),t.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(k.AudioPlaybackFailed,new Error("Audio Context couldn't be started automatically"))}).catch(i=>{this.emit(k.AudioPlaybackFailed,i)})}disconnectWebAudio(){var e,A;(e=this.gainNode)===null||e===void 0||e.disconnect(),(A=this.sourceNode)===null||A===void 0||A.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 A;return e.forEach(t=>{t.type==="inbound-rtp"&&(A={type:"audio",streamId:t.id,timestamp:t.timestamp,jitter:t.jitter,bytesReceived:t.bytesReceived,concealedSamples:t.concealedSamples,concealmentEvents:t.concealmentEvents,silentConcealedSamples:t.silentConcealedSamples,silentConcealmentEvents:t.silentConcealmentEvents,totalAudioEnergy:t.totalAudioEnergy,totalSamplesDuration:t.totalSamplesDuration})}),A})}}const Ys=100;class Vp extends $l{constructor(e,A,t,i,r){super(e,A,Q.Kind.Video,t,r),this.elementInfos=[],this.monitorReceiver=()=>p(this,void 0,void 0,function*(){if(!this.receiver){this._currentBitrate=0;return}const s=yield this.getReceiverStats();s&&this.prevStats&&this.receiver&&(this._currentBitrate=Ei(s,this.prevStats)),this.prevStats=s}),this.debouncedHandleResize=Ms(()=>{this.updateDimensions()},Ys),this.adaptiveStreamSettings=i}get isAdaptiveStream(){return this.adaptiveStreamSettings!==void 0}get mediaStreamTrack(){return this._mediaStreamTrack}setMuted(e){super.setMuted(e),this.attachedElements.forEach(A=>{e?Dt(this._mediaStreamTrack,A):Lt(this._mediaStreamTrack,A)})}attach(e){if(e?super.attach(e):e=super.attach(),this.adaptiveStreamSettings&&this.elementInfos.find(A=>A.element===e)===void 0){const A=new Gp(e);this.observeElementInfo(A)}return e}observeElementInfo(e){this.adaptiveStreamSettings&&this.elementInfos.find(A=>A===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 A=this.elementInfos.filter(t=>t===e);for(const t of A)t.stopObserving();this.elementInfos=this.elementInfos.filter(t=>t!==e),this.updateVisibility(),this.debouncedHandleResize()}detach(e){let A=[];if(e)return this.stopObservingElement(e),super.detach(e);A=super.detach();for(const t of A)this.stopObservingElement(t);return A}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 A,t="",i=new Map;return e.forEach(r=>{r.type==="inbound-rtp"?(t=r.codecId,A={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"&&i.set(r.id,r)}),A&&t!==""&&i.get(t)&&(A.mimeType=i.get(t).mimeType),A})}stopObservingElement(e){const A=this.elementInfos.filter(t=>t.element===e);for(const t of A)this.stopObservingElementInfo(t)}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(){var e,A;const t=this.elementInfos.reduce((o,a)=>Math.max(o,a.visibilityChangedAt||0),0),i=!((A=(e=this.adaptiveStreamSettings)===null||e===void 0?void 0:e.pauseVideoInBackground)!==null&&A!==void 0)||A?this.isInBackground:!1,r=this.elementInfos.some(o=>o.pictureInPicture),s=this.elementInfos.some(o=>o.visible)&&!i||r;if(this.lastVisible!==s){if(!s&&Date.now()-t<Ys){ve.setTimeout(()=>{this.updateVisibility()},Ys);return}this.lastVisible=s,this.emit(k.VisibilityChanged,s,this)}}updateDimensions(){var e,A;let t=0,i=0;const r=this.getPixelDensity();for(const s of this.elementInfos){const o=s.width()*r,a=s.height()*r;o+a>t+i&&(t=o,i=a)}((e=this.lastDimensions)===null||e===void 0?void 0:e.width)===t&&((A=this.lastDimensions)===null||A===void 0?void 0:A.height)===i||(this.lastDimensions={width:t,height:i},this.emit(k.VideoDimensionsChanged,this.lastDimensions,this))}getPixelDensity(){var e;const A=(e=this.adaptiveStreamSettings)===null||e===void 0?void 0:e.pixelDensity;return A==="screen"?pl():A||(pl()>2?2:1)}}class Gp{get visible(){return this.isPiP||this.isIntersecting}get pictureInPicture(){return this.isPiP}constructor(e,A){this.onVisibilityChanged=t=>{var i;const{target:r,isIntersecting:s}=t;r===this.element&&(this.isIntersecting=s,this.isPiP=mn(this.element),this.visibilityChangedAt=Date.now(),(i=this.handleVisibilityChanged)===null||i===void 0||i.call(this))},this.onEnterPiP=()=>{var t,i,r;(i=(t=window.documentPictureInPicture)===null||t===void 0?void 0:t.window)===null||i===void 0||i.addEventListener("pagehide",this.onLeavePiP),this.isPiP=mn(this.element),(r=this.handleVisibilityChanged)===null||r===void 0||r.call(this)},this.onLeavePiP=()=>{var t;this.isPiP=mn(this.element),(t=this.handleVisibilityChanged)===null||t===void 0||t.call(this)},this.element=e,this.isIntersecting=A??qs(e),this.isPiP=Re()&&mn(e),this.visibilityChangedAt=0}width(){return this.element.clientWidth}height(){return this.element.clientHeight}observe(){var e,A,t;this.isIntersecting=qs(this.element),this.isPiP=mn(this.element),this.element.handleResize=()=>{var i;(i=this.handleResize)===null||i===void 0||i.call(this)},this.element.handleVisibilityChanged=this.onVisibilityChanged,Bl().observe(this.element),ml().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),(t=(A=window.documentPictureInPicture)===null||A===void 0?void 0:A.window)===null||t===void 0||t.addEventListener("pagehide",this.onLeavePiP)}stopObserving(){var e,A,t,i,r;(e=Bl())===null||e===void 0||e.unobserve(this.element),(A=ml())===null||A===void 0||A.unobserve(this.element),this.element.removeEventListener("enterpictureinpicture",this.onEnterPiP),this.element.removeEventListener("leavepictureinpicture",this.onLeavePiP),(t=window.documentPictureInPicture)===null||t===void 0||t.removeEventListener("enter",this.onEnterPiP),(r=(i=window.documentPictureInPicture)===null||i===void 0?void 0:i.window)===null||r===void 0||r.removeEventListener("pagehide",this.onLeavePiP)}}function mn(n){var e,A;return document.pictureInPictureElement===n?!0:!((e=window.documentPictureInPicture)===null||e===void 0)&&e.window?qs(n,(A=window.documentPictureInPicture)===null||A===void 0?void 0:A.window):!1}function qs(n,e){const A=e||window;let t=n.offsetTop,i=n.offsetLeft;const r=n.offsetWidth,s=n.offsetHeight,{hidden:o}=n,{display:a}=getComputedStyle(n);for(;n.offsetParent;)n=n.offsetParent,t+=n.offsetTop,i+=n.offsetLeft;return t<A.pageYOffset+A.innerHeight&&i<A.pageXOffset+A.innerWidth&&t+s>A.pageYOffset&&i+r>A.pageXOffset&&!o&&a!=="none"}class vA extends sA.EventEmitter{constructor(e,A,t,i){var r;super(),this.metadataMuted=!1,this.encryption=He.NONE,this.log=V,this.handleMuted=()=>{this.emit(k.Muted)},this.handleUnmuted=()=>{this.emit(k.Unmuted)},this.log=pA((r=i==null?void 0:i.loggerName)!==null&&r!==void 0?r:Ye.Publication),this.loggerContextCb=this.loggerContextCb,this.setMaxListeners(100),this.kind=e,this.trackSid=A,this.trackName=t,this.source=Q.Source.Unknown}setTrack(e){this.track&&(this.track.off(k.Muted,this.handleMuted),this.track.off(k.Unmuted,this.handleUnmuted)),this.track=e,e&&(e.on(k.Muted,this.handleMuted),e.on(k.Unmuted,this.handleUnmuted))}get logContext(){var e;return Object.assign(Object.assign({},(e=this.loggerContextCb)===null||e===void 0?void 0:e.call(this)),X(this))}get isMuted(){return this.metadataMuted}get isEnabled(){return!0}get isSubscribed(){return this.track!==void 0}get isEncrypted(){return this.encryption!==He.NONE}get audioTrack(){if(BA(this.track))return this.track}get videoTrack(){if(Ot(this.track))return this.track}updateInfo(e){this.trackSid=e.sid,this.trackName=e.name,this.source=Q.sourceFromProto(e.source),this.mimeType=e.mimeType,this.kind===Q.Kind.Video&&e.width>0&&(this.dimensions={width:e.width,height:e.height},this.simulcasted=e.simulcast),this.encryption=e.encryption,this.trackInfo=e,this.log.debug("update publication info",Object.assign(Object.assign({},this.logContext),{info:e}))}}(function(n){(function(e){e.Desired="desired",e.Subscribed="subscribed",e.Unsubscribed="unsubscribed"})(n.SubscriptionStatus||(n.SubscriptionStatus={})),function(e){e.Allowed="allowed",e.NotAllowed="not_allowed"}(n.PermissionStatus||(n.PermissionStatus={}))})(vA||(vA={}));class Zs extends vA{get isUpstreamPaused(){var e;return(e=this.track)===null||e===void 0?void 0:e.isUpstreamPaused}constructor(e,A,t,i){super(e,A.sid,A.name,i),this.track=void 0,this.handleTrackEnded=()=>{this.emit(k.Ended)},this.updateInfo(A),this.setTrack(t)}setTrack(e){this.track&&this.track.off(k.Ended,this.handleTrackEnded),super.setTrack(e),e&&e.on(k.Ended,this.handleTrackEnded)}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(BA(this.track)){const A=this.track.getSourceTrackSettings(),t=new Set;return A.autoGainControl&&t.add(Xe.TF_AUTO_GAIN_CONTROL),A.echoCancellation&&t.add(Xe.TF_ECHO_CANCELLATION),A.noiseSuppression&&t.add(Xe.TF_NOISE_SUPPRESSION),A.channelCount&&A.channelCount>1&&t.add(Xe.TF_STEREO),!((e=this.options)===null||e===void 0)&&e.dtx||t.add(Xe.TF_NO_DTX),this.track.enhancedNoiseCancellation&&t.add(Xe.TF_ENHANCED_NOISE_CANCELLATION),Array.from(t.values())}else return[]}}function ki(n,e){return p(this,void 0,void 0,function*(){n??(n={});let A=!1;const{audioProcessor:t,videoProcessor:i,optionsWithoutProcessor:r}=Ql(n);let s=r.audio,o=r.video;if(t&&typeof r.audio=="object"&&(r.audio.processor=t),i&&typeof r.video=="object"&&(r.video.processor=i),n.audio&&typeof r.audio=="object"&&typeof r.audio.deviceId=="string"){const u=r.audio.deviceId;r.audio.deviceId={exact:u},A=!0,s=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},A=!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 a=wl(r,Ll,Dl),c=xs(a),l=navigator.mediaDevices.getUserMedia(c);r.audio&&(me.userMediaPromiseMap.set("audioinput",l),l.catch(()=>me.userMediaPromiseMap.delete("audioinput"))),r.video&&(me.userMediaPromiseMap.set("videoinput",l),l.catch(()=>me.userMediaPromiseMap.delete("videoinput")));try{const u=yield l;return yield Promise.all(u.getTracks().map(d=>p(this,void 0,void 0,function*(){const h=d.kind==="audio";let f=h?a.audio:a.video;(typeof f=="boolean"||!f)&&(f={});let g;const m=h?c.audio:c.video;typeof m!="boolean"&&(g=m);const C=d.getSettings().deviceId;g!=null&&g.deviceId&&LA(g.deviceId)!==C?g.deviceId=C:g||(g={deviceId:C});const y=wp(d,g,e);return y.kind===Q.Kind.Video?y.source=Q.Source.Camera:y.kind===Q.Kind.Audio&&(y.source=Q.Source.Microphone),y.mediaStream=u,BA(y)&&t?yield y.setProcessor(t):Ot(y)&&i&&(yield y.setProcessor(i)),y})))}catch(u){if(!A)throw u;return ki(Object.assign(Object.assign({},n),{audio:s,video:o}),e)}})}function jp(n){return p(this,void 0,void 0,function*(){return(yield ki({audio:!1,video:n??!0}))[0]})}function Jp(n){return p(this,void 0,void 0,function*(){return(yield ki({audio:n??!0,video:!1}))[0]})}var HA;(function(n){n.Excellent="excellent",n.Good="good",n.Poor="poor",n.Lost="lost",n.Unknown="unknown"})(HA||(HA={}));function Wp(n){switch(n){case cn.EXCELLENT:return HA.Excellent;case cn.GOOD:return HA.Good;case cn.POOR:return HA.Poor;case cn.LOST:return HA.Lost;default:return HA.Unknown}}class Yl extends sA.EventEmitter{get logContext(){var e,A;return Object.assign({},(A=(e=this.loggerOptions)===null||e===void 0?void 0:e.loggerContextCb)===null||A===void 0?void 0:A.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===ai.AGENT}get isActive(){var e;return((e=this.participantInfo)===null||e===void 0?void 0:e.state)===It.ACTIVE}get kind(){return this._kind}get attributes(){return Object.freeze(Object.assign({},this._attributes))}constructor(e,A,t,i,r,s){let o=arguments.length>6&&arguments[6]!==void 0?arguments[6]:ai.STANDARD;var a;super(),this.audioLevel=0,this.isSpeaking=!1,this._connectionQuality=HA.Unknown,this.log=V,this.log=pA((a=s==null?void 0:s.loggerName)!==null&&a!==void 0?a:Ye.Participant),this.loggerOptions=s,this.setMaxListeners(100),this.sid=e,this.identity=A,this.name=t,this.metadata=i,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[,A]of this.trackPublications)if(A.source===e)return A}getTrackPublicationByName(e){for(const[,A]of this.trackPublications)if(A.trackName===e)return A}waitUntilActive(){return this.isActive?Promise.resolve():this.activeFuture?this.activeFuture.promise:(this.activeFuture=new Ts,this.once(x.Active,()=>{var e,A;(A=(e=this.activeFuture)===null||e===void 0?void 0:e.resolve)===null||A===void 0||A.call(e),this.activeFuture=void 0}),this.activeFuture.promise)}get connectionQuality(){return this._connectionQuality}get isCameraEnabled(){var e;const A=this.getTrackPublication(Q.Source.Camera);return!(!((e=A==null?void 0:A.isMuted)!==null&&e!==void 0)||e)}get isMicrophoneEnabled(){var e;const A=this.getTrackPublication(Q.Source.Microphone);return!(!((e=A==null?void 0:A.isMuted)!==null&&e!==void 0)||e)}get isScreenShareEnabled(){return!!this.getTrackPublication(Q.Source.ScreenShare)}get isLocal(){return!1}get joinedAt(){return this.participantInfo?new Date(Number.parseInt(this.participantInfo.joinedAt.toString())*1e3):new Date}updateInfo(e){var A;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===It.ACTIVE&&((A=this.participantInfo)===null||A===void 0?void 0:A.state)!==It.ACTIVE&&this.emit(x.Active),e.permission&&this.setPermissions(e.permission),this.participantInfo=e,!0)}_setMetadata(e){const A=this.metadata!==e,t=this.metadata;this.metadata=e,A&&this.emit(x.ParticipantMetadataChanged,t)}_setName(e){const A=this.name!==e;this.name=e,A&&this.emit(x.ParticipantNameChanged,e)}_setAttributes(e){const A=Ap(this.attributes,e);this._attributes=e,Object.keys(A).length>0&&this.emit(x.AttributesChanged,A)}setPermissions(e){var A,t,i,r,s,o;const a=this.permissions,c=e.canPublish!==((A=this.permissions)===null||A===void 0?void 0:A.canPublish)||e.canSubscribe!==((t=this.permissions)===null||t===void 0?void 0:t.canSubscribe)||e.canPublishData!==((i=this.permissions)===null||i===void 0?void 0:i.canPublishData)||e.hidden!==((r=this.permissions)===null||r===void 0?void 0:r.hidden)||e.recorder!==((s=this.permissions)===null||s===void 0?void 0:s.recorder)||e.canPublishSources.length!==this.permissions.canPublishSources.length||e.canPublishSources.some((l,u)=>{var d;return l!==((d=this.permissions)===null||d===void 0?void 0:d.canPublishSources[u])})||e.canSubscribeMetrics!==((o=this.permissions)===null||o===void 0?void 0:o.canSubscribeMetrics);return this.permissions=e,c&&this.emit(x.ParticipantPermissionsChanged,a),c}setIsSpeaking(e){e!==this.isSpeaking&&(this.isSpeaking=e,e&&(this.lastSpokeAt=new Date),this.emit(x.IsSpeakingChanged,e))}setConnectionQuality(e){const A=this._connectionQuality;this._connectionQuality=Wp(e),A!==this._connectionQuality&&this.emit(x.ConnectionQualityChanged,this._connectionQuality)}setDisconnected(){var e,A;this.activeFuture&&((A=(e=this.activeFuture).reject)===null||A===void 0||A.call(e,new Error("Participant disconnected")),this.activeFuture=void 0)}setAudioContext(e){this.audioContext=e,this.audioTrackPublications.forEach(A=>BA(A.track)&&A.track.setAudioContext(e))}addTrackPublication(e){e.on(k.Muted,()=>{this.emit(x.TrackMuted,e)}),e.on(k.Unmuted,()=>{this.emit(x.TrackUnmuted,e)});const A=e;switch(A.track&&(A.track.sid=e.trackSid),this.trackPublications.set(e.trackSid,e),e.kind){case Q.Kind.Audio:this.audioTrackPublications.set(e.trackSid,e);break;case Q.Kind.Video:this.videoTrackPublications.set(e.trackSid,e);break}}}function Xp(n){var e,A,t;if(!n.participantSid&&!n.participantIdentity)throw new Error("Invalid track permission, must provide at least one of participantIdentity and participantSid");return new fc({participantIdentity:(e=n.participantIdentity)!==null&&e!==void 0?e:"",participantSid:(A=n.participantSid)!==null&&A!==void 0?A:"",allTracks:(t=n.allowAll)!==null&&t!==void 0?t:!1,trackSids:n.allowedTrackSids||[]})}const ql=15e3;class $p extends Yl{constructor(e,A,t,i,r){super(e,A,void 0,void 0,void 0,{loggerName:i.loggerName,loggerContextCb:()=>this.engine.logContext}),this.pendingPublishing=new Set,this.pendingPublishPromises=new Map,this.participantTrackPermissions=[],this.allParticipantsAllowedToSubscribe=!0,this.encryptionType=He.NONE,this.enabledPublishVideoCodecs=[],this.pendingAcks=new Map,this.pendingResponses=new Map,this.handleReconnecting=()=>{this.reconnectFuture||(this.reconnectFuture=new Ts)},this.handleReconnected=()=>{var s,o;(o=(s=this.reconnectFuture)===null||s===void 0?void 0:s.resolve)===null||o===void 0||o.call(s),this.reconnectFuture=void 0,this.updateTrackSubscriptionPermissions()},this.handleDisconnected=()=>{var s,o;this.reconnectFuture&&(this.reconnectFuture.promise.catch(a=>this.log.warn(a.message,this.logContext)),(o=(s=this.reconnectFuture)===null||s===void 0?void 0:s.reject)===null||o===void 0||o.call(s,"Got disconnected during reconnection attempt"),this.reconnectFuture=void 0)},this.handleSignalRequestResponse=s=>{const{requestId:o,reason:a,message:c}=s,l=this.pendingSignalRequests.get(o);l&&(a!==ts.OK&&l.reject(new cl(c,a)),this.pendingSignalRequests.delete(o))},this.handleDataPacket=s=>{switch(s.value.case){case"rpcResponse":let o=s.value.value,a=null,c=null;o.value.case==="payload"?a=o.value.value:o.value.case==="error"&&(c=oe.fromProto(o.value.value)),this.handleIncomingRpcResponse(o.requestId,a,c);break;case"rpcAck":let l=s.value.value;this.handleIncomingRpcAck(l.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(s=>Xp(s)))},this.onTrackUnmuted=s=>{this.onTrackMuted(s,s.isUpstreamPaused)},this.onTrackMuted=(s,o)=>{if(o===void 0&&(o=!0),!s.sid){this.log.error("could not update mute status for unpublished track",Object.assign(Object.assign({},this.logContext),X(s)));return}this.engine.updateMuteStatus(s.sid,o)},this.onTrackUpstreamPaused=s=>{this.log.debug("upstream paused",Object.assign(Object.assign({},this.logContext),X(s))),this.onTrackMuted(s,!0)},this.onTrackUpstreamResumed=s=>{this.log.debug("upstream resumed",Object.assign(Object.assign({},this.logContext),X(s))),this.onTrackMuted(s,s.isMuted)},this.onTrackFeatureUpdate=s=>{const o=this.audioTrackPublications.get(s.sid);if(!o){this.log.warn("Could not update local audio track settings, missing publication for track ".concat(s.sid),this.logContext);return}this.engine.client.sendUpdateLocalAudioTrack(o.trackSid,o.getTrackFeatures())},this.handleSubscribedQualityUpdate=s=>p(this,void 0,void 0,function*(){var o,a,c,l,u,d;if(!(!((u=this.roomOptions)===null||u===void 0)&&u.dynacast))return;const h=this.videoTrackPublications.get(s.trackSid);if(!h){this.log.warn("received subscribed quality update for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:s.trackSid}));return}if(s.subscribedCodecs.length>0){if(!h.videoTrack)return;const C=yield h.videoTrack.setPublishingCodecs(s.subscribedCodecs);try{for(var f=!0,g=kA(C),m;m=yield g.next(),o=m.done,!o;f=!0){l=m.value,f=!1;const y=l;xg(y)&&(this.log.debug("publish ".concat(y," for ").concat(h.videoTrack.sid),Object.assign(Object.assign({},this.logContext),X(h))),yield this.publishAdditionalCodecForTrack(h.videoTrack,y,h.options))}}catch(y){a={error:y}}finally{try{!f&&!o&&(c=g.return)&&(yield c.call(g))}finally{if(a)throw a.error}}}else s.subscribedQualities.length>0&&(yield(d=h.videoTrack)===null||d===void 0?void 0:d.setPublishingLayers(s.subscribedQualities))}),this.handleLocalTrackUnpublished=s=>{const o=this.trackPublications.get(s.trackSid);if(!o){this.log.warn("received unpublished event for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:s.trackSid}));return}this.unpublishTrack(o.track)},this.handleTrackEnded=s=>p(this,void 0,void 0,function*(){if(s.source===Q.Source.ScreenShare||s.source===Q.Source.ScreenShareAudio)this.log.debug("unpublishing local track due to TrackEnded",Object.assign(Object.assign({},this.logContext),X(s))),this.unpublishTrack(s);else if(s.isUserProvided)yield s.mute();else if(ut(s)||DA(s))try{if(Re())try{const o=yield navigator==null?void 0:navigator.permissions.query({name:s.source===Q.Source.Camera?"camera":"microphone"});if(o&&o.state==="denied")throw this.log.warn("user has revoked access to ".concat(s.source),Object.assign(Object.assign({},this.logContext),X(s))),o.onchange=()=>{o.state!=="denied"&&(s.isMuted||s.restartTrack(),o.onchange=null)},new Error("GetUserMedia Permission denied")}catch{}s.isMuted||(this.log.debug("track ended, attempting to use a different device",Object.assign(Object.assign({},this.logContext),X(s))),ut(s)?yield s.restartTrack({deviceId:"default"}):yield s.restartTrack())}catch{this.log.warn("could not restart track, muting instead",Object.assign(Object.assign({},this.logContext),X(s))),yield s.mute()}}),this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this.engine=t,this.roomOptions=i,this.setupEngine(t),this.activeDeviceMap=new Map([["audioinput","default"],["videoinput","default"],["audiooutput","default"]]),this.pendingSignalRequests=new Map,this.rpcHandlers=r}get lastCameraError(){return this.cameraError}get lastMicrophoneError(){return this.microphoneError}get isE2EEEnabled(){return this.encryptionType!==He.NONE}getTrackPublication(e){const A=super.getTrackPublication(e);if(A)return A}getTrackPublicationByName(e){const A=super.getTrackPublicationByName(e);if(A)return A}setupEngine(e){this.engine=e,this.engine.on(I.RemoteMute,(A,t)=>{const i=this.trackPublications.get(A);!i||!i.track||(t?i.mute():i.unmute())}),this.engine.on(I.Connected,this.handleReconnected).on(I.SignalRestarted,this.handleReconnected).on(I.SignalResumed,this.handleReconnected).on(I.Restarting,this.handleReconnecting).on(I.Resuming,this.handleReconnecting).on(I.LocalTrackUnpublished,this.handleLocalTrackUnpublished).on(I.SubscribedQualityUpdate,this.handleSubscribedQualityUpdate).on(I.Disconnected,this.handleDisconnected).on(I.SignalRequestResponse,this.handleSignalRequestResponse).on(I.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(A){var t=this;let{metadata:i,name:r,attributes:s}=A;return function*(){return new Promise((o,a)=>p(t,void 0,void 0,function*(){var c,l;try{let u=!1;const d=yield this.engine.client.sendUpdateLocalMetadata((c=i??this.metadata)!==null&&c!==void 0?c:"",(l=r??this.name)!==null&&l!==void 0?l:"",s),h=performance.now();for(this.pendingSignalRequests.set(d,{resolve:o,reject:f=>{a(f),u=!0},values:{name:r,metadata:i,attributes:s}});performance.now()-h<5e3&&!u;){if((!r||this.name===r)&&(!i||this.metadata===i)&&(!s||Object.entries(s).every(f=>{let[g,m]=f;return this.attributes[g]===m||m===""&&!this.attributes[g]}))){this.pendingSignalRequests.delete(d),o();return}yield Ie(50)}a(new cl("Request to update local metadata timed out","TimeoutError"))}catch(u){u instanceof Error&&a(u)}}))}()})}setCameraEnabled(e,A,t){return this.setTrackEnabled(Q.Source.Camera,e,A,t)}setMicrophoneEnabled(e,A,t){return this.setTrackEnabled(Q.Source.Microphone,e,A,t)}setScreenShareEnabled(e,A,t){return this.setTrackEnabled(Q.Source.ScreenShare,e,A,t)}setPermissions(e){const A=this.permissions,t=super.setPermissions(e);return t&&A&&this.emit(x.ParticipantPermissionsChanged,A),t}setE2EEEnabled(e){return p(this,void 0,void 0,function*(){this.encryptionType=e?He.GCM:He.NONE,yield this.republishAllTracks(void 0,!1)})}setTrackEnabled(e,A,t,i){return p(this,void 0,void 0,function*(){var r,s;this.log.debug("setTrackEnabled",Object.assign(Object.assign({},this.logContext),{source:e,enabled:A})),this.republishPromise&&(yield this.republishPromise);let o=this.getTrackPublication(e);if(A)if(o)yield o.unmute();else{let a;if(this.pendingPublishing.has(e)){const c=yield this.waitForPendingPublicationOfSource(e);return c||this.log.info("waiting for pending publication promise timed out",Object.assign(Object.assign({},this.logContext),{source:e})),yield c==null?void 0:c.unmute(),c}this.pendingPublishing.add(e);try{switch(e){case Q.Source.Camera:a=yield this.createTracks({video:(r=t)!==null&&r!==void 0?r:!0});break;case Q.Source.Microphone:a=yield this.createTracks({audio:(s=t)!==null&&s!==void 0?s:!0});break;case Q.Source.ScreenShare:a=yield this.createScreenTracks(Object.assign({},t));break;default:throw new mA(e)}}catch(c){throw a==null||a.forEach(l=>{l.stop()}),c instanceof Error&&this.emit(x.MediaDevicesError,c),this.pendingPublishing.delete(e),c}try{const c=[];for(const u of a)this.log.info("publishing track",Object.assign(Object.assign({},this.logContext),X(u))),c.push(this.publishTrack(u,i));[o]=yield Promise.all(c)}catch(c){throw a==null||a.forEach(l=>{l.stop()}),c}finally{this.pendingPublishing.delete(e)}}else if(!(o!=null&&o.track)&&this.pendingPublishing.has(e)&&(o=yield this.waitForPendingPublicationOfSource(e),o||this.log.info("waiting for pending publication promise timed out",Object.assign(Object.assign({},this.logContext),{source:e}))),o&&o.track)if(e===Q.Source.ScreenShare){o=yield this.unpublishTrack(o.track);const a=this.getTrackPublication(Q.Source.ScreenShareAudio);a&&a.track&&this.unpublishTrack(a.track)}else yield o.mute();return o})}enableCameraAndMicrophone(){return p(this,void 0,void 0,function*(){if(!(this.pendingPublishing.has(Q.Source.Camera)||this.pendingPublishing.has(Q.Source.Microphone))){this.pendingPublishing.add(Q.Source.Camera),this.pendingPublishing.add(Q.Source.Microphone);try{const e=yield this.createTracks({audio:!0,video:!0});yield Promise.all(e.map(A=>this.publishTrack(A)))}finally{this.pendingPublishing.delete(Q.Source.Camera),this.pendingPublishing.delete(Q.Source.Microphone)}}})}createTracks(e){return p(this,void 0,void 0,function*(){var A,t;e??(e={});const i=wl(e,(A=this.roomOptions)===null||A===void 0?void 0:A.audioCaptureDefaults,(t=this.roomOptions)===null||t===void 0?void 0:t.videoCaptureDefaults);try{return(yield ki(i,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext})).map(o=>(BA(o)&&(this.microphoneError=void 0,o.setAudioContext(this.audioContext),o.source=Q.Source.Microphone,this.emit(x.AudioStreamAcquired)),Ot(o)&&(this.cameraError=void 0,o.source=Q.Source.Camera),o))}catch(r){throw r instanceof Error&&(e.audio&&(this.microphoneError=r),e.video&&(this.cameraError=r)),r}})}createScreenTracks(e){return p(this,void 0,void 0,function*(){if(e===void 0&&(e={}),navigator.mediaDevices.getDisplayMedia===void 0)throw new hs("getDisplayMedia not supported");e.resolution===void 0&&!Og()&&(e.resolution=Cs.h1080fps30.resolution);const A=Zg(e),t=yield navigator.mediaDevices.getDisplayMedia(A),i=t.getVideoTracks();if(i.length===0)throw new mA("no video track found");const r=new Fi(i[0],void 0,!1,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});r.source=Q.Source.ScreenShare,e.contentHint&&(r.mediaStreamTrack.contentHint=e.contentHint);const s=[r];if(t.getAudioTracks().length>0){this.emit(x.AudioStreamAcquired);const o=new Si(t.getAudioTracks()[0],void 0,!1,this.audioContext,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});o.source=Q.Source.ScreenShareAudio,s.push(o)}return s})}publishTrack(e,A){return p(this,void 0,void 0,function*(){return this.publishOrRepublishTrack(e,A)})}publishOrRepublishTrack(e,A){return p(this,arguments,void 0,function(t,i){var r=this;let s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1;return function*(){var o,a,c,l;ut(t)&&t.setAudioContext(r.audioContext),yield(o=r.reconnectFuture)===null||o===void 0?void 0:o.promise,r.republishPromise&&!s&&(yield r.republishPromise),Ht(t)&&r.pendingPublishPromises.has(t)&&(yield r.pendingPublishPromises.get(t));let u;if(t instanceof MediaStreamTrack)u=t.getConstraints();else{u=t.constraints;let C;switch(t.source){case Q.Source.Microphone:C="audioinput";break;case Q.Source.Camera:C="videoinput"}C&&r.activeDeviceMap.has(C)&&(u=Object.assign(Object.assign({},u),{deviceId:r.activeDeviceMap.get(C)}))}if(t instanceof MediaStreamTrack)switch(t.kind){case"audio":t=new Si(t,u,!0,r.audioContext,{loggerName:r.roomOptions.loggerName,loggerContextCb:()=>r.logContext});break;case"video":t=new Fi(t,u,!0,{loggerName:r.roomOptions.loggerName,loggerContextCb:()=>r.logContext});break;default:throw new mA("unsupported MediaStreamTrack kind ".concat(t.kind))}else t.updateLoggerOptions({loggerName:r.roomOptions.loggerName,loggerContextCb:()=>r.logContext});let d;if(r.trackPublications.forEach(C=>{C.track&&C.track===t&&(d=C)}),d)return r.log.warn("track has already been published, skipping",Object.assign(Object.assign({},r.logContext),X(d))),d;const h="channelCount"in t.mediaStreamTrack.getSettings()&&t.mediaStreamTrack.getSettings().channelCount===2||t.mediaStreamTrack.getConstraints().channelCount===2,f=(a=i==null?void 0:i.forceStereo)!==null&&a!==void 0?a:h;f&&(i||(i={}),i.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),X(t))),i.red===void 0&&r.log.info("Opus RED will be disabled for stereo tracks by default. Enable them explicitly to make it work."),(c=i.dtx)!==null&&c!==void 0||(i.dtx=!1),(l=i.red)!==null&&l!==void 0||(i.red=!1));const g=Object.assign(Object.assign({},r.roomOptions.publishDefaults),i);!Mg()&&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)),g.simulcast=!1),g.source&&(t.source=g.source);const m=new Promise((C,y)=>p(r,void 0,void 0,function*(){try{if(this.engine.client.currentState!==Ae.CONNECTED){this.log.debug("deferring track publication until signal is connected",Object.assign(Object.assign({},this.logContext),{track:X(t)}));const U=()=>p(this,void 0,void 0,function*(){try{const v=yield this.publish(t,g,f);C(v)}catch(v){y(v)}});setTimeout(()=>{this.engine.off(I.SignalConnected,U),y(new gs("publishing rejected as engine not connected within timeout",408))},15e3),this.engine.once(I.SignalConnected,U),this.engine.on(I.Closing,()=>{this.engine.off(I.SignalConnected,U),y(new gs("publishing rejected as engine closed",499))})}else try{const U=yield this.publish(t,g,f);C(U)}catch(U){y(U)}}catch(U){y(U)}}));r.pendingPublishPromises.set(t,m);try{return yield m}catch(C){throw C}finally{r.pendingPublishPromises.delete(t)}}()})}hasPermissionsToPublish(e){if(!this.permissions)return this.log.warn("no permissions present for publishing track",Object.assign(Object.assign({},this.logContext),X(e))),!1;const{canPublish:A,canPublishSources:t}=this.permissions;return A&&(t.length===0||t.map(i=>tp(i)).includes(e.source))?!0:(this.log.warn("insufficient permissions to publish",Object.assign(Object.assign({},this.logContext),X(e))),!1)}publish(e,A,t){return p(this,void 0,void 0,function*(){var i,r,s,o,a,c,l,u,d,h;if(!this.hasPermissionsToPublish(e))throw new gs("failed to publish track, insufficient permissions",403);Array.from(this.trackPublications.values()).find(B=>Ht(e)&&B.source===e.source)&&e.source!==Q.Source.Unknown&&this.log.info("publishing a second track with the same source: ".concat(e.source),Object.assign(Object.assign({},this.logContext),X(e))),A.stopMicTrackOnMute&&BA(e)&&(e.stopOnMute=!0),e.source===Q.Source.ScreenShare&&_t()&&(A.simulcast=!1),A.videoCodec==="av1"&&!Dg()&&(A.videoCodec=void 0),A.videoCodec==="vp9"&&!_g()&&(A.videoCodec=void 0),A.videoCodec===void 0&&(A.videoCodec=Ns),this.enabledPublishVideoCodecs.length>0&&(this.enabledPublishVideoCodecs.some(B=>A.videoCodec===Ui(B.mime))||(A.videoCodec=Ui(this.enabledPublishVideoCodecs[0].mime)));const g=A.videoCodec;e.on(k.Muted,this.onTrackMuted),e.on(k.Unmuted,this.onTrackUnmuted),e.on(k.Ended,this.handleTrackEnded),e.on(k.UpstreamPaused,this.onTrackUpstreamPaused),e.on(k.UpstreamResumed,this.onTrackUpstreamResumed),e.on(k.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate);const m=new qr({cid:e.mediaStreamTrack.id,name:A.name,type:Q.kindToProto(e.kind),muted:e.isMuted,source:Q.sourceToProto(e.source),disableDtx:!(!((i=A.dtx)!==null&&i!==void 0)||i),encryption:this.encryptionType,stereo:t,disableRed:this.isE2EEEnabled||!(!((r=A.red)!==null&&r!==void 0)||r),stream:A==null?void 0:A.stream,backupCodecPolicy:A==null?void 0:A.backupCodecPolicy});let C;if(e.kind===Q.Kind.Video){let B={width:0,height:0};try{B=yield e.waitForDimensions()}catch{const S=(o=(s=this.roomOptions.videoCaptureDefaults)===null||s===void 0?void 0:s.resolution)!==null&&o!==void 0?o:hn.h720.resolution;B={width:S.width,height:S.height},this.log.error("could not determine track dimensions, using defaults",Object.assign(Object.assign(Object.assign({},this.logContext),X(e)),{dims:B}))}m.width=B.width,m.height=B.height,DA(e)&&(fn(g)&&(e.source===Q.Source.ScreenShare&&(A.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),X(e))))),A.scalabilityMode=(a=A.scalabilityMode)!==null&&a!==void 0?a:"L3T3_KEY"),m.simulcastCodecs=[new Yr({codec:g,cid:e.mediaStreamTrack.id})],A.backupCodec===!0&&(A.backupCodec={codec:Ns}),A.backupCodec&&g!==A.backupCodec.codec&&m.encryption===He.NONE&&(this.roomOptions.dynacast||(this.roomOptions.dynacast=!0),m.simulcastCodecs.push(new Yr({codec:A.backupCodec.codec,cid:""})))),C=Js(e.source===Q.Source.ScreenShare,m.width,m.height,A),m.layers=Gl(m.width,m.height,C,fn(A.videoCodec))}else e.kind===Q.Kind.Audio&&(C=[{maxBitrate:(c=A.audioPreset)===null||c===void 0?void 0:c.maxBitrate,priority:(u=(l=A.audioPreset)===null||l===void 0?void 0:l.priority)!==null&&u!==void 0?u:"high",networkPriority:(h=(d=A.audioPreset)===null||d===void 0?void 0:d.priority)!==null&&h!==void 0?h:"high"}]);if(!this.engine||this.engine.isClosed)throw new ge("cannot publish track when not connected");const y=()=>p(this,void 0,void 0,function*(){var B,w,S;if(!this.engine.pcManager)throw new ge("pcManager is not ready");if(e.sender=yield this.engine.createSender(e,A,C),DA(e)&&((B=A.degradationPreference)!==null&&B!==void 0||(A.degradationPreference=Ip(e)),e.setDegradationPreference(A.degradationPreference)),C)if(_t()&&e.kind===Q.Kind.Audio){let F;for(const R of this.engine.pcManager.publisher.getTransceivers())if(R.sender===e.sender){F=R;break}F&&this.engine.pcManager.publisher.setTrackCodecBitrate({transceiver:F,codec:"opus",maxbr:!((w=C[0])===null||w===void 0)&&w.maxBitrate?C[0].maxBitrate/1e3:0})}else e.codec&&fn(e.codec)&&(!((S=C[0])===null||S===void 0)&&S.maxBitrate)&&this.engine.pcManager.publisher.setTrackCodecBitrate({cid:m.cid,codec:e.codec,maxbr:C[0].maxBitrate/1e3});yield this.engine.negotiate()});let U;if(this.enabledPublishVideoCodecs.length>0)U=(yield Promise.all([this.engine.addTrack(m),y()]))[0];else{U=yield this.engine.addTrack(m);let B;if(U.codecs.forEach(w=>{B===void 0&&(B=w.mimeType)}),B&&e.kind===Q.Kind.Video){const w=Ui(B);w!==g&&(this.log.debug("falling back to server selected codec",Object.assign(Object.assign(Object.assign({},this.logContext),X(e)),{codec:w})),A.videoCodec=w,C=Js(e.source===Q.Source.ScreenShare,m.width,m.height,A))}yield y()}const v=new Zs(e.kind,U,e,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});return v.options=A,e.sid=U.sid,this.log.debug("publishing ".concat(e.kind," with encodings"),Object.assign(Object.assign({},this.logContext),{encodings:C,trackInfo:U})),DA(e)?e.startMonitor(this.engine.client):ut(e)&&e.startMonitor(),this.addTrackPublication(v),this.emit(x.LocalTrackPublished,v),v})}get isLocal(){return!0}publishAdditionalCodecForTrack(e,A,t){return p(this,void 0,void 0,function*(){var i;if(this.encryptionType!==He.NONE)return;let r;if(this.trackPublications.forEach(h=>{h.track&&h.track===e&&(r=h)}),!r)throw new mA("track is not published");if(!DA(e))throw new mA("track is not a video track");const s=Object.assign(Object.assign({},(i=this.roomOptions)===null||i===void 0?void 0:i.publishDefaults),t),o=Tp(e,A,s);if(!o){this.log.info("backup codec has been disabled, ignoring request to add additional codec for track",Object.assign(Object.assign({},this.logContext),X(e)));return}const a=e.addSimulcastTrack(A,o);if(!a)return;const c=new qr({cid:a.mediaStreamTrack.id,type:Q.kindToProto(e.kind),muted:e.isMuted,source:Q.sourceToProto(e.source),sid:e.sid,simulcastCodecs:[{codec:s.videoCodec,cid:a.mediaStreamTrack.id}]});if(c.layers=Gl(c.width,c.height,o),!this.engine||this.engine.isClosed)throw new ge("cannot publish track when not connected");const l=()=>p(this,void 0,void 0,function*(){yield this.engine.createSimulcastSender(e,a,s,o),yield this.engine.negotiate()}),d=(yield Promise.all([this.engine.addTrack(c),l()]))[0];this.log.debug("published ".concat(A," for track ").concat(e.sid),Object.assign(Object.assign({},this.logContext),{encodings:o,trackInfo:d}))})}unpublishTrack(e,A){return p(this,void 0,void 0,function*(){var t,i;if(Ht(e)){const c=this.pendingPublishPromises.get(e);c&&(this.log.info("awaiting publish promise before attempting to unpublish",Object.assign(Object.assign({},this.logContext),X(e))),yield c)}const r=this.getPublicationForTrack(e),s=r?X(r):void 0;if(this.log.debug("unpublishing track",Object.assign(Object.assign({},this.logContext),s)),!r||!r.track){this.log.warn("track was not unpublished because no publication was found",Object.assign(Object.assign({},this.logContext),s));return}e=r.track,e.off(k.Muted,this.onTrackMuted),e.off(k.Unmuted,this.onTrackUnmuted),e.off(k.Ended,this.handleTrackEnded),e.off(k.UpstreamPaused,this.onTrackUpstreamPaused),e.off(k.UpstreamResumed,this.onTrackUpstreamResumed),e.off(k.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate),A===void 0&&(A=(i=(t=this.roomOptions)===null||t===void 0?void 0:t.stopLocalTrackOnUnpublish)!==null&&i!==void 0?i:!0),A?e.stop():e.stopMonitor();let o=!1;const a=e.sender;if(e.sender=void 0,this.engine.pcManager&&this.engine.pcManager.currentState<se.FAILED&&a)try{for(const c of this.engine.pcManager.publisher.getTransceivers())c.sender===a&&(c.direction="inactive",o=!0);if(this.engine.removeTrack(a)&&(o=!0),DA(e)){for(const[,c]of e.simulcastCodecs)c.sender&&(this.engine.removeTrack(c.sender)&&(o=!0),c.sender=void 0);e.simulcastCodecs.clear()}}catch(c){this.log.warn("failed to unpublish track",Object.assign(Object.assign(Object.assign({},this.logContext),s),{error:c}))}switch(this.trackPublications.delete(r.trackSid),r.kind){case Q.Kind.Audio:this.audioTrackPublications.delete(r.trackSid);break;case Q.Kind.Video:this.videoTrackPublications.delete(r.trackSid);break}return this.emit(x.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(t=>this.unpublishTrack(t)))).filter(t=>!!t)})}republishAllTracks(e){return p(this,arguments,void 0,function(A){var t=this;let i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){t.republishPromise&&(yield t.republishPromise),t.republishPromise=new Promise((r,s)=>p(t,void 0,void 0,function*(){try{const o=[];this.trackPublications.forEach(a=>{a.track&&(A&&(a.options=Object.assign(Object.assign({},a.options),A)),o.push(a))}),yield Promise.all(o.map(a=>p(this,void 0,void 0,function*(){const c=a.track;yield this.unpublishTrack(c,!1),i&&!c.isMuted&&c.source!==Q.Source.ScreenShare&&c.source!==Q.Source.ScreenShareAudio&&(ut(c)||DA(c))&&!c.isUserProvided&&(this.log.debug("restarting existing track",Object.assign(Object.assign({},this.logContext),{track:a.trackSid})),yield c.restartTrack()),yield this.publishOrRepublishTrack(c,a.options,!0)}))),r()}catch(o){s(o)}finally{this.republishPromise=void 0}})),yield t.republishPromise}()})}publishData(e){return p(this,arguments,void 0,function(A){var t=this;let i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return function*(){const r=i.reliable?J.RELIABLE:J.LOSSY,s=i.destinationIdentities,o=i.topic,a=new ke({kind:r,value:{case:"user",value:new Xa({participantIdentity:t.identity,payload:A,destinationIdentities:s,topic:o})}});yield t.engine.sendDataPacket(a,r)}()})}publishDtmf(e,A){return p(this,void 0,void 0,function*(){const t=new ke({kind:J.RELIABLE,value:{case:"sipDtmf",value:new $a({code:e,digit:A})}});yield this.engine.sendDataPacket(t,J.RELIABLE)})}sendChatMessage(e,A){return p(this,void 0,void 0,function*(){const t={id:crypto.randomUUID(),message:e,timestamp:Date.now(),attachedFiles:A==null?void 0:A.attachments},i=new ke({value:{case:"chatMessage",value:new Gr(Object.assign(Object.assign({},t),{timestamp:ne.parse(t.timestamp)}))}});return yield this.engine.sendDataPacket(i,J.RELIABLE),this.emit(x.ChatMessage,t),t})}editChatMessage(e,A){return p(this,void 0,void 0,function*(){const t=Object.assign(Object.assign({},A),{message:e,editTimestamp:Date.now()}),i=new ke({value:{case:"chatMessage",value:new Gr(Object.assign(Object.assign({},t),{timestamp:ne.parse(t.timestamp),editTimestamp:ne.parse(t.editTimestamp)}))}});return yield this.engine.sendDataPacket(i,J.RELIABLE),this.emit(x.ChatMessage,t),t})}sendText(e,A){return p(this,void 0,void 0,function*(){var t;const i=crypto.randomUUID(),s=new TextEncoder().encode(e).byteLength,o=(t=A==null?void 0:A.attachments)===null||t===void 0?void 0:t.map(()=>crypto.randomUUID()),a=new Array(o?o.length+1:1).fill(0),c=(u,d)=>{var h;a[d]=u;const f=a.reduce((g,m)=>g+m,0);(h=A==null?void 0:A.onProgress)===null||h===void 0||h.call(A,f)},l=yield this.streamText({streamId:i,totalSize:s,destinationIdentities:A==null?void 0:A.destinationIdentities,topic:A==null?void 0:A.topic,attachedStreamIds:o,attributes:A==null?void 0:A.attributes});return yield l.write(e),c(1,0),yield l.close(),A!=null&&A.attachments&&o&&(yield Promise.all(A.attachments.map((u,d)=>p(this,void 0,void 0,function*(){return this._sendFile(o[d],u,{topic:A.topic,mimeType:u.type,onProgress:h=>{c(h,d+1)}})})))),l.info})}streamText(e){return p(this,void 0,void 0,function*(){var A,t;const i=(A=e==null?void 0:e.streamId)!==null&&A!==void 0?A:crypto.randomUUID(),r={id:i,mimeType:"text/plain",timestamp:Date.now(),topic:(t=e==null?void 0:e.topic)!==null&&t!==void 0?t:"",size:e==null?void 0:e.totalSize,attributes:e==null?void 0:e.attributes},s=new Jr({streamId:i,mimeType:r.mimeType,topic:r.topic,timestamp:lt(r.timestamp),totalLength:lt(e==null?void 0:e.totalSize),attributes:r.attributes,contentHeader:{case:"textHeader",value:new sc({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"?jr.UPDATE:jr.CREATE})}}),o=e==null?void 0:e.destinationIdentities,a=new ke({destinationIdentities:o,value:{case:"streamHeader",value:s}});yield this.engine.sendDataPacket(a,J.RELIABLE);let c=0;const l=this,u=new WritableStream({write(f){return p(this,void 0,void 0,function*(){for(const g of Yg(f,ql)){yield l.engine.waitForBufferStatusLow(J.RELIABLE);const m=new Wr({content:g,streamId:i,chunkIndex:lt(c)}),C=new ke({destinationIdentities:o,value:{case:"streamChunk",value:m}});yield l.engine.sendDataPacket(C,J.RELIABLE),c+=1}})},close(){return p(this,void 0,void 0,function*(){const f=new Xr({streamId:i}),g=new ke({destinationIdentities:o,value:{case:"streamTrailer",value:f}});yield l.engine.sendDataPacket(g,J.RELIABLE)})},abort(f){console.log("Sink error:",f)}});let d=()=>p(this,void 0,void 0,function*(){yield h.close()});l.engine.once(I.Closing,d);const h=new Mp(u,r,()=>this.engine.off(I.Closing,d));return h})}sendFile(e,A){return p(this,void 0,void 0,function*(){const t=crypto.randomUUID();return yield this._sendFile(t,e,A),{id:t}})}_sendFile(e,A,t){return p(this,void 0,void 0,function*(){var i;const r=yield this.streamBytes({streamId:e,totalSize:A.size,name:A.name,mimeType:(i=t==null?void 0:t.mimeType)!==null&&i!==void 0?i:A.type,topic:t==null?void 0:t.topic,destinationIdentities:t==null?void 0:t.destinationIdentities}),s=A.stream().getReader();for(;;){const{done:o,value:a}=yield s.read();if(o)break;yield r.write(a)}return yield r.close(),r.info})}streamBytes(e){return p(this,void 0,void 0,function*(){var A,t,i,r,s;const o=(A=e==null?void 0:e.streamId)!==null&&A!==void 0?A:crypto.randomUUID(),a=e==null?void 0:e.destinationIdentities,c={id:o,mimeType:(t=e==null?void 0:e.mimeType)!==null&&t!==void 0?t:"application/octet-stream",topic:(i=e==null?void 0:e.topic)!==null&&i!==void 0?i:"",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"},l=new Jr({totalLength:lt((s=c.size)!==null&&s!==void 0?s:0),mimeType:c.mimeType,streamId:o,topic:c.topic,timestamp:lt(Date.now()),attributes:c.attributes,contentHeader:{case:"byteHeader",value:new oc({name:c.name})}}),u=new ke({destinationIdentities:a,value:{case:"streamHeader",value:l}});yield this.engine.sendDataPacket(u,J.RELIABLE);let d=0;const h=new Te,f=this.engine,g=this.log,m=new WritableStream({write(y){return p(this,void 0,void 0,function*(){const U=yield h.lock();let v=0;try{for(;v<y.byteLength;){const B=y.slice(v,v+ql);yield f.waitForBufferStatusLow(J.RELIABLE);const w=new ke({destinationIdentities:a,value:{case:"streamChunk",value:new Wr({content:B,streamId:o,chunkIndex:lt(d)})}});yield f.sendDataPacket(w,J.RELIABLE),d+=1,v+=B.byteLength}}finally{U()}})},close(){return p(this,void 0,void 0,function*(){const y=new Xr({streamId:o}),U=new ke({destinationIdentities:a,value:{case:"streamTrailer",value:y}});yield f.sendDataPacket(U,J.RELIABLE)})},abort(y){g.error("Sink error:",y)}});return new Np(m,c)})}performRpc(e){return p(this,arguments,void 0,function(A){var t=this;let{destinationIdentity:i,method:r,payload:s,responseTimeout:o=1e4}=A;return function*(){return new Promise((c,l)=>p(t,void 0,void 0,function*(){var u,d,h,f;if(Vs(s)>_l){l(oe.builtIn("REQUEST_PAYLOAD_TOO_LARGE"));return}if(!((d=(u=this.engine.latestJoinResponse)===null||u===void 0?void 0:u.serverInfo)===null||d===void 0)&&d.version&&ct((f=(h=this.engine.latestJoinResponse)===null||h===void 0?void 0:h.serverInfo)===null||f===void 0?void 0:f.version,"1.8.0")<0){l(oe.builtIn("UNSUPPORTED_SERVER"));return}const g=crypto.randomUUID();yield this.publishRpcRequest(i,g,r,s,o-2e3);const m=setTimeout(()=>{this.pendingAcks.delete(g),l(oe.builtIn("CONNECTION_TIMEOUT")),this.pendingResponses.delete(g),clearTimeout(C)},2e3);this.pendingAcks.set(g,{resolve:()=>{clearTimeout(m)},participantIdentity:i});const C=setTimeout(()=>{this.pendingResponses.delete(g),l(oe.builtIn("RESPONSE_TIMEOUT"))},o);this.pendingResponses.set(g,{resolve:(y,U)=>{clearTimeout(C),this.pendingAcks.has(g)&&(console.warn("RPC response received before ack",g),this.pendingAcks.delete(g),clearTimeout(m)),U?l(U):c(y??"")},participantIdentity:i})}))}()})}registerRpcMethod(e,A){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,A)}unregisterRpcMethod(e){this.rpcHandlers.delete(e)}setTrackSubscriptionPermissions(e){let A=arguments.length>1&&arguments[1]!==void 0?arguments[1]:[];this.participantTrackPermissions=A,this.allParticipantsAllowedToSubscribe=e,this.engine.client.isDisconnected||this.updateTrackSubscriptionPermissions()}handleIncomingRpcAck(e){const A=this.pendingAcks.get(e);A?(A.resolve(),this.pendingAcks.delete(e)):console.error("Ack received for unexpected RPC request",e)}handleIncomingRpcResponse(e,A,t){const i=this.pendingResponses.get(e);i?(i.resolve(A,t),this.pendingResponses.delete(e)):console.error("Response received for unexpected RPC request",e)}publishRpcRequest(e,A,t,i,r){return p(this,void 0,void 0,function*(){const s=new ke({destinationIdentities:[e],kind:J.RELIABLE,value:{case:"rpcRequest",value:new Ya({id:A,method:t,payload:i,responseTimeoutMs:r,version:1})}});yield this.engine.sendDataPacket(s,J.RELIABLE)})}handleParticipantDisconnected(e){for(const[A,{participantIdentity:t}]of this.pendingAcks)t===e&&this.pendingAcks.delete(A);for(const[A,{participantIdentity:t,resolve:i}]of this.pendingResponses)t===e&&(i(null,oe.builtIn("RECIPIENT_DISCONNECTED")),this.pendingResponses.delete(A))}setEnabledPublishCodecs(e){this.enabledPublishVideoCodecs=e.filter(A=>A.mime.split("/")[0].toLowerCase()==="video")}updateInfo(e){return super.updateInfo(e)?(e.tracks.forEach(A=>{var t,i;const r=this.trackPublications.get(A.sid);if(r){const s=r.isMuted||((i=(t=r.track)===null||t===void 0?void 0:t.isUpstreamPaused)!==null&&i!==void 0?i:!1);s!==A.muted&&(this.log.debug("updating server mute state after reconcile",Object.assign(Object.assign(Object.assign({},this.logContext),X(r)),{mutedOnServer:s})),this.engine.client.sendMuteTrack(A.sid,s))}}),!0):!1}getPublicationForTrack(e){let A;return this.trackPublications.forEach(t=>{const i=t.track;i&&(e instanceof MediaStreamTrack?(ut(i)||DA(i))&&i.mediaStreamTrack===e&&(A=t):e===i&&(A=t))}),A}waitForPendingPublicationOfSource(e){return p(this,void 0,void 0,function*(){const t=Date.now();for(;Date.now()<t+1e4;){const i=Array.from(this.pendingPublishPromises.entries()).find(r=>{let[s]=r;return s.source===e});if(i)return i[1];yield Ie(20)}})}}class Yp extends vA{constructor(e,A,t,i){super(e,A.sid,A.name,i),this.track=void 0,this.allowed=!0,this.disabled=!1,this.currentVideoQuality=Ne.HIGH,this.handleEnded=r=>{this.setTrack(void 0),this.emit(k.Ended,r)},this.handleVisibilityChange=r=>{this.log.debug("adaptivestream video visibility ".concat(this.trackSid,", visible=").concat(r),this.logContext),this.disabled=!r,this.emitTrackUpdate()},this.handleVideoDimensionsChange=r=>{this.log.debug("adaptivestream video dimensions ".concat(r.width,"x").concat(r.height),this.logContext),this.videoDimensions=r,this.emitTrackUpdate()},this.subscribed=t,this.updateInfo(A)}setSubscribed(e){const A=this.subscriptionStatus,t=this.permissionStatus;this.subscribed=e,e&&(this.allowed=!0);const i=new ci({trackSids:[this.trackSid],subscribe:this.subscribed,participantTracks:[new ec({participantSid:"",trackSids:[this.trackSid]})]});this.emit(k.UpdateSubscription,i),this.emitSubscriptionUpdateIfChanged(A),this.emitPermissionUpdateIfChanged(t)}get subscriptionStatus(){return this.subscribed===!1?vA.SubscriptionStatus.Unsubscribed:super.isSubscribed?vA.SubscriptionStatus.Subscribed:vA.SubscriptionStatus.Desired}get permissionStatus(){return this.allowed?vA.PermissionStatus.Allowed:vA.PermissionStatus.NotAllowed}get isSubscribed(){return this.subscribed===!1?!1:super.isSubscribed}get isDesired(){return this.subscribed!==!1}get isEnabled(){return!this.disabled}get isLocal(){return!1}setEnabled(e){!this.isManualOperationAllowed()||this.disabled===!e||(this.disabled=!e,this.emitTrackUpdate())}setVideoQuality(e){!this.isManualOperationAllowed()||this.currentVideoQuality===e||(this.currentVideoQuality=e,this.videoDimensions=void 0,this.emitTrackUpdate())}setVideoDimensions(e){var A,t;this.isManualOperationAllowed()&&(((A=this.videoDimensions)===null||A===void 0?void 0:A.width)===e.width&&((t=this.videoDimensions)===null||t===void 0?void 0:t.height)===e.height||(Is(this.track)&&(this.videoDimensions=e),this.currentVideoQuality=void 0,this.emitTrackUpdate()))}setVideoFPS(e){this.isManualOperationAllowed()&&Is(this.track)&&this.fps!==e&&(this.fps=e,this.emitTrackUpdate())}get videoQuality(){return this.currentVideoQuality}setTrack(e){const A=this.subscriptionStatus,t=this.permissionStatus,i=this.track;i!==e&&(i&&(i.off(k.VideoDimensionsChanged,this.handleVideoDimensionsChange),i.off(k.VisibilityChanged,this.handleVisibilityChange),i.off(k.Ended,this.handleEnded),i.detach(),i.stopMonitor(),this.emit(k.Unsubscribed,i)),super.setTrack(e),e&&(e.sid=this.trackSid,e.on(k.VideoDimensionsChanged,this.handleVideoDimensionsChange),e.on(k.VisibilityChanged,this.handleVisibilityChange),e.on(k.Ended,this.handleEnded),this.emit(k.Subscribed,e)),this.emitPermissionUpdateIfChanged(t),this.emitSubscriptionUpdateIfChanged(A))}setAllowed(e){const A=this.subscriptionStatus,t=this.permissionStatus;this.allowed=e,this.emitPermissionUpdateIfChanged(t),this.emitSubscriptionUpdateIfChanged(A)}setSubscriptionError(e){this.emit(k.SubscriptionFailed,e)}updateInfo(e){super.updateInfo(e);const A=this.metadataMuted;this.metadataMuted=e.muted,this.track?this.track.setMuted(e.muted):A!==e.muted&&this.emit(e.muted?k.Muted:k.Unmuted)}emitSubscriptionUpdateIfChanged(e){const A=this.subscriptionStatus;e!==A&&this.emit(k.SubscriptionStatusChanged,A,e)}emitPermissionUpdateIfChanged(e){this.permissionStatus!==e&&this.emit(k.SubscriptionPermissionChanged,this.permissionStatus,e)}isManualOperationAllowed(){return this.kind===Q.Kind.Video&&this.isAdaptiveStream?(this.log.warn("adaptive stream is enabled, cannot change video track settings",this.logContext),!1):this.isDesired?!0:(this.log.warn("cannot update track settings when not subscribed",this.logContext),!1)}get isAdaptiveStream(){return Is(this.track)&&this.track.isAdaptiveStream}emitTrackUpdate(){const e=new cc({trackSids:[this.trackSid],disabled:this.disabled,fps:this.fps});this.videoDimensions?(e.width=Math.ceil(this.videoDimensions.width),e.height=Math.ceil(this.videoDimensions.height)):this.currentVideoQuality!==void 0?e.quality=this.currentVideoQuality:e.quality=Ne.HIGH,this.emit(k.UpdateSettings,e)}}class Ii extends Yl{static fromParticipantInfo(e,A,t){return new Ii(e,A.sid,A.identity,A.name,A.metadata,A.attributes,t,A.kind)}get logContext(){return Object.assign(Object.assign({},super.logContext),{rpID:this.sid,remoteParticipant:this.identity})}constructor(e,A,t,i,r,s,o){let a=arguments.length>7&&arguments[7]!==void 0?arguments[7]:ai.STANDARD;super(A,t||"",i,r,s,o,a),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(k.UpdateSettings,A=>{this.log.debug("send update settings",Object.assign(Object.assign({},this.logContext),X(e))),this.signalClient.sendUpdateTrackSettings(A)}),e.on(k.UpdateSubscription,A=>{A.participantTracks.forEach(t=>{t.participantSid=this.sid}),this.signalClient.sendUpdateSubscription(A)}),e.on(k.SubscriptionPermissionChanged,A=>{this.emit(x.TrackSubscriptionPermissionChanged,e,A)}),e.on(k.SubscriptionStatusChanged,A=>{this.emit(x.TrackSubscriptionStatusChanged,e,A)}),e.on(k.Subscribed,A=>{this.emit(x.TrackSubscribed,A,e)}),e.on(k.Unsubscribed,A=>{this.emit(x.TrackUnsubscribed,A,e)}),e.on(k.SubscriptionFailed,A=>{this.emit(x.TrackSubscriptionFailed,e.trackSid,A)})}getTrackPublication(e){const A=super.getTrackPublication(e);if(A)return A}getTrackPublicationByName(e){const A=super.getTrackPublicationByName(e);if(A)return A}setVolume(e){let A=arguments.length>1&&arguments[1]!==void 0?arguments[1]:Q.Source.Microphone;this.volumeMap.set(A,e);const t=this.getTrackPublication(A);t&&t.track&&t.track.setVolume(e)}getVolume(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:Q.Source.Microphone;const A=this.getTrackPublication(e);return A&&A.track?A.track.getVolume():this.volumeMap.get(e)}addSubscribedMediaTrack(e,A,t,i,r,s){let o=this.getTrackPublicationBySid(A);if(o||A.startsWith("TR")||this.trackPublications.forEach(l=>{!o&&e.kind===l.kind.toString()&&(o=l)}),!o){if(s===0){this.log.error("could not find published track",Object.assign(Object.assign({},this.logContext),{trackSid:A})),this.emit(x.TrackSubscriptionFailed,A);return}s===void 0&&(s=20),setTimeout(()=>{this.addSubscribedMediaTrack(e,A,t,i,r,s-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),X(o))),this.emit(x.TrackSubscriptionFailed,A);return}const a=e.kind==="video";let c;return a?c=new Vp(e,A,i,r):c=new Kp(e,A,i,this.audioContext,this.audioOutput),c.source=o.source,c.isMuted=o.isMuted,c.setMediaStream(t),c.start(),o.setTrack(c),this.volumeMap.has(o.source)&&ks(c)&&BA(c)&&c.setVolume(this.volumeMap.get(o.source)),o}get hasMetadata(){return!!this.participantInfo}getTrackPublicationBySid(e){return this.trackPublications.get(e)}updateInfo(e){if(!super.updateInfo(e))return!1;const A=new Map,t=new Map;return e.tracks.forEach(i=>{var r,s;let o=this.getTrackPublicationBySid(i.sid);if(o)o.updateInfo(i);else{const a=Q.kindFromProto(i.type);if(!a)return;o=new Yp(a,i,(r=this.signalClient.connectOptions)===null||r===void 0?void 0:r.autoSubscribe,{loggerContextCb:()=>this.logContext,loggerName:(s=this.loggerOptions)===null||s===void 0?void 0:s.loggerName}),o.updateInfo(i),t.set(i.sid,o);const c=Array.from(this.trackPublications.values()).find(l=>l.source===(o==null?void 0:o.source));c&&o.source!==Q.Source.Unknown&&this.log.debug("received a second track publication for ".concat(this.identity," with the same source: ").concat(o.source),Object.assign(Object.assign({},this.logContext),{oldTrack:X(c),newTrack:X(o)})),this.addTrackPublication(o)}A.set(i.sid,o)}),this.trackPublications.forEach(i=>{A.has(i.trackSid)||(this.log.trace("detected removed track on remote participant, unpublishing",Object.assign(Object.assign({},this.logContext),X(i))),this.unpublishTrack(i.trackSid,!0))}),t.forEach(i=>{this.emit(x.TrackPublished,i)}),!0}unpublishTrack(e,A){const t=this.trackPublications.get(e);if(!t)return;const{track:i}=t;switch(i&&(i.stop(),t.setTrack(void 0)),this.trackPublications.delete(e),t.kind){case Q.Kind.Audio:this.audioTrackPublications.delete(e);break;case Q.Kind.Video:this.videoTrackPublications.delete(e);break}A&&this.emit(x.TrackUnpublished,t)}setAudioOutput(e){return p(this,void 0,void 0,function*(){this.audioOutput=e;const A=[];this.audioTrackPublications.forEach(t=>{var i;BA(t.track)&&ks(t.track)&&A.push(t.track.setSinkId((i=e.deviceId)!==null&&i!==void 0?i:"default"))}),yield Promise.all(A)})}emit(e){for(var A=arguments.length,t=new Array(A>1?A-1:0),i=1;i<A;i++)t[i-1]=arguments[i];return this.log.trace("participant event",Object.assign(Object.assign({},this.logContext),{event:e,args:t})),super.emit(e,...t)}}var W;(function(n){n.Disconnected="disconnected",n.Connecting="connecting",n.Connected="connected",n.Reconnecting="reconnecting",n.SignalReconnecting="signalReconnecting"})(W||(W={}));const qp=4*1e3;class dt extends sA.EventEmitter{constructor(e){var A,t,i,r;if(super(),A=this,this.state=W.Disconnected,this.activeSpeakers=[],this.isE2EEEnabled=!1,this.audioEnabled=!0,this.isVideoPlaybackBlocked=!1,this.log=V,this.bufferedEvents=[],this.isResuming=!1,this.byteStreamControllers=new Map,this.textStreamControllers=new Map,this.byteStreamHandlers=new Map,this.textStreamHandlers=new Map,this.rpcHandlers=new Map,this.connect=(s,o,a)=>p(this,void 0,void 0,function*(){var c;if(!Hg())throw oA()?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 l=yield this.disconnectLock.lock();if(this.state===W.Connected)return this.log.info("already connected to room ".concat(this.name),this.logContext),l(),Promise.resolve();if(this.connectFuture)return l(),this.connectFuture.promise;this.setAndEmitConnectionState(W.Connecting),((c=this.regionUrlProvider)===null||c===void 0?void 0:c.getServerUrl().toString())!==s&&(this.regionUrl=void 0,this.regionUrlProvider=void 0),Us(new URL(s))&&(this.regionUrlProvider===void 0?this.regionUrlProvider=new $s(s,o):this.regionUrlProvider.updateToken(o),this.regionUrlProvider.fetchRegionSettings().then(h=>{var f;(f=this.regionUrlProvider)===null||f===void 0||f.setServerReportedRegions(h)}).catch(h=>{this.log.warn("could not fetch region settings",Object.assign(Object.assign({},this.logContext),{error:h}))}));const u=(h,f,g)=>p(this,void 0,void 0,function*(){var m,C;this.abortController&&this.abortController.abort();const y=new AbortController;this.abortController=y,l==null||l();try{yield this.attemptConnection(g??s,o,a,y),this.abortController=void 0,h()}catch(U){if(this.regionUrlProvider&&U instanceof Z&&U.reason!==G.Cancelled&&U.reason!==G.NotAllowed){let v=null;try{v=yield this.regionUrlProvider.getNextBestRegionUrl((m=this.abortController)===null||m===void 0?void 0:m.signal)}catch(B){if(B instanceof Z&&(B.status===401||B.reason===G.Cancelled)){this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),f(B);return}}v&&!(!((C=this.abortController)===null||C===void 0)&&C.signal.aborted)?(this.log.info("Initial connection failed with ConnectionError: ".concat(U.message,". Retrying with another region: ").concat(v),this.logContext),this.recreateEngine(),yield u(h,f,v)):(this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,Cl(U)),f(U))}else{let v=We.UNKNOWN_REASON;U instanceof Z&&(v=Cl(U)),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,v),f(U)}}}),d=this.regionUrl;return this.regionUrl=void 0,this.connectFuture=new Ts((h,f)=>{u(h,f,d)},()=>{this.clearConnectionFutures()}),this.connectFuture.promise}),this.connectSignal=(s,o,a,c,l,u)=>p(this,void 0,void 0,function*(){var d,h,f;const g=yield a.join(s,o,{autoSubscribe:c.autoSubscribe,adaptiveStream:typeof l.adaptiveStream=="object"?!0:l.adaptiveStream,maxRetries:c.maxRetries,e2eeEnabled:!!this.e2eeManager,websocketTimeout:c.websocketTimeout},u.signal);let m=g.serverInfo;if(m||(m={version:g.serverVersion,region:g.serverRegion}),this.serverInfo=m,this.log.debug("connected to Livekit Server ".concat(Object.entries(m).map(C=>{let[y,U]=C;return"".concat(y,": ").concat(U)}).join(", ")),{room:(d=g.room)===null||d===void 0?void 0:d.name,roomSid:(h=g.room)===null||h===void 0?void 0:h.sid,identity:(f=g.participant)===null||f===void 0?void 0:f.identity}),!m.version)throw new bg("unknown server version");return m.version==="0.15.1"&&this.options.dynacast&&(this.log.debug("disabling dynacast due to server version",this.logContext),l.dynacast=!1),g}),this.applyJoinResponse=s=>{const o=s.participant;if(this.localParticipant.sid=o.sid,this.localParticipant.identity=o.identity,this.localParticipant.setEnabledPublishCodecs(s.enabledPublishCodecs),this.options.e2ee&&this.e2eeManager)try{this.e2eeManager.setSifTrailer(s.sifTrailer)}catch(a){this.log.error(a instanceof Error?a.message:"Could not set SifTrailer",Object.assign(Object.assign({},this.logContext),{error:a}))}this.handleParticipantUpdates([o,...s.otherParticipants]),s.room&&this.handleRoomUpdate(s.room)},this.attemptConnection=(s,o,a,c)=>p(this,void 0,void 0,function*(){var l,u;this.state===W.Reconnecting||this.isResuming||!((l=this.engine)===null||l===void 0)&&l.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({},Ks),a),this.connOptions.rtcConfig&&(this.engine.rtcConfig=this.connOptions.rtcConfig),this.connOptions.peerConnectionTimeout&&(this.engine.peerConnectionTimeout=this.connOptions.peerConnectionTimeout);try{const d=yield this.connectSignal(s,o,this.engine,this.connOptions,this.options,c);this.applyJoinResponse(d),this.setupLocalParticipantEvents(),this.emit(T.SignalConnected)}catch(d){yield this.engine.close(),this.recreateEngine();const h=new Z("could not establish signal connection",G.ServerUnreachable);throw d instanceof Error&&(h.message="".concat(h.message,": ").concat(d.message)),d instanceof Z&&(h.reason=d.reason,h.status=d.status),this.log.debug("error trying to establish signal connection",Object.assign(Object.assign({},this.logContext),{error:d})),h}if(c.signal.aborted)throw yield this.engine.close(),this.recreateEngine(),new Z("Connection attempt aborted",G.Cancelled);try{yield this.engine.waitForPCInitialConnection(this.connOptions.peerConnectionTimeout,c)}catch(d){throw yield this.engine.close(),this.recreateEngine(),d}Re()&&this.options.disconnectOnPageLeave&&(window.addEventListener("pagehide",this.onPageLeave),window.addEventListener("beforeunload",this.onPageLeave)),Re()&&document.addEventListener("freeze",this.onPageLeave),this.setAndEmitConnectionState(W.Connected),this.emit(T.Connected),this.registerConnectionReconcile()}),this.disconnect=function(){for(var s=arguments.length,o=new Array(s),a=0;a<s;a++)o[a]=arguments[a];return p(A,[...o],void 0,function(){var c=this;let l=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){var u,d,h,f;const g=yield c.disconnectLock.lock();try{if(c.state===W.Disconnected){c.log.debug("already disconnected",c.logContext);return}c.log.info("disconnect from room",Object.assign({},c.logContext)),(c.state===W.Connecting||c.state===W.Reconnecting||c.isResuming)&&(c.log.warn("abort connection attempt",c.logContext),(u=c.abortController)===null||u===void 0||u.abort(),(h=(d=c.connectFuture)===null||d===void 0?void 0:d.reject)===null||h===void 0||h.call(d,new Z("Client initiated disconnect",G.Cancelled)),c.connectFuture=void 0),!((f=c.engine)===null||f===void 0)&&f.client.isDisconnected||(yield c.engine.client.sendLeave()),c.engine&&(yield c.engine.close()),c.handleDisconnect(l,We.CLIENT_INITIATED),c.engine=void 0}finally{g()}}()})},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 s=[],o=qe();if(o&&o.os==="iOS"){const a="livekit-dummy-audio-el";let c=document.getElementById(a);if(!c){c=document.createElement("audio"),c.id=a,c.autoplay=!0,c.hidden=!0;const l=Ss();l.enabled=!0;const u=new MediaStream([l]);c.srcObject=u,document.addEventListener("visibilitychange",()=>{c&&(c.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(c),this.once(T.Disconnected,()=>{c==null||c.remove(),c=null})}s.push(c)}this.remoteParticipants.forEach(a=>{a.audioTrackPublications.forEach(c=>{c.track&&c.track.attachedElements.forEach(l=>{s.push(l)})})});try{yield Promise.all([this.acquireAudioContext(),...s.map(a=>(a.muted=!1,a.play()))]),this.handleAudioPlaybackStarted()}catch(a){throw this.handleAudioPlaybackFailed(a),a}}),this.startVideo=()=>p(this,void 0,void 0,function*(){const s=[];for(const o of this.remoteParticipants.values())o.videoTrackPublications.forEach(a=>{var c;(c=a.track)===null||c===void 0||c.attachedElements.forEach(l=>{s.includes(l)||s.push(l)})});yield Promise.all(s.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 s of this.remoteParticipants.values())this.handleParticipantDisconnected(s.identity,s);this.setAndEmitConnectionState(W.Reconnecting)&&this.emit(T.Reconnecting)},this.handleSignalRestarted=s=>p(this,void 0,void 0,function*(){this.log.debug("signal reconnected to server, region ".concat(s.serverRegion),Object.assign(Object.assign({},this.logContext),{region:s.serverRegion})),this.bufferedEvents=[],this.applyJoinResponse(s);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:s.serverRegion}))}catch{return}this.setAndEmitConnectionState(W.Connected),this.emit(T.Reconnected),this.registerConnectionReconcile(),this.emitBufferedEvents()}),this.handleParticipantUpdates=s=>{s.forEach(o=>{var a;if(o.identity===this.localParticipant.identity){this.localParticipant.updateInfo(o);return}o.identity===""&&(o.identity=(a=this.sidToIdentity.get(o.sid))!==null&&a!==void 0?a:"");let c=this.remoteParticipants.get(o.identity);o.state===It.DISCONNECTED?this.handleParticipantDisconnected(o.identity,c):c=this.getOrCreateParticipant(o.identity,o)})},this.handleActiveSpeakersUpdate=s=>{const o=[],a={};s.forEach(c=>{if(a[c.sid]=!0,c.sid===this.localParticipant.sid)this.localParticipant.audioLevel=c.level,this.localParticipant.setIsSpeaking(!0),o.push(this.localParticipant);else{const l=this.getRemoteParticipantBySid(c.sid);l&&(l.audioLevel=c.level,l.setIsSpeaking(!0),o.push(l))}}),a[this.localParticipant.sid]||(this.localParticipant.audioLevel=0,this.localParticipant.setIsSpeaking(!1)),this.remoteParticipants.forEach(c=>{a[c.sid]||(c.audioLevel=0,c.setIsSpeaking(!1))}),this.activeSpeakers=o,this.emitWhenConnected(T.ActiveSpeakersChanged,o)},this.handleSpeakersChanged=s=>{const o=new Map;this.activeSpeakers.forEach(c=>{const l=this.remoteParticipants.get(c.identity);l&&l.sid!==c.sid||o.set(c.sid,c)}),s.forEach(c=>{let l=this.getRemoteParticipantBySid(c.sid);c.sid===this.localParticipant.sid&&(l=this.localParticipant),l&&(l.audioLevel=c.level,l.setIsSpeaking(c.active),c.active?o.set(c.sid,l):o.delete(c.sid))});const a=Array.from(o.values());a.sort((c,l)=>l.audioLevel-c.audioLevel),this.activeSpeakers=a,this.emitWhenConnected(T.ActiveSpeakersChanged,a)},this.handleStreamStateUpdate=s=>{s.streamStates.forEach(o=>{const a=this.getRemoteParticipantBySid(o.participantSid);if(!a)return;const c=a.getTrackPublicationBySid(o.trackSid);if(!c||!c.track)return;const l=Q.streamStateFromProto(o.state);l!==c.track.streamState&&(c.track.streamState=l,a.emit(x.TrackStreamStateChanged,c,c.track.streamState),this.emitWhenConnected(T.TrackStreamStateChanged,c,c.track.streamState,a))})},this.handleSubscriptionPermissionUpdate=s=>{const o=this.getRemoteParticipantBySid(s.participantSid);if(!o)return;const a=o.getTrackPublicationBySid(s.trackSid);a&&a.setAllowed(s.allowed)},this.handleSubscriptionError=s=>{const o=Array.from(this.remoteParticipants.values()).find(c=>c.trackPublications.has(s.trackSid));if(!o)return;const a=o.getTrackPublicationBySid(s.trackSid);a&&a.setSubscriptionError(s.err)},this.handleDataPacket=s=>{const o=this.remoteParticipants.get(s.participantIdentity);if(s.value.case==="user")this.handleUserPacket(o,s.value.value,s.kind);else if(s.value.case==="transcription")this.handleTranscription(o,s.value.value);else if(s.value.case==="sipDtmf")this.handleSipDtmf(o,s.value.value);else if(s.value.case==="chatMessage")this.handleChatMessage(o,s.value.value);else if(s.value.case==="metrics")this.handleMetrics(s.value.value,o);else if(s.value.case==="streamHeader")this.handleStreamHeader(s.value.value,s.participantIdentity);else if(s.value.case==="streamChunk")this.handleStreamChunk(s.value.value);else if(s.value.case==="streamTrailer")this.handleStreamTrailer(s.value.value);else if(s.value.case==="rpcRequest"){const a=s.value.value;this.handleIncomingRpcRequest(s.participantIdentity,a.id,a.method,a.payload,a.responseTimeoutMs,a.version)}},this.handleUserPacket=(s,o,a)=>{this.emit(T.DataReceived,o.payload,s,a,o.topic),s==null||s.emit(x.DataReceived,o.payload,a)},this.handleSipDtmf=(s,o)=>{this.emit(T.SipDTMFReceived,o,s),s==null||s.emit(x.SipDTMFReceived,o)},this.bufferedSegments=new Map,this.handleTranscription=(s,o)=>{const a=o.transcribedParticipantIdentity===this.localParticipant.identity?this.localParticipant:this.getParticipantByIdentity(o.transcribedParticipantIdentity),c=a==null?void 0:a.trackPublications.get(o.trackId),l=Jg(o,this.transcriptionReceivedTimes);c==null||c.emit(k.TranscriptionReceived,l),a==null||a.emit(x.TranscriptionReceived,l,c),this.emit(T.TranscriptionReceived,l,a,c)},this.handleChatMessage=(s,o)=>{const a=Wg(o);this.emit(T.ChatMessage,a,s)},this.handleMetrics=(s,o)=>{this.emit(T.MetricsReceived,s,o)},this.handleAudioPlaybackStarted=()=>{this.canPlaybackAudio||(this.audioEnabled=!0,this.emit(T.AudioPlaybackStatusChanged,!0))},this.handleAudioPlaybackFailed=s=>{this.log.warn("could not playback audio",Object.assign(Object.assign({},this.logContext),{error:s})),this.canPlaybackAudio&&(this.audioEnabled=!1,this.emit(T.AudioPlaybackStatusChanged,!1))},this.handleVideoPlaybackStarted=()=>{this.isVideoPlaybackBlocked&&(this.isVideoPlaybackBlocked=!1,this.emit(T.VideoPlaybackStatusChanged,!0))},this.handleVideoPlaybackFailed=()=>{this.isVideoPlaybackBlocked||(this.isVideoPlaybackBlocked=!0,this.emit(T.VideoPlaybackStatusChanged,!1))},this.handleDeviceChange=()=>p(this,void 0,void 0,function*(){var s,o,a;const c=me.getInstance().previousDevices,l=yield me.getInstance().getDevices(void 0,!1),u=qe();if((u==null?void 0:u.name)==="Chrome"&&u.os!=="iOS")for(let h of l){const f=c.find(g=>g.deviceId===h.deviceId);f&&f.label!==""&&f.kind===h.kind&&f.label!==h.label&&this.getActiveDevice(h.kind)==="default"&&this.emit(T.ActiveDeviceChanged,h.kind,h.deviceId)}const d=["audiooutput","audioinput","videoinput"];for(let h of d){const f=qg(h),g=this.localParticipant.getTrackPublication(f);if(g&&(!((s=g.track)===null||s===void 0)&&s.isUserProvided))continue;const m=l.filter(y=>y.kind===h),C=this.getActiveDevice(h);if(C===((o=c.filter(y=>y.kind===h)[0])===null||o===void 0?void 0:o.deviceId)&&m.length>0&&((a=m[0])===null||a===void 0?void 0:a.deviceId)!==C){yield this.switchActiveDevice(h,m[0].deviceId);continue}h==="audioinput"&&!PA()||h==="videoinput"||m.length>0&&!m.find(y=>y.deviceId===this.getActiveDevice(h))&&(yield this.switchActiveDevice(h,m[0].deviceId))}this.emit(T.MediaDevicesChanged)}),this.handleRoomUpdate=s=>{const o=this.roomInfo;this.roomInfo=s,o&&o.metadata!==s.metadata&&this.emitWhenConnected(T.RoomMetadataChanged,s.metadata),(o==null?void 0:o.activeRecording)!==s.activeRecording&&this.emitWhenConnected(T.RecordingStatusChanged,s.activeRecording)},this.handleConnectionQualityUpdate=s=>{s.updates.forEach(o=>{if(o.participantSid===this.localParticipant.sid){this.localParticipant.setConnectionQuality(o.quality);return}const a=this.getRemoteParticipantBySid(o.participantSid);a&&a.setConnectionQuality(o.quality)})},this.onLocalParticipantMetadataChanged=s=>{this.emit(T.ParticipantMetadataChanged,s,this.localParticipant)},this.onLocalParticipantNameChanged=s=>{this.emit(T.ParticipantNameChanged,s,this.localParticipant)},this.onLocalAttributesChanged=s=>{this.emit(T.ParticipantAttributesChanged,s,this.localParticipant)},this.onLocalTrackMuted=s=>{this.emit(T.TrackMuted,s,this.localParticipant)},this.onLocalTrackUnmuted=s=>{this.emit(T.TrackUnmuted,s,this.localParticipant)},this.onTrackProcessorUpdate=s=>{var o;(o=s==null?void 0:s.onPublish)===null||o===void 0||o.call(s,this)},this.onLocalTrackPublished=s=>p(this,void 0,void 0,function*(){var o,a,c,l,u,d;(o=s.track)===null||o===void 0||o.on(k.TrackProcessorUpdate,this.onTrackProcessorUpdate),(a=s.track)===null||a===void 0||a.on(k.Restarted,this.onLocalTrackRestarted),(u=(l=(c=s.track)===null||c===void 0?void 0:c.getProcessor())===null||l===void 0?void 0:l.onPublish)===null||u===void 0||u.call(l,this),this.emit(T.LocalTrackPublished,s,this.localParticipant),ut(s.track)&&(yield s.track.checkForSilence())&&this.emit(T.LocalAudioSilenceDetected,s);const h=yield(d=s.track)===null||d===void 0?void 0:d.getDeviceId(!1),f=Ul(s.source);f&&h&&h!==this.localParticipant.activeDeviceMap.get(f)&&(this.localParticipant.activeDeviceMap.set(f,h),this.emit(T.ActiveDeviceChanged,f,h))}),this.onLocalTrackUnpublished=s=>{var o,a;(o=s.track)===null||o===void 0||o.off(k.TrackProcessorUpdate,this.onTrackProcessorUpdate),(a=s.track)===null||a===void 0||a.off(k.Restarted,this.onLocalTrackRestarted),this.emit(T.LocalTrackUnpublished,s,this.localParticipant)},this.onLocalTrackRestarted=s=>p(this,void 0,void 0,function*(){const o=yield s.getDeviceId(!1),a=Ul(s.source);a&&o&&o!==this.localParticipant.activeDeviceMap.get(a)&&(this.log.debug("local track restarted, setting ".concat(a," ").concat(o," active"),this.logContext),this.localParticipant.activeDeviceMap.set(a,o),this.emit(T.ActiveDeviceChanged,a,o))}),this.onLocalConnectionQualityChanged=s=>{this.emit(T.ConnectionQualityChanged,s,this.localParticipant)},this.onMediaDevicesError=s=>{this.emit(T.MediaDevicesError,s)},this.onLocalParticipantPermissionsChanged=s=>{this.emit(T.ParticipantPermissionsChanged,s,this.localParticipant)},this.onLocalChatMessageSent=s=>{this.emit(T.ChatMessage,s,this.localParticipant)},this.setMaxListeners(100),this.remoteParticipants=new Map,this.sidToIdentity=new Map,this.options=Object.assign(Object.assign({},Bp),e),this.log=pA((t=this.options.loggerName)!==null&&t!==void 0?t:Ye.Room),this.transcriptionReceivedTimes=new Map,this.options.audioCaptureDefaults=Object.assign(Object.assign({},Ll),e==null?void 0:e.audioCaptureDefaults),this.options.videoCaptureDefaults=Object.assign(Object.assign({},Dl),e==null?void 0:e.videoCaptureDefaults),this.options.publishDefaults=Object.assign(Object.assign({},mp),e==null?void 0:e.publishDefaults),this.maybeCreateEngine(),this.disconnectLock=new Te,this.localParticipant=new $p("","",this.engine,this.options,this.rpcHandlers),this.options.videoCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("videoinput",LA(this.options.videoCaptureDefaults.deviceId)),this.options.audioCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("audioinput",LA(this.options.audioCaptureDefaults.deviceId)),!((i=this.options.audioOutput)===null||i===void 0)&&i.deviceId&&this.switchActiveDevice("audiooutput",LA(this.options.audioOutput.deviceId)).catch(s=>this.log.warn("Could not set audio output: ".concat(s.message),this.logContext)),this.options.e2ee&&this.setupE2EE(),Re()){const s=new AbortController;(r=navigator.mediaDevices)===null||r===void 0||r.addEventListener("devicechange",this.handleDeviceChange,{signal:s.signal}),dt.cleanupRegistry&&dt.cleanupRegistry.register(this,()=>{s.abort()})}}registerTextStreamHandler(e,A){if(this.textStreamHandlers.has(e))throw new TypeError('A text stream handler for topic "'.concat(e,'" has already been set.'));this.textStreamHandlers.set(e,A)}unregisterTextStreamHandler(e){this.textStreamHandlers.delete(e)}registerByteStreamHandler(e,A){if(this.byteStreamHandlers.has(e))throw new TypeError('A byte stream handler for topic "'.concat(e,'" has already been set.'));this.byteStreamHandlers.set(e,A)}unregisterByteStreamHandler(e){this.byteStreamHandlers.delete(e)}registerRpcMethod(e,A){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,A)}unregisterRpcMethod(e){this.rpcHandlers.delete(e)}handleIncomingRpcRequest(e,A,t,i,r,s){return p(this,void 0,void 0,function*(){if(yield this.engine.publishRpcAck(e,A),s!==1){yield this.engine.publishRpcResponse(e,A,null,oe.builtIn("UNSUPPORTED_VERSION"));return}const o=this.rpcHandlers.get(t);if(!o){yield this.engine.publishRpcResponse(e,A,null,oe.builtIn("UNSUPPORTED_METHOD"));return}let a=null,c=null;try{const l=yield o({requestId:A,callerIdentity:e,payload:i,responseTimeout:r});Vs(l)>_l?(a=oe.builtIn("RESPONSE_PAYLOAD_TOO_LARGE"),console.warn("RPC Response payload too large for ".concat(t))):c=l}catch(l){l instanceof oe?a=l:(console.warn("Uncaught error returned by RPC handler for ".concat(t,". Returning APPLICATION_ERROR instead."),l),a=oe.builtIn("APPLICATION_ERROR"))}yield this.engine.publishRpcResponse(e,A,c,a)})}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 np(this.options.e2ee),this.e2eeManager.on(RA.ParticipantEncryptionStatusChanged,(A,t)=>{$g(t)&&(this.isE2EEEnabled=A),this.emit(T.ParticipantEncryptionStatusChanged,A,t)}),this.e2eeManager.on(RA.EncryptionError,A=>this.emit(T.EncryptionError,A)),(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,A;return(A=(e=this.roomInfo)===null||e===void 0?void 0:e.activeRecording)!==null&&A!==void 0?A:!1}getSid(){return p(this,void 0,void 0,function*(){return this.state===W.Disconnected?"":this.roomInfo&&this.roomInfo.sid!==""?this.roomInfo.sid:new Promise((e,A)=>{const t=i=>{i.sid!==""&&(this.engine.off(I.RoomUpdate,t),e(i.sid))};this.engine.on(I.RoomUpdate,t),this.once(T.Disconnected,()=>{this.engine.off(I.RoomUpdate,t),A("Room disconnected before room server id was available")})})})}get name(){var e,A;return(A=(e=this.roomInfo)===null||e===void 0?void 0:e.name)!==null&&A!==void 0?A:""}get metadata(){var e;return(e=this.roomInfo)===null||e===void 0?void 0:e.metadata}get numParticipants(){var e,A;return(A=(e=this.roomInfo)===null||e===void 0?void 0:e.numParticipants)!==null&&A!==void 0?A:0}get numPublishers(){var e,A;return(A=(e=this.roomInfo)===null||e===void 0?void 0:e.numPublishers)!==null&&A!==void 0?A:0}maybeCreateEngine(){this.engine&&!this.engine.isClosed||(this.engine=new Pp(this.options),this.engine.on(I.ParticipantUpdate,this.handleParticipantUpdates).on(I.RoomUpdate,this.handleRoomUpdate).on(I.SpeakersChanged,this.handleSpeakersChanged).on(I.StreamStateChanged,this.handleStreamStateUpdate).on(I.ConnectionQualityUpdate,this.handleConnectionQualityUpdate).on(I.SubscriptionError,this.handleSubscriptionError).on(I.SubscriptionPermissionUpdate,this.handleSubscriptionPermissionUpdate).on(I.MediaTrackAdded,(e,A,t)=>{this.onTrackAdded(e,A,t)}).on(I.Disconnected,e=>{this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e)}).on(I.ActiveSpeakersUpdate,this.handleActiveSpeakersUpdate).on(I.DataPacketReceived,this.handleDataPacket).on(I.Resuming,()=>{this.clearConnectionReconcile(),this.isResuming=!0,this.log.info("Resuming signal connection",this.logContext),this.setAndEmitConnectionState(W.SignalReconnecting)&&this.emit(T.SignalReconnecting)}).on(I.Resumed,()=>{this.registerConnectionReconcile(),this.isResuming=!1,this.log.info("Resumed signal connection",this.logContext),this.updateSubscriptions(),this.emitBufferedEvents(),this.setAndEmitConnectionState(W.Connected)&&this.emit(T.Reconnected)}).on(I.SignalResumed,()=>{this.bufferedEvents=[],(this.state===W.Reconnecting||this.isResuming)&&this.sendSyncState()}).on(I.Restarting,this.handleRestarting).on(I.SignalRestarted,this.handleSignalRestarted).on(I.Offline,()=>{this.setAndEmitConnectionState(W.Reconnecting)&&this.emit(T.Reconnecting)}).on(I.DCBufferStatusChanged,(e,A)=>{this.emit(T.DCBufferStatusChanged,e,A)}).on(I.LocalTrackSubscribed,e=>{const A=this.localParticipant.getTrackPublications().find(t=>{let{trackSid:i}=t;return i===e});if(!A){this.log.warn("could not find local track subscription for subscribed event",this.logContext);return}this.localParticipant.emit(x.LocalTrackSubscribed,A),this.emitWhenConnected(T.LocalTrackSubscribed,A,this.localParticipant)}).on(I.RoomMoved,e=>{this.log.debug("room moved",e),e.room&&this.handleRoomUpdate(e.room),this.remoteParticipants.forEach((A,t)=>{this.handleParticipantDisconnected(t,A)}),this.emit(T.Moved,e.room.name,e.token),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))}static getLocalDevices(e){let A=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return me.getInstance().getDevices(e,A)}prepareConnection(e,A){return p(this,void 0,void 0,function*(){if(this.state===W.Disconnected){this.log.debug("prepareConnection to ".concat(e),this.logContext);try{if(Us(new URL(e))&&A){this.regionUrlProvider=new $s(e,A);const t=yield this.regionUrlProvider.getNextBestRegionUrl();t&&this.state===W.Disconnected&&(this.regionUrl=t,yield fetch(Fs(t),{method:"HEAD"}),this.log.debug("prepared connection to ".concat(t),this.logContext))}else yield fetch(Fs(e),{method:"HEAD"})}catch(t){this.log.warn("could not prepare connection",Object.assign(Object.assign({},this.logContext),{error:t}))}}})}getParticipantByIdentity(e){return this.localParticipant.identity===e?this.localParticipant:this.remoteParticipants.get(e)}clearConnectionFutures(){this.connectFuture=void 0}simulateScenario(e,A){return p(this,void 0,void 0,function*(){let t=()=>{},i;switch(e){case"signal-reconnect":yield this.engine.client.handleOnClose("simulate disconnect");break;case"speaker":i=new rA({scenario:{case:"speakerUpdate",value:3}});break;case"node-failure":i=new rA({scenario:{case:"nodeFailure",value:!0}});break;case"server-leave":i=new rA({scenario:{case:"serverLeave",value:!0}});break;case"migration":i=new rA({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":t=()=>p(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),i=new rA({scenario:{case:"disconnectSignalOnResume",value:!0}});break;case"disconnect-signal-on-resume-no-messages":t=()=>p(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),i=new rA({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":i=new rA({scenario:{case:"switchCandidateProtocol",value:e==="force-tls"?2:1}}),t=()=>p(this,void 0,void 0,function*(){const r=this.engine.client.onLeave;r&&r(new li({reason:We.CLIENT_INITIATED,action:xt.RECONNECT}))});break;case"subscriber-bandwidth":if(A===void 0||typeof A!="number")throw new Error("subscriber-bandwidth requires a number as argument");i=new rA({scenario:{case:"subscriberBandwidth",value:lt(A)}});break;case"leave-full-reconnect":i=new rA({scenario:{case:"leaveRequestFullReconnect",value:!0}})}i&&(yield this.engine.client.sendSimulateScenario(i),yield t())})}get canPlaybackAudio(){return this.audioEnabled}get canPlaybackVideo(){return!this.isVideoPlaybackBlocked}getActiveDevice(e){return this.localParticipant.activeDeviceMap.get(e)}switchActiveDevice(e,A){return p(this,arguments,void 0,function(t,i){var r=this;let s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0;return function*(){var o,a,c,l,u,d,h,f;let g=!0,m=!1;const C=s?{exact:i}:i;if(t==="audioinput"){m=r.localParticipant.audioTrackPublications.size===0;const y=(o=r.getActiveDevice(t))!==null&&o!==void 0?o:r.options.audioCaptureDefaults.deviceId;r.options.audioCaptureDefaults.deviceId=C;const U=Array.from(r.localParticipant.audioTrackPublications.values()).filter(v=>v.source===Q.Source.Microphone);try{g=(yield Promise.all(U.map(v=>{var B;return(B=v.audioTrack)===null||B===void 0?void 0:B.setDeviceId(C)}))).every(v=>v===!0)}catch(v){throw r.options.audioCaptureDefaults.deviceId=y,v}}else if(t==="videoinput"){m=r.localParticipant.videoTrackPublications.size===0;const y=(a=r.getActiveDevice(t))!==null&&a!==void 0?a:r.options.videoCaptureDefaults.deviceId;r.options.videoCaptureDefaults.deviceId=C;const U=Array.from(r.localParticipant.videoTrackPublications.values()).filter(v=>v.source===Q.Source.Camera);try{g=(yield Promise.all(U.map(v=>{var B;return(B=v.videoTrack)===null||B===void 0?void 0:B.setDeviceId(C)}))).every(v=>v===!0)}catch(v){throw r.options.videoCaptureDefaults.deviceId=y,v}}else if(t==="audiooutput"){if(!bs()&&!r.options.webAudioMix||r.options.webAudioMix&&r.audioContext&&!("setSinkId"in r.audioContext))throw new Error("cannot switch audio output, setSinkId not supported");r.options.webAudioMix&&(i=(c=yield me.getInstance().normalizeDeviceId("audiooutput",i))!==null&&c!==void 0?c:""),(l=(f=r.options).audioOutput)!==null&&l!==void 0||(f.audioOutput={});const y=(u=r.getActiveDevice(t))!==null&&u!==void 0?u:r.options.audioOutput.deviceId;r.options.audioOutput.deviceId=i;try{r.options.webAudioMix&&((d=r.audioContext)===null||d===void 0||d.setSinkId(i)),yield Promise.all(Array.from(r.remoteParticipants.values()).map(U=>U.setAudioOutput({deviceId:i})))}catch(U){throw r.options.audioOutput.deviceId=y,U}}return(m||t==="audiooutput")&&(r.localParticipant.activeDeviceMap.set(t,t==="audiooutput"&&((h=r.options.audioOutput)===null||h===void 0?void 0:h.deviceId)||i),r.emit(T.ActiveDeviceChanged,t,i)),g}()})}setupLocalParticipantEvents(){this.localParticipant.on(x.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).on(x.ParticipantNameChanged,this.onLocalParticipantNameChanged).on(x.AttributesChanged,this.onLocalAttributesChanged).on(x.TrackMuted,this.onLocalTrackMuted).on(x.TrackUnmuted,this.onLocalTrackUnmuted).on(x.LocalTrackPublished,this.onLocalTrackPublished).on(x.LocalTrackUnpublished,this.onLocalTrackUnpublished).on(x.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).on(x.MediaDevicesError,this.onMediaDevicesError).on(x.AudioStreamAcquired,this.startAudio).on(x.ChatMessage,this.onLocalChatMessageSent).on(x.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,A,t){if(this.state===W.Connecting||this.state===W.Reconnecting){const l=()=>{this.onTrackAdded(e,A,t),u()},u=()=>{this.off(T.Reconnected,l),this.off(T.Connected,l),this.off(T.Disconnected,u)};this.once(T.Reconnected,l),this.once(T.Connected,l),this.once(T.Disconnected,u);return}if(this.state===W.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 i=Lg(A.id),r=i[0];let s=i[1],o=e.id;if(s&&s.startsWith("TR")&&(o=s),r===this.localParticipant.sid){this.log.warn("tried to create RemoteParticipant for local participant",this.logContext);return}const a=Array.from(this.remoteParticipants.values()).find(l=>l.sid===r);if(!a){this.log.error("Tried to add a track for a participant, that's not present. Sid: ".concat(r),this.logContext);return}let c;this.options.adaptiveStream&&(typeof this.options.adaptiveStream=="object"?c=this.options.adaptiveStream:c={}),a.addSubscribedMediaTrack(e,o,A,t,c)}handleDisconnect(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0,A=arguments.length>1?arguments[1]:void 0;var t;if(this.clearConnectionReconcile(),this.isResuming=!1,this.bufferedEvents=[],this.transcriptionReceivedTimes.clear(),this.state!==W.Disconnected){this.regionUrl=void 0;try{this.remoteParticipants.forEach(i=>{i.trackPublications.forEach(r=>{i.unpublishTrack(r.trackSid)})}),this.localParticipant.trackPublications.forEach(i=>{var r,s,o;i.track&&this.localParticipant.unpublishTrack(i.track,e),e?((r=i.track)===null||r===void 0||r.detach(),(s=i.track)===null||s===void 0||s.stop()):(o=i.track)===null||o===void 0||o.stopMonitor()}),this.localParticipant.off(x.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).off(x.ParticipantNameChanged,this.onLocalParticipantNameChanged).off(x.AttributesChanged,this.onLocalAttributesChanged).off(x.TrackMuted,this.onLocalTrackMuted).off(x.TrackUnmuted,this.onLocalTrackUnmuted).off(x.LocalTrackPublished,this.onLocalTrackPublished).off(x.LocalTrackUnpublished,this.onLocalTrackUnpublished).off(x.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).off(x.MediaDevicesError,this.onMediaDevicesError).off(x.AudioStreamAcquired,this.startAudio).off(x.ChatMessage,this.onLocalChatMessageSent).off(x.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),Re()&&(window.removeEventListener("beforeunload",this.onPageLeave),window.removeEventListener("pagehide",this.onPageLeave),window.removeEventListener("freeze",this.onPageLeave),(t=navigator.mediaDevices)===null||t===void 0||t.removeEventListener("devicechange",this.handleDeviceChange))}finally{this.setAndEmitConnectionState(W.Disconnected),this.emit(T.Disconnected,A)}}}handleParticipantDisconnected(e,A){var t;this.remoteParticipants.delete(e),A&&(A.trackPublications.forEach(i=>{A.unpublishTrack(i.trackSid,!0)}),this.emit(T.ParticipantDisconnected,A),A.setDisconnected(),(t=this.localParticipant)===null||t===void 0||t.handleParticipantDisconnected(A.identity))}handleStreamHeader(e,A){return p(this,void 0,void 0,function*(){var t;if(e.contentHeader.case==="byteHeader"){const i=this.byteStreamHandlers.get(e.topic);if(!i){this.log.debug("ignoring incoming byte stream due to no handler for topic",e.topic);return}let r;const s={id:e.streamId,name:(t=e.contentHeader.value.name)!==null&&t!==void 0?t:"unknown",mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:bi(e.timestamp),attributes:e.attributes},o=new ReadableStream({start:a=>{r=a,this.byteStreamControllers.set(e.streamId,{info:s,controller:r,startTime:Date.now()})}});i(new Hp(s,o,bi(e.totalLength)),{identity:A})}else if(e.contentHeader.case==="textHeader"){const i=this.textStreamHandlers.get(e.topic);if(!i){this.log.debug("ignoring incoming text stream due to no handler for topic",e.topic);return}let r;const s={id:e.streamId,mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:Number(e.timestamp),attributes:e.attributes},o=new ReadableStream({start:a=>{r=a,this.textStreamControllers.set(e.streamId,{info:s,controller:r,startTime:Date.now()})}});i(new Op(s,o,bi(e.totalLength)),{identity:A})}})}handleStreamChunk(e){const A=this.byteStreamControllers.get(e.streamId);A&&e.content.length>0&&A.controller.enqueue(e);const t=this.textStreamControllers.get(e.streamId);t&&e.content.length>0&&t.controller.enqueue(e)}handleStreamTrailer(e){const A=this.textStreamControllers.get(e.streamId);A&&(A.info.attributes=Object.assign(Object.assign({},A.info.attributes),e.attributes),A.controller.close(),this.textStreamControllers.delete(e.streamId));const t=this.byteStreamControllers.get(e.streamId);t&&(t.info.attributes=Object.assign(Object.assign({},t.info.attributes),e.attributes),t.controller.close(),this.byteStreamControllers.delete(e.streamId))}acquireAudioContext(){return p(this,void 0,void 0,function*(){var e,A;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=bl())!==null&&e!==void 0?e:void 0),this.options.webAudioMix&&this.remoteParticipants.forEach(i=>i.setAudioContext(this.audioContext)),this.localParticipant.setAudioContext(this.audioContext),this.audioContext&&this.audioContext.state==="suspended")try{yield Promise.race([this.audioContext.resume(),Ie(200)])}catch(i){this.log.warn("Could not resume audio context",Object.assign(Object.assign({},this.logContext),{error:i}))}const t=((A=this.audioContext)===null||A===void 0?void 0:A.state)==="running";t!==this.canPlaybackAudio&&(this.audioEnabled=t,this.emit(T.AudioPlaybackStatusChanged,t))})}createParticipant(e,A){var t;let i;return A?i=Ii.fromParticipantInfo(this.engine.client,A,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}):i=new Ii(this.engine.client,"",e,void 0,void 0,void 0,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}),this.options.webAudioMix&&i.setAudioContext(this.audioContext),!((t=this.options.audioOutput)===null||t===void 0)&&t.deviceId&&i.setAudioOutput(this.options.audioOutput).catch(r=>this.log.warn("Could not set audio output: ".concat(r.message),this.logContext)),i}getOrCreateParticipant(e,A){if(this.remoteParticipants.has(e)){const i=this.remoteParticipants.get(e);return A&&i.updateInfo(A)&&this.sidToIdentity.set(A.sid,A.identity),i}const t=this.createParticipant(e,A);return this.remoteParticipants.set(e,t),this.sidToIdentity.set(A.sid,A.identity),this.emitWhenConnected(T.ParticipantConnected,t),t.on(x.TrackPublished,i=>{this.emitWhenConnected(T.TrackPublished,i,t)}).on(x.TrackSubscribed,(i,r)=>{i.kind===Q.Kind.Audio?(i.on(k.AudioPlaybackStarted,this.handleAudioPlaybackStarted),i.on(k.AudioPlaybackFailed,this.handleAudioPlaybackFailed)):i.kind===Q.Kind.Video&&(i.on(k.VideoPlaybackFailed,this.handleVideoPlaybackFailed),i.on(k.VideoPlaybackStarted,this.handleVideoPlaybackStarted)),this.emit(T.TrackSubscribed,i,r,t)}).on(x.TrackUnpublished,i=>{this.emit(T.TrackUnpublished,i,t)}).on(x.TrackUnsubscribed,(i,r)=>{this.emit(T.TrackUnsubscribed,i,r,t)}).on(x.TrackMuted,i=>{this.emitWhenConnected(T.TrackMuted,i,t)}).on(x.TrackUnmuted,i=>{this.emitWhenConnected(T.TrackUnmuted,i,t)}).on(x.ParticipantMetadataChanged,i=>{this.emitWhenConnected(T.ParticipantMetadataChanged,i,t)}).on(x.ParticipantNameChanged,i=>{this.emitWhenConnected(T.ParticipantNameChanged,i,t)}).on(x.AttributesChanged,i=>{this.emitWhenConnected(T.ParticipantAttributesChanged,i,t)}).on(x.ConnectionQualityChanged,i=>{this.emitWhenConnected(T.ConnectionQualityChanged,i,t)}).on(x.ParticipantPermissionsChanged,i=>{this.emitWhenConnected(T.ParticipantPermissionsChanged,i,t)}).on(x.TrackSubscriptionStatusChanged,(i,r)=>{this.emitWhenConnected(T.TrackSubscriptionStatusChanged,i,r,t)}).on(x.TrackSubscriptionFailed,(i,r)=>{this.emit(T.TrackSubscriptionFailed,i,t,r)}).on(x.TrackSubscriptionPermissionChanged,(i,r)=>{this.emitWhenConnected(T.TrackSubscriptionPermissionChanged,i,r,t)}).on(x.Active,()=>{this.emitWhenConnected(T.ParticipantActive,t)}),A&&t.updateInfo(A),t}sendSyncState(){const e=Array.from(this.remoteParticipants.values()).reduce((t,i)=>(t.push(...i.getTrackPublications()),t),[]),A=this.localParticipant.getTrackPublications();this.engine.sendSyncState(e,A)}updateSubscriptions(){for(const e of this.remoteParticipants.values())for(const A of e.videoTrackPublications.values())A.isSubscribed&&Xg(A)&&A.emitTrackUpdate()}getRemoteParticipantBySid(e){const A=this.sidToIdentity.get(e);if(A)return this.remoteParticipants.get(A)}registerConnectionReconcile(){this.clearConnectionReconcile();let e=0;this.connectionReconcileInterval=ve.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,We.STATE_MISMATCH))):e=0},qp)}clearConnectionReconcile(){this.connectionReconcileInterval&&ve.clearInterval(this.connectionReconcileInterval)}setAndEmitConnectionState(e){return e===this.state?!1:(this.state=e,this.emit(T.ConnectionStateChanged,this.state),!0)}emitBufferedEvents(){this.bufferedEvents.forEach(e=>{let[A,t]=e;this.emit(A,...t)}),this.bufferedEvents=[]}emitWhenConnected(e){for(var A=arguments.length,t=new Array(A>1?A-1:0),i=1;i<A;i++)t[i-1]=arguments[i];if(this.state===W.Reconnecting||this.isResuming||!this.engine||this.engine.pendingReconnect)this.bufferedEvents.push([e,t]);else if(this.state===W.Connected)return this.emit(e,...t);return!1}simulateParticipants(e){return p(this,void 0,void 0,function*(){var A,t;const i=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 si({sid:"RM_SIMULATED",name:"simulated-room",emptyTimeout:0,maxParticipants:0,creationTime:ne.parse(new Date().getTime()),metadata:"",numParticipants:1,numPublishers:1,turnPassword:"",enabledCodecs:[],activeRecording:!1}),this.localParticipant.updateInfo(new rt({identity:"simulated-local",name:"local-name"})),this.setupLocalParticipantEvents(),this.emit(T.SignalConnected),this.emit(T.Connected),this.setAndEmitConnectionState(W.Connected),i.video){const s=new Zs(Q.Kind.Video,new Rt({source:de.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:Je.AUDIO,name:"video-dummy"}),new Fi(i.useRealTracks?(yield window.navigator.mediaDevices.getUserMedia({video:!0})).getVideoTracks()[0]:vl(160*((A=r.aspectRatios[0])!==null&&A!==void 0?A:1),160,!0,!0),void 0,!1,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(s),this.localParticipant.emit(x.LocalTrackPublished,s)}if(i.audio){const s=new Zs(Q.Kind.Audio,new Rt({source:de.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:Je.AUDIO}),new Si(i.useRealTracks?(yield navigator.mediaDevices.getUserMedia({audio:!0})).getAudioTracks()[0]:Ss(),void 0,!1,this.audioContext,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(s),this.localParticipant.emit(x.LocalTrackPublished,s)}for(let s=0;s<r.count-1;s+=1){let o=new rt({sid:Math.floor(Math.random()*1e4).toString(),identity:"simulated-".concat(s),state:It.ACTIVE,tracks:[],joinedAt:ne.parse(Date.now())});const a=this.getOrCreateParticipant(o.identity,o);if(r.video){const c=vl(160*((t=r.aspectRatios[s%r.aspectRatios.length])!==null&&t!==void 0?t:1),160,!1,!0),l=new Rt({source:de.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:Je.AUDIO});a.addSubscribedMediaTrack(c,l.sid,new MediaStream([c]),new RTCRtpReceiver),o.tracks=[...o.tracks,l]}if(r.audio){const c=Ss(),l=new Rt({source:de.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:Je.AUDIO});a.addSubscribedMediaTrack(c,l.sid,new MediaStream([c]),new RTCRtpReceiver),o.tracks=[...o.tracks,l]}a.updateInfo(o)}})}emit(e){for(var A=arguments.length,t=new Array(A>1?A-1:0),i=1;i<A;i++)t[i-1]=arguments[i];if(e!==T.ActiveSpeakersChanged&&e!==T.TranscriptionReceived){const r=Zl(t).filter(s=>s!==void 0);this.log.debug("room event ".concat(e),Object.assign(Object.assign({},this.logContext),{event:e,args:r}))}return super.emit(e,...t)}}dt.cleanupRegistry=typeof FinalizationRegistry<"u"&&new FinalizationRegistry(n=>{n()});function Zl(n){return n.map(e=>{if(e)return Array.isArray(e)?Zl(e):typeof e=="object"?"logContext"in e?e.logContext:void 0:e})}var eA;(function(n){n[n.IDLE=0]="IDLE",n[n.RUNNING=1]="RUNNING",n[n.SKIPPED=2]="SKIPPED",n[n.SUCCESS=3]="SUCCESS",n[n.FAILED=4]="FAILED"})(eA||(eA={}));class OA extends sA.EventEmitter{constructor(e,A){let t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.status=eA.IDLE,this.logs=[],this.options={},this.url=e,this.token=A,this.name=this.constructor.name,this.room=new dt(t.roomOptions),this.connectOptions=t.connectOptions,this.options=t}run(e){return p(this,void 0,void 0,function*(){if(this.status!==eA.IDLE)throw Error("check is running already");this.setStatus(eA.RUNNING);try{yield this.perform()}catch(A){A instanceof Error&&(this.options.errorsAsWarnings?this.appendWarning(A.message):this.appendError(A.message))}return yield this.disconnect(),yield new Promise(A=>setTimeout(A,500)),this.status!==eA.SKIPPED&&this.setStatus(this.isSuccess()?eA.SUCCESS:eA.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===W.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!==W.Disconnected&&(yield this.room.disconnect(),yield new Promise(e=>setTimeout(e,500)))})}skip(){this.setStatus(eA.SKIPPED)}switchProtocol(e){return p(this,void 0,void 0,function*(){let A=!1,t=!1;if(this.room.on(T.Reconnecting,()=>{A=!0}),this.room.once(T.Reconnected,()=>{t=!0}),this.room.simulateScenario("force-".concat(e)),yield new Promise(r=>setTimeout(r,1e3)),!A)return;const i=Date.now()+1e4;for(;Date.now()<i;){if(t)return;yield Ie(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 Zp extends OA{get description(){return"Cloud regions"}perform(){return p(this,void 0,void 0,function*(){const e=new $s(this.url,this.token);if(!e.isCloud()){this.skip();return}const A=[],t=new Set;for(let r=0;r<3;r++){const s=yield e.getNextBestRegionUrl();if(!s)break;if(t.has(s))continue;t.add(s);const o=yield this.checkCloudRegion(s);this.appendMessage("".concat(o.region," RTT: ").concat(o.rtt,"ms, duration: ").concat(o.duration,"ms")),A.push(o)}A.sort((r,s)=>(r.duration-s.duration)*.5+(r.rtt-s.rtt)*.5);const i=A[0];this.bestStats=i,this.appendMessage("best Cloud region: ".concat(i.region))})}getInfo(){const e=super.getInfo();return e.data=this.bestStats,e}checkCloudRegion(e){return p(this,void 0,void 0,function*(){var A,t;yield this.connect(e),this.options.protocol==="tcp"&&(yield this.switchProtocol("tcp"));const i=(A=this.room.serverInfo)===null||A===void 0?void 0:A.region;if(!i)throw new Error("Region not found");const r=yield this.room.localParticipant.streamText({topic:"test"}),s=1e3,a=1e6/s,c="A".repeat(s),l=Date.now();for(let f=0;f<a;f++)yield r.write(c);yield r.close();const u=Date.now(),d=yield(t=this.room.engine.pcManager)===null||t===void 0?void 0:t.publisher.getStats(),h={region:i,rtt:1e4,duration:u-l};return d==null||d.forEach(f=>{f.type==="candidate-pair"&&f.nominated&&(h.rtt=f.currentRoundTripTime*1e3)}),yield this.disconnect(),h})}}const zs=1e4;class zp extends OA{get description(){return"Connection via UDP vs TCP"}perform(){return p(this,void 0,void 0,function*(){const e=yield this.checkConnectionProtocol("udp"),A=yield this.checkConnectionProtocol("tcp");this.bestStats=e,e.qualityLimitationDurations.bandwidth-A.qualityLimitationDurations.bandwidth>.5||(e.packetsLost-A.packetsLost)/e.packetsSent>.01?(this.appendMessage("best connection quality via tcp"),this.bestStats=A):this.appendMessage("best connection quality via udp");const t=this.bestStats;this.appendMessage("upstream bitrate: ".concat((t.bitrateTotal/t.count/1e3/1e3).toFixed(2)," mbps")),this.appendMessage("RTT: ".concat((t.rttTotal/t.count*1e3).toFixed(2)," ms")),this.appendMessage("jitter: ".concat((t.jitterTotal/t.count*1e3).toFixed(2)," ms")),t.packetsLost>0&&this.appendWarning("packets lost: ".concat((t.packetsLost/t.packetsSent*100).toFixed(2),"%")),t.qualityLimitationDurations.bandwidth>1&&this.appendWarning("bandwidth limited ".concat((t.qualityLimitationDurations.bandwidth/(zs/1e3)*100).toFixed(2),"%")),t.qualityLimitationDurations.cpu>0&&this.appendWarning("cpu limited ".concat((t.qualityLimitationDurations.cpu/(zs/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 A=document.createElement("canvas");A.width=1280,A.height=720;const t=A.getContext("2d");if(!t)throw new Error("Could not get canvas context");let i=0;const r=()=>{i=(i+1)%360,t.fillStyle="hsl(".concat(i,", 100%, 50%)"),t.fillRect(0,0,A.width,A.height),requestAnimationFrame(r)};r();const o=A.captureStream(30).getVideoTracks()[0],c=(yield this.room.localParticipant.publishTrack(o,{simulcast:!1,degradationPreference:"maintain-resolution",videoEncoding:{maxBitrate:2e6}})).track,l={protocol:e,packetsLost:0,packetsSent:0,qualityLimitationDurations:{},rttTotal:0,jitterTotal:0,bitrateTotal:0,count:0},u=setInterval(()=>p(this,void 0,void 0,function*(){const d=yield c.getRTCStatsReport();d==null||d.forEach(h=>{h.type==="outbound-rtp"?(l.packetsSent=h.packetsSent,l.qualityLimitationDurations=h.qualityLimitationDurations,l.bitrateTotal+=h.targetBitrate,l.count++):h.type==="remote-inbound-rtp"&&(l.packetsLost=h.packetsLost,l.rttTotal+=h.roundTripTime,l.jitterTotal+=h.jitter)})}),1e3);return yield new Promise(d=>setTimeout(d,zs)),clearInterval(u),o.stop(),A.remove(),yield this.disconnect(),l})}}class em extends OA{get description(){return"Can publish audio"}perform(){return p(this,void 0,void 0,function*(){var e;const A=yield this.connect(),t=yield Jp();if(yield yl(t,1e3))throw new Error("unable to detect audio from microphone");this.appendMessage("detected audio from microphone"),A.localParticipant.publishTrack(t),yield new Promise(o=>setTimeout(o,3e3));const r=yield(e=t.sender)===null||e===void 0?void 0:e.getStats();if(!r)throw new Error("Could not get RTCStats");let s=0;if(r.forEach(o=>{o.type==="outbound-rtp"&&(o.kind==="audio"||!o.kind&&o.mediaType==="audio")&&(s=o.packetsSent)}),s===0)throw new Error("Could not determine packets are sent");this.appendMessage("published ".concat(s," audio packets"))})}}class Am extends OA{get description(){return"Can publish video"}perform(){return p(this,void 0,void 0,function*(){var e;const A=yield this.connect(),t=yield jp();yield this.checkForVideo(t.mediaStreamTrack),A.localParticipant.publishTrack(t),yield new Promise(s=>setTimeout(s,5e3));const i=yield(e=t.sender)===null||e===void 0?void 0:e.getStats();if(!i)throw new Error("Could not get RTCStats");let r=0;if(i.forEach(s=>{s.type==="outbound-rtp"&&(s.kind==="video"||!s.kind&&s.mediaType==="video")&&(r+=s.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 A=new MediaStream;A.addTrack(e.clone());const t=document.createElement("video");t.srcObject=A,t.muted=!0,yield new Promise(i=>{t.onplay=()=>{setTimeout(()=>{var r,s,o,a;const c=document.createElement("canvas"),l=e.getSettings(),u=(s=(r=l.width)!==null&&r!==void 0?r:t.videoWidth)!==null&&s!==void 0?s:1280,d=(a=(o=l.height)!==null&&o!==void 0?o:t.videoHeight)!==null&&a!==void 0?a:720;c.width=u,c.height=d;const h=c.getContext("2d");h.drawImage(t,0,0);const g=h.getImageData(0,0,c.width,c.height).data;let m=!0;for(let C=0;C<g.length;C+=4)if(g[C]!==0||g[C+1]!==0||g[C+2]!==0){m=!1;break}m?this.appendError("camera appears to be producing only black frames"):this.appendMessage("received video frames"),i()},1e3)},t.play()}),t.remove()})}}class tm extends OA{get description(){return"Resuming connection after interruption"}perform(){return p(this,void 0,void 0,function*(){var e;const A=yield this.connect();let t=!1,i=!1,r;const s=new Promise(c=>{setTimeout(c,5e3),r=c}),o=()=>{t=!0};A.on(T.SignalReconnecting,o).on(T.Reconnecting,o).on(T.Reconnected,()=>{i=!0,r(!0)}),(e=A.engine.client.ws)===null||e===void 0||e.close();const a=A.engine.client.onClose;if(a&&a(""),yield s,t){if(!i||A.state!==W.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 nm extends OA{get description(){return"Can connect via TURN"}perform(){return p(this,void 0,void 0,function*(){var e,A;const t=new Ls,i=yield t.join(this.url,this.token,{autoSubscribe:!0,maxRetries:0,e2eeEnabled:!1,websocketTimeout:15e3});let r=!1,s=!1,o=!1;for(let a of i.iceServers)for(let c of a.urls)c.startsWith("turn:")?(s=!0,o=!0):c.startsWith("turns:")&&(s=!0,o=!0,r=!0),c.startsWith("stun:")&&(o=!0);o?s&&!r&&this.appendWarning("TURN is configured server side, but TURN/TLS is unavailable."):this.appendWarning("No STUN servers configured on server side."),yield t.close(),!((A=(e=this.connectOptions)===null||e===void 0?void 0:e.rtcConfig)===null||A===void 0)&&A.iceServers||s?yield this.room.connect(this.url,this.token,{rtcConfig:{iceTransportPolicy:"relay"}}):(this.appendWarning("No TURN servers configured."),this.skip(),yield new Promise(a=>setTimeout(a,0)))})}}class im extends OA{get description(){return"Establishing WebRTC connection"}perform(){return p(this,void 0,void 0,function*(){let e=!1,A=!1;this.room.on(T.SignalConnected,()=>{const t=this.room.engine.client.onTrickle;this.room.engine.client.onTrickle=(i,r)=>{if(i.candidate){const s=new RTCIceCandidate(i);let o="".concat(s.protocol," ").concat(s.address,":").concat(s.port," ").concat(s.type);s.address&&(rm(s.address)?o+=" (private)":s.protocol==="tcp"&&s.tcpType==="passive"?(e=!0,o+=" (passive)"):s.protocol==="udp"&&(A=!0)),this.appendMessage(o)}t&&t(i,r)},this.room.engine.pcManager&&(this.room.engine.pcManager.subscriber.onIceCandidateError=i=>{i instanceof RTCPeerConnectionIceErrorEvent&&this.appendWarning("error with ICE candidate: ".concat(i.errorCode," ").concat(i.errorText," ").concat(i.url))})});try{yield this.connect(),V.info("now the room is connected")}catch(t){throw this.appendWarning("ports need to be open on firewall in order to connect."),t}e||this.appendWarning("Server is not configured for ICE/TCP"),A||this.appendWarning("No public IPv4 UDP candidates were found. Your server is likely not configured correctly")})}}function rm(n){const e=n.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 A=parseInt(e[1],10);if(A>=16&&A<=31)return!0}}return!1}class sm extends OA{get description(){return"Connecting to signal connection via WebSocket"}perform(){return p(this,void 0,void 0,function*(){var e,A,t;(this.url.startsWith("ws:")||this.url.startsWith("http:"))&&this.appendWarning("Server is insecure, clients may block connections to it");let i=new Ls;const r=yield i.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)===Ac.Cloud&&(!((A=r.serverInfo)===null||A===void 0)&&A.region)&&this.appendMessage("LiveKit Cloud: ".concat((t=r.serverInfo)===null||t===void 0?void 0:t.region)),yield i.close()})}}class zy extends sA.EventEmitter{constructor(e,A){let t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.options={},this.checkResults=new Map,this.url=e,this.token=A,this.options=t}getNextCheckId(){const e=this.checkResults.size;return this.checkResults.set(e,{logs:[],status:eA.IDLE,name:"",description:""}),e}updateCheck(e,A){this.checkResults.set(e,A),this.emit("checkUpdate",e,A)}isSuccess(){return Array.from(this.checkResults.values()).every(e=>e.status!==eA.FAILED)}getResults(){return Array.from(this.checkResults.values())}createAndRunCheck(e){return p(this,void 0,void 0,function*(){const A=this.getNextCheckId(),t=new e(this.url,this.token,this.options),i=s=>{this.updateCheck(A,s)};t.on("update",i);const r=yield t.run();return t.off("update",i),r})}checkWebsocket(){return p(this,void 0,void 0,function*(){return this.createAndRunCheck(sm)})}checkWebRTC(){return p(this,void 0,void 0,function*(){return this.createAndRunCheck(im)})}checkTURN(){return p(this,void 0,void 0,function*(){return this.createAndRunCheck(nm)})}checkReconnect(){return p(this,void 0,void 0,function*(){return this.createAndRunCheck(tm)})}checkPublishAudio(){return p(this,void 0,void 0,function*(){return this.createAndRunCheck(em)})}checkPublishVideo(){return p(this,void 0,void 0,function*(){return this.createAndRunCheck(Am)})}checkConnectionProtocol(){return p(this,void 0,void 0,function*(){const e=yield this.createAndRunCheck(zp);if(e.data&&"protocol"in e.data){const A=e.data;this.options.protocol=A.protocol}return e})}checkCloudRegion(){return p(this,void 0,void 0,function*(){return this.createAndRunCheck(Zp)})}}const xe=Symbol.for("@ts-pattern/matcher"),zl=Symbol.for("@ts-pattern/isVariadic"),Ri="@ts-pattern/anonymous-select-key",eo=n=>!!(n&&typeof n=="object"),xi=n=>n&&!!n[xe],Ce=(n,e,A)=>{if(xi(n)){const t=n[xe](),{matched:i,selections:r}=t.match(e);return i&&r&&Object.keys(r).forEach(s=>A(s,r[s])),i}if(eo(n)){if(!eo(e))return!1;if(Array.isArray(n)){if(!Array.isArray(e))return!1;let t=[],i=[],r=[];for(const s of n.keys()){const o=n[s];xi(o)&&o[zl]?r.push(o):r.length?i.push(o):t.push(o)}if(r.length){if(r.length>1)throw new Error("Pattern error: Using `...P.array(...)` several times in a single pattern is not allowed.");if(e.length<t.length+i.length)return!1;const s=e.slice(0,t.length),o=i.length===0?[]:e.slice(-i.length),a=e.slice(t.length,i.length===0?1/0:-i.length);return t.every((c,l)=>Ce(c,s[l],A))&&i.every((c,l)=>Ce(c,o[l],A))&&(r.length===0||Ce(r[0],a,A))}return n.length===e.length&&n.every((s,o)=>Ce(s,e[o],A))}return Reflect.ownKeys(n).every(t=>{const i=n[t];return(t in e||xi(r=i)&&r[xe]().matcherType==="optional")&&Ce(i,e[t],A);var r})}return Object.is(e,n)},Oe=n=>{var e,A,t;return eo(n)?xi(n)?(e=(A=(t=n[xe]()).getSelectionKeys)==null?void 0:A.call(t))!=null?e:[]:Array.isArray(n)?Bn(n,Oe):Bn(Object.values(n),Oe):[]},Bn=(n,e)=>n.reduce((A,t)=>A.concat(e(t)),[]);function om(...n){if(n.length===1){const[e]=n;return A=>Ce(e,A,()=>{})}if(n.length===2){const[e,A]=n;return Ce(e,A,()=>{})}throw new Error(`isMatching wasn't given the right number of arguments: expected 1 or 2, received ${n.length}.`)}function we(n){return Object.assign(n,{optional:()=>to(n),and:e=>te(n,e),or:e=>eu(n,e),select:e=>e===void 0?vn(n):vn(e,n)})}function Ao(n){return Object.assign((e=>Object.assign(e,{[Symbol.iterator](){let A=0;const t=[{value:Object.assign(e,{[zl]:!0}),done:!1},{done:!0,value:void 0}];return{next:()=>{var i;return(i=t[A++])!=null?i:t.at(-1)}}}}))(n),{optional:()=>Ao(to(n)),select:e=>Ao(e===void 0?vn(n):vn(e,n))})}function to(n){return we({[xe]:()=>({match:e=>{let A={};const t=(i,r)=>{A[i]=r};return e===void 0?(Oe(n).forEach(i=>t(i,void 0)),{matched:!0,selections:A}):{matched:Ce(n,e,t),selections:A}},getSelectionKeys:()=>Oe(n),matcherType:"optional"})})}const am=(n,e)=>{for(const A of n)if(!e(A))return!1;return!0},cm=(n,e)=>{for(const[A,t]of n.entries())if(!e(t,A))return!1;return!0};function te(...n){return we({[xe]:()=>({match:e=>{let A={};const t=(i,r)=>{A[i]=r};return{matched:n.every(i=>Ce(i,e,t)),selections:A}},getSelectionKeys:()=>Bn(n,Oe),matcherType:"and"})})}function eu(...n){return we({[xe]:()=>({match:e=>{let A={};const t=(i,r)=>{A[i]=r};return Bn(n,Oe).forEach(i=>t(i,void 0)),{matched:n.some(i=>Ce(i,e,t)),selections:A}},getSelectionKeys:()=>Bn(n,Oe),matcherType:"or"})})}function j(n){return{[xe]:()=>({match:e=>({matched:!!n(e)})})}}function vn(...n){const e=typeof n[0]=="string"?n[0]:void 0,A=n.length===2?n[1]:typeof n[0]=="string"?void 0:n[0];return we({[xe]:()=>({match:t=>{let i={[e??Ri]:t};return{matched:A===void 0||Ce(A,t,(r,s)=>{i[r]=s}),selections:i}},getSelectionKeys:()=>[e??Ri].concat(A===void 0?[]:Oe(A))})})}function aA(n){return typeof n=="number"}function MA(n){return typeof n=="string"}function NA(n){return typeof n=="bigint"}const Au=we(j(function(n){return!0})),lm=Au,KA=n=>Object.assign(we(n),{startsWith:e=>{return KA(te(n,(A=e,j(t=>MA(t)&&t.startsWith(A)))));var A},endsWith:e=>{return KA(te(n,(A=e,j(t=>MA(t)&&t.endsWith(A)))));var A},minLength:e=>KA(te(n,(A=>j(t=>MA(t)&&t.length>=A))(e))),length:e=>KA(te(n,(A=>j(t=>MA(t)&&t.length===A))(e))),maxLength:e=>KA(te(n,(A=>j(t=>MA(t)&&t.length<=A))(e))),includes:e=>{return KA(te(n,(A=e,j(t=>MA(t)&&t.includes(A)))));var A},regex:e=>{return KA(te(n,(A=e,j(t=>MA(t)&&!!t.match(A)))));var A}}),um=KA(j(MA)),cA=n=>Object.assign(we(n),{between:(e,A)=>cA(te(n,((t,i)=>j(r=>aA(r)&&t<=r&&i>=r))(e,A))),lt:e=>cA(te(n,(A=>j(t=>aA(t)&&t<A))(e))),gt:e=>cA(te(n,(A=>j(t=>aA(t)&&t>A))(e))),lte:e=>cA(te(n,(A=>j(t=>aA(t)&&t<=A))(e))),gte:e=>cA(te(n,(A=>j(t=>aA(t)&&t>=A))(e))),int:()=>cA(te(n,j(e=>aA(e)&&Number.isInteger(e)))),finite:()=>cA(te(n,j(e=>aA(e)&&Number.isFinite(e)))),positive:()=>cA(te(n,j(e=>aA(e)&&e>0))),negative:()=>cA(te(n,j(e=>aA(e)&&e<0)))}),dm=cA(j(aA)),VA=n=>Object.assign(we(n),{between:(e,A)=>VA(te(n,((t,i)=>j(r=>NA(r)&&t<=r&&i>=r))(e,A))),lt:e=>VA(te(n,(A=>j(t=>NA(t)&&t<A))(e))),gt:e=>VA(te(n,(A=>j(t=>NA(t)&&t>A))(e))),lte:e=>VA(te(n,(A=>j(t=>NA(t)&&t<=A))(e))),gte:e=>VA(te(n,(A=>j(t=>NA(t)&&t>=A))(e))),positive:()=>VA(te(n,j(e=>NA(e)&&e>0))),negative:()=>VA(te(n,j(e=>NA(e)&&e<0)))}),hm=VA(j(NA)),fm=we(j(function(n){return typeof n=="boolean"})),gm=we(j(function(n){return typeof n=="symbol"})),pm=we(j(function(n){return n==null})),mm=we(j(function(n){return n!=null}));var Bm={__proto__:null,matcher:xe,optional:to,array:function(...n){return Ao({[xe]:()=>({match:e=>{if(!Array.isArray(e))return{matched:!1};if(n.length===0)return{matched:!0};const A=n[0];let t={};if(e.length===0)return Oe(A).forEach(r=>{t[r]=[]}),{matched:!0,selections:t};const i=(r,s)=>{t[r]=(t[r]||[]).concat([s])};return{matched:e.every(r=>Ce(A,r,i)),selections:t}},getSelectionKeys:()=>n.length===0?[]:Oe(n[0])})})},set:function(...n){return we({[xe]:()=>({match:e=>{if(!(e instanceof Set))return{matched:!1};let A={};if(e.size===0)return{matched:!0,selections:A};if(n.length===0)return{matched:!0};const t=(r,s)=>{A[r]=(A[r]||[]).concat([s])},i=n[0];return{matched:am(e,r=>Ce(i,r,t)),selections:A}},getSelectionKeys:()=>n.length===0?[]:Oe(n[0])})})},map:function(...n){return we({[xe]:()=>({match:e=>{if(!(e instanceof Map))return{matched:!1};let A={};if(e.size===0)return{matched:!0,selections:A};const t=(o,a)=>{A[o]=(A[o]||[]).concat([a])};if(n.length===0)return{matched:!0};var i;if(n.length===1)throw new Error(`\`P.map\` wasn't given enough arguments. Expected (key, value), received ${(i=n[0])==null?void 0:i.toString()}`);const[r,s]=n;return{matched:cm(e,(o,a)=>{const c=Ce(r,a,t),l=Ce(s,o,t);return c&&l}),selections:A}},getSelectionKeys:()=>n.length===0?[]:[...Oe(n[0]),...Oe(n[1])]})})},intersection:te,union:eu,not:function(n){return we({[xe]:()=>({match:e=>({matched:!Ce(n,e,()=>{})}),getSelectionKeys:()=>[],matcherType:"not"})})},when:j,select:vn,any:Au,_:lm,string:um,number:dm,bigint:hm,boolean:fm,symbol:gm,nullish:pm,nonNullable:mm,instanceOf:function(n){return we(j(function(e){return A=>A instanceof e}(n)))},shape:function(n){return we(j(om(n)))}};class vm extends Error{constructor(e){let A;try{A=JSON.stringify(e)}catch{A=e}super(`Pattern matching error: no pattern matches value ${A}`),this.input=void 0,this.input=e}}const no={matched:!1,value:void 0};function Pi(n){return new Cm(n,no)}let Cm=class da{constructor(e,A){this.input=void 0,this.state=void 0,this.input=e,this.state=A}with(...e){if(this.state.matched)return this;const A=e[e.length-1],t=[e[0]];let i;e.length===3&&typeof e[1]=="function"?i=e[1]:e.length>2&&t.push(...e.slice(1,e.length-1));let r=!1,s={};const o=(c,l)=>{r=!0,s[c]=l},a=!t.some(c=>Ce(c,this.input,o))||i&&!i(this.input)?no:{matched:!0,value:A(r?Ri in s?s[Ri]:s:this.input,this.input)};return new da(this.input,a)}when(e,A){if(this.state.matched)return this;const t=!!e(this.input);return new da(this.input,t?{matched:!0,value:A(this.input,this.input)}:no)}otherwise(e){return this.state.matched?this.state.value:e(this.input)}exhaustive(e=wm){return this.state.matched?this.state.value:e(this.input)}run(){return this.exhaustive()}returnType(){return this}};function wm(n){throw new vm(n)}const ym="https://obi.getcor.io/api";var O;(function(n){n.READY="ready",n.ERROR="error",n.PAUSED="paused",n.LOADING="loading",n.THINKING="thinking",n.RESEARCHING="researching",n.AGENT_SPEAKING="agent_speaking",n.USER_SPEAKING="user_speaking",n.AWAITING_USER_INPUT="awaiting_user_input"})(O||(O={}));class tu{constructor({sessionId:e,apiBaseUrl:A}){this.currentState=O.READY,this.assistantAudioContext=null,this.userAudioContext=null,this._assistantAudioTimer=null,this._userAudioTimer=null,this.sessionId=e,this.apiBaseUrl=A||ym,this.emitter=new Eh}emit(e,A){this.emitter.emit(e,A)}on(e,A){this.emitter.on(e,A)}off(e,A){this.emitter.off(e,A)}setupRoomEventListeners(){this.room&&(this.room.on(T.LocalTrackUnpublished,e=>{e.source===Q.Source.ScreenShare&&(this.screenStream=void 0)}),this.room.on(T.Disconnected,()=>{console.log("Room disconnected"),this.disconnect()}),this.room.on(T.ParticipantDisconnected,()=>{this.disconnect()}),this.room.on(T.TrackSubscribed,(e,A,t)=>{if(e.kind==="audio"&&e.attach(),e.source===Q.Source.Microphone&&t.identity.includes("agent-")){const i=e.mediaStream;if(!i){console.error("No media stream available for assistant track");return}const r=new AudioContext,s=r.createAnalyser();r.createMediaStreamSource(i).connect(s),s.fftSize=2048;const a=new Uint8Array(s.frequencyBinCount);this.analyzeAudio(s,a,"ASSISTANT"),this.assistantAudioContext=r}}),this.room.on(T.ParticipantAttributesChanged,e=>{if(!e["lk.agent.state"]||this.currentState===O.RESEARCHING||this.currentState===O.PAUSED)return;const A=e["lk.agent.state"],t=Pi(A).with("listening",()=>O.USER_SPEAKING).with("speaking",()=>O.AGENT_SPEAKING).with("thinking",()=>O.AGENT_SPEAKING).otherwise(()=>{});t&&this.setState(t)}),this.room.on(T.DataReceived,async e=>{try{const A=JSON.parse(new TextDecoder().decode(e)),t=A.status||A.request;Pi(t).with("using_tool",()=>{this.currentState=O.RESEARCHING,this.emitter.emit("stateChanged",O.RESEARCHING)}).with("using_tool_ended",()=>{this.currentState=O.AGENT_SPEAKING,this.emitter.emit("stateChanged",O.AGENT_SPEAKING)}).with("share_screen",()=>{this.shareScreen()}).with("prompt_user",()=>{this.promptContinue()}).with("capture_page_html",()=>{this.emitter.emit("capturePageHTML")}).with("fill",()=>{this.emitter.emit("fill",A.value)}).otherwise(()=>{console.warn("Unknown data received:",A)})}catch(A){console.error("Error parsing data:",A)}}),this.room.localParticipant.registerRpcMethod("screen_capture",async e=>(this.emitter.emit("screenCaptureRequested"),new Promise(A=>{this.emitter.once("screenCaptureComplete",async t=>{if(t==="error"){A("error");return}try{await this.room.localParticipant.sendFile(new File([t],"screen_capture.png",{type:"image/png"}),{mimeType:"image/png",topic:"screen_capture"}),A("ok")}catch{A("error")}})}))))}async connect(){if(!this.sessionId){console.error("No session ID found"),this.emitter.emit("error",new Error("No session ID provided"));return}try{await this.requestMicrophone(),this.room=new dt({adaptiveStream:!0,dynacast:!0}),this.setupRoomEventListeners();const e=new URLSearchParams({token:this.sessionId,skip_intro:"true"}),A=`${this.apiBaseUrl}/join-token?${e.toString()}`,t=await fetch(A).then(i=>i.json());if(await this.room.connect(t.url,t.token),this.microphoneStream){const i=this.microphoneStream.getAudioTracks()[0];await this.room.localParticipant.publishTrack(i,{name:"microphone",source:Q.Source.Microphone})}return{url:t.url,token:t.token}}catch(e){throw console.error("Failed to connect to LiveKit:",e),this.disconnect(),this.emitter.emit("error",e instanceof Error?e:new Error(String(e))),e}}async disconnect(){var e,A,t;this.room&&(this.room.disconnect(!0),this.room.removeAllListeners(),this.room=void 0),(e=this.screenStream)!=null&&e.track&&this.screenStream.track.stop(),this.microphoneStream&&this.microphoneStream.getTracks().forEach(i=>i.stop()),this._userAudioTimer&&(window.clearTimeout(this._userAudioTimer),this._userAudioTimer=null),this._assistantAudioTimer&&(window.clearTimeout(this._assistantAudioTimer),this._assistantAudioTimer=null),await((A=this.userAudioContext)==null?void 0:A.close().catch(()=>{})),this.userAudioContext=null,await((t=this.assistantAudioContext)==null?void 0:t.close().catch(()=>{})),this.assistantAudioContext=null,this.setState(O.READY)}setState(e){e!==this.currentState&&(this.currentState=e,this.emitter.emit("stateChanged",e))}async requestMicrophone(){try{const e=await navigator.mediaDevices.getUserMedia({audio:!0});this.microphoneStream=e;const A=new AudioContext;this.userAudioContext=A;const t=A.createAnalyser(),i=A.createMediaStreamSource(e),r=A.createGain();r.gain.value=1.5,i.connect(r),r.connect(t),t.fftSize=2048;const s=new Uint8Array(t.frequencyBinCount);this.analyzeAudio(t,s,"USER")}catch(e){throw console.error("Microphone permission denied:",e),new Error("Microphone permission denied")}}async shareScreen(){if(!this.room){console.warn("[obi] shareScreen called while not connected");return}this.emitter.emit("preScreenShare");try{if(this.screenStream=await this.room.localParticipant.setScreenShareEnabled(!0,{video:{displaySurface:"window"}}),!this.screenStream){console.warn("Failed to share screen");return}await this.room.localParticipant.publishData(new TextEncoder().encode(JSON.stringify({request:"share_screen",success:!0})),{reliable:!0})}catch(e){console.error("Error sharing screen:",e),this.emitter.emit("error",e instanceof Error?e:new Error(String(e)))}}pauseRecording(){var e,A,t;this.room&&(this.setState(O.PAUSED),this.room.localParticipant.getTrackPublications().forEach(i=>{var r,s;i.handleMuted(),(s=(r=i.track)==null?void 0:r.mediaStream)==null||s.getTracks().forEach(o=>o.enabled=!1)}),(e=this.microphoneStream)==null||e.getTracks().forEach(i=>i.enabled=!1),(t=(A=this.screenStream)==null?void 0:A.track)==null||t.mute())}resumeRecording(){var e,A,t;this.room&&(this.setState(O.USER_SPEAKING),this.room.localParticipant.getTrackPublications().forEach(i=>{var r,s;i.handleUnmuted(),(s=(r=i.track)==null?void 0:r.mediaStream)==null||s.getTracks().forEach(o=>o.enabled=!0)}),(e=this.microphoneStream)==null||e.getTracks().forEach(i=>i.enabled=!0),(t=(A=this.screenStream)==null?void 0:A.track)==null||t.unmute())}async promptContinue(){await this.room.localParticipant.publishData(new TextEncoder().encode(JSON.stringify({request:"prompt_user",success:!0})),{reliable:!0})}async analyzeAudio(e,A,t){if(t==="USER"&&this.currentState===O.USER_SPEAKING||t==="ASSISTANT"&&this.currentState===O.AGENT_SPEAKING){e.getByteFrequencyData(A);const i=A.reduce((o,a)=>o+a,0)/A.length,r=Math.max(.01,Math.min(1,i/128));let s;t==="USER"&&this.currentState===O.USER_SPEAKING?s="USER":t==="ASSISTANT"&&this.currentState===O.AGENT_SPEAKING&&(s="ASSISTANT"),s&&this.emitter.emit("volume",{speaker:s,spectrum:Array.from(A),volume:r})}t==="USER"?this._userAudioTimer=window.setTimeout(()=>this.analyzeAudio(e,A,t),200):this._assistantAudioTimer=window.setTimeout(()=>this.analyzeAudio(e,A,t),200)}async sendHTML(e){if(!this.room){console.log("Cannot send HTML: Not connected to room");return}try{const A={type:"page_content",html:e,timestamp:new Date().toISOString()},t=JSON.stringify(A),r=new TextEncoder().encode(t);await this.room.localParticipant.publishData(r,{reliable:!0})}catch(A){console.error("Error sending HTML to LiveKit:",A),this.emitter.emit("error",A instanceof Error?A:new Error(String(A)))}}async reconnect(e,A,t){try{if(!e||!A)return console.error("Missing room URL or token for reconnection"),this.emitter.emit("error",new Error("Missing room URL or token for reconnection")),!1;if(await this.requestMicrophone(),this.room=new dt({adaptiveStream:!0,dynacast:!0}),this.setupRoomEventListeners(),await this.room.connect(e,A),this.microphoneStream){const i=this.microphoneStream.getAudioTracks()[0];await this.room.localParticipant.publishTrack(i,{name:"microphone",source:Q.Source.Microphone})}return this.setState(t),t===O.PAUSED&&this.pauseRecording(),!0}catch(i){return console.error("Failed to reconnect to room:",i),this.disconnect(),this.emitter.emit("error",i instanceof Error?i:new Error(String(i))),!1}}}/*!
39
+ * html2canvas 1.4.1 <https://html2canvas.hertzen.com>
40
+ * Copyright (c) 2022 Niklas von Hertzen <https://hertzen.com>
41
+ * Released under MIT License
42
+ *//*! *****************************************************************************
43
+ Copyright (c) Microsoft Corporation.
44
+
45
+ Permission to use, copy, modify, and/or distribute this software for any
46
+ purpose with or without fee is hereby granted.
47
+
48
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
49
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
50
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
51
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
52
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
53
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
54
+ PERFORMANCE OF THIS SOFTWARE.
55
+ ***************************************************************************** */var io=function(n,e){return io=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(A,t){A.__proto__=t}||function(A,t){for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&(A[i]=t[i])},io(n,e)};function AA(n,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");io(n,e);function A(){this.constructor=n}n.prototype=e===null?Object.create(e):(A.prototype=e.prototype,new A)}var ro=function(){return ro=Object.assign||function(e){for(var A,t=1,i=arguments.length;t<i;t++){A=arguments[t];for(var r in A)Object.prototype.hasOwnProperty.call(A,r)&&(e[r]=A[r])}return e},ro.apply(this,arguments)};function Ee(n,e,A,t){function i(r){return r instanceof A?r:new A(function(s){s(r)})}return new(A||(A=Promise))(function(r,s){function o(l){try{c(t.next(l))}catch(u){s(u)}}function a(l){try{c(t.throw(l))}catch(u){s(u)}}function c(l){l.done?r(l.value):i(l.value).then(o,a)}c((t=t.apply(n,e||[])).next())})}function Ue(n,e){var A={label:0,sent:function(){if(r[0]&1)throw r[1];return r[1]},trys:[],ops:[]},t,i,r,s;return s={next:o(0),throw:o(1),return:o(2)},typeof Symbol=="function"&&(s[Symbol.iterator]=function(){return this}),s;function o(c){return function(l){return a([c,l])}}function a(c){if(t)throw new TypeError("Generator is already executing.");for(;A;)try{if(t=1,i&&(r=c[0]&2?i.return:c[0]?i.throw||((r=i.return)&&r.call(i),0):i.next)&&!(r=r.call(i,c[1])).done)return r;switch(i=0,r&&(c=[c[0]&2,r.value]),c[0]){case 0:case 1:r=c;break;case 4:return A.label++,{value:c[1],done:!1};case 5:A.label++,i=c[1],c=[0];continue;case 7:c=A.ops.pop(),A.trys.pop();continue;default:if(r=A.trys,!(r=r.length>0&&r[r.length-1])&&(c[0]===6||c[0]===2)){A=0;continue}if(c[0]===3&&(!r||c[1]>r[0]&&c[1]<r[3])){A.label=c[1];break}if(c[0]===6&&A.label<r[1]){A.label=r[1],r=c;break}if(r&&A.label<r[2]){A.label=r[2],A.ops.push(c);break}r[2]&&A.ops.pop(),A.trys.pop();continue}c=e.call(n,A)}catch(l){c=[6,l],i=0}finally{t=r=0}if(c[0]&5)throw c[1];return{value:c[0]?c[1]:void 0,done:!0}}}function Li(n,e,A){if(A||arguments.length===2)for(var t=0,i=e.length,r;t<i;t++)(r||!(t in e))&&(r||(r=Array.prototype.slice.call(e,0,t)),r[t]=e[t]);return n.concat(r||e)}for(var CA=function(){function n(e,A,t,i){this.left=e,this.top=A,this.width=t,this.height=i}return n.prototype.add=function(e,A,t,i){return new n(this.left+e,this.top+A,this.width+t,this.height+i)},n.fromClientRect=function(e,A){return new n(A.left+e.windowBounds.left,A.top+e.windowBounds.top,A.width,A.height)},n.fromDOMRectList=function(e,A){var t=Array.from(A).find(function(i){return i.width!==0});return t?new n(t.left+e.windowBounds.left,t.top+e.windowBounds.top,t.width,t.height):n.EMPTY},n.EMPTY=new n(0,0,0,0),n}(),Di=function(n,e){return CA.fromClientRect(n,e.getBoundingClientRect())},bm=function(n){var e=n.body,A=n.documentElement;if(!e||!A)throw new Error("Unable to get document size");var t=Math.max(Math.max(e.scrollWidth,A.scrollWidth),Math.max(e.offsetWidth,A.offsetWidth),Math.max(e.clientWidth,A.clientWidth)),i=Math.max(Math.max(e.scrollHeight,A.scrollHeight),Math.max(e.offsetHeight,A.offsetHeight),Math.max(e.clientHeight,A.clientHeight));return new CA(0,0,t,i)},_i=function(n){for(var e=[],A=0,t=n.length;A<t;){var i=n.charCodeAt(A++);if(i>=55296&&i<=56319&&A<t){var r=n.charCodeAt(A++);(r&64512)===56320?e.push(((i&1023)<<10)+(r&1023)+65536):(e.push(i),A--)}else e.push(i)}return e},le=function(){for(var n=[],e=0;e<arguments.length;e++)n[e]=arguments[e];if(String.fromCodePoint)return String.fromCodePoint.apply(String,n);var A=n.length;if(!A)return"";for(var t=[],i=-1,r="";++i<A;){var s=n[i];s<=65535?t.push(s):(s-=65536,t.push((s>>10)+55296,s%1024+56320)),(i+1===A||t.length>16384)&&(r+=String.fromCharCode.apply(String,t),t.length=0)}return r},nu="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Um=typeof Uint8Array>"u"?[]:new Uint8Array(256),Hi=0;Hi<nu.length;Hi++)Um[nu.charCodeAt(Hi)]=Hi;for(var iu="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Cn=typeof Uint8Array>"u"?[]:new Uint8Array(256),Oi=0;Oi<iu.length;Oi++)Cn[iu.charCodeAt(Oi)]=Oi;for(var Qm=function(n){var e=n.length*.75,A=n.length,t,i=0,r,s,o,a;n[n.length-1]==="="&&(e--,n[n.length-2]==="="&&e--);var c=typeof ArrayBuffer<"u"&&typeof Uint8Array<"u"&&typeof Uint8Array.prototype.slice<"u"?new ArrayBuffer(e):new Array(e),l=Array.isArray(c)?c:new Uint8Array(c);for(t=0;t<A;t+=4)r=Cn[n.charCodeAt(t)],s=Cn[n.charCodeAt(t+1)],o=Cn[n.charCodeAt(t+2)],a=Cn[n.charCodeAt(t+3)],l[i++]=r<<2|s>>4,l[i++]=(s&15)<<4|o>>2,l[i++]=(o&3)<<6|a&63;return c},Em=function(n){for(var e=n.length,A=[],t=0;t<e;t+=2)A.push(n[t+1]<<8|n[t]);return A},Sm=function(n){for(var e=n.length,A=[],t=0;t<e;t+=4)A.push(n[t+3]<<24|n[t+2]<<16|n[t+1]<<8|n[t]);return A},ht=5,so=6+5,oo=2,Tm=so-ht,ru=65536>>ht,Fm=1<<ht,ao=Fm-1,km=1024>>ht,Im=ru+km,Rm=Im,xm=32,Pm=Rm+xm,Lm=65536>>so,Dm=1<<Tm,_m=Dm-1,su=function(n,e,A){return n.slice?n.slice(e,A):new Uint16Array(Array.prototype.slice.call(n,e,A))},Hm=function(n,e,A){return n.slice?n.slice(e,A):new Uint32Array(Array.prototype.slice.call(n,e,A))},Om=function(n,e){var A=Qm(n),t=Array.isArray(A)?Sm(A):new Uint32Array(A),i=Array.isArray(A)?Em(A):new Uint16Array(A),r=24,s=su(i,r/2,t[4]/2),o=t[5]===2?su(i,(r+t[4])/2):Hm(t,Math.ceil((r+t[4])/4));return new Mm(t[0],t[1],t[2],t[3],s,o)},Mm=function(){function n(e,A,t,i,r,s){this.initialValue=e,this.errorValue=A,this.highStart=t,this.highValueIndex=i,this.index=r,this.data=s}return n.prototype.get=function(e){var A;if(e>=0){if(e<55296||e>56319&&e<=65535)return A=this.index[e>>ht],A=(A<<oo)+(e&ao),this.data[A];if(e<=65535)return A=this.index[ru+(e-55296>>ht)],A=(A<<oo)+(e&ao),this.data[A];if(e<this.highStart)return A=Pm-Lm+(e>>so),A=this.index[A],A+=e>>ht&_m,A=this.index[A],A=(A<<oo)+(e&ao),this.data[A];if(e<=1114111)return this.data[this.highValueIndex]}return this.errorValue},n}(),ou="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Nm=typeof Uint8Array>"u"?[]:new Uint8Array(256),Mi=0;Mi<ou.length;Mi++)Nm[ou.charCodeAt(Mi)]=Mi;var Km="KwAAAAAAAAAACA4AUD0AADAgAAACAAAAAAAIABAAGABAAEgAUABYAGAAaABgAGgAYgBqAF8AZwBgAGgAcQB5AHUAfQCFAI0AlQCdAKIAqgCyALoAYABoAGAAaABgAGgAwgDKAGAAaADGAM4A0wDbAOEA6QDxAPkAAQEJAQ8BFwF1AH0AHAEkASwBNAE6AUIBQQFJAVEBWQFhAWgBcAF4ATAAgAGGAY4BlQGXAZ8BpwGvAbUBvQHFAc0B0wHbAeMB6wHxAfkBAQIJAvEBEQIZAiECKQIxAjgCQAJGAk4CVgJeAmQCbAJ0AnwCgQKJApECmQKgAqgCsAK4ArwCxAIwAMwC0wLbAjAA4wLrAvMC+AIAAwcDDwMwABcDHQMlAy0DNQN1AD0DQQNJA0kDSQNRA1EDVwNZA1kDdQB1AGEDdQBpA20DdQN1AHsDdQCBA4kDkQN1AHUAmQOhA3UAdQB1AHUAdQB1AHUAdQB1AHUAdQB1AHUAdQB1AHUAdQB1AKYDrgN1AHUAtgO+A8YDzgPWAxcD3gPjA+sD8wN1AHUA+wMDBAkEdQANBBUEHQQlBCoEFwMyBDgEYABABBcDSARQBFgEYARoBDAAcAQzAXgEgASIBJAEdQCXBHUAnwSnBK4EtgS6BMIEyAR1AHUAdQB1AHUAdQCVANAEYABgAGAAYABgAGAAYABgANgEYADcBOQEYADsBPQE/AQEBQwFFAUcBSQFLAU0BWQEPAVEBUsFUwVbBWAAYgVgAGoFcgV6BYIFigWRBWAAmQWfBaYFYABgAGAAYABgAKoFYACxBbAFuQW6BcEFwQXHBcEFwQXPBdMF2wXjBeoF8gX6BQIGCgYSBhoGIgYqBjIGOgZgAD4GRgZMBmAAUwZaBmAAYABgAGAAYABgAGAAYABgAGAAYABgAGIGYABpBnAGYABgAGAAYABgAGAAYABgAGAAYAB4Bn8GhQZgAGAAYAB1AHcDFQSLBmAAYABgAJMGdQA9A3UAmwajBqsGqwaVALMGuwbDBjAAywbSBtIG1QbSBtIG0gbSBtIG0gbdBuMG6wbzBvsGAwcLBxMHAwcbByMHJwcsBywHMQcsB9IGOAdAB0gHTgfSBkgHVgfSBtIG0gbSBtIG0gbSBtIG0gbSBiwHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAdgAGAALAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAdbB2MHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsB2kH0gZwB64EdQB1AHUAdQB1AHUAdQB1AHUHfQdgAIUHjQd1AHUAlQedB2AAYAClB6sHYACzB7YHvgfGB3UAzgfWBzMB3gfmB1EB7gf1B/0HlQENAQUIDQh1ABUIHQglCBcDLQg1CD0IRQhNCEEDUwh1AHUAdQBbCGMIZAhlCGYIZwhoCGkIYwhkCGUIZghnCGgIaQhjCGQIZQhmCGcIaAhpCGMIZAhlCGYIZwhoCGkIYwhkCGUIZghnCGgIaQhjCGQIZQhmCGcIaAhpCGMIZAhlCGYIZwhoCGkIYwhkCGUIZghnCGgIaQhjCGQIZQhmCGcIaAhpCGMIZAhlCGYIZwhoCGkIYwhkCGUIZghnCGgIaQhjCGQIZQhmCGcIaAhpCGMIZAhlCGYIZwhoCGkIYwhkCGUIZghnCGgIaQhjCGQIZQhmCGcIaAhpCGMIZAhlCGYIZwhoCGkIYwhkCGUIZghnCGgIaQhjCGQIZQhmCGcIaAhpCGMIZAhlCGYIZwhoCGkIYwhkCGUIZghnCGgIaQhjCGQIZQhmCGcIaAhpCGMIZAhlCGYIZwhoCGkIYwhkCGUIZghnCGgIaQhjCGQIZQhmCGcIaAhpCGMIZAhlCGYIZwhoCGkIYwhkCGUIZghnCGgIaQhjCGQIZQhmCGcIaAhpCGMIZAhlCGYIZwhoCGkIYwhkCGUIZghnCGgIaQhjCGQIZQhmCGcIaAhpCGMIZAhlCGYIZwhoCGkIYwhkCGUIZghnCGgIaQhjCGQIZQhmCGcIaAhpCGMIZAhlCGYIZwhoCGkIYwhkCGUIZghnCGgIaQhjCGQIZQhmCGcIaAhpCGMIZAhlCGYIZwhoCGkIYwhkCGUIZghnCGgIaQhjCGQIZQhmCGcIaAhpCGMIZAhlCGYIZwhoCGkIYwhkCGUIZghnCGgIaQhjCGQIZQhmCGcIaAhpCGMIZAhlCGYIZwhoCGkIYwhkCGUIZghnCGgIaQhjCGQIZQhmCGcIaAhpCGMIZAhlCGYIZwhoCGkIYwhkCGUIZghnCGgIaQhjCGQIZQhmCGcIaAhpCGMIZAhlCGYIZwhoCGkIYwhkCGUIZghnCGgIcAh3CHoIMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwAIIIggiCCIIIggiCCIIIggiCCIIIggiCCIIIggiCCIIIggiCCIIIggiCCIIIggiCCIIIggiCCIIIggiCCIIIgggwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAALAcsBywHLAcsBywHLAcsBywHLAcsB4oILAcsB44I0gaWCJ4Ipgh1AHUAqgiyCHUAdQB1AHUAdQB1AHUAdQB1AHUAtwh8AXUAvwh1AMUIyQjRCNkI4AjoCHUAdQB1AO4I9gj+CAYJDgkTCS0HGwkjCYIIggiCCIIIggiCCIIIggiCCIIIggiCCIIIggiCCIIIggiCCIIIggiCCIIIggiCCIIIggiCCIIIggiCCIIIggiAAIAAAAFAAYABgAGIAXwBgAHEAdQBFAJUAogCyAKAAYABgAEIA4ABGANMA4QDxAMEBDwE1AFwBLAE6AQEBUQF4QkhCmEKoQrhCgAHIQsAB0MLAAcABwAHAAeDC6ABoAHDCwMMAAcABwAHAAdDDGMMAAcAB6MM4wwjDWMNow3jDaABoAGgAaABoAGgAaABoAGgAaABoAGgAaABoAGgAaABoAGgAaABoAEjDqABWw6bDqABpg6gAaABoAHcDvwOPA+gAaABfA/8DvwO/A78DvwO/A78DvwO/A78DvwO/A78DvwO/A78DvwO/A78DvwO/A78DvwO/A78DvwO/A78DpcPAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcAB9cPKwkyCToJMAB1AHUAdQBCCUoJTQl1AFUJXAljCWcJawkwADAAMAAwAHMJdQB2CX4JdQCECYoJjgmWCXUAngkwAGAAYABxAHUApgn3A64JtAl1ALkJdQDACTAAMAAwADAAdQB1AHUAdQB1AHUAdQB1AHUAowYNBMUIMAAwADAAMADICcsJ0wnZCRUE4QkwAOkJ8An4CTAAMAB1AAAKvwh1AAgKDwoXCh8KdQAwACcKLgp1ADYKqAmICT4KRgowADAAdQB1AE4KMAB1AFYKdQBeCnUAZQowADAAMAAwADAAMAAwADAAMAAVBHUAbQowADAAdQC5CXUKMAAwAHwBxAijBogEMgF9CoQKiASMCpQKmgqIBKIKqgquCogEDQG2Cr4KxgrLCjAAMADTCtsKCgHjCusK8Qr5CgELMAAwADAAMAB1AIsECQsRC3UANAEZCzAAMAAwADAAMAB1ACELKQswAHUANAExCzkLdQBBC0kLMABRC1kLMAAwADAAMAAwADAAdQBhCzAAMAAwAGAAYABpC3ELdwt/CzAAMACHC4sLkwubC58Lpwt1AK4Ltgt1APsDMAAwADAAMAAwADAAMAAwAL4LwwvLC9IL1wvdCzAAMADlC+kL8Qv5C/8LSQswADAAMAAwADAAMAAwADAAMAAHDDAAMAAwADAAMAAODBYMHgx1AHUAdQB1AHUAdQB1AHUAdQB1AHUAdQB1AHUAdQB1AHUAdQB1AHUAdQB1AHUAdQB1AHUAdQB1ACYMMAAwADAAdQB1AHUALgx1AHUAdQB1AHUAdQA2DDAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwAHUAdQB1AHUAdQB1AHUAdQB1AHUAdQB1AHUAdQB1AHUAdQB1AD4MdQBGDHUAdQB1AHUAdQB1AEkMdQB1AHUAdQB1AFAMMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwAHUAdQB1AHUAdQB1AHUAdQB1AHUAdQB1AHUAdQBYDHUAdQB1AF8MMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAB1AHUAdQB1AHUAdQB1AHUAdQB1AHUAdQB1AHUAdQB1AHUA+wMVBGcMMAAwAHwBbwx1AHcMfwyHDI8MMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAYABgAJcMMAAwADAAdQB1AJ8MlQClDDAAMACtDCwHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsB7UMLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHdQB1AHUAdQB1AHUAdQB1AHUAdQB1AHUAdQB1AA0EMAC9DDAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAsBywHLAcsBywHLAcsBywHLQcwAMEMyAwsBywHLAcsBywHLAcsBywHLAcsBywHzAwwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwAHUAdQB1ANQM2QzhDDAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMABgAGAAYABgAGAAYABgAOkMYADxDGAA+AwADQYNYABhCWAAYAAODTAAMAAwADAAFg1gAGAAHg37AzAAMAAwADAAYABgACYNYAAsDTQNPA1gAEMNPg1LDWAAYABgAGAAYABgAGAAYABgAGAAUg1aDYsGVglhDV0NcQBnDW0NdQ15DWAAYABgAGAAYABgAGAAYABgAGAAYABgAGAAYABgAGAAlQCBDZUAiA2PDZcNMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAnw2nDTAAMAAwADAAMAAwAHUArw23DTAAMAAwADAAMAAwADAAMAAwADAAMAB1AL8NMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAB1AHUAdQB1AHUAdQDHDTAAYABgAM8NMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAA1w11ANwNMAAwAD0B5A0wADAAMAAwADAAMADsDfQN/A0EDgwOFA4wABsOMAAwADAAMAAwADAAMAAwANIG0gbSBtIG0gbSBtIG0gYjDigOwQUuDsEFMw7SBjoO0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIGQg5KDlIOVg7SBtIGXg5lDm0OdQ7SBtIGfQ6EDooOjQ6UDtIGmg6hDtIG0gaoDqwO0ga0DrwO0gZgAGAAYADEDmAAYAAkBtIGzA5gANIOYADaDokO0gbSBt8O5w7SBu8O0gb1DvwO0gZgAGAAxA7SBtIG0gbSBtIGYABgAGAAYAAED2AAsAUMD9IG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIGFA8sBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAccD9IGLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHJA8sBywHLAcsBywHLAccDywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywPLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAc0D9IG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIGLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAccD9IG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIGFA8sBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHLAcsBywHPA/SBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gbSBtIG0gYUD0QPlQCVAJUAMAAwADAAMACVAJUAlQCVAJUAlQCVAEwPMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAA//8EAAQABAAEAAQABAAEAAQABAANAAMAAQABAAIABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQACgATABcAHgAbABoAHgAXABYAEgAeABsAGAAPABgAHABLAEsASwBLAEsASwBLAEsASwBLABgAGAAeAB4AHgATAB4AUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQABYAGwASAB4AHgAeAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAWAA0AEQAeAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArAAQABAAEAAQABAAFAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAJABYAGgAbABsAGwAeAB0AHQAeAE8AFwAeAA0AHgAeABoAGwBPAE8ADgBQAB0AHQAdAE8ATwAXAE8ATwBPABYAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAB0AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAdAFAAUABQAFAAUABQAFAAUAAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAFAAHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAeAB4AHgAeAFAATwBAAE8ATwBPAEAATwBQAFAATwBQAB4AHgAeAB4AHgAeAB0AHQAdAB0AHgAdAB4ADgBQAFAAUABQAFAAHgAeAB4AHgAeAB4AHgBQAB4AUAAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4ABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAJAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAkACQAJAAkACQAJAAkABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAeAB4AHgAeAFAAHgAeAB4AKwArAFAAUABQAFAAGABQACsAKwArACsAHgAeAFAAHgBQAFAAUAArAFAAKwAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AKwAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4ABAAEAAQABAAEAAQABAAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsAUAAeAB4AHgAeAB4AHgBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAYAA0AKwArAB4AHgAbACsABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQADQAEAB4ABAAEAB4ABAAEABMABAArACsAKwArACsAKwArACsAVgBWAFYAVgBWAFYAVgBWAFYAVgBWAFYAVgBWAFYAVgBWAFYAVgBWAFYAVgBWAFYAVgBWAFYAKwArACsAKwBWAFYAVgBWAB4AHgArACsAKwArACsAKwArACsAKwArACsAHgAeAB4AHgAeAB4AHgAeAB4AGgAaABoAGAAYAB4AHgAEAAQABAAEAAQABAAEAAQABAAEAAQAEwAEACsAEwATAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABABLAEsASwBLAEsASwBLAEsASwBLABoAGQAZAB4AUABQAAQAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQABMAUAAEAAQABAAEAAQABAAEAB4AHgAEAAQABAAEAAQABABQAFAABAAEAB4ABAAEAAQABABQAFAASwBLAEsASwBLAEsASwBLAEsASwBQAFAAUAAeAB4AUAAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AKwAeAFAABABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAABAAEAAQABAAEAAQABAAEAAQABAAEAFAAKwArACsAKwArACsAKwArACsAKwArACsAKwArAEsASwBLAEsASwBLAEsASwBLAEsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAABAAEAAQABAAEAAQABAAEAAQAUABQAB4AHgAYABMAUAArACsABAAbABsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAEAAQABAAEAFAABAAEAAQABAAEAFAABAAEAAQAUAAEAAQABAAEAAQAKwArAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAEAAQABAArACsAHgArAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArAFAAUABQAFAAUABQAFAAUABQAFAAKwArACsAKwArACsAKwArACsAKwArAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAB4ABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAAQABAAEAFAABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQAUAAEAAQABAAEAAQABAAEAFAAUABQAFAAUABQAFAAUABQAFAABAAEAA0ADQBLAEsASwBLAEsASwBLAEsASwBLAB4AUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAEAAQABAArAFAAUABQAFAAUABQAFAAUAArACsAUABQACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwBQAFAAUABQAFAAUABQACsAUAArACsAKwBQAFAAUABQACsAKwAEAFAABAAEAAQABAAEAAQABAArACsABAAEACsAKwAEAAQABABQACsAKwArACsAKwArACsAKwAEACsAKwArACsAUABQACsAUABQAFAABAAEACsAKwBLAEsASwBLAEsASwBLAEsASwBLAFAAUAAaABoAUABQAFAAUABQAEwAHgAbAFAAHgAEACsAKwAEAAQABAArAFAAUABQAFAAUABQACsAKwArACsAUABQACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwBQAFAAUABQAFAAUABQACsAUABQACsAUABQACsAUABQACsAKwAEACsABAAEAAQABAAEACsAKwArACsABAAEACsAKwAEAAQABAArACsAKwAEACsAKwArACsAKwArACsAUABQAFAAUAArAFAAKwArACsAKwArACsAKwBLAEsASwBLAEsASwBLAEsASwBLAAQABABQAFAAUAAEAB4AKwArACsAKwArACsAKwArACsAKwAEAAQABAArAFAAUABQAFAAUABQAFAAUABQACsAUABQAFAAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwBQAFAAUABQAFAAUABQACsAUABQACsAUABQAFAAUABQACsAKwAEAFAABAAEAAQABAAEAAQABAAEACsABAAEAAQAKwAEAAQABAArACsAUAArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwBQAFAABAAEACsAKwBLAEsASwBLAEsASwBLAEsASwBLAB4AGwArACsAKwArACsAKwArAFAABAAEAAQABAAEAAQAKwAEAAQABAArAFAAUABQAFAAUABQAFAAUAArACsAUABQACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAAQABAAEAAQABAArACsABAAEACsAKwAEAAQABAArACsAKwArACsAKwArAAQABAAEACsAKwArACsAUABQACsAUABQAFAABAAEACsAKwBLAEsASwBLAEsASwBLAEsASwBLAB4AUABQAFAAUABQAFAAUAArACsAKwArACsAKwArACsAKwArAAQAUAArAFAAUABQAFAAUABQACsAKwArAFAAUABQACsAUABQAFAAUAArACsAKwBQAFAAKwBQACsAUABQACsAKwArAFAAUAArACsAKwBQAFAAUAArACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsAKwArAAQABAAEAAQABAArACsAKwAEAAQABAArAAQABAAEAAQAKwArAFAAKwArACsAKwArACsABAArACsAKwArACsAKwArACsAKwArAEsASwBLAEsASwBLAEsASwBLAEsAUABQAFAAHgAeAB4AHgAeAB4AGwAeACsAKwArACsAKwAEAAQABAAEAAQAUABQAFAAUABQAFAAUABQACsAUABQAFAAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwArACsAUAAEAAQABAAEAAQABAAEACsABAAEAAQAKwAEAAQABAAEACsAKwArACsAKwArACsABAAEACsAUABQAFAAKwArACsAKwArAFAAUAAEAAQAKwArAEsASwBLAEsASwBLAEsASwBLAEsAKwArACsAKwArACsAKwAOAFAAUABQAFAAUABQAFAAHgBQAAQABAAEAA4AUABQAFAAUABQAFAAUABQACsAUABQAFAAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArAFAAUABQAFAAUABQAFAAUABQAFAAKwBQAFAAUABQAFAAKwArAAQAUAAEAAQABAAEAAQABAAEACsABAAEAAQAKwAEAAQABAAEACsAKwArACsAKwArACsABAAEACsAKwArACsAKwArACsAUAArAFAAUAAEAAQAKwArAEsASwBLAEsASwBLAEsASwBLAEsAKwBQAFAAKwArACsAKwArACsAKwArACsAKwArACsAKwAEAAQABAAEAFAAUABQAFAAUABQAFAAUABQACsAUABQAFAAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAABAAEAFAABAAEAAQABAAEAAQABAArAAQABAAEACsABAAEAAQABABQAB4AKwArACsAKwBQAFAAUAAEAFAAUABQAFAAUABQAFAAUABQAFAABAAEACsAKwBLAEsASwBLAEsASwBLAEsASwBLAFAAUABQAFAAUABQAFAAUABQABoAUABQAFAAUABQAFAAKwAEAAQABAArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArAFAAUABQAFAAUABQAFAAUABQACsAUAArACsAUABQAFAAUABQAFAAUAArACsAKwAEACsAKwArACsABAAEAAQABAAEAAQAKwAEACsABAAEAAQABAAEAAQABAAEACsAKwArACsAKwArAEsASwBLAEsASwBLAEsASwBLAEsAKwArAAQABAAeACsAKwArACsAKwArACsAKwArACsAKwArAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXAAqAFwAXAAqACoAKgAqACoAKgAqACsAKwArACsAGwBcAFwAXABcAFwAXABcACoAKgAqACoAKgAqACoAKgAeAEsASwBLAEsASwBLAEsASwBLAEsADQANACsAKwArACsAKwBcAFwAKwBcACsAXABcAFwAXABcACsAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcACsAXAArAFwAXABcAFwAXABcAFwAXABcAFwAKgBcAFwAKgAqACoAKgAqACoAKgAqACoAXAArACsAXABcAFwAXABcACsAXAArACoAKgAqACoAKgAqACsAKwBLAEsASwBLAEsASwBLAEsASwBLACsAKwBcAFwAXABcAFAADgAOAA4ADgAeAA4ADgAJAA4ADgANAAkAEwATABMAEwATAAkAHgATAB4AHgAeAAQABAAeAB4AHgAeAB4AHgBLAEsASwBLAEsASwBLAEsASwBLAFAAUABQAFAAUABQAFAAUABQAFAADQAEAB4ABAAeAAQAFgARABYAEQAEAAQAUABQAFAAUABQAFAAUABQACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwArACsAKwAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQADQAEAAQABAAEAAQADQAEAAQAUABQAFAAUABQAAQABAAEAAQABAAEAAQABAAEAAQABAArAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAArAA0ADQAeAB4AHgAeAB4AHgAEAB4AHgAeAB4AHgAeACsAHgAeAA4ADgANAA4AHgAeAB4AHgAeAAkACQArACsAKwArACsAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcACoAKgAqACoAKgAqACoAKgAqACoAKgAqACoAKgAqACoAKgAqACoAKgBcAEsASwBLAEsASwBLAEsASwBLAEsADQANAB4AHgAeAB4AXABcAFwAXABcAFwAKgAqACoAKgBcAFwAXABcACoAKgAqAFwAKgAqACoAXABcACoAKgAqACoAKgAqACoAXABcAFwAKgAqACoAKgBcAFwAXABcAFwAXABcAFwAXABcAFwAXABcACoAKgAqACoAKgAqACoAKgAqACoAKgAqAFwAKgBLAEsASwBLAEsASwBLAEsASwBLACoAKgAqACoAKgAqAFAAUABQAFAAUABQACsAUAArACsAKwArACsAUAArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAHgBQAFAAUABQAFgAWABYAFgAWABYAFgAWABYAFgAWABYAFgAWABYAFgAWABYAFgAWABYAFgAWABYAFgAWABYAFgAWABYAFgAWABZAFkAWQBZAFkAWQBZAFkAWQBZAFkAWQBZAFkAWQBZAFkAWQBZAFkAWQBZAFkAWQBZAFkAWQBZAFkAWQBZAFkAWgBaAFoAWgBaAFoAWgBaAFoAWgBaAFoAWgBaAFoAWgBaAFoAWgBaAFoAWgBaAFoAWgBaAFoAWgBaAFoAWgBaAFAAUABQAFAAUABQAFAAUABQACsAUABQAFAAUAArACsAUABQAFAAUABQAFAAUAArAFAAKwBQAFAAUABQACsAKwBQAFAAUABQAFAAUABQAFAAUAArAFAAUABQAFAAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArAFAAUABQAFAAKwArAFAAUABQAFAAUABQAFAAKwBQACsAUABQAFAAUAArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwBQAFAAUABQACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsABAAEAAQAHgANAB4AHgAeAB4AHgAeAB4AUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAHgAeAB4AHgAeAB4AHgAeAB4AHgArACsAKwArACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAKwBQAFAAUABQAFAAUAArACsADQBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAHgAeAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAANAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAWABEAKwArACsAUABQAFAAUABQAFAAUABQAFAAUABQAA0ADQANAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsAKwArACsAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwBQAFAAUABQAAQABAAEACsAKwArACsAKwArACsAKwArACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAEAAQABAANAA0AKwArACsAKwArACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAABAAEACsAKwArACsAKwArACsAKwArACsAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwBQAFAAUAArAAQABAArACsAKwArACsAKwArACsAKwArACsAKwBcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAKgAqACoAKgAqACoAKgAqACoAKgAqACoAKgAqACoAKgAqACoAKgAqAA0ADQAVAFwADQAeAA0AGwBcACoAKwArAEsASwBLAEsASwBLAEsASwBLAEsAKwArACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUAArACsAKwArACsAKwAeAB4AEwATAA0ADQAOAB4AEwATAB4ABAAEAAQACQArAEsASwBLAEsASwBLAEsASwBLAEsAKwArACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsAKwArACsAKwArAFAAUABQAFAAUAAEAAQAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAAQAUAArACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsAKwArACsAKwArACsAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwAEAAQABAAEAAQABAAEAAQABAAEAAQABAArACsAKwArAAQABAAEAAQABAAEAAQABAAEAAQABAAEACsAKwArACsAHgArACsAKwATABMASwBLAEsASwBLAEsASwBLAEsASwBcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXAArACsAXABcAFwAXABcACsAKwArACsAKwArACsAKwArACsAKwBcAFwAXABcAFwAXABcAFwAXABcAFwAXAArACsAKwArAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcACsAKwArACsAKwArAEsASwBLAEsASwBLAEsASwBLAEsAXAArACsAKwAqACoAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAAQABAAEAAQABAArACsAHgAeAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcACoAKgAqACoAKgAqACoAKgAqACoAKwAqACoAKgAqACoAKgAqACoAKgAqACoAKgAqACoAKgAqACoAKgAqACoAKgAqACoAKgAqACoAKgAqACoAKwArAAQASwBLAEsASwBLAEsASwBLAEsASwArACsAKwArACsAKwBLAEsASwBLAEsASwBLAEsASwBLACsAKwArACsAKwArACoAKgAqACoAKgAqACoAXAAqACoAKgAqACoAKgArACsABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsABAAEAAQABAAEAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAAQABAAEAAQABABQAFAAUABQAFAAUABQACsAKwArACsASwBLAEsASwBLAEsASwBLAEsASwANAA0AHgANAA0ADQANAB4AHgAeAB4AHgAeAB4AHgAeAB4ABAAEAAQABAAEAAQABAAEAAQAHgAeAB4AHgAeAB4AHgAeAB4AKwArACsABAAEAAQAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAABAAEAAQABAAEAAQABAAEAAQABAAEAAQABABQAFAASwBLAEsASwBLAEsASwBLAEsASwBQAFAAUABQAFAAUABQAFAABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEACsAKwArACsAKwArACsAKwAeAB4AHgAeAFAAUABQAFAABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEACsAKwArAA0ADQANAA0ADQBLAEsASwBLAEsASwBLAEsASwBLACsAKwArAFAAUABQAEsASwBLAEsASwBLAEsASwBLAEsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAA0ADQBQAFAAUABQAFAAUABQAFAAUAArACsAKwArACsAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAKwBQAFAAUAAeAB4AHgAeAB4AHgAeAB4AKwArACsAKwArACsAKwArAAQABAAEAB4ABAAEAAQABAAEAAQABAAEAAQABAAEAAQABABQAFAAUABQAAQAUABQAFAAUABQAFAABABQAFAABAAEAAQAUAArACsAKwArACsABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEACsABAAEAAQABAAEAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AKwArAFAAUABQAFAAUABQACsAKwBQAFAAUABQAFAAUABQAFAAKwBQACsAUAArAFAAKwAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeACsAKwAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgArAB4AHgAeAB4AHgAeAB4AHgBQAB4AHgAeAFAAUABQACsAHgAeAB4AHgAeAB4AHgAeAB4AHgBQAFAAUABQACsAKwAeAB4AHgAeAB4AHgArAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AKwArAFAAUABQACsAHgAeAB4AHgAeAB4AHgAOAB4AKwANAA0ADQANAA0ADQANAAkADQANAA0ACAAEAAsABAAEAA0ACQANAA0ADAAdAB0AHgAXABcAFgAXABcAFwAWABcAHQAdAB4AHgAUABQAFAANAAEAAQAEAAQABAAEAAQACQAaABoAGgAaABoAGgAaABoAHgAXABcAHQAVABUAHgAeAB4AHgAeAB4AGAAWABEAFQAVABUAHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4ADQAeAA0ADQANAA0AHgANAA0ADQAHAB4AHgAeAB4AKwAEAAQABAAEAAQABAAEAAQABAAEAFAAUAArACsATwBQAFAAUABQAFAAHgAeAB4AFgARAE8AUABPAE8ATwBPAFAAUABQAFAAUAAeAB4AHgAWABEAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAKwArABsAGwAbABsAGwAbABsAGgAbABsAGwAbABsAGwAbABsAGwAbABsAGwAbABsAGgAbABsAGwAbABoAGwAbABoAGwAbABsAGwAbABsAGwAbABsAGwAbABsAGwAbABsAGwAbAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQAHgAeAFAAGgAeAB0AHgBQAB4AGgAeAB4AHgAeAB4AHgAeAB4AHgBPAB4AUAAbAB4AHgBQAFAAUABQAFAAHgAeAB4AHQAdAB4AUAAeAFAAHgBQAB4AUABPAFAAUAAeAB4AHgAeAB4AHgAeAFAAUABQAFAAUAAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAFAAHgBQAFAAUABQAE8ATwBQAFAAUABQAFAATwBQAFAATwBQAE8ATwBPAE8ATwBPAE8ATwBPAE8ATwBPAFAAUABQAFAATwBPAE8ATwBPAE8ATwBPAE8ATwBQAFAAUABQAFAAUABQAFAAUAAeAB4AUABQAFAAUABPAB4AHgArACsAKwArAB0AHQAdAB0AHQAdAB0AHQAdAB0AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB0AHgAdAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAdAB4AHQAdAB4AHgAeAB0AHQAeAB4AHQAeAB4AHgAdAB4AHQAbABsAHgAdAB4AHgAeAB4AHQAeAB4AHQAdAB0AHQAeAB4AHQAeAB0AHgAdAB0AHQAdAB0AHQAeAB0AHgAeAB4AHgAeAB0AHQAdAB0AHgAeAB4AHgAdAB0AHgAeAB4AHgAeAB4AHgAeAB4AHgAdAB4AHgAeAB0AHgAeAB4AHgAeAB0AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAdAB0AHgAeAB0AHQAdAB0AHgAeAB0AHQAeAB4AHQAdAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB0AHQAeAB4AHQAdAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHQAeAB4AHgAdAB4AHgAeAB4AHgAeAB4AHQAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB0AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AFAAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeABYAEQAWABEAHgAeAB4AHgAeAB4AHQAeAB4AHgAeAB4AHgAeACUAJQAeAB4AHgAeAB4AHgAeAB4AHgAWABEAHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AJQAlACUAJQAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArAE8ATwBPAE8ATwBPAE8ATwBPAE8ATwBPAE8ATwBPAE8ATwBPAE8ATwBPAE8ATwBPAE8ATwBPAE8ATwBPAE8ATwAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAE8ATwBPAE8ATwBPAE8ATwBPAE8ATwBPAE8ATwBPAE8ATwBPAE8ATwBPAFAAHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHgAeAB4AHgAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAeAB4AHQAdAB0AHQAeAB4AHgAeAB4AHgAeAB4AHgAeAB0AHQAeAB0AHQAdAB0AHQAdAB0AHgAeAB4AHgAeAB4AHgAeAB0AHQAeAB4AHQAdAB4AHgAeAB4AHQAdAB4AHgAeAB4AHQAdAB0AHgAeAB0AHgAeAB0AHQAdAB0AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAdAB0AHQAdAB4AHgAeAB4AHgAeAB4AHgAeAB0AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAlACUAJQAlAB4AHQAdAB4AHgAdAB4AHgAeAB4AHQAdAB4AHgAeAB4AJQAlAB0AHQAlAB4AJQAlACUAIAAlACUAHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAlACUAJQAeAB4AHgAeAB0AHgAdAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAdAB0AHgAdAB0AHQAeAB0AJQAdAB0AHgAdAB0AHgAdAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeACUAHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHQAdAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAlACUAJQAlACUAJQAlACUAJQAlACUAJQAdAB0AHQAdACUAHgAlACUAJQAdACUAJQAdAB0AHQAlACUAHQAdACUAHQAdACUAJQAlAB4AHQAeAB4AHgAeAB0AHQAlAB0AHQAdAB0AHQAdACUAJQAlACUAJQAdACUAJQAgACUAHQAdACUAJQAlACUAJQAlACUAJQAeAB4AHgAlACUAIAAgACAAIAAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB0AHgAeAB4AFwAXABcAFwAXABcAHgATABMAJQAeAB4AHgAWABEAFgARABYAEQAWABEAFgARABYAEQAWABEATwBPAE8ATwBPAE8ATwBPAE8ATwBPAE8ATwBPAE8ATwBPAE8ATwBPAE8ATwAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeABYAEQAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAWABEAFgARABYAEQAWABEAFgARAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AFgARABYAEQAWABEAFgARABYAEQAWABEAFgARABYAEQAWABEAFgARABYAEQAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAWABEAFgARAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AFgARAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAdAB0AHQAdAB0AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgArACsAHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AKwAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AUABQAFAAUAAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAEAAQABAAeAB4AKwArACsAKwArABMADQANAA0AUAATAA0AUABQAFAAUABQAFAAUABQACsAKwArACsAKwArACsAUAANACsAKwArACsAKwArACsAKwArACsAKwArACsAKwAEAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsAKwArACsAKwArACsAKwBQAFAAUABQAFAAUABQACsAUABQAFAAUABQAFAAUAArAFAAUABQAFAAUABQAFAAKwBQAFAAUABQAFAAUABQACsAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXAA0ADQANAA0ADQANAA0ADQAeAA0AFgANAB4AHgAXABcAHgAeABcAFwAWABEAFgARABYAEQAWABEADQANAA0ADQATAFAADQANAB4ADQANAB4AHgAeAB4AHgAMAAwADQANAA0AHgANAA0AFgANAA0ADQANAA0ADQANAA0AHgANAB4ADQANAB4AHgAeACsAKwArACsAKwArACsAKwArACsAKwArACsAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACsAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAKwArACsAKwArACsAKwArACsAKwArACsAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwAlACUAJQAlACUAJQAlACUAJQAlACUAJQArACsAKwArAA0AEQARACUAJQBHAFcAVwAWABEAFgARABYAEQAWABEAFgARACUAJQAWABEAFgARABYAEQAWABEAFQAWABEAEQAlAFcAVwBXAFcAVwBXAFcAVwBXAAQABAAEAAQABAAEACUAVwBXAFcAVwA2ACUAJQBXAFcAVwBHAEcAJQAlACUAKwBRAFcAUQBXAFEAVwBRAFcAUQBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFEAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBRAFcAUQBXAFEAVwBXAFcAVwBXAFcAUQBXAFcAVwBXAFcAVwBRAFEAKwArAAQABAAVABUARwBHAFcAFQBRAFcAUQBXAFEAVwBRAFcAUQBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFEAVwBRAFcAUQBXAFcAVwBXAFcAVwBRAFcAVwBXAFcAVwBXAFEAUQBXAFcAVwBXABUAUQBHAEcAVwArACsAKwArACsAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAKwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAKwAlACUAVwBXAFcAVwAlACUAJQAlACUAJQAlACUAJQAlACsAKwArACsAKwArACsAKwArACsAKwArAFEAUQBRAFEAUQBRAFEAUQBRAFEAUQBRAFEAUQBRAFEAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQArAFcAVwBXAFcAVwBXAFcAVwBXAFcAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQBPAE8ATwBPAE8ATwBPAE8AJQBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXACUAJQAlAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAEcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAKwArACsAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQArACsAKwArACsAKwArACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAADQATAA0AUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABLAEsASwBLAEsASwBLAEsASwBLAFAAUAArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAFAABAAEAAQABAAeAAQABAAEAAQABAAEAAQABAAEAAQAHgBQAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AUABQAAQABABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAAQABAAeAA0ADQANAA0ADQArACsAKwArACsAKwArACsAHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAFAAUABQAFAAUABQAFAAUABQAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AUAAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgBQAB4AHgAeAB4AHgAeAFAAHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgArACsAHgAeAB4AHgAeAB4AHgAeAB4AKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwAeAB4AUABQAFAAUABQAFAAUABQAFAAUABQAAQAUABQAFAABABQAFAAUABQAAQAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAAQABAAEAAQABAAeAB4AHgAeAAQAKwArACsAUABQAFAAUABQAFAAHgAeABoAHgArACsAKwArACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAADgAOABMAEwArACsAKwArACsAKwArACsABAAEAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAAQABAAEAAQABAAEACsAKwArACsAKwArACsAKwANAA0ASwBLAEsASwBLAEsASwBLAEsASwArACsAKwArACsAKwAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABABQAFAAUABQAFAAUAAeAB4AHgBQAA4AUABQAAQAUABQAFAAUABQAFAABAAEAAQABAAEAAQABAAEAA0ADQBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQAKwArACsAKwArACsAKwArACsAKwArAB4AWABYAFgAWABYAFgAWABYAFgAWABYAFgAWABYAFgAWABYAFgAWABYAFgAWABYAFgAWABYAFgAWABYACsAKwArAAQAHgAeAB4AHgAeAB4ADQANAA0AHgAeAB4AHgArAFAASwBLAEsASwBLAEsASwBLAEsASwArACsAKwArAB4AHgBcAFwAXABcAFwAKgBcAFwAXABcAFwAXABcAFwAXABcAEsASwBLAEsASwBLAEsASwBLAEsAXABcAFwAXABcACsAUABQAFAAUABQAFAAUABQAFAABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEACsAKwArACsAKwArACsAKwArAFAAUABQAAQAUABQAFAAUABQAFAAUABQAAQABAArACsASwBLAEsASwBLAEsASwBLAEsASwArACsAHgANAA0ADQBcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAKgAqACoAXAAqACoAKgBcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXAAqAFwAKgAqACoAXABcACoAKgBcAFwAXABcAFwAKgAqAFwAKgBcACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArAFwAXABcACoAKgBQAFAAUABQAFAAUABQAFAAUABQAFAABAAEAAQABAAEAA0ADQBQAFAAUAAEAAQAKwArACsAKwArACsAKwArACsAKwBQAFAAUABQAFAAUAArACsAUABQAFAAUABQAFAAKwArAFAAUABQAFAAUABQACsAKwArACsAKwArACsAKwArAFAAUABQAFAAUABQAFAAKwBQAFAAUABQAFAAUABQACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAHgAeACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAEAAQABAAEAAQABAAEAAQADQAEAAQAKwArAEsASwBLAEsASwBLAEsASwBLAEsAKwArACsAKwArACsAVABVAFUAVQBVAFUAVQBVAFUAVQBVAFUAVQBVAFUAVQBVAFUAVQBVAFUAVQBVAFUAVQBVAFUAVQBUAFUAVQBVAFUAVQBVAFUAVQBVAFUAVQBVAFUAVQBVAFUAVQBVAFUAVQBVAFUAVQBVAFUAVQBVACsAKwArACsAKwArACsAKwArACsAKwArAFkAWQBZAFkAWQBZAFkAWQBZAFkAWQBZAFkAWQBZAFkAWQBZAFkAKwArACsAKwBaAFoAWgBaAFoAWgBaAFoAWgBaAFoAWgBaAFoAWgBaAFoAWgBaAFoAWgBaAFoAWgBaAFoAWgBaAFoAKwArACsAKwAGAAYABgAGAAYABgAGAAYABgAGAAYABgAGAAYABgAGAAYABgAGAAYABgAGAAYABgAGAAYABgAGAAYABgAGAAYAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXACUAJQBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAJQAlACUAJQAlACUAUABQAFAAUABQAFAAUAArACsAKwArACsAKwArACsAKwArACsAKwBQAFAAUABQAFAAKwArACsAKwArAFYABABWAFYAVgBWAFYAVgBWAFYAVgBWAB4AVgBWAFYAVgBWAFYAVgBWAFYAVgBWAFYAVgArAFYAVgBWAFYAVgArAFYAKwBWAFYAKwBWAFYAKwBWAFYAVgBWAFYAVgBWAFYAVgBWAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAEQAWAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUAAaAB4AKwArAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQAGAARABEAGAAYABMAEwAWABEAFAArACsAKwArACsAKwAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEACUAJQAlACUAJQAWABEAFgARABYAEQAWABEAFgARABYAEQAlACUAFgARACUAJQAlACUAJQAlACUAEQAlABEAKwAVABUAEwATACUAFgARABYAEQAWABEAJQAlACUAJQAlACUAJQAlACsAJQAbABoAJQArACsAKwArAFAAUABQAFAAUAArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwArAAcAKwATACUAJQAbABoAJQAlABYAEQAlACUAEQAlABEAJQBXAFcAVwBXAFcAVwBXAFcAVwBXABUAFQAlACUAJQATACUAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXABYAJQARACUAJQAlAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwAWACUAEQAlABYAEQARABYAEQARABUAVwBRAFEAUQBRAFEAUQBRAFEAUQBRAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAEcARwArACsAVwBXAFcAVwBXAFcAKwArAFcAVwBXAFcAVwBXACsAKwBXAFcAVwBXAFcAVwArACsAVwBXAFcAKwArACsAGgAbACUAJQAlABsAGwArAB4AHgAeAB4AHgAeAB4AKwArACsAKwArACsAKwArACsAKwAEAAQABAAQAB0AKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwBQAFAAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsAKwArACsADQANAA0AKwArACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAKwArAB4AHgAeAB4AHgAeAB4AHgAeAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgBQAFAAHgAeAB4AKwAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAAQAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwAEAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAKwArACsAKwArACsAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwArACsAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAABAAEAAQABAAEACsAKwArACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArAA0AUABQAFAAUAArACsAKwArAFAAUABQAFAAUABQAFAAUAANAFAAUABQAFAAUAArACsAKwArACsAKwArACsAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwArACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAKwArACsAKwArACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAKwArACsAKwArACsAKwArACsAKwAeACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAUABQAFAAUABQAFAAKwArAFAAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArAFAAUAArACsAKwBQACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwANAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAeAB4AUABQAFAAUABQAFAAUAArACsAKwArACsAKwArAFAAUABQAFAAUABQAFAAUABQACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArAFAAUAArACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAKwArAA0AUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAKwArACsAKwAeAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAKwArACsAUABQAFAAUABQAAQABAAEACsABAAEACsAKwArACsAKwAEAAQABAAEAFAAUABQAFAAKwBQAFAAUAArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwArAAQABAAEACsAKwArACsABABQAFAAUABQAFAAUABQAFAAUAArACsAKwArACsAKwArAA0ADQANAA0ADQANAA0ADQAeACsAKwArACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAeAFAAUABQAFAAUABQAFAAUAAeAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAAQABAArACsAKwArAFAAUABQAFAAUAANAA0ADQANAA0ADQAUACsAKwArACsAKwArACsAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwArACsADQANAA0ADQANAA0ADQBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsAKwArACsAKwArAB4AHgAeAB4AKwArACsAKwArACsAKwArACsAKwArACsAUABQAFAAUABQAFAAUAArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArAFAAUABQAFAAUABQAFAAUABQACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAKwArACsAKwArACsAKwArACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsAKwArACsAKwArAFAAUABQAFAAUABQAAQABAAEAAQAKwArACsAKwArACsAKwArAEsASwBLAEsASwBLAEsASwBLAEsAKwArACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUAArAAQABAANACsAKwBQAFAAKwArACsAKwArACsAKwArACsAKwArACsAKwArAFAAUABQAFAAUABQAAQABAAEAAQABAAEAAQABAAEAAQABABQAFAAUABQAB4AHgAeAB4AHgArACsAKwArACsAKwAEAAQABAAEAAQABAAEAA0ADQAeAB4AHgAeAB4AKwArACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAEsASwBLAEsASwBLAEsASwBLAEsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsABABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAAQABAAEAAQABAAEAAQABAAEAAQABAAeAB4AHgANAA0ADQANACsAKwArACsAKwArACsAKwArACsAKwAeACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwArACsAKwArACsAKwBLAEsASwBLAEsASwBLAEsASwBLACsAKwArACsAKwArAFAAUABQAFAAUABQAFAABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEACsASwBLAEsASwBLAEsASwBLAEsASwANAA0ADQANAFAABAAEAFAAKwArACsAKwArACsAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAABAAeAA4AUAArACsAKwArACsAKwArACsAKwAEAFAAUABQAFAADQANAB4ADQAEAAQABAAEAB4ABAAEAEsASwBLAEsASwBLAEsASwBLAEsAUAAOAFAADQANAA0AKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwArACsAKwArACsAKwArACsAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAEAAQABAAEAAQABAAEAAQABAAEAAQABAANAA0AHgANAA0AHgAEACsAUABQAFAAUABQAFAAUAArAFAAKwBQAFAAUABQACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwBQAFAAUABQAFAAUABQAFAAUABQAA0AKwArACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAEAAQABAAEAAQABAAEAAQABAAEAAQAKwArACsAKwArAEsASwBLAEsASwBLAEsASwBLAEsAKwArACsAKwArACsABAAEAAQABAArAFAAUABQAFAAUABQAFAAUAArACsAUABQACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwBQAFAAUABQAFAAUABQACsAUABQACsAUABQAFAAUABQACsABAAEAFAABAAEAAQABAAEAAQABAArACsABAAEACsAKwAEAAQABAArACsAUAArACsAKwArACsAKwAEACsAKwArACsAKwBQAFAAUABQAFAABAAEACsAKwAEAAQABAAEAAQABAAEACsAKwArAAQABAAEAAQABAArACsAKwArACsAKwArACsAKwArACsABAAEAAQABAAEAAQABABQAFAAUABQAA0ADQANAA0AHgBLAEsASwBLAEsASwBLAEsASwBLAA0ADQArAB4ABABQAFAAUAArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwAEAAQABAAEAFAAUAAeAFAAKwArACsAKwArACsAKwArAEsASwBLAEsASwBLAEsASwBLAEsAKwArACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAABAAEAAQABAAEAAQABAArACsABAAEAAQABAAEAAQABAAEAAQADgANAA0AEwATAB4AHgAeAA0ADQANAA0ADQANAA0ADQANAA0ADQANAA0ADQANAFAAUABQAFAABAAEACsAKwAEAA0ADQAeAFAAKwArACsAKwArACsAKwArACsAKwArAEsASwBLAEsASwBLAEsASwBLAEsAKwArACsAKwArACsADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAFAAKwArACsAKwArACsAKwBLAEsASwBLAEsASwBLAEsASwBLACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAXABcAFwAKwArACoAKgAqACoAKgAqACoAKgAqACoAKgAqACoAKgAqACsAKwArACsASwBLAEsASwBLAEsASwBLAEsASwBcAFwADQANAA0AKgBQAFAAUABQAFAAUABQAFAAUABQAFAAUAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAeACsAKwArACsASwBLAEsASwBLAEsASwBLAEsASwBQAFAAUABQAFAAUABQAFAAUAArACsAKwArACsAKwArACsAKwArACsAKwBQAFAAUABQAFAAUABQAFAAKwArAFAAKwArAFAAUABQAFAAUABQAFAAUAArAFAAUAArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAABAAEAAQABAAEAAQAKwAEAAQAKwArAAQABAAEAAQAUAAEAFAABAAEAA0ADQANACsAKwArACsAKwArACsAKwArAEsASwBLAEsASwBLAEsASwBLAEsAKwArACsAKwArACsAUABQAFAAUABQAFAAUABQACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAABAAEAAQABAAEAAQABAArACsABAAEAAQABAAEAAQABABQAA4AUAAEACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArAFAABAAEAAQABAAEAAQABAAEAAQABABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAEAAQABAAEAAQABAAEAFAABAAEAAQABAAOAB4ADQANAA0ADQAOAB4ABAArACsAKwArACsAKwArACsAUAAEAAQABAAEAAQABAAEAAQABAAEAAQAUABQAFAAUABQAFAAUABQAFAAUAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAA0ADQANAFAADgAOAA4ADQANACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwBQAFAAUABQAFAAUABQAFAAUAArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAABAAEAAQABAAEAAQABAAEACsABAAEAAQABAAEAAQABAAEAFAADQANAA0ADQANACsAKwArACsAKwArACsAKwArACsASwBLAEsASwBLAEsASwBLAEsASwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsAKwAOABMAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwArAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAArAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAArACsAKwArACsAKwArACsAKwBQAFAAUABQAFAAUABQACsAUABQACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAEAAQABAAEAAQABAArACsAKwAEACsABAAEACsABAAEAAQABAAEAAQABABQAAQAKwArACsAKwArACsAKwArAEsASwBLAEsASwBLAEsASwBLAEsAKwArACsAKwArACsAUABQAFAAUABQAFAAKwBQAFAAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAEAAQABAAEAAQAKwAEAAQAKwAEAAQABAAEAAQAUAArACsAKwArACsAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAABAAEAAQABAAeAB4AKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwBQACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAB4AHgAeAB4AHgAeAB4AHgAaABoAGgAaAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgArACsAKwArACsAKwArACsAKwArACsAKwArAA0AUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAKwArACsAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsADQANAA0ADQANACsAKwArACsAKwArACsAKwArACsAKwBQAFAAUABQACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAASABIAEgAQwBDAEMAUABQAFAAUABDAFAAUABQAEgAQwBIAEMAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAASABDAEMAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwAJAAkACQAJAAkACQAJABYAEQArACsAKwArACsAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABIAEMAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArAEsASwBLAEsASwBLAEsASwBLAEsAKwArACsAKwANAA0AKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwArAAQABAAEAAQABAANACsAKwArACsAKwArACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAEAAQABAAEAAQABAAEAA0ADQANAB4AHgAeAB4AHgAeAFAAUABQAFAADQAeACsAKwArACsAKwArACsAKwArACsASwBLAEsASwBLAEsASwBLAEsASwArAFAAUABQAFAAUABQAFAAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAANAA0AHgAeACsAKwArACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAKwArACsAKwAEAFAABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQAKwArACsAKwArACsAKwAEAAQABAAEAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAARwBHABUARwAJACsAKwArACsAKwArACsAKwArACsAKwAEAAQAKwArACsAKwArACsAKwArACsAKwArACsAKwArAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXACsAKwArACsAKwArACsAKwBXAFcAVwBXAFcAVwBXAFcAVwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAUQBRAFEAKwArACsAKwArACsAKwArACsAKwArACsAKwBRAFEAUQBRACsAKwArACsAKwArACsAKwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUABQACsAKwArACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAKwArACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUAArACsAHgAEAAQADQAEAAQABAAEACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgArACsAKwArACsAKwArACsAKwArAB4AHgAeAB4AHgAeAB4AKwArAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAAQABAAEAAQABAAeAB4AHgAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAB4AHgAEAAQABAAEAAQABAAEAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4ABAAEAAQABAAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4ABAAEAAQAHgArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAKwArACsAKwArACsAKwArACsAKwArAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgArACsAKwArACsAKwArACsAKwAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgArAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AKwBQAFAAKwArAFAAKwArAFAAUAArACsAUABQAFAAUAArAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeACsAUAArAFAAUABQAFAAUABQAFAAKwAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AKwBQAFAAUABQACsAKwBQAFAAUABQAFAAUABQAFAAKwBQAFAAUABQAFAAUABQACsAHgAeAFAAUABQAFAAUAArAFAAKwArACsAUABQAFAAUABQAFAAUAArAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAHgBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgBQAFAAUABQAFAAUABQAFAAUABQAFAAHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAB4AHgAeAB4AHgAeAB4AHgAeACsAKwBLAEsASwBLAEsASwBLAEsASwBLAEsASwBLAEsASwBLAEsASwBLAEsASwBLAEsASwBLAEsASwBLAEsASwBLAEsASwBLAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAeAB4AHgAeAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAeAB4AHgAeAB4AHgAeAB4ABAAeAB4AHgAeAB4AHgAeAB4AHgAeAAQAHgAeAA0ADQANAA0AHgArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwAEAAQABAAEAAQAKwAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArAAQABAAEAAQABAAEAAQAKwAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQAKwArAAQABAAEAAQABAAEAAQAKwAEAAQAKwAEAAQABAAEAAQAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsAKwAEAAQABAAEAAQABAAEAFAAUABQAFAAUABQAFAAKwArAEsASwBLAEsASwBLAEsASwBLAEsAKwArACsAKwBQAB4AKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUAAEAAQABAAEAEsASwBLAEsASwBLAEsASwBLAEsAKwArACsAKwArABsAUABQAFAAUABQACsAKwBQAFAAUABQAFAAUABQAFAAUAAEAAQABAAEAAQABAAEACsAKwArACsAKwArACsAKwArAB4AHgAeAB4ABAAEAAQABAAEAAQABABQACsAKwArACsASwBLAEsASwBLAEsASwBLAEsASwArACsAKwArABYAFgArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAGgBQAFAAUAAaAFAAUABQAFAAKwArACsAKwArACsAKwArACsAKwArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAeAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQACsAKwBQAFAAUABQACsAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwBQAFAAKwBQACsAKwBQACsAUABQAFAAUABQAFAAUABQAFAAUAArAFAAUABQAFAAKwBQACsAUAArACsAKwArACsAKwBQACsAKwArACsAUAArAFAAKwBQACsAUABQAFAAKwBQAFAAKwBQACsAKwBQACsAUAArAFAAKwBQACsAUAArAFAAUAArAFAAKwArAFAAUABQAFAAKwBQAFAAUABQAFAAUABQACsAUABQAFAAUAArAFAAUABQAFAAKwBQACsAUABQAFAAUABQAFAAUABQAFAAUAArAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAArACsAKwArACsAUABQAFAAKwBQAFAAUABQAFAAKwBQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwAeAB4AKwArACsAKwArACsAKwArACsAKwArACsAKwArAE8ATwBPAE8ATwBPAE8ATwBPAE8ATwBPAE8AJQAlACUAHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHgAeAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB4AHgAeACUAJQAlAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQApACkAKQApACkAKQApACkAKQApACkAKQApACkAKQApACkAKQApACkAKQApACkAKQApACkAJQAlACUAJQAlACAAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAeAB4AJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlAB4AHgAlACUAJQAlACUAHgAlACUAJQAlACUAIAAgACAAJQAlACAAJQAlACAAIAAgACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACEAIQAhACEAIQAlACUAIAAgACUAJQAgACAAIAAgACAAIAAgACAAIAAgACAAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAJQAlACUAIAAlACUAJQAlACAAIAAgACUAIAAgACAAJQAlACUAJQAlACUAJQAgACUAIAAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAHgAlAB4AJQAeACUAJQAlACUAJQAgACUAJQAlACUAHgAlAB4AHgAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlAB4AHgAeAB4AHgAeAB4AJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAeAB4AHgAeAB4AHgAeAB4AHgAeACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACAAIAAlACUAJQAlACAAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACAAJQAlACUAJQAgACAAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAHgAeAB4AHgAeAB4AHgAeACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAeAB4AHgAeAB4AHgAlACUAJQAlACUAJQAlACAAIAAgACUAJQAlACAAIAAgACAAIAAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeABcAFwAXABUAFQAVAB4AHgAeAB4AJQAlACUAIAAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACAAIAAgACUAJQAlACUAJQAlACUAJQAlACAAJQAlACUAJQAlACUAJQAlACUAJQAlACAAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AJQAlACUAJQAlACUAJQAlACUAJQAlACUAHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AJQAlACUAJQAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeACUAJQAlACUAJQAlACUAJQAeAB4AHgAeAB4AHgAeAB4AHgAeACUAJQAlACUAJQAlAB4AHgAeAB4AHgAeAB4AHgAlACUAJQAlACUAJQAlACUAHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAgACUAJQAgACUAJQAlACUAJQAlACUAJQAgACAAIAAgACAAIAAgACAAJQAlACUAJQAlACUAIAAlACUAJQAlACUAJQAlACUAJQAgACAAIAAgACAAIAAgACAAIAAgACUAJQAgACAAIAAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAgACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACAAIAAlACAAIAAlACAAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAgACAAIAAlACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAJQAlAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AKwAeAB4AHgAeAB4AHgAeAB4AHgAeAB4AHgArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArAEsASwBLAEsASwBLAEsASwBLAEsAKwArACsAKwArACsAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAKwArAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXACUAJQBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwAlACUAJQAlACUAJQAlACUAJQAlACUAVwBXACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQBXAFcAVwBXAFcAVwBXAFcAVwBXAFcAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAJQAlACUAKwAEACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArACsAKwArAA==",au=50,Vm=1,cu=2,lu=3,Gm=4,jm=5,uu=7,du=8,hu=9,GA=10,co=11,fu=12,lo=13,Jm=14,wn=15,uo=16,Ni=17,yn=18,Wm=19,gu=20,ho=21,bn=22,fo=23,Kt=24,Me=25,Un=26,Qn=27,Vt=28,Xm=29,ft=30,$m=31,Ki=32,Vi=33,go=34,po=35,mo=36,En=37,Bo=38,Gi=39,ji=40,vo=41,pu=42,Ym=43,qm=[9001,65288],mu="!",M="×",Ji="÷",Co=Om(Km),wA=[ft,mo],wo=[Vm,cu,lu,jm],Bu=[GA,du],vu=[Qn,Un],Zm=wo.concat(Bu),Cu=[Bo,Gi,ji,go,po],zm=[wn,lo],eB=function(n,e){e===void 0&&(e="strict");var A=[],t=[],i=[];return n.forEach(function(r,s){var o=Co.get(r);if(o>au?(i.push(!0),o-=au):i.push(!1),["normal","auto","loose"].indexOf(e)!==-1&&[8208,8211,12316,12448].indexOf(r)!==-1)return t.push(s),A.push(uo);if(o===Gm||o===co){if(s===0)return t.push(s),A.push(ft);var a=A[s-1];return Zm.indexOf(a)===-1?(t.push(t[s-1]),A.push(a)):(t.push(s),A.push(ft))}if(t.push(s),o===$m)return A.push(e==="strict"?ho:En);if(o===pu||o===Xm)return A.push(ft);if(o===Ym)return r>=131072&&r<=196605||r>=196608&&r<=262141?A.push(En):A.push(ft);A.push(o)}),[t,A,i]},yo=function(n,e,A,t){var i=t[A];if(Array.isArray(n)?n.indexOf(i)!==-1:n===i)for(var r=A;r<=t.length;){r++;var s=t[r];if(s===e)return!0;if(s!==GA)break}if(i===GA)for(var r=A;r>0;){r--;var o=t[r];if(Array.isArray(n)?n.indexOf(o)!==-1:n===o)for(var a=A;a<=t.length;){a++;var s=t[a];if(s===e)return!0;if(s!==GA)break}if(o!==GA)break}return!1},wu=function(n,e){for(var A=n;A>=0;){var t=e[A];if(t===GA)A--;else return t}return 0},AB=function(n,e,A,t,i){if(A[t]===0)return M;var r=t-1;if(Array.isArray(i)&&i[r]===!0)return M;var s=r-1,o=r+1,a=e[r],c=s>=0?e[s]:0,l=e[o];if(a===cu&&l===lu)return M;if(wo.indexOf(a)!==-1)return mu;if(wo.indexOf(l)!==-1||Bu.indexOf(l)!==-1)return M;if(wu(r,e)===du)return Ji;if(Co.get(n[r])===co||(a===Ki||a===Vi)&&Co.get(n[o])===co||a===uu||l===uu||a===hu||[GA,lo,wn].indexOf(a)===-1&&l===hu||[Ni,yn,Wm,Kt,Vt].indexOf(l)!==-1||wu(r,e)===bn||yo(fo,bn,r,e)||yo([Ni,yn],ho,r,e)||yo(fu,fu,r,e))return M;if(a===GA)return Ji;if(a===fo||l===fo)return M;if(l===uo||a===uo)return Ji;if([lo,wn,ho].indexOf(l)!==-1||a===Jm||c===mo&&zm.indexOf(a)!==-1||a===Vt&&l===mo||l===gu||wA.indexOf(l)!==-1&&a===Me||wA.indexOf(a)!==-1&&l===Me||a===Qn&&[En,Ki,Vi].indexOf(l)!==-1||[En,Ki,Vi].indexOf(a)!==-1&&l===Un||wA.indexOf(a)!==-1&&vu.indexOf(l)!==-1||vu.indexOf(a)!==-1&&wA.indexOf(l)!==-1||[Qn,Un].indexOf(a)!==-1&&(l===Me||[bn,wn].indexOf(l)!==-1&&e[o+1]===Me)||[bn,wn].indexOf(a)!==-1&&l===Me||a===Me&&[Me,Vt,Kt].indexOf(l)!==-1)return M;if([Me,Vt,Kt,Ni,yn].indexOf(l)!==-1)for(var u=r;u>=0;){var d=e[u];if(d===Me)return M;if([Vt,Kt].indexOf(d)!==-1)u--;else break}if([Qn,Un].indexOf(l)!==-1)for(var u=[Ni,yn].indexOf(a)!==-1?s:r;u>=0;){var d=e[u];if(d===Me)return M;if([Vt,Kt].indexOf(d)!==-1)u--;else break}if(Bo===a&&[Bo,Gi,go,po].indexOf(l)!==-1||[Gi,go].indexOf(a)!==-1&&[Gi,ji].indexOf(l)!==-1||[ji,po].indexOf(a)!==-1&&l===ji||Cu.indexOf(a)!==-1&&[gu,Un].indexOf(l)!==-1||Cu.indexOf(l)!==-1&&a===Qn||wA.indexOf(a)!==-1&&wA.indexOf(l)!==-1||a===Kt&&wA.indexOf(l)!==-1||wA.concat(Me).indexOf(a)!==-1&&l===bn&&qm.indexOf(n[o])===-1||wA.concat(Me).indexOf(l)!==-1&&a===yn)return M;if(a===vo&&l===vo){for(var h=A[r],f=1;h>0&&(h--,e[h]===vo);)f++;if(f%2!==0)return M}return a===Ki&&l===Vi?M:Ji},tB=function(n,e){e||(e={lineBreak:"normal",wordBreak:"normal"});var A=eB(n,e.lineBreak),t=A[0],i=A[1],r=A[2];(e.wordBreak==="break-all"||e.wordBreak==="break-word")&&(i=i.map(function(o){return[Me,ft,pu].indexOf(o)!==-1?En:o}));var s=e.wordBreak==="keep-all"?r.map(function(o,a){return o&&n[a]>=19968&&n[a]<=40959}):void 0;return[t,i,s]},nB=function(){function n(e,A,t,i){this.codePoints=e,this.required=A===mu,this.start=t,this.end=i}return n.prototype.slice=function(){return le.apply(void 0,this.codePoints.slice(this.start,this.end))},n}(),iB=function(n,e){var A=_i(n),t=tB(A,e),i=t[0],r=t[1],s=t[2],o=A.length,a=0,c=0;return{next:function(){if(c>=o)return{done:!0,value:null};for(var l=M;c<o&&(l=AB(A,r,i,++c,s))===M;);if(l!==M||c===o){var u=new nB(A,l,a,c);return a=c,{value:u,done:!1}}return{done:!0,value:null}}}},rB=1,sB=2,Sn=4,yu=8,Wi=10,bu=47,Tn=92,oB=9,aB=32,Xi=34,Fn=61,cB=35,lB=36,uB=37,$i=39,Yi=40,kn=41,dB=95,Pe=45,hB=33,fB=60,gB=62,pB=64,mB=91,BB=93,vB=61,CB=123,qi=63,wB=125,Uu=124,yB=126,bB=128,Qu=65533,bo=42,gt=43,UB=44,QB=58,EB=59,In=46,SB=0,TB=8,FB=11,kB=14,IB=31,RB=127,lA=-1,Eu=48,Su=97,Tu=101,xB=102,PB=117,LB=122,Fu=65,ku=69,Iu=70,DB=85,_B=90,Qe=function(n){return n>=Eu&&n<=57},HB=function(n){return n>=55296&&n<=57343},Gt=function(n){return Qe(n)||n>=Fu&&n<=Iu||n>=Su&&n<=xB},OB=function(n){return n>=Su&&n<=LB},MB=function(n){return n>=Fu&&n<=_B},NB=function(n){return OB(n)||MB(n)},KB=function(n){return n>=bB},Zi=function(n){return n===Wi||n===oB||n===aB},zi=function(n){return NB(n)||KB(n)||n===dB},Ru=function(n){return zi(n)||Qe(n)||n===Pe},VB=function(n){return n>=SB&&n<=TB||n===FB||n>=kB&&n<=IB||n===RB},jA=function(n,e){return n!==Tn?!1:e!==Wi},er=function(n,e,A){return n===Pe?zi(e)||jA(e,A):zi(n)?!0:!!(n===Tn&&jA(n,e))},Uo=function(n,e,A){return n===gt||n===Pe?Qe(e)?!0:e===In&&Qe(A):Qe(n===In?e:n)},GB=function(n){var e=0,A=1;(n[e]===gt||n[e]===Pe)&&(n[e]===Pe&&(A=-1),e++);for(var t=[];Qe(n[e]);)t.push(n[e++]);var i=t.length?parseInt(le.apply(void 0,t),10):0;n[e]===In&&e++;for(var r=[];Qe(n[e]);)r.push(n[e++]);var s=r.length,o=s?parseInt(le.apply(void 0,r),10):0;(n[e]===ku||n[e]===Tu)&&e++;var a=1;(n[e]===gt||n[e]===Pe)&&(n[e]===Pe&&(a=-1),e++);for(var c=[];Qe(n[e]);)c.push(n[e++]);var l=c.length?parseInt(le.apply(void 0,c),10):0;return A*(i+o*Math.pow(10,-s))*Math.pow(10,a*l)},jB={type:2},JB={type:3},WB={type:4},XB={type:13},$B={type:8},YB={type:21},qB={type:9},ZB={type:10},zB={type:11},ev={type:12},Av={type:14},Ar={type:23},tv={type:1},nv={type:25},iv={type:24},rv={type:26},sv={type:27},ov={type:28},av={type:29},cv={type:31},Qo={type:32},xu=function(){function n(){this._value=[]}return n.prototype.write=function(e){this._value=this._value.concat(_i(e))},n.prototype.read=function(){for(var e=[],A=this.consumeToken();A!==Qo;)e.push(A),A=this.consumeToken();return e},n.prototype.consumeToken=function(){var e=this.consumeCodePoint();switch(e){case Xi:return this.consumeStringToken(Xi);case cB:var A=this.peekCodePoint(0),t=this.peekCodePoint(1),i=this.peekCodePoint(2);if(Ru(A)||jA(t,i)){var r=er(A,t,i)?sB:rB,s=this.consumeName();return{type:5,value:s,flags:r}}break;case lB:if(this.peekCodePoint(0)===Fn)return this.consumeCodePoint(),XB;break;case $i:return this.consumeStringToken($i);case Yi:return jB;case kn:return JB;case bo:if(this.peekCodePoint(0)===Fn)return this.consumeCodePoint(),Av;break;case gt:if(Uo(e,this.peekCodePoint(0),this.peekCodePoint(1)))return this.reconsumeCodePoint(e),this.consumeNumericToken();break;case UB:return WB;case Pe:var o=e,a=this.peekCodePoint(0),c=this.peekCodePoint(1);if(Uo(o,a,c))return this.reconsumeCodePoint(e),this.consumeNumericToken();if(er(o,a,c))return this.reconsumeCodePoint(e),this.consumeIdentLikeToken();if(a===Pe&&c===gB)return this.consumeCodePoint(),this.consumeCodePoint(),iv;break;case In:if(Uo(e,this.peekCodePoint(0),this.peekCodePoint(1)))return this.reconsumeCodePoint(e),this.consumeNumericToken();break;case bu:if(this.peekCodePoint(0)===bo)for(this.consumeCodePoint();;){var l=this.consumeCodePoint();if(l===bo&&(l=this.consumeCodePoint(),l===bu))return this.consumeToken();if(l===lA)return this.consumeToken()}break;case QB:return rv;case EB:return sv;case fB:if(this.peekCodePoint(0)===hB&&this.peekCodePoint(1)===Pe&&this.peekCodePoint(2)===Pe)return this.consumeCodePoint(),this.consumeCodePoint(),nv;break;case pB:var u=this.peekCodePoint(0),d=this.peekCodePoint(1),h=this.peekCodePoint(2);if(er(u,d,h)){var s=this.consumeName();return{type:7,value:s}}break;case mB:return ov;case Tn:if(jA(e,this.peekCodePoint(0)))return this.reconsumeCodePoint(e),this.consumeIdentLikeToken();break;case BB:return av;case vB:if(this.peekCodePoint(0)===Fn)return this.consumeCodePoint(),$B;break;case CB:return zB;case wB:return ev;case PB:case DB:var f=this.peekCodePoint(0),g=this.peekCodePoint(1);return f===gt&&(Gt(g)||g===qi)&&(this.consumeCodePoint(),this.consumeUnicodeRangeToken()),this.reconsumeCodePoint(e),this.consumeIdentLikeToken();case Uu:if(this.peekCodePoint(0)===Fn)return this.consumeCodePoint(),qB;if(this.peekCodePoint(0)===Uu)return this.consumeCodePoint(),YB;break;case yB:if(this.peekCodePoint(0)===Fn)return this.consumeCodePoint(),ZB;break;case lA:return Qo}return Zi(e)?(this.consumeWhiteSpace(),cv):Qe(e)?(this.reconsumeCodePoint(e),this.consumeNumericToken()):zi(e)?(this.reconsumeCodePoint(e),this.consumeIdentLikeToken()):{type:6,value:le(e)}},n.prototype.consumeCodePoint=function(){var e=this._value.shift();return typeof e>"u"?-1:e},n.prototype.reconsumeCodePoint=function(e){this._value.unshift(e)},n.prototype.peekCodePoint=function(e){return e>=this._value.length?-1:this._value[e]},n.prototype.consumeUnicodeRangeToken=function(){for(var e=[],A=this.consumeCodePoint();Gt(A)&&e.length<6;)e.push(A),A=this.consumeCodePoint();for(var t=!1;A===qi&&e.length<6;)e.push(A),A=this.consumeCodePoint(),t=!0;if(t){var i=parseInt(le.apply(void 0,e.map(function(a){return a===qi?Eu:a})),16),r=parseInt(le.apply(void 0,e.map(function(a){return a===qi?Iu:a})),16);return{type:30,start:i,end:r}}var s=parseInt(le.apply(void 0,e),16);if(this.peekCodePoint(0)===Pe&&Gt(this.peekCodePoint(1))){this.consumeCodePoint(),A=this.consumeCodePoint();for(var o=[];Gt(A)&&o.length<6;)o.push(A),A=this.consumeCodePoint();var r=parseInt(le.apply(void 0,o),16);return{type:30,start:s,end:r}}else return{type:30,start:s,end:s}},n.prototype.consumeIdentLikeToken=function(){var e=this.consumeName();return e.toLowerCase()==="url"&&this.peekCodePoint(0)===Yi?(this.consumeCodePoint(),this.consumeUrlToken()):this.peekCodePoint(0)===Yi?(this.consumeCodePoint(),{type:19,value:e}):{type:20,value:e}},n.prototype.consumeUrlToken=function(){var e=[];if(this.consumeWhiteSpace(),this.peekCodePoint(0)===lA)return{type:22,value:""};var A=this.peekCodePoint(0);if(A===$i||A===Xi){var t=this.consumeStringToken(this.consumeCodePoint());return t.type===0&&(this.consumeWhiteSpace(),this.peekCodePoint(0)===lA||this.peekCodePoint(0)===kn)?(this.consumeCodePoint(),{type:22,value:t.value}):(this.consumeBadUrlRemnants(),Ar)}for(;;){var i=this.consumeCodePoint();if(i===lA||i===kn)return{type:22,value:le.apply(void 0,e)};if(Zi(i))return this.consumeWhiteSpace(),this.peekCodePoint(0)===lA||this.peekCodePoint(0)===kn?(this.consumeCodePoint(),{type:22,value:le.apply(void 0,e)}):(this.consumeBadUrlRemnants(),Ar);if(i===Xi||i===$i||i===Yi||VB(i))return this.consumeBadUrlRemnants(),Ar;if(i===Tn)if(jA(i,this.peekCodePoint(0)))e.push(this.consumeEscapedCodePoint());else return this.consumeBadUrlRemnants(),Ar;else e.push(i)}},n.prototype.consumeWhiteSpace=function(){for(;Zi(this.peekCodePoint(0));)this.consumeCodePoint()},n.prototype.consumeBadUrlRemnants=function(){for(;;){var e=this.consumeCodePoint();if(e===kn||e===lA)return;jA(e,this.peekCodePoint(0))&&this.consumeEscapedCodePoint()}},n.prototype.consumeStringSlice=function(e){for(var A=5e4,t="";e>0;){var i=Math.min(A,e);t+=le.apply(void 0,this._value.splice(0,i)),e-=i}return this._value.shift(),t},n.prototype.consumeStringToken=function(e){var A="",t=0;do{var i=this._value[t];if(i===lA||i===void 0||i===e)return A+=this.consumeStringSlice(t),{type:0,value:A};if(i===Wi)return this._value.splice(0,t),tv;if(i===Tn){var r=this._value[t+1];r!==lA&&r!==void 0&&(r===Wi?(A+=this.consumeStringSlice(t),t=-1,this._value.shift()):jA(i,r)&&(A+=this.consumeStringSlice(t),A+=le(this.consumeEscapedCodePoint()),t=-1))}t++}while(!0)},n.prototype.consumeNumber=function(){var e=[],A=Sn,t=this.peekCodePoint(0);for((t===gt||t===Pe)&&e.push(this.consumeCodePoint());Qe(this.peekCodePoint(0));)e.push(this.consumeCodePoint());t=this.peekCodePoint(0);var i=this.peekCodePoint(1);if(t===In&&Qe(i))for(e.push(this.consumeCodePoint(),this.consumeCodePoint()),A=yu;Qe(this.peekCodePoint(0));)e.push(this.consumeCodePoint());t=this.peekCodePoint(0),i=this.peekCodePoint(1);var r=this.peekCodePoint(2);if((t===ku||t===Tu)&&((i===gt||i===Pe)&&Qe(r)||Qe(i)))for(e.push(this.consumeCodePoint(),this.consumeCodePoint()),A=yu;Qe(this.peekCodePoint(0));)e.push(this.consumeCodePoint());return[GB(e),A]},n.prototype.consumeNumericToken=function(){var e=this.consumeNumber(),A=e[0],t=e[1],i=this.peekCodePoint(0),r=this.peekCodePoint(1),s=this.peekCodePoint(2);if(er(i,r,s)){var o=this.consumeName();return{type:15,number:A,flags:t,unit:o}}return i===uB?(this.consumeCodePoint(),{type:16,number:A,flags:t}):{type:17,number:A,flags:t}},n.prototype.consumeEscapedCodePoint=function(){var e=this.consumeCodePoint();if(Gt(e)){for(var A=le(e);Gt(this.peekCodePoint(0))&&A.length<6;)A+=le(this.consumeCodePoint());Zi(this.peekCodePoint(0))&&this.consumeCodePoint();var t=parseInt(A,16);return t===0||HB(t)||t>1114111?Qu:t}return e===lA?Qu:e},n.prototype.consumeName=function(){for(var e="";;){var A=this.consumeCodePoint();if(Ru(A))e+=le(A);else if(jA(A,this.peekCodePoint(0)))e+=le(this.consumeEscapedCodePoint());else return this.reconsumeCodePoint(A),e}},n}(),Pu=function(){function n(e){this._tokens=e}return n.create=function(e){var A=new xu;return A.write(e),new n(A.read())},n.parseValue=function(e){return n.create(e).parseComponentValue()},n.parseValues=function(e){return n.create(e).parseComponentValues()},n.prototype.parseComponentValue=function(){for(var e=this.consumeToken();e.type===31;)e=this.consumeToken();if(e.type===32)throw new SyntaxError("Error parsing CSS component value, unexpected EOF");this.reconsumeToken(e);var A=this.consumeComponentValue();do e=this.consumeToken();while(e.type===31);if(e.type===32)return A;throw new SyntaxError("Error parsing CSS component value, multiple values found when expecting only one")},n.prototype.parseComponentValues=function(){for(var e=[];;){var A=this.consumeComponentValue();if(A.type===32)return e;e.push(A),e.push()}},n.prototype.consumeComponentValue=function(){var e=this.consumeToken();switch(e.type){case 11:case 28:case 2:return this.consumeSimpleBlock(e.type);case 19:return this.consumeFunction(e)}return e},n.prototype.consumeSimpleBlock=function(e){for(var A={type:e,values:[]},t=this.consumeToken();;){if(t.type===32||uv(t,e))return A;this.reconsumeToken(t),A.values.push(this.consumeComponentValue()),t=this.consumeToken()}},n.prototype.consumeFunction=function(e){for(var A={name:e.value,values:[],type:18};;){var t=this.consumeToken();if(t.type===32||t.type===3)return A;this.reconsumeToken(t),A.values.push(this.consumeComponentValue())}},n.prototype.consumeToken=function(){var e=this._tokens.shift();return typeof e>"u"?Qo:e},n.prototype.reconsumeToken=function(e){this._tokens.unshift(e)},n}(),Rn=function(n){return n.type===15},jt=function(n){return n.type===17},q=function(n){return n.type===20},lv=function(n){return n.type===0},Eo=function(n,e){return q(n)&&n.value===e},Lu=function(n){return n.type!==31},Jt=function(n){return n.type!==31&&n.type!==4},uA=function(n){var e=[],A=[];return n.forEach(function(t){if(t.type===4){if(A.length===0)throw new Error("Error parsing function args, zero tokens for arg");e.push(A),A=[];return}t.type!==31&&A.push(t)}),A.length&&e.push(A),e},uv=function(n,e){return e===11&&n.type===12||e===28&&n.type===29?!0:e===2&&n.type===3},JA=function(n){return n.type===17||n.type===15},he=function(n){return n.type===16||JA(n)},Du=function(n){return n.length>1?[n[0],n[1]]:[n[0]]},ye={type:17,number:0,flags:Sn},So={type:16,number:50,flags:Sn},WA={type:16,number:100,flags:Sn},xn=function(n,e,A){var t=n[0],i=n[1];return[ee(t,e),ee(typeof i<"u"?i:t,A)]},ee=function(n,e){if(n.type===16)return n.number/100*e;if(Rn(n))switch(n.unit){case"rem":case"em":return 16*n.number;case"px":default:return n.number}return n.number},_u="deg",Hu="grad",Ou="rad",Mu="turn",tr={name:"angle",parse:function(n,e){if(e.type===15)switch(e.unit){case _u:return Math.PI*e.number/180;case Hu:return Math.PI/200*e.number;case Ou:return e.number;case Mu:return Math.PI*2*e.number}throw new Error("Unsupported angle type")}},Nu=function(n){return n.type===15&&(n.unit===_u||n.unit===Hu||n.unit===Ou||n.unit===Mu)},Ku=function(n){var e=n.filter(q).map(function(A){return A.value}).join(" ");switch(e){case"to bottom right":case"to right bottom":case"left top":case"top left":return[ye,ye];case"to top":case"bottom":return Ke(0);case"to bottom left":case"to left bottom":case"right top":case"top right":return[ye,WA];case"to right":case"left":return Ke(90);case"to top left":case"to left top":case"right bottom":case"bottom right":return[WA,WA];case"to bottom":case"top":return Ke(180);case"to top right":case"to right top":case"left bottom":case"bottom left":return[WA,ye];case"to left":case"right":return Ke(270)}return 0},Ke=function(n){return Math.PI*n/180},XA={name:"color",parse:function(n,e){if(e.type===18){var A=dv[e.name];if(typeof A>"u")throw new Error('Attempting to parse an unsupported color function "'+e.name+'"');return A(n,e.values)}if(e.type===5){if(e.value.length===3){var t=e.value.substring(0,1),i=e.value.substring(1,2),r=e.value.substring(2,3);return YA(parseInt(t+t,16),parseInt(i+i,16),parseInt(r+r,16),1)}if(e.value.length===4){var t=e.value.substring(0,1),i=e.value.substring(1,2),r=e.value.substring(2,3),s=e.value.substring(3,4);return YA(parseInt(t+t,16),parseInt(i+i,16),parseInt(r+r,16),parseInt(s+s,16)/255)}if(e.value.length===6){var t=e.value.substring(0,2),i=e.value.substring(2,4),r=e.value.substring(4,6);return YA(parseInt(t,16),parseInt(i,16),parseInt(r,16),1)}if(e.value.length===8){var t=e.value.substring(0,2),i=e.value.substring(2,4),r=e.value.substring(4,6),s=e.value.substring(6,8);return YA(parseInt(t,16),parseInt(i,16),parseInt(r,16),parseInt(s,16)/255)}}if(e.type===20){var o=yA[e.value.toUpperCase()];if(typeof o<"u")return o}return yA.TRANSPARENT}},$A=function(n){return(255&n)===0},Be=function(n){var e=255&n,A=255&n>>8,t=255&n>>16,i=255&n>>24;return e<255?"rgba("+i+","+t+","+A+","+e/255+")":"rgb("+i+","+t+","+A+")"},YA=function(n,e,A,t){return(n<<24|e<<16|A<<8|Math.round(t*255)<<0)>>>0},Vu=function(n,e){if(n.type===17)return n.number;if(n.type===16){var A=e===3?1:255;return e===3?n.number/100*A:Math.round(n.number/100*A)}return 0},Gu=function(n,e){var A=e.filter(Jt);if(A.length===3){var t=A.map(Vu),i=t[0],r=t[1],s=t[2];return YA(i,r,s,1)}if(A.length===4){var o=A.map(Vu),i=o[0],r=o[1],s=o[2],a=o[3];return YA(i,r,s,a)}return 0};function To(n,e,A){return A<0&&(A+=1),A>=1&&(A-=1),A<1/6?(e-n)*A*6+n:A<1/2?e:A<2/3?(e-n)*6*(2/3-A)+n:n}var ju=function(n,e){var A=e.filter(Jt),t=A[0],i=A[1],r=A[2],s=A[3],o=(t.type===17?Ke(t.number):tr.parse(n,t))/(Math.PI*2),a=he(i)?i.number/100:0,c=he(r)?r.number/100:0,l=typeof s<"u"&&he(s)?ee(s,1):1;if(a===0)return YA(c*255,c*255,c*255,1);var u=c<=.5?c*(a+1):c+a-c*a,d=c*2-u,h=To(d,u,o+1/3),f=To(d,u,o),g=To(d,u,o-1/3);return YA(h*255,f*255,g*255,l)},dv={hsl:ju,hsla:ju,rgb:Gu,rgba:Gu},Pn=function(n,e){return XA.parse(n,Pu.create(e).parseComponentValue())},yA={ALICEBLUE:4042850303,ANTIQUEWHITE:4209760255,AQUA:16777215,AQUAMARINE:2147472639,AZURE:4043309055,BEIGE:4126530815,BISQUE:4293182719,BLACK:255,BLANCHEDALMOND:4293643775,BLUE:65535,BLUEVIOLET:2318131967,BROWN:2771004159,BURLYWOOD:3736635391,CADETBLUE:1604231423,CHARTREUSE:2147418367,CHOCOLATE:3530104575,CORAL:4286533887,CORNFLOWERBLUE:1687547391,CORNSILK:4294499583,CRIMSON:3692313855,CYAN:16777215,DARKBLUE:35839,DARKCYAN:9145343,DARKGOLDENROD:3095837695,DARKGRAY:2846468607,DARKGREEN:6553855,DARKGREY:2846468607,DARKKHAKI:3182914559,DARKMAGENTA:2332068863,DARKOLIVEGREEN:1433087999,DARKORANGE:4287365375,DARKORCHID:2570243327,DARKRED:2332033279,DARKSALMON:3918953215,DARKSEAGREEN:2411499519,DARKSLATEBLUE:1211993087,DARKSLATEGRAY:793726975,DARKSLATEGREY:793726975,DARKTURQUOISE:13554175,DARKVIOLET:2483082239,DEEPPINK:4279538687,DEEPSKYBLUE:12582911,DIMGRAY:1768516095,DIMGREY:1768516095,DODGERBLUE:512819199,FIREBRICK:2988581631,FLORALWHITE:4294635775,FORESTGREEN:579543807,FUCHSIA:4278255615,GAINSBORO:3705462015,GHOSTWHITE:4177068031,GOLD:4292280575,GOLDENROD:3668254975,GRAY:2155905279,GREEN:8388863,GREENYELLOW:2919182335,GREY:2155905279,HONEYDEW:4043305215,HOTPINK:4285117695,INDIANRED:3445382399,INDIGO:1258324735,IVORY:4294963455,KHAKI:4041641215,LAVENDER:3873897215,LAVENDERBLUSH:4293981695,LAWNGREEN:2096890111,LEMONCHIFFON:4294626815,LIGHTBLUE:2916673279,LIGHTCORAL:4034953471,LIGHTCYAN:3774873599,LIGHTGOLDENRODYELLOW:4210742015,LIGHTGRAY:3553874943,LIGHTGREEN:2431553791,LIGHTGREY:3553874943,LIGHTPINK:4290167295,LIGHTSALMON:4288707327,LIGHTSEAGREEN:548580095,LIGHTSKYBLUE:2278488831,LIGHTSLATEGRAY:2005441023,LIGHTSLATEGREY:2005441023,LIGHTSTEELBLUE:2965692159,LIGHTYELLOW:4294959359,LIME:16711935,LIMEGREEN:852308735,LINEN:4210091775,MAGENTA:4278255615,MAROON:2147483903,MEDIUMAQUAMARINE:1724754687,MEDIUMBLUE:52735,MEDIUMORCHID:3126187007,MEDIUMPURPLE:2473647103,MEDIUMSEAGREEN:1018393087,MEDIUMSLATEBLUE:2070474495,MEDIUMSPRINGGREEN:16423679,MEDIUMTURQUOISE:1221709055,MEDIUMVIOLETRED:3340076543,MIDNIGHTBLUE:421097727,MINTCREAM:4127193855,MISTYROSE:4293190143,MOCCASIN:4293178879,NAVAJOWHITE:4292783615,NAVY:33023,OLDLACE:4260751103,OLIVE:2155872511,OLIVEDRAB:1804477439,ORANGE:4289003775,ORANGERED:4282712319,ORCHID:3664828159,PALEGOLDENROD:4008225535,PALEGREEN:2566625535,PALETURQUOISE:2951671551,PALEVIOLETRED:3681588223,PAPAYAWHIP:4293907967,PEACHPUFF:4292524543,PERU:3448061951,PINK:4290825215,PLUM:3718307327,POWDERBLUE:2967529215,PURPLE:2147516671,REBECCAPURPLE:1714657791,RED:4278190335,ROSYBROWN:3163525119,ROYALBLUE:1097458175,SADDLEBROWN:2336560127,SALMON:4202722047,SANDYBROWN:4104413439,SEAGREEN:780883967,SEASHELL:4294307583,SIENNA:2689740287,SILVER:3233857791,SKYBLUE:2278484991,SLATEBLUE:1784335871,SLATEGRAY:1887473919,SLATEGREY:1887473919,SNOW:4294638335,SPRINGGREEN:16744447,STEELBLUE:1182971135,TAN:3535047935,TEAL:8421631,THISTLE:3636451583,TOMATO:4284696575,TRANSPARENT:0,TURQUOISE:1088475391,VIOLET:4001558271,WHEAT:4125012991,WHITE:4294967295,WHITESMOKE:4126537215,YELLOW:4294902015,YELLOWGREEN:2597139199},hv={name:"background-clip",initialValue:"border-box",prefix:!1,type:1,parse:function(n,e){return e.map(function(A){if(q(A))switch(A.value){case"padding-box":return 1;case"content-box":return 2}return 0})}},fv={name:"background-color",initialValue:"transparent",prefix:!1,type:3,format:"color"},nr=function(n,e){var A=XA.parse(n,e[0]),t=e[1];return t&&he(t)?{color:A,stop:t}:{color:A,stop:null}},Ju=function(n,e){var A=n[0],t=n[n.length-1];A.stop===null&&(A.stop=ye),t.stop===null&&(t.stop=WA);for(var i=[],r=0,s=0;s<n.length;s++){var o=n[s].stop;if(o!==null){var a=ee(o,e);a>r?i.push(a):i.push(r),r=a}else i.push(null)}for(var c=null,s=0;s<i.length;s++){var l=i[s];if(l===null)c===null&&(c=s);else if(c!==null){for(var u=s-c,d=i[c-1],h=(l-d)/(u+1),f=1;f<=u;f++)i[c+f-1]=h*f;c=null}}return n.map(function(g,m){var C=g.color;return{color:C,stop:Math.max(Math.min(1,i[m]/e),0)}})},gv=function(n,e,A){var t=e/2,i=A/2,r=ee(n[0],e)-t,s=i-ee(n[1],A);return(Math.atan2(s,r)+Math.PI*2)%(Math.PI*2)},pv=function(n,e,A){var t=typeof n=="number"?n:gv(n,e,A),i=Math.abs(e*Math.sin(t))+Math.abs(A*Math.cos(t)),r=e/2,s=A/2,o=i/2,a=Math.sin(t-Math.PI/2)*o,c=Math.cos(t-Math.PI/2)*o;return[i,r-c,r+c,s-a,s+a]},tA=function(n,e){return Math.sqrt(n*n+e*e)},Wu=function(n,e,A,t,i){var r=[[0,0],[0,e],[n,0],[n,e]];return r.reduce(function(s,o){var a=o[0],c=o[1],l=tA(A-a,t-c);return(i?l<s.optimumDistance:l>s.optimumDistance)?{optimumCorner:o,optimumDistance:l}:s},{optimumDistance:i?1/0:-1/0,optimumCorner:null}).optimumCorner},mv=function(n,e,A,t,i){var r=0,s=0;switch(n.size){case 0:n.shape===0?r=s=Math.min(Math.abs(e),Math.abs(e-t),Math.abs(A),Math.abs(A-i)):n.shape===1&&(r=Math.min(Math.abs(e),Math.abs(e-t)),s=Math.min(Math.abs(A),Math.abs(A-i)));break;case 2:if(n.shape===0)r=s=Math.min(tA(e,A),tA(e,A-i),tA(e-t,A),tA(e-t,A-i));else if(n.shape===1){var o=Math.min(Math.abs(A),Math.abs(A-i))/Math.min(Math.abs(e),Math.abs(e-t)),a=Wu(t,i,e,A,!0),c=a[0],l=a[1];r=tA(c-e,(l-A)/o),s=o*r}break;case 1:n.shape===0?r=s=Math.max(Math.abs(e),Math.abs(e-t),Math.abs(A),Math.abs(A-i)):n.shape===1&&(r=Math.max(Math.abs(e),Math.abs(e-t)),s=Math.max(Math.abs(A),Math.abs(A-i)));break;case 3:if(n.shape===0)r=s=Math.max(tA(e,A),tA(e,A-i),tA(e-t,A),tA(e-t,A-i));else if(n.shape===1){var o=Math.max(Math.abs(A),Math.abs(A-i))/Math.max(Math.abs(e),Math.abs(e-t)),u=Wu(t,i,e,A,!1),c=u[0],l=u[1];r=tA(c-e,(l-A)/o),s=o*r}break}return Array.isArray(n.size)&&(r=ee(n.size[0],t),s=n.size.length===2?ee(n.size[1],i):r),[r,s]},Bv=function(n,e){var A=Ke(180),t=[];return uA(e).forEach(function(i,r){if(r===0){var s=i[0];if(s.type===20&&s.value==="to"){A=Ku(i);return}else if(Nu(s)){A=tr.parse(n,s);return}}var o=nr(n,i);t.push(o)}),{angle:A,stops:t,type:1}},ir=function(n,e){var A=Ke(180),t=[];return uA(e).forEach(function(i,r){if(r===0){var s=i[0];if(s.type===20&&["top","left","right","bottom"].indexOf(s.value)!==-1){A=Ku(i);return}else if(Nu(s)){A=(tr.parse(n,s)+Ke(270))%Ke(360);return}}var o=nr(n,i);t.push(o)}),{angle:A,stops:t,type:1}},vv=function(n,e){var A=Ke(180),t=[],i=1,r=0,s=3,o=[];return uA(e).forEach(function(a,c){var l=a[0];if(c===0){if(q(l)&&l.value==="linear"){i=1;return}else if(q(l)&&l.value==="radial"){i=2;return}}if(l.type===18){if(l.name==="from"){var u=XA.parse(n,l.values[0]);t.push({stop:ye,color:u})}else if(l.name==="to"){var u=XA.parse(n,l.values[0]);t.push({stop:WA,color:u})}else if(l.name==="color-stop"){var d=l.values.filter(Jt);if(d.length===2){var u=XA.parse(n,d[1]),h=d[0];jt(h)&&t.push({stop:{type:16,number:h.number*100,flags:h.flags},color:u})}}}}),i===1?{angle:(A+Ke(180))%Ke(360),stops:t,type:i}:{size:s,shape:r,stops:t,position:o,type:i}},Xu="closest-side",$u="farthest-side",Yu="closest-corner",qu="farthest-corner",Zu="circle",zu="ellipse",ed="cover",Ad="contain",Cv=function(n,e){var A=0,t=3,i=[],r=[];return uA(e).forEach(function(s,o){var a=!0;if(o===0){var c=!1;a=s.reduce(function(u,d){if(c)if(q(d))switch(d.value){case"center":return r.push(So),u;case"top":case"left":return r.push(ye),u;case"right":case"bottom":return r.push(WA),u}else(he(d)||JA(d))&&r.push(d);else if(q(d))switch(d.value){case Zu:return A=0,!1;case zu:return A=1,!1;case"at":return c=!0,!1;case Xu:return t=0,!1;case ed:case $u:return t=1,!1;case Ad:case Yu:return t=2,!1;case qu:return t=3,!1}else if(JA(d)||he(d))return Array.isArray(t)||(t=[]),t.push(d),!1;return u},a)}if(a){var l=nr(n,s);i.push(l)}}),{size:t,shape:A,stops:i,position:r,type:2}},rr=function(n,e){var A=0,t=3,i=[],r=[];return uA(e).forEach(function(s,o){var a=!0;if(o===0?a=s.reduce(function(l,u){if(q(u))switch(u.value){case"center":return r.push(So),!1;case"top":case"left":return r.push(ye),!1;case"right":case"bottom":return r.push(WA),!1}else if(he(u)||JA(u))return r.push(u),!1;return l},a):o===1&&(a=s.reduce(function(l,u){if(q(u))switch(u.value){case Zu:return A=0,!1;case zu:return A=1,!1;case Ad:case Xu:return t=0,!1;case $u:return t=1,!1;case Yu:return t=2,!1;case ed:case qu:return t=3,!1}else if(JA(u)||he(u))return Array.isArray(t)||(t=[]),t.push(u),!1;return l},a)),a){var c=nr(n,s);i.push(c)}}),{size:t,shape:A,stops:i,position:r,type:2}},wv=function(n){return n.type===1},yv=function(n){return n.type===2},Fo={name:"image",parse:function(n,e){if(e.type===22){var A={url:e.value,type:0};return n.cache.addImage(e.value),A}if(e.type===18){var t=td[e.name];if(typeof t>"u")throw new Error('Attempting to parse an unsupported image function "'+e.name+'"');return t(n,e.values)}throw new Error("Unsupported image type "+e.type)}};function bv(n){return!(n.type===20&&n.value==="none")&&(n.type!==18||!!td[n.name])}var td={"linear-gradient":Bv,"-moz-linear-gradient":ir,"-ms-linear-gradient":ir,"-o-linear-gradient":ir,"-webkit-linear-gradient":ir,"radial-gradient":Cv,"-moz-radial-gradient":rr,"-ms-radial-gradient":rr,"-o-radial-gradient":rr,"-webkit-radial-gradient":rr,"-webkit-gradient":vv},Uv={name:"background-image",initialValue:"none",type:1,prefix:!1,parse:function(n,e){if(e.length===0)return[];var A=e[0];return A.type===20&&A.value==="none"?[]:e.filter(function(t){return Jt(t)&&bv(t)}).map(function(t){return Fo.parse(n,t)})}},Qv={name:"background-origin",initialValue:"border-box",prefix:!1,type:1,parse:function(n,e){return e.map(function(A){if(q(A))switch(A.value){case"padding-box":return 1;case"content-box":return 2}return 0})}},Ev={name:"background-position",initialValue:"0% 0%",type:1,prefix:!1,parse:function(n,e){return uA(e).map(function(A){return A.filter(he)}).map(Du)}},Sv={name:"background-repeat",initialValue:"repeat",prefix:!1,type:1,parse:function(n,e){return uA(e).map(function(A){return A.filter(q).map(function(t){return t.value}).join(" ")}).map(Tv)}},Tv=function(n){switch(n){case"no-repeat":return 1;case"repeat-x":case"repeat no-repeat":return 2;case"repeat-y":case"no-repeat repeat":return 3;case"repeat":default:return 0}},Wt;(function(n){n.AUTO="auto",n.CONTAIN="contain",n.COVER="cover"})(Wt||(Wt={}));var Fv={name:"background-size",initialValue:"0",prefix:!1,type:1,parse:function(n,e){return uA(e).map(function(A){return A.filter(kv)})}},kv=function(n){return q(n)||he(n)},sr=function(n){return{name:"border-"+n+"-color",initialValue:"transparent",prefix:!1,type:3,format:"color"}},Iv=sr("top"),Rv=sr("right"),xv=sr("bottom"),Pv=sr("left"),or=function(n){return{name:"border-radius-"+n,initialValue:"0 0",prefix:!1,type:1,parse:function(e,A){return Du(A.filter(he))}}},Lv=or("top-left"),Dv=or("top-right"),_v=or("bottom-right"),Hv=or("bottom-left"),ar=function(n){return{name:"border-"+n+"-style",initialValue:"solid",prefix:!1,type:2,parse:function(e,A){switch(A){case"none":return 0;case"dashed":return 2;case"dotted":return 3;case"double":return 4}return 1}}},Ov=ar("top"),Mv=ar("right"),Nv=ar("bottom"),Kv=ar("left"),cr=function(n){return{name:"border-"+n+"-width",initialValue:"0",type:0,prefix:!1,parse:function(e,A){return Rn(A)?A.number:0}}},Vv=cr("top"),Gv=cr("right"),jv=cr("bottom"),Jv=cr("left"),Wv={name:"color",initialValue:"transparent",prefix:!1,type:3,format:"color"},Xv={name:"direction",initialValue:"ltr",prefix:!1,type:2,parse:function(n,e){switch(e){case"rtl":return 1;case"ltr":default:return 0}}},$v={name:"display",initialValue:"inline-block",prefix:!1,type:1,parse:function(n,e){return e.filter(q).reduce(function(A,t){return A|Yv(t.value)},0)}},Yv=function(n){switch(n){case"block":case"-webkit-box":return 2;case"inline":return 4;case"run-in":return 8;case"flow":return 16;case"flow-root":return 32;case"table":return 64;case"flex":case"-webkit-flex":return 128;case"grid":case"-ms-grid":return 256;case"ruby":return 512;case"subgrid":return 1024;case"list-item":return 2048;case"table-row-group":return 4096;case"table-header-group":return 8192;case"table-footer-group":return 16384;case"table-row":return 32768;case"table-cell":return 65536;case"table-column-group":return 131072;case"table-column":return 262144;case"table-caption":return 524288;case"ruby-base":return 1048576;case"ruby-text":return 2097152;case"ruby-base-container":return 4194304;case"ruby-text-container":return 8388608;case"contents":return 16777216;case"inline-block":return 33554432;case"inline-list-item":return 67108864;case"inline-table":return 134217728;case"inline-flex":return 268435456;case"inline-grid":return 536870912}return 0},qv={name:"float",initialValue:"none",prefix:!1,type:2,parse:function(n,e){switch(e){case"left":return 1;case"right":return 2;case"inline-start":return 3;case"inline-end":return 4}return 0}},Zv={name:"letter-spacing",initialValue:"0",prefix:!1,type:0,parse:function(n,e){return e.type===20&&e.value==="normal"?0:e.type===17||e.type===15?e.number:0}},lr;(function(n){n.NORMAL="normal",n.STRICT="strict"})(lr||(lr={}));var zv={name:"line-break",initialValue:"normal",prefix:!1,type:2,parse:function(n,e){switch(e){case"strict":return lr.STRICT;case"normal":default:return lr.NORMAL}}},eC={name:"line-height",initialValue:"normal",prefix:!1,type:4},nd=function(n,e){return q(n)&&n.value==="normal"?1.2*e:n.type===17?e*n.number:he(n)?ee(n,e):e},AC={name:"list-style-image",initialValue:"none",type:0,prefix:!1,parse:function(n,e){return e.type===20&&e.value==="none"?null:Fo.parse(n,e)}},tC={name:"list-style-position",initialValue:"outside",prefix:!1,type:2,parse:function(n,e){switch(e){case"inside":return 0;case"outside":default:return 1}}},ko={name:"list-style-type",initialValue:"none",prefix:!1,type:2,parse:function(n,e){switch(e){case"disc":return 0;case"circle":return 1;case"square":return 2;case"decimal":return 3;case"cjk-decimal":return 4;case"decimal-leading-zero":return 5;case"lower-roman":return 6;case"upper-roman":return 7;case"lower-greek":return 8;case"lower-alpha":return 9;case"upper-alpha":return 10;case"arabic-indic":return 11;case"armenian":return 12;case"bengali":return 13;case"cambodian":return 14;case"cjk-earthly-branch":return 15;case"cjk-heavenly-stem":return 16;case"cjk-ideographic":return 17;case"devanagari":return 18;case"ethiopic-numeric":return 19;case"georgian":return 20;case"gujarati":return 21;case"gurmukhi":return 22;case"hebrew":return 22;case"hiragana":return 23;case"hiragana-iroha":return 24;case"japanese-formal":return 25;case"japanese-informal":return 26;case"kannada":return 27;case"katakana":return 28;case"katakana-iroha":return 29;case"khmer":return 30;case"korean-hangul-formal":return 31;case"korean-hanja-formal":return 32;case"korean-hanja-informal":return 33;case"lao":return 34;case"lower-armenian":return 35;case"malayalam":return 36;case"mongolian":return 37;case"myanmar":return 38;case"oriya":return 39;case"persian":return 40;case"simp-chinese-formal":return 41;case"simp-chinese-informal":return 42;case"tamil":return 43;case"telugu":return 44;case"thai":return 45;case"tibetan":return 46;case"trad-chinese-formal":return 47;case"trad-chinese-informal":return 48;case"upper-armenian":return 49;case"disclosure-open":return 50;case"disclosure-closed":return 51;case"none":default:return-1}}},ur=function(n){return{name:"margin-"+n,initialValue:"0",prefix:!1,type:4}},nC=ur("top"),iC=ur("right"),rC=ur("bottom"),sC=ur("left"),oC={name:"overflow",initialValue:"visible",prefix:!1,type:1,parse:function(n,e){return e.filter(q).map(function(A){switch(A.value){case"hidden":return 1;case"scroll":return 2;case"clip":return 3;case"auto":return 4;case"visible":default:return 0}})}},aC={name:"overflow-wrap",initialValue:"normal",prefix:!1,type:2,parse:function(n,e){switch(e){case"break-word":return"break-word";case"normal":default:return"normal"}}},dr=function(n){return{name:"padding-"+n,initialValue:"0",prefix:!1,type:3,format:"length-percentage"}},cC=dr("top"),lC=dr("right"),uC=dr("bottom"),dC=dr("left"),hC={name:"text-align",initialValue:"left",prefix:!1,type:2,parse:function(n,e){switch(e){case"right":return 2;case"center":case"justify":return 1;case"left":default:return 0}}},fC={name:"position",initialValue:"static",prefix:!1,type:2,parse:function(n,e){switch(e){case"relative":return 1;case"absolute":return 2;case"fixed":return 3;case"sticky":return 4}return 0}},gC={name:"text-shadow",initialValue:"none",type:1,prefix:!1,parse:function(n,e){return e.length===1&&Eo(e[0],"none")?[]:uA(e).map(function(A){for(var t={color:yA.TRANSPARENT,offsetX:ye,offsetY:ye,blur:ye},i=0,r=0;r<A.length;r++){var s=A[r];JA(s)?(i===0?t.offsetX=s:i===1?t.offsetY=s:t.blur=s,i++):t.color=XA.parse(n,s)}return t})}},pC={name:"text-transform",initialValue:"none",prefix:!1,type:2,parse:function(n,e){switch(e){case"uppercase":return 2;case"lowercase":return 1;case"capitalize":return 3}return 0}},mC={name:"transform",initialValue:"none",prefix:!0,type:0,parse:function(n,e){if(e.type===20&&e.value==="none")return null;if(e.type===18){var A=CC[e.name];if(typeof A>"u")throw new Error('Attempting to parse an unsupported transform function "'+e.name+'"');return A(e.values)}return null}},BC=function(n){var e=n.filter(function(A){return A.type===17}).map(function(A){return A.number});return e.length===6?e:null},vC=function(n){var e=n.filter(function(a){return a.type===17}).map(function(a){return a.number}),A=e[0],t=e[1];e[2],e[3];var i=e[4],r=e[5];e[6],e[7],e[8],e[9],e[10],e[11];var s=e[12],o=e[13];return e[14],e[15],e.length===16?[A,t,i,r,s,o]:null},CC={matrix:BC,matrix3d:vC},id={type:16,number:50,flags:Sn},wC=[id,id],yC={name:"transform-origin",initialValue:"50% 50%",prefix:!0,type:1,parse:function(n,e){var A=e.filter(he);return A.length!==2?wC:[A[0],A[1]]}},bC={name:"visible",initialValue:"none",prefix:!1,type:2,parse:function(n,e){switch(e){case"hidden":return 1;case"collapse":return 2;case"visible":default:return 0}}},Ln;(function(n){n.NORMAL="normal",n.BREAK_ALL="break-all",n.KEEP_ALL="keep-all"})(Ln||(Ln={}));for(var UC={name:"word-break",initialValue:"normal",prefix:!1,type:2,parse:function(n,e){switch(e){case"break-all":return Ln.BREAK_ALL;case"keep-all":return Ln.KEEP_ALL;case"normal":default:return Ln.NORMAL}}},QC={name:"z-index",initialValue:"auto",prefix:!1,type:0,parse:function(n,e){if(e.type===20)return{auto:!0,order:0};if(jt(e))return{auto:!1,order:e.number};throw new Error("Invalid z-index number parsed")}},rd={name:"time",parse:function(n,e){if(e.type===15)switch(e.unit.toLowerCase()){case"s":return 1e3*e.number;case"ms":return e.number}throw new Error("Unsupported time type")}},EC={name:"opacity",initialValue:"1",type:0,prefix:!1,parse:function(n,e){return jt(e)?e.number:1}},SC={name:"text-decoration-color",initialValue:"transparent",prefix:!1,type:3,format:"color"},TC={name:"text-decoration-line",initialValue:"none",prefix:!1,type:1,parse:function(n,e){return e.filter(q).map(function(A){switch(A.value){case"underline":return 1;case"overline":return 2;case"line-through":return 3;case"none":return 4}return 0}).filter(function(A){return A!==0})}},FC={name:"font-family",initialValue:"",prefix:!1,type:1,parse:function(n,e){var A=[],t=[];return e.forEach(function(i){switch(i.type){case 20:case 0:A.push(i.value);break;case 17:A.push(i.number.toString());break;case 4:t.push(A.join(" ")),A.length=0;break}}),A.length&&t.push(A.join(" ")),t.map(function(i){return i.indexOf(" ")===-1?i:"'"+i+"'"})}},kC={name:"font-size",initialValue:"0",prefix:!1,type:3,format:"length"},IC={name:"font-weight",initialValue:"normal",type:0,prefix:!1,parse:function(n,e){if(jt(e))return e.number;if(q(e))switch(e.value){case"bold":return 700;case"normal":default:return 400}return 400}},RC={name:"font-variant",initialValue:"none",type:1,prefix:!1,parse:function(n,e){return e.filter(q).map(function(A){return A.value})}},xC={name:"font-style",initialValue:"normal",prefix:!1,type:2,parse:function(n,e){switch(e){case"oblique":return"oblique";case"italic":return"italic";case"normal":default:return"normal"}}},pe=function(n,e){return(n&e)!==0},PC={name:"content",initialValue:"none",type:1,prefix:!1,parse:function(n,e){if(e.length===0)return[];var A=e[0];return A.type===20&&A.value==="none"?[]:e}},LC={name:"counter-increment",initialValue:"none",prefix:!0,type:1,parse:function(n,e){if(e.length===0)return null;var A=e[0];if(A.type===20&&A.value==="none")return null;for(var t=[],i=e.filter(Lu),r=0;r<i.length;r++){var s=i[r],o=i[r+1];if(s.type===20){var a=o&&jt(o)?o.number:1;t.push({counter:s.value,increment:a})}}return t}},DC={name:"counter-reset",initialValue:"none",prefix:!0,type:1,parse:function(n,e){if(e.length===0)return[];for(var A=[],t=e.filter(Lu),i=0;i<t.length;i++){var r=t[i],s=t[i+1];if(q(r)&&r.value!=="none"){var o=s&&jt(s)?s.number:0;A.push({counter:r.value,reset:o})}}return A}},_C={name:"duration",initialValue:"0s",prefix:!1,type:1,parse:function(n,e){return e.filter(Rn).map(function(A){return rd.parse(n,A)})}},HC={name:"quotes",initialValue:"none",prefix:!0,type:1,parse:function(n,e){if(e.length===0)return null;var A=e[0];if(A.type===20&&A.value==="none")return null;var t=[],i=e.filter(lv);if(i.length%2!==0)return null;for(var r=0;r<i.length;r+=2){var s=i[r].value,o=i[r+1].value;t.push({open:s,close:o})}return t}},sd=function(n,e,A){if(!n)return"";var t=n[Math.min(e,n.length-1)];return t?A?t.open:t.close:""},OC={name:"box-shadow",initialValue:"none",type:1,prefix:!1,parse:function(n,e){return e.length===1&&Eo(e[0],"none")?[]:uA(e).map(function(A){for(var t={color:255,offsetX:ye,offsetY:ye,blur:ye,spread:ye,inset:!1},i=0,r=0;r<A.length;r++){var s=A[r];Eo(s,"inset")?t.inset=!0:JA(s)?(i===0?t.offsetX=s:i===1?t.offsetY=s:i===2?t.blur=s:t.spread=s,i++):t.color=XA.parse(n,s)}return t})}},MC={name:"paint-order",initialValue:"normal",prefix:!1,type:1,parse:function(n,e){var A=[0,1,2],t=[];return e.filter(q).forEach(function(i){switch(i.value){case"stroke":t.push(1);break;case"fill":t.push(0);break;case"markers":t.push(2);break}}),A.forEach(function(i){t.indexOf(i)===-1&&t.push(i)}),t}},NC={name:"-webkit-text-stroke-color",initialValue:"currentcolor",prefix:!1,type:3,format:"color"},KC={name:"-webkit-text-stroke-width",initialValue:"0",type:0,prefix:!1,parse:function(n,e){return Rn(e)?e.number:0}},VC=function(){function n(e,A){var t,i;this.animationDuration=L(e,_C,A.animationDuration),this.backgroundClip=L(e,hv,A.backgroundClip),this.backgroundColor=L(e,fv,A.backgroundColor),this.backgroundImage=L(e,Uv,A.backgroundImage),this.backgroundOrigin=L(e,Qv,A.backgroundOrigin),this.backgroundPosition=L(e,Ev,A.backgroundPosition),this.backgroundRepeat=L(e,Sv,A.backgroundRepeat),this.backgroundSize=L(e,Fv,A.backgroundSize),this.borderTopColor=L(e,Iv,A.borderTopColor),this.borderRightColor=L(e,Rv,A.borderRightColor),this.borderBottomColor=L(e,xv,A.borderBottomColor),this.borderLeftColor=L(e,Pv,A.borderLeftColor),this.borderTopLeftRadius=L(e,Lv,A.borderTopLeftRadius),this.borderTopRightRadius=L(e,Dv,A.borderTopRightRadius),this.borderBottomRightRadius=L(e,_v,A.borderBottomRightRadius),this.borderBottomLeftRadius=L(e,Hv,A.borderBottomLeftRadius),this.borderTopStyle=L(e,Ov,A.borderTopStyle),this.borderRightStyle=L(e,Mv,A.borderRightStyle),this.borderBottomStyle=L(e,Nv,A.borderBottomStyle),this.borderLeftStyle=L(e,Kv,A.borderLeftStyle),this.borderTopWidth=L(e,Vv,A.borderTopWidth),this.borderRightWidth=L(e,Gv,A.borderRightWidth),this.borderBottomWidth=L(e,jv,A.borderBottomWidth),this.borderLeftWidth=L(e,Jv,A.borderLeftWidth),this.boxShadow=L(e,OC,A.boxShadow),this.color=L(e,Wv,A.color),this.direction=L(e,Xv,A.direction),this.display=L(e,$v,A.display),this.float=L(e,qv,A.cssFloat),this.fontFamily=L(e,FC,A.fontFamily),this.fontSize=L(e,kC,A.fontSize),this.fontStyle=L(e,xC,A.fontStyle),this.fontVariant=L(e,RC,A.fontVariant),this.fontWeight=L(e,IC,A.fontWeight),this.letterSpacing=L(e,Zv,A.letterSpacing),this.lineBreak=L(e,zv,A.lineBreak),this.lineHeight=L(e,eC,A.lineHeight),this.listStyleImage=L(e,AC,A.listStyleImage),this.listStylePosition=L(e,tC,A.listStylePosition),this.listStyleType=L(e,ko,A.listStyleType),this.marginTop=L(e,nC,A.marginTop),this.marginRight=L(e,iC,A.marginRight),this.marginBottom=L(e,rC,A.marginBottom),this.marginLeft=L(e,sC,A.marginLeft),this.opacity=L(e,EC,A.opacity);var r=L(e,oC,A.overflow);this.overflowX=r[0],this.overflowY=r[r.length>1?1:0],this.overflowWrap=L(e,aC,A.overflowWrap),this.paddingTop=L(e,cC,A.paddingTop),this.paddingRight=L(e,lC,A.paddingRight),this.paddingBottom=L(e,uC,A.paddingBottom),this.paddingLeft=L(e,dC,A.paddingLeft),this.paintOrder=L(e,MC,A.paintOrder),this.position=L(e,fC,A.position),this.textAlign=L(e,hC,A.textAlign),this.textDecorationColor=L(e,SC,(t=A.textDecorationColor)!==null&&t!==void 0?t:A.color),this.textDecorationLine=L(e,TC,(i=A.textDecorationLine)!==null&&i!==void 0?i:A.textDecoration),this.textShadow=L(e,gC,A.textShadow),this.textTransform=L(e,pC,A.textTransform),this.transform=L(e,mC,A.transform),this.transformOrigin=L(e,yC,A.transformOrigin),this.visibility=L(e,bC,A.visibility),this.webkitTextStrokeColor=L(e,NC,A.webkitTextStrokeColor),this.webkitTextStrokeWidth=L(e,KC,A.webkitTextStrokeWidth),this.wordBreak=L(e,UC,A.wordBreak),this.zIndex=L(e,QC,A.zIndex)}return n.prototype.isVisible=function(){return this.display>0&&this.opacity>0&&this.visibility===0},n.prototype.isTransparent=function(){return $A(this.backgroundColor)},n.prototype.isTransformed=function(){return this.transform!==null},n.prototype.isPositioned=function(){return this.position!==0},n.prototype.isPositionedWithZIndex=function(){return this.isPositioned()&&!this.zIndex.auto},n.prototype.isFloating=function(){return this.float!==0},n.prototype.isInlineLevel=function(){return pe(this.display,4)||pe(this.display,33554432)||pe(this.display,268435456)||pe(this.display,536870912)||pe(this.display,67108864)||pe(this.display,134217728)},n}(),GC=function(){function n(e,A){this.content=L(e,PC,A.content),this.quotes=L(e,HC,A.quotes)}return n}(),od=function(){function n(e,A){this.counterIncrement=L(e,LC,A.counterIncrement),this.counterReset=L(e,DC,A.counterReset)}return n}(),L=function(n,e,A){var t=new xu,i=A!==null&&typeof A<"u"?A.toString():e.initialValue;t.write(i);var r=new Pu(t.read());switch(e.type){case 2:var s=r.parseComponentValue();return e.parse(n,q(s)?s.value:e.initialValue);case 0:return e.parse(n,r.parseComponentValue());case 1:return e.parse(n,r.parseComponentValues());case 4:return r.parseComponentValue();case 3:switch(e.format){case"angle":return tr.parse(n,r.parseComponentValue());case"color":return XA.parse(n,r.parseComponentValue());case"image":return Fo.parse(n,r.parseComponentValue());case"length":var o=r.parseComponentValue();return JA(o)?o:ye;case"length-percentage":var a=r.parseComponentValue();return he(a)?a:ye;case"time":return rd.parse(n,r.parseComponentValue())}break}},jC="data-html2canvas-debug",JC=function(n){var e=n.getAttribute(jC);switch(e){case"all":return 1;case"clone":return 2;case"parse":return 3;case"render":return 4;default:return 0}},Io=function(n,e){var A=JC(n);return A===1||e===A},dA=function(){function n(e,A){if(this.context=e,this.textNodes=[],this.elements=[],this.flags=0,Io(A,3))debugger;this.styles=new VC(e,window.getComputedStyle(A,null)),jo(A)&&(this.styles.animationDuration.some(function(t){return t>0})&&(A.style.animationDuration="0s"),this.styles.transform!==null&&(A.style.transform="none")),this.bounds=Di(this.context,A),Io(A,4)&&(this.flags|=16)}return n}(),WC="AAAAAAAAAAAAEA4AGBkAAFAaAAACAAAAAAAIABAAGAAwADgACAAQAAgAEAAIABAACAAQAAgAEAAIABAACAAQAAgAEAAIABAAQABIAEQATAAIABAACAAQAAgAEAAIABAAVABcAAgAEAAIABAACAAQAGAAaABwAHgAgACIAI4AlgAIABAAmwCjAKgAsAC2AL4AvQDFAMoA0gBPAVYBWgEIAAgACACMANoAYgFkAWwBdAF8AX0BhQGNAZUBlgGeAaMBlQGWAasBswF8AbsBwwF0AcsBYwHTAQgA2wG/AOMBdAF8AekB8QF0AfkB+wHiAHQBfAEIAAMC5gQIAAsCEgIIAAgAFgIeAggAIgIpAggAMQI5AkACygEIAAgASAJQAlgCYAIIAAgACAAKBQoFCgUTBRMFGQUrBSsFCAAIAAgACAAIAAgACAAIAAgACABdAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACABoAmgCrwGvAQgAbgJ2AggAHgEIAAgACADnAXsCCAAIAAgAgwIIAAgACAAIAAgACACKAggAkQKZAggAPADJAAgAoQKkAqwCsgK6AsICCADJAggA0AIIAAgACAAIANYC3gIIAAgACAAIAAgACABAAOYCCAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAkASoB+QIEAAgACAA8AEMCCABCBQgACABJBVAFCAAIAAgACAAIAAgACAAIAAgACABTBVoFCAAIAFoFCABfBWUFCAAIAAgACAAIAAgAbQUIAAgACAAIAAgACABzBXsFfQWFBYoFigWKBZEFigWKBYoFmAWfBaYFrgWxBbkFCAAIAAgACAAIAAgACAAIAAgACAAIAMEFCAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAMgFCADQBQgACAAIAAgACAAIAAgACAAIAAgACAAIAO4CCAAIAAgAiQAIAAgACABAAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAD0AggACAD8AggACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIANYFCAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAMDvwAIAAgAJAIIAAgACAAIAAgACAAIAAgACwMTAwgACAB9BOsEGwMjAwgAKwMyAwsFYgE3A/MEPwMIAEUDTQNRAwgAWQOsAGEDCAAIAAgACAAIAAgACABpAzQFNQU2BTcFOAU5BToFNAU1BTYFNwU4BTkFOgU0BTUFNgU3BTgFOQU6BTQFNQU2BTcFOAU5BToFNAU1BTYFNwU4BTkFOgU0BTUFNgU3BTgFOQU6BTQFNQU2BTcFOAU5BToFNAU1BTYFNwU4BTkFOgU0BTUFNgU3BTgFOQU6BTQFNQU2BTcFOAU5BToFNAU1BTYFNwU4BTkFOgU0BTUFNgU3BTgFOQU6BTQFNQU2BTcFOAU5BToFNAU1BTYFNwU4BTkFOgU0BTUFNgU3BTgFOQU6BTQFNQU2BTcFOAU5BToFNAU1BTYFNwU4BTkFOgU0BTUFNgU3BTgFOQU6BTQFNQU2BTcFOAU5BToFNAU1BTYFNwU4BTkFOgU0BTUFNgU3BTgFOQU6BTQFNQU2BTcFOAU5BToFNAU1BTYFNwU4BTkFOgU0BTUFNgU3BTgFOQU6BTQFNQU2BTcFOAU5BToFNAU1BTYFNwU4BTkFOgU0BTUFNgU3BTgFOQU6BTQFNQU2BTcFOAU5BToFNAU1BTYFNwU4BTkFOgU0BTUFNgU3BTgFOQU6BTQFNQU2BTcFOAU5BToFNAU1BTYFNwU4BTkFOgU0BTUFNgU3BTgFOQU6BTQFNQU2BTcFOAU5BToFNAU1BTYFNwU4BTkFOgU0BTUFNgU3BTgFOQU6BTQFNQU2BTcFOAU5BToFNAU1BTYFNwU4BTkFOgU0BTUFNgU3BTgFOQU6BTQFNQU2BTcFOAU5BToFNAU1BTYFNwU4BTkFOgU0BTUFNgU3BTgFOQU6BTQFNQU2BTcFOAU5BToFNAU1BTYFNwU4BTkFOgU0BTUFNgU3BTgFOQU6BTQFNQU2BTcFOAU5BToFNAU1BTYFNwU4BTkFOgU0BTUFNgU3BTgFOQU6BTQFNQU2BTcFOAU5BToFNAU1BTYFNwU4BTkFIQUoBSwFCAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACABtAwgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACABMAEwACAAIAAgACAAIABgACAAIAAgACAC/AAgACAAyAQgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACACAAIAAwAAgACAAIAAgACAAIAAgACAAIAAAARABIAAgACAAIABQASAAIAAgAIABwAEAAjgCIABsAqAC2AL0AigDQAtwC+IJIQqVAZUBWQqVAZUBlQGVAZUBlQGrC5UBlQGVAZUBlQGVAZUBlQGVAXsKlQGVAbAK6wsrDGUMpQzlDJUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAZUBlQGVAfAKAAuZA64AtwCJALoC6ADwAAgAuACgA/oEpgO6AqsD+AAIAAgAswMIAAgACAAIAIkAuwP5AfsBwwPLAwgACAAIAAgACADRA9kDCAAIAOED6QMIAAgACAAIAAgACADuA/YDCAAIAP4DyQAIAAgABgQIAAgAXQAOBAgACAAIAAgACAAIABMECAAIAAgACAAIAAgACAD8AAQBCAAIAAgAGgQiBCoECAExBAgAEAEIAAgACAAIAAgACAAIAAgACAAIAAgACAA4BAgACABABEYECAAIAAgATAQYAQgAVAQIAAgACAAIAAgACAAIAAgACAAIAFoECAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgAOQEIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAB+BAcACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAEABhgSMBAgACAAIAAgAlAQIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAwAEAAQABAADAAMAAwADAAQABAAEAAQABAAEAAQABHATAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgAdQMIAAgACAAIAAgACAAIAMkACAAIAAgAfQMIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACACFA4kDCAAIAAgACAAIAOcBCAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAIcDCAAIAAgACAAIAAgACAAIAAgACAAIAJEDCAAIAAgACADFAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACABgBAgAZgQIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgAbAQCBXIECAAIAHkECAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACABAAJwEQACjBKoEsgQIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAC6BMIECAAIAAgACAAIAAgACABmBAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgAxwQIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAGYECAAIAAgAzgQIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgAigWKBYoFigWKBYoFigWKBd0FXwUIAOIF6gXxBYoF3gT5BQAGCAaKBYoFigWKBYoFigWKBYoFigWKBYoFigXWBIoFigWKBYoFigWKBYoFigWKBYsFEAaKBYoFigWKBYoFigWKBRQGCACKBYoFigWKBQgACAAIANEECAAIABgGigUgBggAJgYIAC4GMwaKBYoF0wQ3Bj4GigWKBYoFigWKBYoFigWKBYoFigWKBYoFigUIAAgACAAIAAgACAAIAAgAigWKBYoFigWKBYoFigWKBYoFigWKBYoFigWKBYoFigWKBYoFigWKBYoFigWKBYoFigWKBYoFigWKBYoFigWLBf///////wQABAAEAAQABAAEAAQABAAEAAQAAwAEAAQAAgAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAAAAAAAAAAAAAAAAAAAAAAAAAOAAAAAAAAAAQADgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUABQAFAAUABQAFAAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAAAAUAAAAFAAUAAAAFAAUAAAAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAEAAQABAAEAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAUABQAFAAUABQAFAAUABQAFAAUABQAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUABQAFAAUABQAFAAUAAQAAAAUABQAFAAUABQAFAAAAAAAFAAUAAAAFAAUABQAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAUABQAFAAUABQAFAAUABQAFAAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAUABQAFAAUABQAFAAUABQAAAAAAAAAAAAAAAAAAAAAAAAAFAAAAAAAFAAUAAQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABwAFAAUABQAFAAAABwAHAAcAAAAHAAcABwAFAAEAAAAAAAAAAAAAAAAAAAAAAAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHAAcABwAFAAUABQAFAAcABwAFAAUAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHAAAAAQABAAAAAAAAAAAAAAAFAAUABQAFAAAABwAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAHAAcABwAHAAcAAAAHAAcAAAAAAAUABQAHAAUAAQAHAAEABwAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAFAAUABQAFAAUABwABAAUABQAFAAUAAAAAAAAAAAAAAAEAAQABAAEAAQABAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABwAFAAUAAAAAAAAAAAAAAAAABQAFAAUABQAFAAUAAQAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUABQAFAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQABQANAAQABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQABAAEAAQABAAEAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAOAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAEAAQABAAEAAQABAAEAAQABAAEAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAQABAAEAAQABAAEAAQABAAAAAAAAAAAAAAAAAAAAAAABQAHAAUABQAFAAAAAAAAAAcABQAFAAUABQAFAAQABAAEAAQABAAEAAQABAAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAEAAQABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUABQAFAAUAAAAFAAUABQAFAAUAAAAFAAUABQAAAAUABQAFAAUABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAUABQAAAAAAAAAAAAUABQAFAAcAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAHAAUAAAAHAAcABwAFAAUABQAFAAUABQAFAAUABwAHAAcABwAFAAcABwAAAAUABQAFAAUABQAFAAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUABwAHAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAAAAUABwAHAAUABQAFAAUAAAAAAAcABwAAAAAABwAHAAUAAAAAAAAAAAAAAAAAAAAAAAAABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAUABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAAAAAABQAFAAcAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAAABwAHAAcABQAFAAAAAAAAAAAABQAFAAAAAAAFAAUABQAAAAAAAAAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUABQAAAAAAAAAFAAAAAAAAAAAAAAAAAAAAAAAAAAAABwAFAAUABQAFAAUAAAAFAAUABwAAAAcABwAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAUABQAFAAUABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUAAAAFAAUABwAFAAUABQAFAAAAAAAHAAcAAAAAAAcABwAFAAAAAAAAAAAAAAAAAAAABQAFAAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAcABwAAAAAAAAAHAAcABwAAAAcABwAHAAUAAAAAAAAAAAAAAAAAAAAAAAAABQAAAAAAAAAAAAAAAAAAAAAABQAHAAcABwAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUABwAHAAcABwAAAAUABQAFAAAABQAFAAUABQAAAAAAAAAAAAAAAAAAAAUABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAAAAcABQAHAAcABQAHAAcAAAAFAAcABwAAAAcABwAFAAUAAAAAAAAAAAAAAAAAAAAFAAUAAAAAAAAAAAAAAAAAAAAAAAAABQAFAAcABwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUABQAAAAUABwAAAAAAAAAAAAAAAAAAAAAAAAAAAAUAAAAAAAAAAAAFAAcABwAFAAUABQAAAAUAAAAHAAcABwAHAAcABwAHAAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUAAAAHAAUABQAFAAUABQAFAAUAAAAAAAAAAAAAAAAAAAAAAAUABQAFAAUABQAFAAUABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAAABwAFAAUABQAFAAUABQAFAAUABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAFAAUABQAFAAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAAAAUAAAAFAAAAAAAAAAAABwAHAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABwAFAAUABQAFAAUAAAAFAAUAAAAAAAAAAAAAAAUABQAFAAUABQAFAAUABQAFAAUABQAAAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUABQAFAAUABwAFAAUABQAFAAUABQAAAAUABQAHAAcABQAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHAAcABQAFAAAAAAAAAAAABQAFAAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAUABQAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAAAAcABQAFAAAAAAAAAAAAAAAAAAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAFAAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUABQAHAAUABQAFAAUABQAFAAUABwAHAAcABwAHAAcABwAHAAUABwAHAAUABQAFAAUABQAFAAUABQAFAAUABQAAAAAAAAAAAAAAAAAAAAAAAAAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAFAAUABwAHAAcABwAFAAUABwAHAAcAAAAAAAAAAAAHAAcABQAHAAcABwAHAAcABwAFAAUABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAFAAcABwAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAcABQAHAAUABQAFAAUABQAFAAUAAAAFAAAABQAAAAAABQAFAAUABQAFAAUABQAFAAcABwAHAAcABwAHAAUABQAFAAUABQAFAAUABQAFAAUAAAAAAAUABQAFAAUABQAHAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUABQAFAAUABQAFAAUABwAFAAcABwAHAAcABwAFAAcABwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAUABQAFAAUABQAFAAUABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAUABwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHAAUABQAFAAUABwAHAAUABQAHAAUABQAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAcABQAFAAcABwAHAAUABwAFAAUABQAHAAcAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABwAHAAcABwAHAAcABwAHAAUABQAFAAUABQAFAAUABQAHAAcABQAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAFAAUAAAAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAcABQAFAAUABQAFAAUABQAAAAAAAAAAAAUAAAAAAAAAAAAAAAAABQAAAAAABwAFAAUAAAAAAAAAAAAAAAAABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAAABQAFAAUABQAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUABQAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAFAAUABQAFAAUADgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAOAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUABQAFAAUAAAAFAAUABQAFAAUABQAFAAUABQAFAAAAAAAAAAAABQAAAAAAAAAFAAAAAAAAAAAABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABwAHAAUABQAHAAAAAAAAAAAABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAcABwAHAAcABQAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUAAAAAAAAAAAAAAAAABQAFAAUABQAFAAUABQAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUABQAFAAUABQAFAAUABQAFAAUABQAHAAcAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAcABwAFAAUABQAFAAcABwAFAAUABwAHAAAAAAAAAAAAAAAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUABQAFAAUABQAFAAcABwAFAAUABwAHAAUABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAAAAAAAAAAAAAAAAAAAAAAFAAcAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUAAAAFAAUABQAAAAAABQAFAAAAAAAAAAAAAAAFAAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAcABQAFAAcABwAAAAAAAAAAAAAABwAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAcABwAFAAcABwAFAAcABwAAAAcABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUABQAFAAUABQAAAAAAAAAAAAAAAAAFAAUABQAAAAUABQAAAAAAAAAAAAAABQAFAAUABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAUABQAAAAAAAAAAAAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAcABQAHAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAUABQAFAAUABwAFAAUABQAFAAUABQAFAAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABwAHAAcABQAFAAUABQAFAAUABQAFAAUABwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHAAcABwAFAAUABQAHAAcABQAHAAUABQAAAAAAAAAAAAAAAAAFAAAABwAHAAcABQAFAAUABQAFAAUABQAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUABwAHAAcABwAAAAAABwAHAAAAAAAHAAcABwAAAAAAAAAAAAAAAAAAAAAAAAAFAAAAAAAAAAAAAAAAAAAAAAAAAAAABwAHAAAAAAAFAAUABQAFAAUABQAFAAAAAAAAAAUABQAFAAUABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHAAcABwAFAAUABQAFAAUABQAFAAUABwAHAAUABQAFAAcABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAHAAcABQAFAAUABQAFAAUABwAFAAcABwAFAAcABQAFAAcABQAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAHAAcABQAFAAUABQAAAAAABwAHAAcABwAFAAUABwAFAAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAcABwAHAAUABQAFAAUABQAFAAUABQAHAAcABQAHAAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUABwAFAAcABwAFAAUABQAFAAUABQAHAAUAAAAAAAAAAAAAAAAAAAAAAAcABwAFAAUABQAFAAcABQAFAAUABQAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHAAcABwAFAAUABQAFAAUABQAFAAUABQAHAAUABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHAAcABwAFAAUABQAFAAAAAAAFAAUABwAHAAcABwAFAAAAAAAAAAcAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAUABQAFAAUABQAFAAUABQAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUAAAAAAAAAAAAAAAAAAAAAAAAABQAFAAUABQAFAAUABwAHAAUABQAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAcABQAFAAUABQAFAAUABQAAAAUABQAFAAUABQAFAAcABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUAAAAHAAUABQAFAAUABQAFAAUABwAFAAUABwAFAAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAFAAUABQAFAAUAAAAAAAAABQAAAAUABQAAAAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAHAAcABwAHAAcAAAAFAAUAAAAHAAcABQAHAAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAUABwAHAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAUABQAFAAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAUABQAFAAUABQAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAAAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAAAAAAAAAAAAAAAAAAABQAFAAUABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAcABwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUABQAAAAUABQAFAAAAAAAFAAUABQAFAAUABQAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAFAAUABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAFAAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAAAAAAAAAAABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAAAAAAAAAAAAAAAAAAAAAAFAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUABQAFAAUABQAAAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAFAAUABQAFAAUABQAAAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAFAAUABQAAAAAABQAFAAUABQAFAAUABQAAAAUABQAAAAUABQAFAAUABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAUABQAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAFAAUABQAFAAUABQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAFAAUABQAFAAUADgAOAA4ADgAOAA4ADwAPAA8ADwAPAA8ADwAPAA8ADwAPAA8ADwAPAA8ADwAPAA8ADwAPAA8ADwAPAA8ADwAPAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAcABwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABwAHAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAcABwAHAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAAAAAAAAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAKAAoACgAKAAoACgAKAAoACgAKAAoACgAKAAoACgAKAAoACgAKAAoACgAKAAoACgAMAAwADAAMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkAAAAAAAAAAAAKAAoACgAKAAoACgAKAAoACgAKAAoACgAKAAoACgAKAAoACgAKAAoACgAKAAoACgAKAAoACgAKAAoACgAKAAoACgAAAAAAAAAAAAsADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwACwAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAMAAwADAAAAAAADgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAOAA4ADgAOAA4ADgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADgAOAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA4ADgAAAAAAAAAAAAAAAAAAAAAADgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADgAOAA4ADgAOAA4ADgAOAA4ADgAOAAAAAAAAAAAADgAOAA4AAAAAAAAAAAAAAAAAAAAOAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADgAOAAAAAAAAAAAAAAAAAAAAAAAAAAAADgAAAAAAAAAAAAAAAAAAAAAAAAAOAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADgAOAA4ADgAAAA4ADgAOAA4ADgAOAAAADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4AAAAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAAAAAAAAAAAAAAAAAAAAAAAAAAAADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4AAAAAAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAAAA4AAAAOAAAAAAAAAAAAAAAAAA4AAAAAAAAAAAAAAAAADgAAAAAAAAAAAAAAAAAAAAAAAAAAAA4ADgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADgAAAAAADgAAAAAAAAAAAA4AAAAOAAAAAAAAAAAADgAOAA4AAAAOAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAOAA4ADgAOAA4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAOAA4ADgAAAAAAAAAAAAAAAAAAAAAAAAAOAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAOAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAOAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAOAA4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA4ADgAOAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADgAOAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADgAAAAAAAAAAAA4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAOAAAADgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAOAA4ADgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA4ADgAOAA4ADgAOAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA4ADgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADgAAAAAADgAOAA4ADgAOAA4ADgAOAA4ADgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAAAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAAAAAAAAAAAAAAAAAAAAAAAAAAAADgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA4AAAAAAA4ADgAOAA4ADgAOAA4ADgAOAAAADgAOAA4ADgAAAAAAAAAAAAAAAAAAAAAAAAAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4AAAAAAAAAAAAAAAAADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAOAA4ADgAOAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADgAOAA4ADgAOAA4ADgAOAAAAAAAAAAAAAAAAAAAAAAAAAAAADgAOAA4ADgAOAA4AAAAAAAAAAAAAAAAAAAAAAA4ADgAOAA4ADgAOAA4ADgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4AAAAOAA4ADgAOAA4ADgAAAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4ADgAOAA4AAAAAAAAAAAA=",ad="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Dn=typeof Uint8Array>"u"?[]:new Uint8Array(256),hr=0;hr<ad.length;hr++)Dn[ad.charCodeAt(hr)]=hr;for(var XC=function(n){var e=n.length*.75,A=n.length,t,i=0,r,s,o,a;n[n.length-1]==="="&&(e--,n[n.length-2]==="="&&e--);var c=typeof ArrayBuffer<"u"&&typeof Uint8Array<"u"&&typeof Uint8Array.prototype.slice<"u"?new ArrayBuffer(e):new Array(e),l=Array.isArray(c)?c:new Uint8Array(c);for(t=0;t<A;t+=4)r=Dn[n.charCodeAt(t)],s=Dn[n.charCodeAt(t+1)],o=Dn[n.charCodeAt(t+2)],a=Dn[n.charCodeAt(t+3)],l[i++]=r<<2|s>>4,l[i++]=(s&15)<<4|o>>2,l[i++]=(o&3)<<6|a&63;return c},$C=function(n){for(var e=n.length,A=[],t=0;t<e;t+=2)A.push(n[t+1]<<8|n[t]);return A},YC=function(n){for(var e=n.length,A=[],t=0;t<e;t+=4)A.push(n[t+3]<<24|n[t+2]<<16|n[t+1]<<8|n[t]);return A},pt=5,Ro=6+5,xo=2,qC=Ro-pt,cd=65536>>pt,ZC=1<<pt,Po=ZC-1,zC=1024>>pt,e0=cd+zC,A0=e0,t0=32,n0=A0+t0,i0=65536>>Ro,r0=1<<qC,s0=r0-1,ld=function(n,e,A){return n.slice?n.slice(e,A):new Uint16Array(Array.prototype.slice.call(n,e,A))},o0=function(n,e,A){return n.slice?n.slice(e,A):new Uint32Array(Array.prototype.slice.call(n,e,A))},a0=function(n,e){var A=XC(n),t=Array.isArray(A)?YC(A):new Uint32Array(A),i=Array.isArray(A)?$C(A):new Uint16Array(A),r=24,s=ld(i,r/2,t[4]/2),o=t[5]===2?ld(i,(r+t[4])/2):o0(t,Math.ceil((r+t[4])/4));return new c0(t[0],t[1],t[2],t[3],s,o)},c0=function(){function n(e,A,t,i,r,s){this.initialValue=e,this.errorValue=A,this.highStart=t,this.highValueIndex=i,this.index=r,this.data=s}return n.prototype.get=function(e){var A;if(e>=0){if(e<55296||e>56319&&e<=65535)return A=this.index[e>>pt],A=(A<<xo)+(e&Po),this.data[A];if(e<=65535)return A=this.index[cd+(e-55296>>pt)],A=(A<<xo)+(e&Po),this.data[A];if(e<this.highStart)return A=n0-i0+(e>>Ro),A=this.index[A],A+=e>>pt&s0,A=this.index[A],A=(A<<xo)+(e&Po),this.data[A];if(e<=1114111)return this.data[this.highValueIndex]}return this.errorValue},n}(),ud="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",l0=typeof Uint8Array>"u"?[]:new Uint8Array(256),fr=0;fr<ud.length;fr++)l0[ud.charCodeAt(fr)]=fr;var u0=1,Lo=2,Do=3,dd=4,hd=5,d0=7,fd=8,_o=9,Ho=10,gd=11,pd=12,md=13,Bd=14,Oo=15,h0=function(n){for(var e=[],A=0,t=n.length;A<t;){var i=n.charCodeAt(A++);if(i>=55296&&i<=56319&&A<t){var r=n.charCodeAt(A++);(r&64512)===56320?e.push(((i&1023)<<10)+(r&1023)+65536):(e.push(i),A--)}else e.push(i)}return e},f0=function(){for(var n=[],e=0;e<arguments.length;e++)n[e]=arguments[e];if(String.fromCodePoint)return String.fromCodePoint.apply(String,n);var A=n.length;if(!A)return"";for(var t=[],i=-1,r="";++i<A;){var s=n[i];s<=65535?t.push(s):(s-=65536,t.push((s>>10)+55296,s%1024+56320)),(i+1===A||t.length>16384)&&(r+=String.fromCharCode.apply(String,t),t.length=0)}return r},g0=a0(WC),Ve="×",Mo="÷",p0=function(n){return g0.get(n)},m0=function(n,e,A){var t=A-2,i=e[t],r=e[A-1],s=e[A];if(r===Lo&&s===Do)return Ve;if(r===Lo||r===Do||r===dd||s===Lo||s===Do||s===dd)return Mo;if(r===fd&&[fd,_o,gd,pd].indexOf(s)!==-1||(r===gd||r===_o)&&(s===_o||s===Ho)||(r===pd||r===Ho)&&s===Ho||s===md||s===hd||s===d0||r===u0)return Ve;if(r===md&&s===Bd){for(;i===hd;)i=e[--t];if(i===Bd)return Ve}if(r===Oo&&s===Oo){for(var o=0;i===Oo;)o++,i=e[--t];if(o%2===0)return Ve}return Mo},B0=function(n){var e=h0(n),A=e.length,t=0,i=0,r=e.map(p0);return{next:function(){if(t>=A)return{done:!0,value:null};for(var s=Ve;t<A&&(s=m0(e,r,++t))===Ve;);if(s!==Ve||t===A){var o=f0.apply(null,e.slice(i,t));return i=t,{value:o,done:!1}}return{done:!0,value:null}}}},v0=function(n){for(var e=B0(n),A=[],t;!(t=e.next()).done;)t.value&&A.push(t.value.slice());return A},C0=function(n){var e=123;if(n.createRange){var A=n.createRange();if(A.getBoundingClientRect){var t=n.createElement("boundtest");t.style.height=e+"px",t.style.display="block",n.body.appendChild(t),A.selectNode(t);var i=A.getBoundingClientRect(),r=Math.round(i.height);if(n.body.removeChild(t),r===e)return!0}}return!1},w0=function(n){var e=n.createElement("boundtest");e.style.width="50px",e.style.display="block",e.style.fontSize="12px",e.style.letterSpacing="0px",e.style.wordSpacing="0px",n.body.appendChild(e);var A=n.createRange();e.innerHTML=typeof"".repeat=="function"?"&#128104;".repeat(10):"";var t=e.firstChild,i=_i(t.data).map(function(a){return le(a)}),r=0,s={},o=i.every(function(a,c){A.setStart(t,r),A.setEnd(t,r+a.length);var l=A.getBoundingClientRect();r+=a.length;var u=l.x>s.x||l.y>s.y;return s=l,c===0?!0:u});return n.body.removeChild(e),o},y0=function(){return typeof new Image().crossOrigin<"u"},b0=function(){return typeof new XMLHttpRequest().responseType=="string"},U0=function(n){var e=new Image,A=n.createElement("canvas"),t=A.getContext("2d");if(!t)return!1;e.src="data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg'></svg>";try{t.drawImage(e,0,0),A.toDataURL()}catch{return!1}return!0},vd=function(n){return n[0]===0&&n[1]===255&&n[2]===0&&n[3]===255},Q0=function(n){var e=n.createElement("canvas"),A=100;e.width=A,e.height=A;var t=e.getContext("2d");if(!t)return Promise.reject(!1);t.fillStyle="rgb(0, 255, 0)",t.fillRect(0,0,A,A);var i=new Image,r=e.toDataURL();i.src=r;var s=No(A,A,0,0,i);return t.fillStyle="red",t.fillRect(0,0,A,A),Cd(s).then(function(o){t.drawImage(o,0,0);var a=t.getImageData(0,0,A,A).data;t.fillStyle="red",t.fillRect(0,0,A,A);var c=n.createElement("div");return c.style.backgroundImage="url("+r+")",c.style.height=A+"px",vd(a)?Cd(No(A,A,0,0,c)):Promise.reject(!1)}).then(function(o){return t.drawImage(o,0,0),vd(t.getImageData(0,0,A,A).data)}).catch(function(){return!1})},No=function(n,e,A,t,i){var r="http://www.w3.org/2000/svg",s=document.createElementNS(r,"svg"),o=document.createElementNS(r,"foreignObject");return s.setAttributeNS(null,"width",n.toString()),s.setAttributeNS(null,"height",e.toString()),o.setAttributeNS(null,"width","100%"),o.setAttributeNS(null,"height","100%"),o.setAttributeNS(null,"x",A.toString()),o.setAttributeNS(null,"y",t.toString()),o.setAttributeNS(null,"externalResourcesRequired","true"),s.appendChild(o),o.appendChild(i),s},Cd=function(n){return new Promise(function(e,A){var t=new Image;t.onload=function(){return e(t)},t.onerror=A,t.src="data:image/svg+xml;charset=utf-8,"+encodeURIComponent(new XMLSerializer().serializeToString(n))})},be={get SUPPORT_RANGE_BOUNDS(){var n=C0(document);return Object.defineProperty(be,"SUPPORT_RANGE_BOUNDS",{value:n}),n},get SUPPORT_WORD_BREAKING(){var n=be.SUPPORT_RANGE_BOUNDS&&w0(document);return Object.defineProperty(be,"SUPPORT_WORD_BREAKING",{value:n}),n},get SUPPORT_SVG_DRAWING(){var n=U0(document);return Object.defineProperty(be,"SUPPORT_SVG_DRAWING",{value:n}),n},get SUPPORT_FOREIGNOBJECT_DRAWING(){var n=typeof Array.from=="function"&&typeof window.fetch=="function"?Q0(document):Promise.resolve(!1);return Object.defineProperty(be,"SUPPORT_FOREIGNOBJECT_DRAWING",{value:n}),n},get SUPPORT_CORS_IMAGES(){var n=y0();return Object.defineProperty(be,"SUPPORT_CORS_IMAGES",{value:n}),n},get SUPPORT_RESPONSE_TYPE(){var n=b0();return Object.defineProperty(be,"SUPPORT_RESPONSE_TYPE",{value:n}),n},get SUPPORT_CORS_XHR(){var n="withCredentials"in new XMLHttpRequest;return Object.defineProperty(be,"SUPPORT_CORS_XHR",{value:n}),n},get SUPPORT_NATIVE_TEXT_SEGMENTATION(){var n=!!(typeof Intl<"u"&&Intl.Segmenter);return Object.defineProperty(be,"SUPPORT_NATIVE_TEXT_SEGMENTATION",{value:n}),n}},_n=function(){function n(e,A){this.text=e,this.bounds=A}return n}(),E0=function(n,e,A,t){var i=F0(e,A),r=[],s=0;return i.forEach(function(o){if(A.textDecorationLine.length||o.trim().length>0)if(be.SUPPORT_RANGE_BOUNDS){var a=wd(t,s,o.length).getClientRects();if(a.length>1){var c=Ko(o),l=0;c.forEach(function(d){r.push(new _n(d,CA.fromDOMRectList(n,wd(t,l+s,d.length).getClientRects()))),l+=d.length})}else r.push(new _n(o,CA.fromDOMRectList(n,a)))}else{var u=t.splitText(o.length);r.push(new _n(o,S0(n,t))),t=u}else be.SUPPORT_RANGE_BOUNDS||(t=t.splitText(o.length));s+=o.length}),r},S0=function(n,e){var A=e.ownerDocument;if(A){var t=A.createElement("html2canvaswrapper");t.appendChild(e.cloneNode(!0));var i=e.parentNode;if(i){i.replaceChild(t,e);var r=Di(n,t);return t.firstChild&&i.replaceChild(t.firstChild,t),r}}return CA.EMPTY},wd=function(n,e,A){var t=n.ownerDocument;if(!t)throw new Error("Node has no owner document");var i=t.createRange();return i.setStart(n,e),i.setEnd(n,e+A),i},Ko=function(n){if(be.SUPPORT_NATIVE_TEXT_SEGMENTATION){var e=new Intl.Segmenter(void 0,{granularity:"grapheme"});return Array.from(e.segment(n)).map(function(A){return A.segment})}return v0(n)},T0=function(n,e){if(be.SUPPORT_NATIVE_TEXT_SEGMENTATION){var A=new Intl.Segmenter(void 0,{granularity:"word"});return Array.from(A.segment(n)).map(function(t){return t.segment})}return I0(n,e)},F0=function(n,e){return e.letterSpacing!==0?Ko(n):T0(n,e)},k0=[32,160,4961,65792,65793,4153,4241],I0=function(n,e){for(var A=iB(n,{lineBreak:e.lineBreak,wordBreak:e.overflowWrap==="break-word"?"break-word":e.wordBreak}),t=[],i,r=function(){if(i.value){var s=i.value.slice(),o=_i(s),a="";o.forEach(function(c){k0.indexOf(c)===-1?a+=le(c):(a.length&&t.push(a),t.push(le(c)),a="")}),a.length&&t.push(a)}};!(i=A.next()).done;)r();return t},R0=function(){function n(e,A,t){this.text=x0(A.data,t.textTransform),this.textBounds=E0(e,this.text,t,A)}return n}(),x0=function(n,e){switch(e){case 1:return n.toLowerCase();case 3:return n.replace(P0,L0);case 2:return n.toUpperCase();default:return n}},P0=/(^|\s|:|-|\(|\))([a-z])/g,L0=function(n,e,A){return n.length>0?e+A.toUpperCase():n},yd=function(n){AA(e,n);function e(A,t){var i=n.call(this,A,t)||this;return i.src=t.currentSrc||t.src,i.intrinsicWidth=t.naturalWidth,i.intrinsicHeight=t.naturalHeight,i.context.cache.addImage(i.src),i}return e}(dA),bd=function(n){AA(e,n);function e(A,t){var i=n.call(this,A,t)||this;return i.canvas=t,i.intrinsicWidth=t.width,i.intrinsicHeight=t.height,i}return e}(dA),Ud=function(n){AA(e,n);function e(A,t){var i=n.call(this,A,t)||this,r=new XMLSerializer,s=Di(A,t);return t.setAttribute("width",s.width+"px"),t.setAttribute("height",s.height+"px"),i.svg="data:image/svg+xml,"+encodeURIComponent(r.serializeToString(t)),i.intrinsicWidth=t.width.baseVal.value,i.intrinsicHeight=t.height.baseVal.value,i.context.cache.addImage(i.svg),i}return e}(dA),Qd=function(n){AA(e,n);function e(A,t){var i=n.call(this,A,t)||this;return i.value=t.value,i}return e}(dA),Vo=function(n){AA(e,n);function e(A,t){var i=n.call(this,A,t)||this;return i.start=t.start,i.reversed=typeof t.reversed=="boolean"&&t.reversed===!0,i}return e}(dA),D0=[{type:15,flags:0,unit:"px",number:3}],_0=[{type:16,flags:0,number:50}],H0=function(n){return n.width>n.height?new CA(n.left+(n.width-n.height)/2,n.top,n.height,n.height):n.width<n.height?new CA(n.left,n.top+(n.height-n.width)/2,n.width,n.width):n},O0=function(n){var e=n.type===M0?new Array(n.value.length+1).join("•"):n.value;return e.length===0?n.placeholder||"":e},gr="checkbox",pr="radio",M0="password",Ed=707406591,Go=function(n){AA(e,n);function e(A,t){var i=n.call(this,A,t)||this;switch(i.type=t.type.toLowerCase(),i.checked=t.checked,i.value=O0(t),(i.type===gr||i.type===pr)&&(i.styles.backgroundColor=3739148031,i.styles.borderTopColor=i.styles.borderRightColor=i.styles.borderBottomColor=i.styles.borderLeftColor=2779096575,i.styles.borderTopWidth=i.styles.borderRightWidth=i.styles.borderBottomWidth=i.styles.borderLeftWidth=1,i.styles.borderTopStyle=i.styles.borderRightStyle=i.styles.borderBottomStyle=i.styles.borderLeftStyle=1,i.styles.backgroundClip=[0],i.styles.backgroundOrigin=[0],i.bounds=H0(i.bounds)),i.type){case gr:i.styles.borderTopRightRadius=i.styles.borderTopLeftRadius=i.styles.borderBottomRightRadius=i.styles.borderBottomLeftRadius=D0;break;case pr:i.styles.borderTopRightRadius=i.styles.borderTopLeftRadius=i.styles.borderBottomRightRadius=i.styles.borderBottomLeftRadius=_0;break}return i}return e}(dA),Sd=function(n){AA(e,n);function e(A,t){var i=n.call(this,A,t)||this,r=t.options[t.selectedIndex||0];return i.value=r&&r.text||"",i}return e}(dA),Td=function(n){AA(e,n);function e(A,t){var i=n.call(this,A,t)||this;return i.value=t.value,i}return e}(dA),Fd=function(n){AA(e,n);function e(A,t){var i=n.call(this,A,t)||this;i.src=t.src,i.width=parseInt(t.width,10)||0,i.height=parseInt(t.height,10)||0,i.backgroundColor=i.styles.backgroundColor;try{if(t.contentWindow&&t.contentWindow.document&&t.contentWindow.document.documentElement){i.tree=Id(A,t.contentWindow.document.documentElement);var r=t.contentWindow.document.documentElement?Pn(A,getComputedStyle(t.contentWindow.document.documentElement).backgroundColor):yA.TRANSPARENT,s=t.contentWindow.document.body?Pn(A,getComputedStyle(t.contentWindow.document.body).backgroundColor):yA.TRANSPARENT;i.backgroundColor=$A(r)?$A(s)?i.styles.backgroundColor:s:r}}catch{}return i}return e}(dA),N0=["OL","UL","MENU"],mr=function(n,e,A,t){for(var i=e.firstChild,r=void 0;i;i=r)if(r=i.nextSibling,Rd(i)&&i.data.trim().length>0)A.textNodes.push(new R0(n,i,A.styles));else if(Xt(i))if(Hd(i)&&i.assignedNodes)i.assignedNodes().forEach(function(o){return mr(n,o,A,t)});else{var s=kd(n,i);s.styles.isVisible()&&(K0(i,s,t)?s.flags|=4:V0(s.styles)&&(s.flags|=2),N0.indexOf(i.tagName)!==-1&&(s.flags|=8),A.elements.push(s),i.slot,i.shadowRoot?mr(n,i.shadowRoot,s,t):!vr(i)&&!xd(i)&&!Cr(i)&&mr(n,i,s,t))}},kd=function(n,e){return Wo(e)?new yd(n,e):Pd(e)?new bd(n,e):xd(e)?new Ud(n,e):G0(e)?new Qd(n,e):j0(e)?new Vo(n,e):J0(e)?new Go(n,e):Cr(e)?new Sd(n,e):vr(e)?new Td(n,e):Dd(e)?new Fd(n,e):new dA(n,e)},Id=function(n,e){var A=kd(n,e);return A.flags|=4,mr(n,e,A,A),A},K0=function(n,e,A){return e.styles.isPositionedWithZIndex()||e.styles.opacity<1||e.styles.isTransformed()||Jo(n)&&A.styles.isTransparent()},V0=function(n){return n.isPositioned()||n.isFloating()},Rd=function(n){return n.nodeType===Node.TEXT_NODE},Xt=function(n){return n.nodeType===Node.ELEMENT_NODE},jo=function(n){return Xt(n)&&typeof n.style<"u"&&!Br(n)},Br=function(n){return typeof n.className=="object"},G0=function(n){return n.tagName==="LI"},j0=function(n){return n.tagName==="OL"},J0=function(n){return n.tagName==="INPUT"},W0=function(n){return n.tagName==="HTML"},xd=function(n){return n.tagName==="svg"},Jo=function(n){return n.tagName==="BODY"},Pd=function(n){return n.tagName==="CANVAS"},Ld=function(n){return n.tagName==="VIDEO"},Wo=function(n){return n.tagName==="IMG"},Dd=function(n){return n.tagName==="IFRAME"},_d=function(n){return n.tagName==="STYLE"},X0=function(n){return n.tagName==="SCRIPT"},vr=function(n){return n.tagName==="TEXTAREA"},Cr=function(n){return n.tagName==="SELECT"},Hd=function(n){return n.tagName==="SLOT"},Od=function(n){return n.tagName.indexOf("-")>0},$0=function(){function n(){this.counters={}}return n.prototype.getCounterValue=function(e){var A=this.counters[e];return A&&A.length?A[A.length-1]:1},n.prototype.getCounterValues=function(e){var A=this.counters[e];return A||[]},n.prototype.pop=function(e){var A=this;e.forEach(function(t){return A.counters[t].pop()})},n.prototype.parse=function(e){var A=this,t=e.counterIncrement,i=e.counterReset,r=!0;t!==null&&t.forEach(function(o){var a=A.counters[o.counter];a&&o.increment!==0&&(r=!1,a.length||a.push(1),a[Math.max(0,a.length-1)]+=o.increment)});var s=[];return r&&i.forEach(function(o){var a=A.counters[o.counter];s.push(o.counter),a||(a=A.counters[o.counter]=[]),a.push(o.reset)}),s},n}(),Md={integers:[1e3,900,500,400,100,90,50,40,10,9,5,4,1],values:["M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"]},Nd={integers:[9e3,8e3,7e3,6e3,5e3,4e3,3e3,2e3,1e3,900,800,700,600,500,400,300,200,100,90,80,70,60,50,40,30,20,10,9,8,7,6,5,4,3,2,1],values:["Ք","Փ","Ւ","Ց","Ր","Տ","Վ","Ս","Ռ","Ջ","Պ","Չ","Ո","Շ","Ն","Յ","Մ","Ճ","Ղ","Ձ","Հ","Կ","Ծ","Խ","Լ","Ի","Ժ","Թ","Ը","Է","Զ","Ե","Դ","Գ","Բ","Ա"]},Y0={integers:[1e4,9e3,8e3,7e3,6e3,5e3,4e3,3e3,2e3,1e3,400,300,200,100,90,80,70,60,50,40,30,20,19,18,17,16,15,10,9,8,7,6,5,4,3,2,1],values:["י׳","ט׳","ח׳","ז׳","ו׳","ה׳","ד׳","ג׳","ב׳","א׳","ת","ש","ר","ק","צ","פ","ע","ס","נ","מ","ל","כ","יט","יח","יז","טז","טו","י","ט","ח","ז","ו","ה","ד","ג","ב","א"]},q0={integers:[1e4,9e3,8e3,7e3,6e3,5e3,4e3,3e3,2e3,1e3,900,800,700,600,500,400,300,200,100,90,80,70,60,50,40,30,20,10,9,8,7,6,5,4,3,2,1],values:["ჵ","ჰ","ჯ","ჴ","ხ","ჭ","წ","ძ","ც","ჩ","შ","ყ","ღ","ქ","ფ","ჳ","ტ","ს","რ","ჟ","პ","ო","ჲ","ნ","მ","ლ","კ","ი","თ","ჱ","ზ","ვ","ე","დ","გ","ბ","ა"]},$t=function(n,e,A,t,i,r){return n<e||n>A?On(n,i,r.length>0):t.integers.reduce(function(s,o,a){for(;n>=o;)n-=o,s+=t.values[a];return s},"")+r},Kd=function(n,e,A,t){var i="";do A||n--,i=t(n)+i,n/=e;while(n*e>=e);return i},ue=function(n,e,A,t,i){var r=A-e+1;return(n<0?"-":"")+(Kd(Math.abs(n),r,t,function(s){return le(Math.floor(s%r)+e)})+i)},mt=function(n,e,A){A===void 0&&(A=". ");var t=e.length;return Kd(Math.abs(n),t,!1,function(i){return e[Math.floor(i%t)]})+A},Yt=1,qA=2,ZA=4,Hn=8,bA=function(n,e,A,t,i,r){if(n<-9999||n>9999)return On(n,4,i.length>0);var s=Math.abs(n),o=i;if(s===0)return e[0]+o;for(var a=0;s>0&&a<=4;a++){var c=s%10;c===0&&pe(r,Yt)&&o!==""?o=e[c]+o:c>1||c===1&&a===0||c===1&&a===1&&pe(r,qA)||c===1&&a===1&&pe(r,ZA)&&n>100||c===1&&a>1&&pe(r,Hn)?o=e[c]+(a>0?A[a-1]:"")+o:c===1&&a>0&&(o=A[a-1]+o),s=Math.floor(s/10)}return(n<0?t:"")+o},Vd="十百千萬",Gd="拾佰仟萬",jd="マイナス",Xo="마이너스",On=function(n,e,A){var t=A?". ":"",i=A?"、":"",r=A?", ":"",s=A?" ":"";switch(e){case 0:return"•"+s;case 1:return"◦"+s;case 2:return"◾"+s;case 5:var o=ue(n,48,57,!0,t);return o.length<4?"0"+o:o;case 4:return mt(n,"〇一二三四五六七八九",i);case 6:return $t(n,1,3999,Md,3,t).toLowerCase();case 7:return $t(n,1,3999,Md,3,t);case 8:return ue(n,945,969,!1,t);case 9:return ue(n,97,122,!1,t);case 10:return ue(n,65,90,!1,t);case 11:return ue(n,1632,1641,!0,t);case 12:case 49:return $t(n,1,9999,Nd,3,t);case 35:return $t(n,1,9999,Nd,3,t).toLowerCase();case 13:return ue(n,2534,2543,!0,t);case 14:case 30:return ue(n,6112,6121,!0,t);case 15:return mt(n,"子丑寅卯辰巳午未申酉戌亥",i);case 16:return mt(n,"甲乙丙丁戊己庚辛壬癸",i);case 17:case 48:return bA(n,"零一二三四五六七八九",Vd,"負",i,qA|ZA|Hn);case 47:return bA(n,"零壹貳參肆伍陸柒捌玖",Gd,"負",i,Yt|qA|ZA|Hn);case 42:return bA(n,"零一二三四五六七八九",Vd,"负",i,qA|ZA|Hn);case 41:return bA(n,"零壹贰叁肆伍陆柒捌玖",Gd,"负",i,Yt|qA|ZA|Hn);case 26:return bA(n,"〇一二三四五六七八九","十百千万",jd,i,0);case 25:return bA(n,"零壱弐参四伍六七八九","拾百千万",jd,i,Yt|qA|ZA);case 31:return bA(n,"영일이삼사오육칠팔구","십백천만",Xo,r,Yt|qA|ZA);case 33:return bA(n,"零一二三四五六七八九","十百千萬",Xo,r,0);case 32:return bA(n,"零壹貳參四五六七八九","拾百千",Xo,r,Yt|qA|ZA);case 18:return ue(n,2406,2415,!0,t);case 20:return $t(n,1,19999,q0,3,t);case 21:return ue(n,2790,2799,!0,t);case 22:return ue(n,2662,2671,!0,t);case 22:return $t(n,1,10999,Y0,3,t);case 23:return mt(n,"あいうえおかきくけこさしすせそたちつてとなにぬねのはひふへほまみむめもやゆよらりるれろわゐゑをん");case 24:return mt(n,"いろはにほへとちりぬるをわかよたれそつねならむうゐのおくやまけふこえてあさきゆめみしゑひもせす");case 27:return ue(n,3302,3311,!0,t);case 28:return mt(n,"アイウエオカキクケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモヤユヨラリルレロワヰヱヲン",i);case 29:return mt(n,"イロハニホヘトチリヌルヲワカヨタレソツネナラムウヰノオクヤマケフコエテアサキユメミシヱヒモセス",i);case 34:return ue(n,3792,3801,!0,t);case 37:return ue(n,6160,6169,!0,t);case 38:return ue(n,4160,4169,!0,t);case 39:return ue(n,2918,2927,!0,t);case 40:return ue(n,1776,1785,!0,t);case 43:return ue(n,3046,3055,!0,t);case 44:return ue(n,3174,3183,!0,t);case 45:return ue(n,3664,3673,!0,t);case 46:return ue(n,3872,3881,!0,t);case 3:default:return ue(n,48,57,!0,t)}},Jd="data-html2canvas-ignore",Wd=function(){function n(e,A,t){if(this.context=e,this.options=t,this.scrolledElements=[],this.referenceElement=A,this.counters=new $0,this.quoteDepth=0,!A.ownerDocument)throw new Error("Cloned element does not have an owner document");this.documentElement=this.cloneNode(A.ownerDocument.documentElement,!1)}return n.prototype.toIFrame=function(e,A){var t=this,i=Z0(e,A);if(!i.contentWindow)return Promise.reject("Unable to find iframe window");var r=e.defaultView.pageXOffset,s=e.defaultView.pageYOffset,o=i.contentWindow,a=o.document,c=Aw(i).then(function(){return Ee(t,void 0,void 0,function(){var l,u;return Ue(this,function(d){switch(d.label){case 0:return this.scrolledElements.forEach(rw),o&&(o.scrollTo(A.left,A.top),/(iPad|iPhone|iPod)/g.test(navigator.userAgent)&&(o.scrollY!==A.top||o.scrollX!==A.left)&&(this.context.logger.warn("Unable to restore scroll position for cloned document"),this.context.windowBounds=this.context.windowBounds.add(o.scrollX-A.left,o.scrollY-A.top,0,0))),l=this.options.onclone,u=this.clonedReferenceElement,typeof u>"u"?[2,Promise.reject("Error finding the "+this.referenceElement.nodeName+" in the cloned document")]:a.fonts&&a.fonts.ready?[4,a.fonts.ready]:[3,2];case 1:d.sent(),d.label=2;case 2:return/(AppleWebKit)/g.test(navigator.userAgent)?[4,ew(a)]:[3,4];case 3:d.sent(),d.label=4;case 4:return typeof l=="function"?[2,Promise.resolve().then(function(){return l(a,u)}).then(function(){return i})]:[2,i]}})})});return a.open(),a.write(nw(document.doctype)+"<html></html>"),iw(this.referenceElement.ownerDocument,r,s),a.replaceChild(a.adoptNode(this.documentElement),a.documentElement),a.close(),c},n.prototype.createElementClone=function(e){if(Io(e,2))debugger;if(Pd(e))return this.createCanvasClone(e);if(Ld(e))return this.createVideoClone(e);if(_d(e))return this.createStyleClone(e);var A=e.cloneNode(!1);return Wo(A)&&(Wo(e)&&e.currentSrc&&e.currentSrc!==e.src&&(A.src=e.currentSrc,A.srcset=""),A.loading==="lazy"&&(A.loading="eager")),Od(A)?this.createCustomElementClone(A):A},n.prototype.createCustomElementClone=function(e){var A=document.createElement("html2canvascustomelement");return $o(e.style,A),A},n.prototype.createStyleClone=function(e){try{var A=e.sheet;if(A&&A.cssRules){var t=[].slice.call(A.cssRules,0).reduce(function(r,s){return s&&typeof s.cssText=="string"?r+s.cssText:r},""),i=e.cloneNode(!1);return i.textContent=t,i}}catch(r){if(this.context.logger.error("Unable to access cssRules property",r),r.name!=="SecurityError")throw r}return e.cloneNode(!1)},n.prototype.createCanvasClone=function(e){var A;if(this.options.inlineImages&&e.ownerDocument){var t=e.ownerDocument.createElement("img");try{return t.src=e.toDataURL(),t}catch{this.context.logger.info("Unable to inline canvas contents, canvas is tainted",e)}}var i=e.cloneNode(!1);try{i.width=e.width,i.height=e.height;var r=e.getContext("2d"),s=i.getContext("2d");if(s)if(!this.options.allowTaint&&r)s.putImageData(r.getImageData(0,0,e.width,e.height),0,0);else{var o=(A=e.getContext("webgl2"))!==null&&A!==void 0?A:e.getContext("webgl");if(o){var a=o.getContextAttributes();(a==null?void 0:a.preserveDrawingBuffer)===!1&&this.context.logger.warn("Unable to clone WebGL context as it has preserveDrawingBuffer=false",e)}s.drawImage(e,0,0)}return i}catch{this.context.logger.info("Unable to clone canvas as it is tainted",e)}return i},n.prototype.createVideoClone=function(e){var A=e.ownerDocument.createElement("canvas");A.width=e.offsetWidth,A.height=e.offsetHeight;var t=A.getContext("2d");try{return t&&(t.drawImage(e,0,0,A.width,A.height),this.options.allowTaint||t.getImageData(0,0,A.width,A.height)),A}catch{this.context.logger.info("Unable to clone video as it is tainted",e)}var i=e.ownerDocument.createElement("canvas");return i.width=e.offsetWidth,i.height=e.offsetHeight,i},n.prototype.appendChildNode=function(e,A,t){(!Xt(A)||!X0(A)&&!A.hasAttribute(Jd)&&(typeof this.options.ignoreElements!="function"||!this.options.ignoreElements(A)))&&(!this.options.copyStyles||!Xt(A)||!_d(A))&&e.appendChild(this.cloneNode(A,t))},n.prototype.cloneChildNodes=function(e,A,t){for(var i=this,r=e.shadowRoot?e.shadowRoot.firstChild:e.firstChild;r;r=r.nextSibling)if(Xt(r)&&Hd(r)&&typeof r.assignedNodes=="function"){var s=r.assignedNodes();s.length&&s.forEach(function(o){return i.appendChildNode(A,o,t)})}else this.appendChildNode(A,r,t)},n.prototype.cloneNode=function(e,A){if(Rd(e))return document.createTextNode(e.data);if(!e.ownerDocument)return e.cloneNode(!1);var t=e.ownerDocument.defaultView;if(t&&Xt(e)&&(jo(e)||Br(e))){var i=this.createElementClone(e);i.style.transitionProperty="none";var r=t.getComputedStyle(e),s=t.getComputedStyle(e,":before"),o=t.getComputedStyle(e,":after");this.referenceElement===e&&jo(i)&&(this.clonedReferenceElement=i),Jo(i)&&aw(i);var a=this.counters.parse(new od(this.context,r)),c=this.resolvePseudoContent(e,i,s,Mn.BEFORE);Od(e)&&(A=!0),Ld(e)||this.cloneChildNodes(e,i,A),c&&i.insertBefore(c,i.firstChild);var l=this.resolvePseudoContent(e,i,o,Mn.AFTER);return l&&i.appendChild(l),this.counters.pop(a),(r&&(this.options.copyStyles||Br(e))&&!Dd(e)||A)&&$o(r,i),(e.scrollTop!==0||e.scrollLeft!==0)&&this.scrolledElements.push([i,e.scrollLeft,e.scrollTop]),(vr(e)||Cr(e))&&(vr(i)||Cr(i))&&(i.value=e.value),i}return e.cloneNode(!1)},n.prototype.resolvePseudoContent=function(e,A,t,i){var r=this;if(t){var s=t.content,o=A.ownerDocument;if(!(!o||!s||s==="none"||s==="-moz-alt-content"||t.display==="none")){this.counters.parse(new od(this.context,t));var a=new GC(this.context,t),c=o.createElement("html2canvaspseudoelement");$o(t,c),a.content.forEach(function(u){if(u.type===0)c.appendChild(o.createTextNode(u.value));else if(u.type===22){var d=o.createElement("img");d.src=u.value,d.style.opacity="1",c.appendChild(d)}else if(u.type===18){if(u.name==="attr"){var h=u.values.filter(q);h.length&&c.appendChild(o.createTextNode(e.getAttribute(h[0].value)||""))}else if(u.name==="counter"){var f=u.values.filter(Jt),g=f[0],m=f[1];if(g&&q(g)){var C=r.counters.getCounterValue(g.value),y=m&&q(m)?ko.parse(r.context,m.value):3;c.appendChild(o.createTextNode(On(C,y,!1)))}}else if(u.name==="counters"){var U=u.values.filter(Jt),g=U[0],v=U[1],m=U[2];if(g&&q(g)){var B=r.counters.getCounterValues(g.value),w=m&&q(m)?ko.parse(r.context,m.value):3,S=v&&v.type===0?v.value:"",F=B.map(function(H){return On(H,w,!1)}).join(S);c.appendChild(o.createTextNode(F))}}}else if(u.type===20)switch(u.value){case"open-quote":c.appendChild(o.createTextNode(sd(a.quotes,r.quoteDepth++,!0)));break;case"close-quote":c.appendChild(o.createTextNode(sd(a.quotes,--r.quoteDepth,!1)));break;default:c.appendChild(o.createTextNode(u.value))}}),c.className=Yo+" "+qo;var l=i===Mn.BEFORE?" "+Yo:" "+qo;return Br(A)?A.className.baseValue+=l:A.className+=l,c}}},n.destroy=function(e){return e.parentNode?(e.parentNode.removeChild(e),!0):!1},n}(),Mn;(function(n){n[n.BEFORE=0]="BEFORE",n[n.AFTER=1]="AFTER"})(Mn||(Mn={}));var Z0=function(n,e){var A=n.createElement("iframe");return A.className="html2canvas-container",A.style.visibility="hidden",A.style.position="fixed",A.style.left="-10000px",A.style.top="0px",A.style.border="0",A.width=e.width.toString(),A.height=e.height.toString(),A.scrolling="no",A.setAttribute(Jd,"true"),n.body.appendChild(A),A},z0=function(n){return new Promise(function(e){if(n.complete){e();return}if(!n.src){e();return}n.onload=e,n.onerror=e})},ew=function(n){return Promise.all([].slice.call(n.images,0).map(z0))},Aw=function(n){return new Promise(function(e,A){var t=n.contentWindow;if(!t)return A("No window assigned for iframe");var i=t.document;t.onload=n.onload=function(){t.onload=n.onload=null;var r=setInterval(function(){i.body.childNodes.length>0&&i.readyState==="complete"&&(clearInterval(r),e(n))},50)}})},tw=["all","d","content"],$o=function(n,e){for(var A=n.length-1;A>=0;A--){var t=n.item(A);tw.indexOf(t)===-1&&e.style.setProperty(t,n.getPropertyValue(t))}return e},nw=function(n){var e="";return n&&(e+="<!DOCTYPE ",n.name&&(e+=n.name),n.internalSubset&&(e+=n.internalSubset),n.publicId&&(e+='"'+n.publicId+'"'),n.systemId&&(e+='"'+n.systemId+'"'),e+=">"),e},iw=function(n,e,A){n&&n.defaultView&&(e!==n.defaultView.pageXOffset||A!==n.defaultView.pageYOffset)&&n.defaultView.scrollTo(e,A)},rw=function(n){var e=n[0],A=n[1],t=n[2];e.scrollLeft=A,e.scrollTop=t},sw=":before",ow=":after",Yo="___html2canvas___pseudoelement_before",qo="___html2canvas___pseudoelement_after",Xd=`{
56
+ content: "" !important;
57
+ display: none !important;
58
+ }`,aw=function(n){cw(n,"."+Yo+sw+Xd+`
59
+ .`+qo+ow+Xd)},cw=function(n,e){var A=n.ownerDocument;if(A){var t=A.createElement("style");t.textContent=e,n.appendChild(t)}},$d=function(){function n(){}return n.getOrigin=function(e){var A=n._link;return A?(A.href=e,A.href=A.href,A.protocol+A.hostname+A.port):"about:blank"},n.isSameOrigin=function(e){return n.getOrigin(e)===n._origin},n.setContext=function(e){n._link=e.document.createElement("a"),n._origin=n.getOrigin(e.location.href)},n._origin="about:blank",n}(),lw=function(){function n(e,A){this.context=e,this._options=A,this._cache={}}return n.prototype.addImage=function(e){var A=Promise.resolve();return this.has(e)||(zo(e)||fw(e))&&(this._cache[e]=this.loadImage(e)).catch(function(){}),A},n.prototype.match=function(e){return this._cache[e]},n.prototype.loadImage=function(e){return Ee(this,void 0,void 0,function(){var A,t,i,r,s=this;return Ue(this,function(o){switch(o.label){case 0:return A=$d.isSameOrigin(e),t=!Zo(e)&&this._options.useCORS===!0&&be.SUPPORT_CORS_IMAGES&&!A,i=!Zo(e)&&!A&&!zo(e)&&typeof this._options.proxy=="string"&&be.SUPPORT_CORS_XHR&&!t,!A&&this._options.allowTaint===!1&&!Zo(e)&&!zo(e)&&!i&&!t?[2]:(r=e,i?[4,this.proxy(r)]:[3,2]);case 1:r=o.sent(),o.label=2;case 2:return this.context.logger.debug("Added image "+e.substring(0,256)),[4,new Promise(function(a,c){var l=new Image;l.onload=function(){return a(l)},l.onerror=c,(gw(r)||t)&&(l.crossOrigin="anonymous"),l.src=r,l.complete===!0&&setTimeout(function(){return a(l)},500),s._options.imageTimeout>0&&setTimeout(function(){return c("Timed out ("+s._options.imageTimeout+"ms) loading image")},s._options.imageTimeout)})];case 3:return[2,o.sent()]}})})},n.prototype.has=function(e){return typeof this._cache[e]<"u"},n.prototype.keys=function(){return Promise.resolve(Object.keys(this._cache))},n.prototype.proxy=function(e){var A=this,t=this._options.proxy;if(!t)throw new Error("No proxy defined");var i=e.substring(0,256);return new Promise(function(r,s){var o=be.SUPPORT_RESPONSE_TYPE?"blob":"text",a=new XMLHttpRequest;a.onload=function(){if(a.status===200)if(o==="text")r(a.response);else{var u=new FileReader;u.addEventListener("load",function(){return r(u.result)},!1),u.addEventListener("error",function(d){return s(d)},!1),u.readAsDataURL(a.response)}else s("Failed to proxy resource "+i+" with status code "+a.status)},a.onerror=s;var c=t.indexOf("?")>-1?"&":"?";if(a.open("GET",""+t+c+"url="+encodeURIComponent(e)+"&responseType="+o),o!=="text"&&a instanceof XMLHttpRequest&&(a.responseType=o),A._options.imageTimeout){var l=A._options.imageTimeout;a.timeout=l,a.ontimeout=function(){return s("Timed out ("+l+"ms) proxying "+i)}}a.send()})},n}(),uw=/^data:image\/svg\+xml/i,dw=/^data:image\/.*;base64,/i,hw=/^data:image\/.*/i,fw=function(n){return be.SUPPORT_SVG_DRAWING||!pw(n)},Zo=function(n){return hw.test(n)},gw=function(n){return dw.test(n)},zo=function(n){return n.substr(0,4)==="blob"},pw=function(n){return n.substr(-3).toLowerCase()==="svg"||uw.test(n)},P=function(){function n(e,A){this.type=0,this.x=e,this.y=A}return n.prototype.add=function(e,A){return new n(this.x+e,this.y+A)},n}(),qt=function(n,e,A){return new P(n.x+(e.x-n.x)*A,n.y+(e.y-n.y)*A)},wr=function(){function n(e,A,t,i){this.type=1,this.start=e,this.startControl=A,this.endControl=t,this.end=i}return n.prototype.subdivide=function(e,A){var t=qt(this.start,this.startControl,e),i=qt(this.startControl,this.endControl,e),r=qt(this.endControl,this.end,e),s=qt(t,i,e),o=qt(i,r,e),a=qt(s,o,e);return A?new n(this.start,t,s,a):new n(a,o,r,this.end)},n.prototype.add=function(e,A){return new n(this.start.add(e,A),this.startControl.add(e,A),this.endControl.add(e,A),this.end.add(e,A))},n.prototype.reverse=function(){return new n(this.end,this.endControl,this.startControl,this.start)},n}(),Ge=function(n){return n.type===1},mw=function(){function n(e){var A=e.styles,t=e.bounds,i=xn(A.borderTopLeftRadius,t.width,t.height),r=i[0],s=i[1],o=xn(A.borderTopRightRadius,t.width,t.height),a=o[0],c=o[1],l=xn(A.borderBottomRightRadius,t.width,t.height),u=l[0],d=l[1],h=xn(A.borderBottomLeftRadius,t.width,t.height),f=h[0],g=h[1],m=[];m.push((r+a)/t.width),m.push((f+u)/t.width),m.push((s+g)/t.height),m.push((c+d)/t.height);var C=Math.max.apply(Math,m);C>1&&(r/=C,s/=C,a/=C,c/=C,u/=C,d/=C,f/=C,g/=C);var y=t.width-a,U=t.height-d,v=t.width-u,B=t.height-g,w=A.borderTopWidth,S=A.borderRightWidth,F=A.borderBottomWidth,R=A.borderLeftWidth,D=ee(A.paddingTop,e.bounds.width),H=ee(A.paddingRight,e.bounds.width),N=ee(A.paddingBottom,e.bounds.width),K=ee(A.paddingLeft,e.bounds.width);this.topLeftBorderDoubleOuterBox=r>0||s>0?ie(t.left+R/3,t.top+w/3,r-R/3,s-w/3,$.TOP_LEFT):new P(t.left+R/3,t.top+w/3),this.topRightBorderDoubleOuterBox=r>0||s>0?ie(t.left+y,t.top+w/3,a-S/3,c-w/3,$.TOP_RIGHT):new P(t.left+t.width-S/3,t.top+w/3),this.bottomRightBorderDoubleOuterBox=u>0||d>0?ie(t.left+v,t.top+U,u-S/3,d-F/3,$.BOTTOM_RIGHT):new P(t.left+t.width-S/3,t.top+t.height-F/3),this.bottomLeftBorderDoubleOuterBox=f>0||g>0?ie(t.left+R/3,t.top+B,f-R/3,g-F/3,$.BOTTOM_LEFT):new P(t.left+R/3,t.top+t.height-F/3),this.topLeftBorderDoubleInnerBox=r>0||s>0?ie(t.left+R*2/3,t.top+w*2/3,r-R*2/3,s-w*2/3,$.TOP_LEFT):new P(t.left+R*2/3,t.top+w*2/3),this.topRightBorderDoubleInnerBox=r>0||s>0?ie(t.left+y,t.top+w*2/3,a-S*2/3,c-w*2/3,$.TOP_RIGHT):new P(t.left+t.width-S*2/3,t.top+w*2/3),this.bottomRightBorderDoubleInnerBox=u>0||d>0?ie(t.left+v,t.top+U,u-S*2/3,d-F*2/3,$.BOTTOM_RIGHT):new P(t.left+t.width-S*2/3,t.top+t.height-F*2/3),this.bottomLeftBorderDoubleInnerBox=f>0||g>0?ie(t.left+R*2/3,t.top+B,f-R*2/3,g-F*2/3,$.BOTTOM_LEFT):new P(t.left+R*2/3,t.top+t.height-F*2/3),this.topLeftBorderStroke=r>0||s>0?ie(t.left+R/2,t.top+w/2,r-R/2,s-w/2,$.TOP_LEFT):new P(t.left+R/2,t.top+w/2),this.topRightBorderStroke=r>0||s>0?ie(t.left+y,t.top+w/2,a-S/2,c-w/2,$.TOP_RIGHT):new P(t.left+t.width-S/2,t.top+w/2),this.bottomRightBorderStroke=u>0||d>0?ie(t.left+v,t.top+U,u-S/2,d-F/2,$.BOTTOM_RIGHT):new P(t.left+t.width-S/2,t.top+t.height-F/2),this.bottomLeftBorderStroke=f>0||g>0?ie(t.left+R/2,t.top+B,f-R/2,g-F/2,$.BOTTOM_LEFT):new P(t.left+R/2,t.top+t.height-F/2),this.topLeftBorderBox=r>0||s>0?ie(t.left,t.top,r,s,$.TOP_LEFT):new P(t.left,t.top),this.topRightBorderBox=a>0||c>0?ie(t.left+y,t.top,a,c,$.TOP_RIGHT):new P(t.left+t.width,t.top),this.bottomRightBorderBox=u>0||d>0?ie(t.left+v,t.top+U,u,d,$.BOTTOM_RIGHT):new P(t.left+t.width,t.top+t.height),this.bottomLeftBorderBox=f>0||g>0?ie(t.left,t.top+B,f,g,$.BOTTOM_LEFT):new P(t.left,t.top+t.height),this.topLeftPaddingBox=r>0||s>0?ie(t.left+R,t.top+w,Math.max(0,r-R),Math.max(0,s-w),$.TOP_LEFT):new P(t.left+R,t.top+w),this.topRightPaddingBox=a>0||c>0?ie(t.left+Math.min(y,t.width-S),t.top+w,y>t.width+S?0:Math.max(0,a-S),Math.max(0,c-w),$.TOP_RIGHT):new P(t.left+t.width-S,t.top+w),this.bottomRightPaddingBox=u>0||d>0?ie(t.left+Math.min(v,t.width-R),t.top+Math.min(U,t.height-F),Math.max(0,u-S),Math.max(0,d-F),$.BOTTOM_RIGHT):new P(t.left+t.width-S,t.top+t.height-F),this.bottomLeftPaddingBox=f>0||g>0?ie(t.left+R,t.top+Math.min(B,t.height-F),Math.max(0,f-R),Math.max(0,g-F),$.BOTTOM_LEFT):new P(t.left+R,t.top+t.height-F),this.topLeftContentBox=r>0||s>0?ie(t.left+R+K,t.top+w+D,Math.max(0,r-(R+K)),Math.max(0,s-(w+D)),$.TOP_LEFT):new P(t.left+R+K,t.top+w+D),this.topRightContentBox=a>0||c>0?ie(t.left+Math.min(y,t.width+R+K),t.top+w+D,y>t.width+R+K?0:a-R+K,c-(w+D),$.TOP_RIGHT):new P(t.left+t.width-(S+H),t.top+w+D),this.bottomRightContentBox=u>0||d>0?ie(t.left+Math.min(v,t.width-(R+K)),t.top+Math.min(U,t.height+w+D),Math.max(0,u-(S+H)),d-(F+N),$.BOTTOM_RIGHT):new P(t.left+t.width-(S+H),t.top+t.height-(F+N)),this.bottomLeftContentBox=f>0||g>0?ie(t.left+R+K,t.top+B,Math.max(0,f-(R+K)),g-(F+N),$.BOTTOM_LEFT):new P(t.left+R+K,t.top+t.height-(F+N))}return n}(),$;(function(n){n[n.TOP_LEFT=0]="TOP_LEFT",n[n.TOP_RIGHT=1]="TOP_RIGHT",n[n.BOTTOM_RIGHT=2]="BOTTOM_RIGHT",n[n.BOTTOM_LEFT=3]="BOTTOM_LEFT"})($||($={}));var ie=function(n,e,A,t,i){var r=4*((Math.sqrt(2)-1)/3),s=A*r,o=t*r,a=n+A,c=e+t;switch(i){case $.TOP_LEFT:return new wr(new P(n,c),new P(n,c-o),new P(a-s,e),new P(a,e));case $.TOP_RIGHT:return new wr(new P(n,e),new P(n+s,e),new P(a,c-o),new P(a,c));case $.BOTTOM_RIGHT:return new wr(new P(a,e),new P(a,e+o),new P(n+s,c),new P(n,c));case $.BOTTOM_LEFT:default:return new wr(new P(a,c),new P(a-s,c),new P(n,e+o),new P(n,e))}},yr=function(n){return[n.topLeftBorderBox,n.topRightBorderBox,n.bottomRightBorderBox,n.bottomLeftBorderBox]},Bw=function(n){return[n.topLeftContentBox,n.topRightContentBox,n.bottomRightContentBox,n.bottomLeftContentBox]},br=function(n){return[n.topLeftPaddingBox,n.topRightPaddingBox,n.bottomRightPaddingBox,n.bottomLeftPaddingBox]},vw=function(){function n(e,A,t){this.offsetX=e,this.offsetY=A,this.matrix=t,this.type=0,this.target=6}return n}(),Ur=function(){function n(e,A){this.path=e,this.target=A,this.type=1}return n}(),Cw=function(){function n(e){this.opacity=e,this.type=2,this.target=6}return n}(),ww=function(n){return n.type===0},Yd=function(n){return n.type===1},yw=function(n){return n.type===2},qd=function(n,e){return n.length===e.length?n.some(function(A,t){return A===e[t]}):!1},bw=function(n,e,A,t,i){return n.map(function(r,s){switch(s){case 0:return r.add(e,A);case 1:return r.add(e+t,A);case 2:return r.add(e+t,A+i);case 3:return r.add(e,A+i)}return r})},Zd=function(){function n(e){this.element=e,this.inlineLevel=[],this.nonInlineLevel=[],this.negativeZIndex=[],this.zeroOrAutoZIndexOrTransformedOrOpacity=[],this.positiveZIndex=[],this.nonPositionedFloats=[],this.nonPositionedInlineLevel=[]}return n}(),zd=function(){function n(e,A){if(this.container=e,this.parent=A,this.effects=[],this.curves=new mw(this.container),this.container.styles.opacity<1&&this.effects.push(new Cw(this.container.styles.opacity)),this.container.styles.transform!==null){var t=this.container.bounds.left+this.container.styles.transformOrigin[0].number,i=this.container.bounds.top+this.container.styles.transformOrigin[1].number,r=this.container.styles.transform;this.effects.push(new vw(t,i,r))}if(this.container.styles.overflowX!==0){var s=yr(this.curves),o=br(this.curves);qd(s,o)?this.effects.push(new Ur(s,6)):(this.effects.push(new Ur(s,2)),this.effects.push(new Ur(o,4)))}}return n.prototype.getEffects=function(e){for(var A=[2,3].indexOf(this.container.styles.position)===-1,t=this.parent,i=this.effects.slice(0);t;){var r=t.effects.filter(function(a){return!Yd(a)});if(A||t.container.styles.position!==0||!t.parent){if(i.unshift.apply(i,r),A=[2,3].indexOf(t.container.styles.position)===-1,t.container.styles.overflowX!==0){var s=yr(t.curves),o=br(t.curves);qd(s,o)||i.unshift(new Ur(o,6))}}else i.unshift.apply(i,r);t=t.parent}return i.filter(function(a){return pe(a.target,e)})},n}(),ea=function(n,e,A,t){n.container.elements.forEach(function(i){var r=pe(i.flags,4),s=pe(i.flags,2),o=new zd(i,n);pe(i.styles.display,2048)&&t.push(o);var a=pe(i.flags,8)?[]:t;if(r||s){var c=r||i.styles.isPositioned()?A:e,l=new Zd(o);if(i.styles.isPositioned()||i.styles.opacity<1||i.styles.isTransformed()){var u=i.styles.zIndex.order;if(u<0){var d=0;c.negativeZIndex.some(function(f,g){return u>f.element.container.styles.zIndex.order?(d=g,!1):d>0}),c.negativeZIndex.splice(d,0,l)}else if(u>0){var h=0;c.positiveZIndex.some(function(f,g){return u>=f.element.container.styles.zIndex.order?(h=g+1,!1):h>0}),c.positiveZIndex.splice(h,0,l)}else c.zeroOrAutoZIndexOrTransformedOrOpacity.push(l)}else i.styles.isFloating()?c.nonPositionedFloats.push(l):c.nonPositionedInlineLevel.push(l);ea(o,l,r?l:A,a)}else i.styles.isInlineLevel()?e.inlineLevel.push(o):e.nonInlineLevel.push(o),ea(o,e,A,a);pe(i.flags,8)&&eh(i,a)})},eh=function(n,e){for(var A=n instanceof Vo?n.start:1,t=n instanceof Vo?n.reversed:!1,i=0;i<e.length;i++){var r=e[i];r.container instanceof Qd&&typeof r.container.value=="number"&&r.container.value!==0&&(A=r.container.value),r.listValue=On(A,r.container.styles.listStyleType,!0),A+=t?-1:1}},Uw=function(n){var e=new zd(n,null),A=new Zd(e),t=[];return ea(e,A,A,t),eh(e.container,t),A},Ah=function(n,e){switch(e){case 0:return je(n.topLeftBorderBox,n.topLeftPaddingBox,n.topRightBorderBox,n.topRightPaddingBox);case 1:return je(n.topRightBorderBox,n.topRightPaddingBox,n.bottomRightBorderBox,n.bottomRightPaddingBox);case 2:return je(n.bottomRightBorderBox,n.bottomRightPaddingBox,n.bottomLeftBorderBox,n.bottomLeftPaddingBox);case 3:default:return je(n.bottomLeftBorderBox,n.bottomLeftPaddingBox,n.topLeftBorderBox,n.topLeftPaddingBox)}},Qw=function(n,e){switch(e){case 0:return je(n.topLeftBorderBox,n.topLeftBorderDoubleOuterBox,n.topRightBorderBox,n.topRightBorderDoubleOuterBox);case 1:return je(n.topRightBorderBox,n.topRightBorderDoubleOuterBox,n.bottomRightBorderBox,n.bottomRightBorderDoubleOuterBox);case 2:return je(n.bottomRightBorderBox,n.bottomRightBorderDoubleOuterBox,n.bottomLeftBorderBox,n.bottomLeftBorderDoubleOuterBox);case 3:default:return je(n.bottomLeftBorderBox,n.bottomLeftBorderDoubleOuterBox,n.topLeftBorderBox,n.topLeftBorderDoubleOuterBox)}},Ew=function(n,e){switch(e){case 0:return je(n.topLeftBorderDoubleInnerBox,n.topLeftPaddingBox,n.topRightBorderDoubleInnerBox,n.topRightPaddingBox);case 1:return je(n.topRightBorderDoubleInnerBox,n.topRightPaddingBox,n.bottomRightBorderDoubleInnerBox,n.bottomRightPaddingBox);case 2:return je(n.bottomRightBorderDoubleInnerBox,n.bottomRightPaddingBox,n.bottomLeftBorderDoubleInnerBox,n.bottomLeftPaddingBox);case 3:default:return je(n.bottomLeftBorderDoubleInnerBox,n.bottomLeftPaddingBox,n.topLeftBorderDoubleInnerBox,n.topLeftPaddingBox)}},Sw=function(n,e){switch(e){case 0:return Qr(n.topLeftBorderStroke,n.topRightBorderStroke);case 1:return Qr(n.topRightBorderStroke,n.bottomRightBorderStroke);case 2:return Qr(n.bottomRightBorderStroke,n.bottomLeftBorderStroke);case 3:default:return Qr(n.bottomLeftBorderStroke,n.topLeftBorderStroke)}},Qr=function(n,e){var A=[];return Ge(n)?A.push(n.subdivide(.5,!1)):A.push(n),Ge(e)?A.push(e.subdivide(.5,!0)):A.push(e),A},je=function(n,e,A,t){var i=[];return Ge(n)?i.push(n.subdivide(.5,!1)):i.push(n),Ge(A)?i.push(A.subdivide(.5,!0)):i.push(A),Ge(t)?i.push(t.subdivide(.5,!0).reverse()):i.push(t),Ge(e)?i.push(e.subdivide(.5,!1).reverse()):i.push(e),i},th=function(n){var e=n.bounds,A=n.styles;return e.add(A.borderLeftWidth,A.borderTopWidth,-(A.borderRightWidth+A.borderLeftWidth),-(A.borderTopWidth+A.borderBottomWidth))},Er=function(n){var e=n.styles,A=n.bounds,t=ee(e.paddingLeft,A.width),i=ee(e.paddingRight,A.width),r=ee(e.paddingTop,A.width),s=ee(e.paddingBottom,A.width);return A.add(t+e.borderLeftWidth,r+e.borderTopWidth,-(e.borderRightWidth+e.borderLeftWidth+t+i),-(e.borderTopWidth+e.borderBottomWidth+r+s))},Tw=function(n,e){return n===0?e.bounds:n===2?Er(e):th(e)},Fw=function(n,e){return n===0?e.bounds:n===2?Er(e):th(e)},Aa=function(n,e,A){var t=Tw(zt(n.styles.backgroundOrigin,e),n),i=Fw(zt(n.styles.backgroundClip,e),n),r=kw(zt(n.styles.backgroundSize,e),A,t),s=r[0],o=r[1],a=xn(zt(n.styles.backgroundPosition,e),t.width-s,t.height-o),c=Iw(zt(n.styles.backgroundRepeat,e),a,r,t,i),l=Math.round(t.left+a[0]),u=Math.round(t.top+a[1]);return[c,l,u,s,o]},Zt=function(n){return q(n)&&n.value===Wt.AUTO},Sr=function(n){return typeof n=="number"},kw=function(n,e,A){var t=e[0],i=e[1],r=e[2],s=n[0],o=n[1];if(!s)return[0,0];if(he(s)&&o&&he(o))return[ee(s,A.width),ee(o,A.height)];var a=Sr(r);if(q(s)&&(s.value===Wt.CONTAIN||s.value===Wt.COVER)){if(Sr(r)){var c=A.width/A.height;return c<r!=(s.value===Wt.COVER)?[A.width,A.width/r]:[A.height*r,A.height]}return[A.width,A.height]}var l=Sr(t),u=Sr(i),d=l||u;if(Zt(s)&&(!o||Zt(o))){if(l&&u)return[t,i];if(!a&&!d)return[A.width,A.height];if(d&&a){var h=l?t:i*r,f=u?i:t/r;return[h,f]}var g=l?t:A.width,m=u?i:A.height;return[g,m]}if(a){var C=0,y=0;return he(s)?C=ee(s,A.width):he(o)&&(y=ee(o,A.height)),Zt(s)?C=y*r:(!o||Zt(o))&&(y=C/r),[C,y]}var U=null,v=null;if(he(s)?U=ee(s,A.width):o&&he(o)&&(v=ee(o,A.height)),U!==null&&(!o||Zt(o))&&(v=l&&u?U/t*i:A.height),v!==null&&Zt(s)&&(U=l&&u?v/i*t:A.width),U!==null&&v!==null)return[U,v];throw new Error("Unable to calculate background-size for element")},zt=function(n,e){var A=n[e];return typeof A>"u"?n[0]:A},Iw=function(n,e,A,t,i){var r=e[0],s=e[1],o=A[0],a=A[1];switch(n){case 2:return[new P(Math.round(t.left),Math.round(t.top+s)),new P(Math.round(t.left+t.width),Math.round(t.top+s)),new P(Math.round(t.left+t.width),Math.round(a+t.top+s)),new P(Math.round(t.left),Math.round(a+t.top+s))];case 3:return[new P(Math.round(t.left+r),Math.round(t.top)),new P(Math.round(t.left+r+o),Math.round(t.top)),new P(Math.round(t.left+r+o),Math.round(t.height+t.top)),new P(Math.round(t.left+r),Math.round(t.height+t.top))];case 1:return[new P(Math.round(t.left+r),Math.round(t.top+s)),new P(Math.round(t.left+r+o),Math.round(t.top+s)),new P(Math.round(t.left+r+o),Math.round(t.top+s+a)),new P(Math.round(t.left+r),Math.round(t.top+s+a))];default:return[new P(Math.round(i.left),Math.round(i.top)),new P(Math.round(i.left+i.width),Math.round(i.top)),new P(Math.round(i.left+i.width),Math.round(i.height+i.top)),new P(Math.round(i.left),Math.round(i.height+i.top))]}},Rw="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7",nh="Hidden Text",xw=function(){function n(e){this._data={},this._document=e}return n.prototype.parseMetrics=function(e,A){var t=this._document.createElement("div"),i=this._document.createElement("img"),r=this._document.createElement("span"),s=this._document.body;t.style.visibility="hidden",t.style.fontFamily=e,t.style.fontSize=A,t.style.margin="0",t.style.padding="0",t.style.whiteSpace="nowrap",s.appendChild(t),i.src=Rw,i.width=1,i.height=1,i.style.margin="0",i.style.padding="0",i.style.verticalAlign="baseline",r.style.fontFamily=e,r.style.fontSize=A,r.style.margin="0",r.style.padding="0",r.appendChild(this._document.createTextNode(nh)),t.appendChild(r),t.appendChild(i);var o=i.offsetTop-r.offsetTop+2;t.removeChild(r),t.appendChild(this._document.createTextNode(nh)),t.style.lineHeight="normal",i.style.verticalAlign="super";var a=i.offsetTop-t.offsetTop+2;return s.removeChild(t),{baseline:o,middle:a}},n.prototype.getMetrics=function(e,A){var t=e+" "+A;return typeof this._data[t]>"u"&&(this._data[t]=this.parseMetrics(e,A)),this._data[t]},n}(),ih=function(){function n(e,A){this.context=e,this.options=A}return n}(),Pw=1e4,Lw=function(n){AA(e,n);function e(A,t){var i=n.call(this,A,t)||this;return i._activeEffects=[],i.canvas=t.canvas?t.canvas:document.createElement("canvas"),i.ctx=i.canvas.getContext("2d"),t.canvas||(i.canvas.width=Math.floor(t.width*t.scale),i.canvas.height=Math.floor(t.height*t.scale),i.canvas.style.width=t.width+"px",i.canvas.style.height=t.height+"px"),i.fontMetrics=new xw(document),i.ctx.scale(i.options.scale,i.options.scale),i.ctx.translate(-t.x,-t.y),i.ctx.textBaseline="bottom",i._activeEffects=[],i.context.logger.debug("Canvas renderer initialized ("+t.width+"x"+t.height+") with scale "+t.scale),i}return e.prototype.applyEffects=function(A){for(var t=this;this._activeEffects.length;)this.popEffect();A.forEach(function(i){return t.applyEffect(i)})},e.prototype.applyEffect=function(A){this.ctx.save(),yw(A)&&(this.ctx.globalAlpha=A.opacity),ww(A)&&(this.ctx.translate(A.offsetX,A.offsetY),this.ctx.transform(A.matrix[0],A.matrix[1],A.matrix[2],A.matrix[3],A.matrix[4],A.matrix[5]),this.ctx.translate(-A.offsetX,-A.offsetY)),Yd(A)&&(this.path(A.path),this.ctx.clip()),this._activeEffects.push(A)},e.prototype.popEffect=function(){this._activeEffects.pop(),this.ctx.restore()},e.prototype.renderStack=function(A){return Ee(this,void 0,void 0,function(){var t;return Ue(this,function(i){switch(i.label){case 0:return t=A.element.container.styles,t.isVisible()?[4,this.renderStackContent(A)]:[3,2];case 1:i.sent(),i.label=2;case 2:return[2]}})})},e.prototype.renderNode=function(A){return Ee(this,void 0,void 0,function(){return Ue(this,function(t){switch(t.label){case 0:if(pe(A.container.flags,16))debugger;return A.container.styles.isVisible()?[4,this.renderNodeBackgroundAndBorders(A)]:[3,3];case 1:return t.sent(),[4,this.renderNodeContent(A)];case 2:t.sent(),t.label=3;case 3:return[2]}})})},e.prototype.renderTextWithLetterSpacing=function(A,t,i){var r=this;if(t===0)this.ctx.fillText(A.text,A.bounds.left,A.bounds.top+i);else{var s=Ko(A.text);s.reduce(function(o,a){return r.ctx.fillText(a,o,A.bounds.top+i),o+r.ctx.measureText(a).width},A.bounds.left)}},e.prototype.createFontStyle=function(A){var t=A.fontVariant.filter(function(s){return s==="normal"||s==="small-caps"}).join(""),i=Mw(A.fontFamily).join(", "),r=Rn(A.fontSize)?""+A.fontSize.number+A.fontSize.unit:A.fontSize.number+"px";return[[A.fontStyle,t,A.fontWeight,r,i].join(" "),i,r]},e.prototype.renderTextNode=function(A,t){return Ee(this,void 0,void 0,function(){var i,r,s,o,a,c,l,u,d=this;return Ue(this,function(h){return i=this.createFontStyle(t),r=i[0],s=i[1],o=i[2],this.ctx.font=r,this.ctx.direction=t.direction===1?"rtl":"ltr",this.ctx.textAlign="left",this.ctx.textBaseline="alphabetic",a=this.fontMetrics.getMetrics(s,o),c=a.baseline,l=a.middle,u=t.paintOrder,A.textBounds.forEach(function(f){u.forEach(function(g){switch(g){case 0:d.ctx.fillStyle=Be(t.color),d.renderTextWithLetterSpacing(f,t.letterSpacing,c);var m=t.textShadow;m.length&&f.text.trim().length&&(m.slice(0).reverse().forEach(function(C){d.ctx.shadowColor=Be(C.color),d.ctx.shadowOffsetX=C.offsetX.number*d.options.scale,d.ctx.shadowOffsetY=C.offsetY.number*d.options.scale,d.ctx.shadowBlur=C.blur.number,d.renderTextWithLetterSpacing(f,t.letterSpacing,c)}),d.ctx.shadowColor="",d.ctx.shadowOffsetX=0,d.ctx.shadowOffsetY=0,d.ctx.shadowBlur=0),t.textDecorationLine.length&&(d.ctx.fillStyle=Be(t.textDecorationColor||t.color),t.textDecorationLine.forEach(function(C){switch(C){case 1:d.ctx.fillRect(f.bounds.left,Math.round(f.bounds.top+c),f.bounds.width,1);break;case 2:d.ctx.fillRect(f.bounds.left,Math.round(f.bounds.top),f.bounds.width,1);break;case 3:d.ctx.fillRect(f.bounds.left,Math.ceil(f.bounds.top+l),f.bounds.width,1);break}}));break;case 1:t.webkitTextStrokeWidth&&f.text.trim().length&&(d.ctx.strokeStyle=Be(t.webkitTextStrokeColor),d.ctx.lineWidth=t.webkitTextStrokeWidth,d.ctx.lineJoin=window.chrome?"miter":"round",d.ctx.strokeText(f.text,f.bounds.left,f.bounds.top+c)),d.ctx.strokeStyle="",d.ctx.lineWidth=0,d.ctx.lineJoin="miter";break}})}),[2]})})},e.prototype.renderReplacedElement=function(A,t,i){if(i&&A.intrinsicWidth>0&&A.intrinsicHeight>0){var r=Er(A),s=br(t);this.path(s),this.ctx.save(),this.ctx.clip(),this.ctx.drawImage(i,0,0,A.intrinsicWidth,A.intrinsicHeight,r.left,r.top,r.width,r.height),this.ctx.restore()}},e.prototype.renderNodeContent=function(A){return Ee(this,void 0,void 0,function(){var t,i,r,s,o,a,y,y,c,l,u,d,v,h,f,B,g,m,C,y,U,v,B;return Ue(this,function(w){switch(w.label){case 0:this.applyEffects(A.getEffects(4)),t=A.container,i=A.curves,r=t.styles,s=0,o=t.textNodes,w.label=1;case 1:return s<o.length?(a=o[s],[4,this.renderTextNode(a,r)]):[3,4];case 2:w.sent(),w.label=3;case 3:return s++,[3,1];case 4:if(!(t instanceof yd))return[3,8];w.label=5;case 5:return w.trys.push([5,7,,8]),[4,this.context.cache.match(t.src)];case 6:return y=w.sent(),this.renderReplacedElement(t,i,y),[3,8];case 7:return w.sent(),this.context.logger.error("Error loading image "+t.src),[3,8];case 8:if(t instanceof bd&&this.renderReplacedElement(t,i,t.canvas),!(t instanceof Ud))return[3,12];w.label=9;case 9:return w.trys.push([9,11,,12]),[4,this.context.cache.match(t.svg)];case 10:return y=w.sent(),this.renderReplacedElement(t,i,y),[3,12];case 11:return w.sent(),this.context.logger.error("Error loading svg "+t.svg.substring(0,255)),[3,12];case 12:return t instanceof Fd&&t.tree?(c=new e(this.context,{scale:this.options.scale,backgroundColor:t.backgroundColor,x:0,y:0,width:t.width,height:t.height}),[4,c.render(t.tree)]):[3,14];case 13:l=w.sent(),t.width&&t.height&&this.ctx.drawImage(l,0,0,t.width,t.height,t.bounds.left,t.bounds.top,t.bounds.width,t.bounds.height),w.label=14;case 14:if(t instanceof Go&&(u=Math.min(t.bounds.width,t.bounds.height),t.type===gr?t.checked&&(this.ctx.save(),this.path([new P(t.bounds.left+u*.39363,t.bounds.top+u*.79),new P(t.bounds.left+u*.16,t.bounds.top+u*.5549),new P(t.bounds.left+u*.27347,t.bounds.top+u*.44071),new P(t.bounds.left+u*.39694,t.bounds.top+u*.5649),new P(t.bounds.left+u*.72983,t.bounds.top+u*.23),new P(t.bounds.left+u*.84,t.bounds.top+u*.34085),new P(t.bounds.left+u*.39363,t.bounds.top+u*.79)]),this.ctx.fillStyle=Be(Ed),this.ctx.fill(),this.ctx.restore()):t.type===pr&&t.checked&&(this.ctx.save(),this.ctx.beginPath(),this.ctx.arc(t.bounds.left+u/2,t.bounds.top+u/2,u/4,0,Math.PI*2,!0),this.ctx.fillStyle=Be(Ed),this.ctx.fill(),this.ctx.restore())),Dw(t)&&t.value.length){switch(d=this.createFontStyle(r),v=d[0],h=d[1],f=this.fontMetrics.getMetrics(v,h).baseline,this.ctx.font=v,this.ctx.fillStyle=Be(r.color),this.ctx.textBaseline="alphabetic",this.ctx.textAlign=Hw(t.styles.textAlign),B=Er(t),g=0,t.styles.textAlign){case 1:g+=B.width/2;break;case 2:g+=B.width;break}m=B.add(g,0,0,-B.height/2+1),this.ctx.save(),this.path([new P(B.left,B.top),new P(B.left+B.width,B.top),new P(B.left+B.width,B.top+B.height),new P(B.left,B.top+B.height)]),this.ctx.clip(),this.renderTextWithLetterSpacing(new _n(t.value,m),r.letterSpacing,f),this.ctx.restore(),this.ctx.textBaseline="alphabetic",this.ctx.textAlign="left"}if(!pe(t.styles.display,2048))return[3,20];if(t.styles.listStyleImage===null)return[3,19];if(C=t.styles.listStyleImage,C.type!==0)return[3,18];y=void 0,U=C.url,w.label=15;case 15:return w.trys.push([15,17,,18]),[4,this.context.cache.match(U)];case 16:return y=w.sent(),this.ctx.drawImage(y,t.bounds.left-(y.width+10),t.bounds.top),[3,18];case 17:return w.sent(),this.context.logger.error("Error loading list-style-image "+U),[3,18];case 18:return[3,20];case 19:A.listValue&&t.styles.listStyleType!==-1&&(v=this.createFontStyle(r)[0],this.ctx.font=v,this.ctx.fillStyle=Be(r.color),this.ctx.textBaseline="middle",this.ctx.textAlign="right",B=new CA(t.bounds.left,t.bounds.top+ee(t.styles.paddingTop,t.bounds.width),t.bounds.width,nd(r.lineHeight,r.fontSize.number)/2+1),this.renderTextWithLetterSpacing(new _n(A.listValue,B),r.letterSpacing,nd(r.lineHeight,r.fontSize.number)/2+2),this.ctx.textBaseline="bottom",this.ctx.textAlign="left"),w.label=20;case 20:return[2]}})})},e.prototype.renderStackContent=function(A){return Ee(this,void 0,void 0,function(){var t,i,C,r,s,C,o,a,C,c,l,C,u,d,C,h,f,C,g,m,C;return Ue(this,function(y){switch(y.label){case 0:if(pe(A.element.container.flags,16))debugger;return[4,this.renderNodeBackgroundAndBorders(A.element)];case 1:y.sent(),t=0,i=A.negativeZIndex,y.label=2;case 2:return t<i.length?(C=i[t],[4,this.renderStack(C)]):[3,5];case 3:y.sent(),y.label=4;case 4:return t++,[3,2];case 5:return[4,this.renderNodeContent(A.element)];case 6:y.sent(),r=0,s=A.nonInlineLevel,y.label=7;case 7:return r<s.length?(C=s[r],[4,this.renderNode(C)]):[3,10];case 8:y.sent(),y.label=9;case 9:return r++,[3,7];case 10:o=0,a=A.nonPositionedFloats,y.label=11;case 11:return o<a.length?(C=a[o],[4,this.renderStack(C)]):[3,14];case 12:y.sent(),y.label=13;case 13:return o++,[3,11];case 14:c=0,l=A.nonPositionedInlineLevel,y.label=15;case 15:return c<l.length?(C=l[c],[4,this.renderStack(C)]):[3,18];case 16:y.sent(),y.label=17;case 17:return c++,[3,15];case 18:u=0,d=A.inlineLevel,y.label=19;case 19:return u<d.length?(C=d[u],[4,this.renderNode(C)]):[3,22];case 20:y.sent(),y.label=21;case 21:return u++,[3,19];case 22:h=0,f=A.zeroOrAutoZIndexOrTransformedOrOpacity,y.label=23;case 23:return h<f.length?(C=f[h],[4,this.renderStack(C)]):[3,26];case 24:y.sent(),y.label=25;case 25:return h++,[3,23];case 26:g=0,m=A.positiveZIndex,y.label=27;case 27:return g<m.length?(C=m[g],[4,this.renderStack(C)]):[3,30];case 28:y.sent(),y.label=29;case 29:return g++,[3,27];case 30:return[2]}})})},e.prototype.mask=function(A){this.ctx.beginPath(),this.ctx.moveTo(0,0),this.ctx.lineTo(this.canvas.width,0),this.ctx.lineTo(this.canvas.width,this.canvas.height),this.ctx.lineTo(0,this.canvas.height),this.ctx.lineTo(0,0),this.formatPath(A.slice(0).reverse()),this.ctx.closePath()},e.prototype.path=function(A){this.ctx.beginPath(),this.formatPath(A),this.ctx.closePath()},e.prototype.formatPath=function(A){var t=this;A.forEach(function(i,r){var s=Ge(i)?i.start:i;r===0?t.ctx.moveTo(s.x,s.y):t.ctx.lineTo(s.x,s.y),Ge(i)&&t.ctx.bezierCurveTo(i.startControl.x,i.startControl.y,i.endControl.x,i.endControl.y,i.end.x,i.end.y)})},e.prototype.renderRepeat=function(A,t,i,r){this.path(A),this.ctx.fillStyle=t,this.ctx.translate(i,r),this.ctx.fill(),this.ctx.translate(-i,-r)},e.prototype.resizeImage=function(A,t,i){var r;if(A.width===t&&A.height===i)return A;var s=(r=this.canvas.ownerDocument)!==null&&r!==void 0?r:document,o=s.createElement("canvas");o.width=Math.max(1,t),o.height=Math.max(1,i);var a=o.getContext("2d");return a.drawImage(A,0,0,A.width,A.height,0,0,t,i),o},e.prototype.renderBackgroundImage=function(A){return Ee(this,void 0,void 0,function(){var t,i,r,s,o,a;return Ue(this,function(c){switch(c.label){case 0:t=A.styles.backgroundImage.length-1,i=function(l){var u,d,h,D,De,_e,K,ae,F,f,D,De,_e,K,ae,g,m,C,y,U,v,B,w,S,F,R,D,H,N,K,ae,hA,De,_e,bt,fA,tt,Ut,Qt,EA,Et,SA;return Ue(this,function(rn){switch(rn.label){case 0:if(l.type!==0)return[3,5];u=void 0,d=l.url,rn.label=1;case 1:return rn.trys.push([1,3,,4]),[4,r.context.cache.match(d)];case 2:return u=rn.sent(),[3,4];case 3:return rn.sent(),r.context.logger.error("Error loading background-image "+d),[3,4];case 4:return u&&(h=Aa(A,t,[u.width,u.height,u.width/u.height]),D=h[0],De=h[1],_e=h[2],K=h[3],ae=h[4],F=r.ctx.createPattern(r.resizeImage(u,K,ae),"repeat"),r.renderRepeat(D,F,De,_e)),[3,6];case 5:wv(l)?(f=Aa(A,t,[null,null,null]),D=f[0],De=f[1],_e=f[2],K=f[3],ae=f[4],g=pv(l.angle,K,ae),m=g[0],C=g[1],y=g[2],U=g[3],v=g[4],B=document.createElement("canvas"),B.width=K,B.height=ae,w=B.getContext("2d"),S=w.createLinearGradient(C,U,y,v),Ju(l.stops,m).forEach(function(Yn){return S.addColorStop(Yn.stop,Be(Yn.color))}),w.fillStyle=S,w.fillRect(0,0,K,ae),K>0&&ae>0&&(F=r.ctx.createPattern(B,"repeat"),r.renderRepeat(D,F,De,_e))):yv(l)&&(R=Aa(A,t,[null,null,null]),D=R[0],H=R[1],N=R[2],K=R[3],ae=R[4],hA=l.position.length===0?[So]:l.position,De=ee(hA[0],K),_e=ee(hA[hA.length-1],ae),bt=mv(l,De,_e,K,ae),fA=bt[0],tt=bt[1],fA>0&&tt>0&&(Ut=r.ctx.createRadialGradient(H+De,N+_e,0,H+De,N+_e,fA),Ju(l.stops,fA*2).forEach(function(Yn){return Ut.addColorStop(Yn.stop,Be(Yn.color))}),r.path(D),r.ctx.fillStyle=Ut,fA!==tt?(Qt=A.bounds.left+.5*A.bounds.width,EA=A.bounds.top+.5*A.bounds.height,Et=tt/fA,SA=1/Et,r.ctx.save(),r.ctx.translate(Qt,EA),r.ctx.transform(1,0,0,Et,0,0),r.ctx.translate(-Qt,-EA),r.ctx.fillRect(H,SA*(N-EA)+EA,K,ae*SA),r.ctx.restore()):r.ctx.fill())),rn.label=6;case 6:return t--,[2]}})},r=this,s=0,o=A.styles.backgroundImage.slice(0).reverse(),c.label=1;case 1:return s<o.length?(a=o[s],[5,i(a)]):[3,4];case 2:c.sent(),c.label=3;case 3:return s++,[3,1];case 4:return[2]}})})},e.prototype.renderSolidBorder=function(A,t,i){return Ee(this,void 0,void 0,function(){return Ue(this,function(r){return this.path(Ah(i,t)),this.ctx.fillStyle=Be(A),this.ctx.fill(),[2]})})},e.prototype.renderDoubleBorder=function(A,t,i,r){return Ee(this,void 0,void 0,function(){var s,o;return Ue(this,function(a){switch(a.label){case 0:return t<3?[4,this.renderSolidBorder(A,i,r)]:[3,2];case 1:return a.sent(),[2];case 2:return s=Qw(r,i),this.path(s),this.ctx.fillStyle=Be(A),this.ctx.fill(),o=Ew(r,i),this.path(o),this.ctx.fill(),[2]}})})},e.prototype.renderNodeBackgroundAndBorders=function(A){return Ee(this,void 0,void 0,function(){var t,i,r,s,o,a,c,l,u=this;return Ue(this,function(d){switch(d.label){case 0:return this.applyEffects(A.getEffects(2)),t=A.container.styles,i=!$A(t.backgroundColor)||t.backgroundImage.length,r=[{style:t.borderTopStyle,color:t.borderTopColor,width:t.borderTopWidth},{style:t.borderRightStyle,color:t.borderRightColor,width:t.borderRightWidth},{style:t.borderBottomStyle,color:t.borderBottomColor,width:t.borderBottomWidth},{style:t.borderLeftStyle,color:t.borderLeftColor,width:t.borderLeftWidth}],s=_w(zt(t.backgroundClip,0),A.curves),i||t.boxShadow.length?(this.ctx.save(),this.path(s),this.ctx.clip(),$A(t.backgroundColor)||(this.ctx.fillStyle=Be(t.backgroundColor),this.ctx.fill()),[4,this.renderBackgroundImage(A.container)]):[3,2];case 1:d.sent(),this.ctx.restore(),t.boxShadow.slice(0).reverse().forEach(function(h){u.ctx.save();var f=yr(A.curves),g=h.inset?0:Pw,m=bw(f,-g+(h.inset?1:-1)*h.spread.number,(h.inset?1:-1)*h.spread.number,h.spread.number*(h.inset?-2:2),h.spread.number*(h.inset?-2:2));h.inset?(u.path(f),u.ctx.clip(),u.mask(m)):(u.mask(f),u.ctx.clip(),u.path(m)),u.ctx.shadowOffsetX=h.offsetX.number+g,u.ctx.shadowOffsetY=h.offsetY.number,u.ctx.shadowColor=Be(h.color),u.ctx.shadowBlur=h.blur.number,u.ctx.fillStyle=h.inset?Be(h.color):"rgba(0,0,0,1)",u.ctx.fill(),u.ctx.restore()}),d.label=2;case 2:o=0,a=0,c=r,d.label=3;case 3:return a<c.length?(l=c[a],l.style!==0&&!$A(l.color)&&l.width>0?l.style!==2?[3,5]:[4,this.renderDashedDottedBorder(l.color,l.width,o,A.curves,2)]:[3,11]):[3,13];case 4:return d.sent(),[3,11];case 5:return l.style!==3?[3,7]:[4,this.renderDashedDottedBorder(l.color,l.width,o,A.curves,3)];case 6:return d.sent(),[3,11];case 7:return l.style!==4?[3,9]:[4,this.renderDoubleBorder(l.color,l.width,o,A.curves)];case 8:return d.sent(),[3,11];case 9:return[4,this.renderSolidBorder(l.color,o,A.curves)];case 10:d.sent(),d.label=11;case 11:o++,d.label=12;case 12:return a++,[3,3];case 13:return[2]}})})},e.prototype.renderDashedDottedBorder=function(A,t,i,r,s){return Ee(this,void 0,void 0,function(){var o,a,c,l,u,d,h,f,g,m,C,y,U,v,B,w,B,w;return Ue(this,function(S){return this.ctx.save(),o=Sw(r,i),a=Ah(r,i),s===2&&(this.path(a),this.ctx.clip()),Ge(a[0])?(c=a[0].start.x,l=a[0].start.y):(c=a[0].x,l=a[0].y),Ge(a[1])?(u=a[1].end.x,d=a[1].end.y):(u=a[1].x,d=a[1].y),i===0||i===2?h=Math.abs(c-u):h=Math.abs(l-d),this.ctx.beginPath(),s===3?this.formatPath(o):this.formatPath(a.slice(0,2)),f=t<3?t*3:t*2,g=t<3?t*2:t,s===3&&(f=t,g=t),m=!0,h<=f*2?m=!1:h<=f*2+g?(C=h/(2*f+g),f*=C,g*=C):(y=Math.floor((h+g)/(f+g)),U=(h-y*f)/(y-1),v=(h-(y+1)*f)/y,g=v<=0||Math.abs(g-U)<Math.abs(g-v)?U:v),m&&(s===3?this.ctx.setLineDash([0,f+g]):this.ctx.setLineDash([f,g])),s===3?(this.ctx.lineCap="round",this.ctx.lineWidth=t):this.ctx.lineWidth=t*2+1.1,this.ctx.strokeStyle=Be(A),this.ctx.stroke(),this.ctx.setLineDash([]),s===2&&(Ge(a[0])&&(B=a[3],w=a[0],this.ctx.beginPath(),this.formatPath([new P(B.end.x,B.end.y),new P(w.start.x,w.start.y)]),this.ctx.stroke()),Ge(a[1])&&(B=a[1],w=a[2],this.ctx.beginPath(),this.formatPath([new P(B.end.x,B.end.y),new P(w.start.x,w.start.y)]),this.ctx.stroke())),this.ctx.restore(),[2]})})},e.prototype.render=function(A){return Ee(this,void 0,void 0,function(){var t;return Ue(this,function(i){switch(i.label){case 0:return this.options.backgroundColor&&(this.ctx.fillStyle=Be(this.options.backgroundColor),this.ctx.fillRect(this.options.x,this.options.y,this.options.width,this.options.height)),t=Uw(A),[4,this.renderStack(t)];case 1:return i.sent(),this.applyEffects([]),[2,this.canvas]}})})},e}(ih),Dw=function(n){return n instanceof Td||n instanceof Sd?!0:n instanceof Go&&n.type!==pr&&n.type!==gr},_w=function(n,e){switch(n){case 0:return yr(e);case 2:return Bw(e);case 1:default:return br(e)}},Hw=function(n){switch(n){case 1:return"center";case 2:return"right";case 0:default:return"left"}},Ow=["-apple-system","system-ui"],Mw=function(n){return/iPhone OS 15_(0|1)/.test(window.navigator.userAgent)?n.filter(function(e){return Ow.indexOf(e)===-1}):n},Nw=function(n){AA(e,n);function e(A,t){var i=n.call(this,A,t)||this;return i.canvas=t.canvas?t.canvas:document.createElement("canvas"),i.ctx=i.canvas.getContext("2d"),i.options=t,i.canvas.width=Math.floor(t.width*t.scale),i.canvas.height=Math.floor(t.height*t.scale),i.canvas.style.width=t.width+"px",i.canvas.style.height=t.height+"px",i.ctx.scale(i.options.scale,i.options.scale),i.ctx.translate(-t.x,-t.y),i.context.logger.debug("EXPERIMENTAL ForeignObject renderer initialized ("+t.width+"x"+t.height+" at "+t.x+","+t.y+") with scale "+t.scale),i}return e.prototype.render=function(A){return Ee(this,void 0,void 0,function(){var t,i;return Ue(this,function(r){switch(r.label){case 0:return t=No(this.options.width*this.options.scale,this.options.height*this.options.scale,this.options.scale,this.options.scale,A),[4,Kw(t)];case 1:return i=r.sent(),this.options.backgroundColor&&(this.ctx.fillStyle=Be(this.options.backgroundColor),this.ctx.fillRect(0,0,this.options.width*this.options.scale,this.options.height*this.options.scale)),this.ctx.drawImage(i,-this.options.x*this.options.scale,-this.options.y*this.options.scale),[2,this.canvas]}})})},e}(ih),Kw=function(n){return new Promise(function(e,A){var t=new Image;t.onload=function(){e(t)},t.onerror=A,t.src="data:image/svg+xml;charset=utf-8,"+encodeURIComponent(new XMLSerializer().serializeToString(n))})},Vw=function(){function n(e){var A=e.id,t=e.enabled;this.id=A,this.enabled=t,this.start=Date.now()}return n.prototype.debug=function(){for(var e=[],A=0;A<arguments.length;A++)e[A]=arguments[A];this.enabled&&(typeof window<"u"&&window.console&&typeof console.debug=="function"?console.debug.apply(console,Li([this.id,this.getTime()+"ms"],e)):this.info.apply(this,e))},n.prototype.getTime=function(){return Date.now()-this.start},n.prototype.info=function(){for(var e=[],A=0;A<arguments.length;A++)e[A]=arguments[A];this.enabled&&typeof window<"u"&&window.console&&typeof console.info=="function"&&console.info.apply(console,Li([this.id,this.getTime()+"ms"],e))},n.prototype.warn=function(){for(var e=[],A=0;A<arguments.length;A++)e[A]=arguments[A];this.enabled&&(typeof window<"u"&&window.console&&typeof console.warn=="function"?console.warn.apply(console,Li([this.id,this.getTime()+"ms"],e)):this.info.apply(this,e))},n.prototype.error=function(){for(var e=[],A=0;A<arguments.length;A++)e[A]=arguments[A];this.enabled&&(typeof window<"u"&&window.console&&typeof console.error=="function"?console.error.apply(console,Li([this.id,this.getTime()+"ms"],e)):this.info.apply(this,e))},n.instances={},n}(),Gw=function(){function n(e,A){var t;this.windowBounds=A,this.instanceName="#"+n.instanceCount++,this.logger=new Vw({id:this.instanceName,enabled:e.logging}),this.cache=(t=e.cache)!==null&&t!==void 0?t:new lw(this,e)}return n.instanceCount=1,n}(),jw=function(n,e){return e===void 0&&(e={}),Jw(n,e)};typeof window<"u"&&$d.setContext(window);var Jw=function(n,e){return Ee(void 0,void 0,void 0,function(){var A,t,i,r,s,o,a,c,l,u,d,h,f,g,m,C,y,U,v,B,S,w,S,F,R,D,H,N,K,ae,hA,De,_e,bt,fA,tt,Ut,Qt,EA,Et;return Ue(this,function(SA){switch(SA.label){case 0:if(!n||typeof n!="object")return[2,Promise.reject("Invalid element provided as first argument")];if(A=n.ownerDocument,!A)throw new Error("Element is not attached to a Document");if(t=A.defaultView,!t)throw new Error("Document is not attached to a Window");return i={allowTaint:(F=e.allowTaint)!==null&&F!==void 0?F:!1,imageTimeout:(R=e.imageTimeout)!==null&&R!==void 0?R:15e3,proxy:e.proxy,useCORS:(D=e.useCORS)!==null&&D!==void 0?D:!1},r=ro({logging:(H=e.logging)!==null&&H!==void 0?H:!0,cache:e.cache},i),s={windowWidth:(N=e.windowWidth)!==null&&N!==void 0?N:t.innerWidth,windowHeight:(K=e.windowHeight)!==null&&K!==void 0?K:t.innerHeight,scrollX:(ae=e.scrollX)!==null&&ae!==void 0?ae:t.pageXOffset,scrollY:(hA=e.scrollY)!==null&&hA!==void 0?hA:t.pageYOffset},o=new CA(s.scrollX,s.scrollY,s.windowWidth,s.windowHeight),a=new Gw(r,o),c=(De=e.foreignObjectRendering)!==null&&De!==void 0?De:!1,l={allowTaint:(_e=e.allowTaint)!==null&&_e!==void 0?_e:!1,onclone:e.onclone,ignoreElements:e.ignoreElements,inlineImages:c,copyStyles:c},a.logger.debug("Starting document clone with size "+o.width+"x"+o.height+" scrolled to "+-o.left+","+-o.top),u=new Wd(a,n,l),d=u.clonedReferenceElement,d?[4,u.toIFrame(A,o)]:[2,Promise.reject("Unable to find element in cloned iframe")];case 1:return h=SA.sent(),f=Jo(d)||W0(d)?bm(d.ownerDocument):Di(a,d),g=f.width,m=f.height,C=f.left,y=f.top,U=Ww(a,d,e.backgroundColor),v={canvas:e.canvas,backgroundColor:U,scale:(fA=(bt=e.scale)!==null&&bt!==void 0?bt:t.devicePixelRatio)!==null&&fA!==void 0?fA:1,x:((tt=e.x)!==null&&tt!==void 0?tt:0)+C,y:((Ut=e.y)!==null&&Ut!==void 0?Ut:0)+y,width:(Qt=e.width)!==null&&Qt!==void 0?Qt:Math.ceil(g),height:(EA=e.height)!==null&&EA!==void 0?EA:Math.ceil(m)},c?(a.logger.debug("Document cloned, using foreign object rendering"),S=new Nw(a,v),[4,S.render(d)]):[3,3];case 2:return B=SA.sent(),[3,5];case 3:return a.logger.debug("Document cloned, element located at "+C+","+y+" with size "+g+"x"+m+" using computed rendering"),a.logger.debug("Starting DOM parsing"),w=Id(a,d),U===w.styles.backgroundColor&&(w.styles.backgroundColor=yA.TRANSPARENT),a.logger.debug("Starting renderer for element at "+v.x+","+v.y+" with size "+v.width+"x"+v.height),S=new Lw(a,v),[4,S.render(w)];case 4:B=SA.sent(),SA.label=5;case 5:return(!((Et=e.removeContainer)!==null&&Et!==void 0)||Et)&&(Wd.destroy(h)||a.logger.error("Cannot detach cloned iframe as it is not in the DOM anymore")),a.logger.debug("Finished rendering"),[2,B]}})})},Ww=function(n,e,A){var t=e.ownerDocument,i=t.documentElement?Pn(n,getComputedStyle(t.documentElement).backgroundColor):yA.TRANSPARENT,r=t.body?Pn(n,getComputedStyle(t.body).backgroundColor):yA.TRANSPARENT,s=typeof A=="string"?Pn(n,A):A===null?yA.TRANSPARENT:4294967295;return e===t.documentElement?$A(i)?$A(r)?s:r:i:s};/**
2
60
  * @license
3
61
  * Copyright 2019 Google LLC
4
62
  * SPDX-License-Identifier: BSD-3-Clause
5
- */const ln=globalThis,us=ln.ShadowRoot&&(ln.ShadyCSS===void 0||ln.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,Zr=Symbol(),Jr=new WeakMap;let Td=class{constructor(e,t,i){if(this._$cssResult$=!0,i!==Zr)throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=e,this.t=t}get styleSheet(){let e=this.o;const t=this.t;if(us&&e===void 0){const i=t!==void 0&&t.length===1;i&&(e=Jr.get(t)),e===void 0&&((this.o=e=new CSSStyleSheet).replaceSync(this.cssText),i&&Jr.set(t,e))}return e}toString(){return this.cssText}};const Sd=n=>new Td(typeof n=="string"?n:n+"",void 0,Zr),Cd=(n,e)=>{if(us)n.adoptedStyleSheets=e.map(t=>t instanceof CSSStyleSheet?t:t.styleSheet);else for(const t of e){const i=document.createElement("style"),s=ln.litNonce;s!==void 0&&i.setAttribute("nonce",s),i.textContent=t.cssText,n.appendChild(i)}},Yr=us?n=>n:n=>n instanceof CSSStyleSheet?(e=>{let t="";for(const i of e.cssRules)t+=i.cssText;return Sd(t)})(n):n;/**
63
+ */const Tr=globalThis,ta=Tr.ShadowRoot&&(Tr.ShadyCSS===void 0||Tr.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,rh=Symbol(),sh=new WeakMap;let Xw=class{constructor(e,A,t){if(this._$cssResult$=!0,t!==rh)throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=e,this.t=A}get styleSheet(){let e=this.o;const A=this.t;if(ta&&e===void 0){const t=A!==void 0&&A.length===1;t&&(e=sh.get(A)),e===void 0&&((this.o=e=new CSSStyleSheet).replaceSync(this.cssText),t&&sh.set(A,e))}return e}toString(){return this.cssText}};const $w=n=>new Xw(typeof n=="string"?n:n+"",void 0,rh),Yw=(n,e)=>{if(ta)n.adoptedStyleSheets=e.map(A=>A instanceof CSSStyleSheet?A:A.styleSheet);else for(const A of e){const t=document.createElement("style"),i=Tr.litNonce;i!==void 0&&t.setAttribute("nonce",i),t.textContent=A.cssText,n.appendChild(t)}},oh=ta?n=>n:n=>n instanceof CSSStyleSheet?(e=>{let A="";for(const t of e.cssRules)A+=t.cssText;return $w(A)})(n):n;/**
6
64
  * @license
7
65
  * Copyright 2017 Google LLC
8
66
  * SPDX-License-Identifier: BSD-3-Clause
9
- */const{is:_d,defineProperty:Ed,getOwnPropertyDescriptor:wd,getOwnPropertyNames:Pd,getOwnPropertySymbols:Rd,getPrototypeOf:xd}=Object,ht=globalThis,Qr=ht.trustedTypes,Id=Qr?Qr.emptyScript:"",hs=ht.reactiveElementPolyfillSupport,Ci=(n,e)=>n,un={toAttribute(n,e){switch(e){case Boolean:n=n?Id:null;break;case Object:case Array:n=n==null?n:JSON.stringify(n)}return n},fromAttribute(n,e){let t=n;switch(e){case Boolean:t=n!==null;break;case Number:t=n===null?null:Number(n);break;case Object:case Array:try{t=JSON.parse(n)}catch{t=null}}return t}},fs=(n,e)=>!_d(n,e),Xr={attribute:!0,type:String,converter:un,reflect:!1,useDefault:!1,hasChanged:fs};Symbol.metadata??(Symbol.metadata=Symbol("metadata")),ht.litPropertyMetadata??(ht.litPropertyMetadata=new WeakMap);let _i=class extends HTMLElement{static addInitializer(e){this._$Ei(),(this.l??(this.l=[])).push(e)}static get observedAttributes(){return this.finalize(),this._$Eh&&[...this._$Eh.keys()]}static createProperty(e,t=Xr){if(t.state&&(t.attribute=!1),this._$Ei(),this.prototype.hasOwnProperty(e)&&((t=Object.create(t)).wrapped=!0),this.elementProperties.set(e,t),!t.noAccessor){const i=Symbol(),s=this.getPropertyDescriptor(e,i,t);s!==void 0&&Ed(this.prototype,e,s)}}static getPropertyDescriptor(e,t,i){const{get:s,set:r}=wd(this.prototype,e)??{get(){return this[t]},set(a){this[t]=a}};return{get:s,set(a){const o=s==null?void 0:s.call(this);r==null||r.call(this,a),this.requestUpdate(e,o,i)},configurable:!0,enumerable:!0}}static getPropertyOptions(e){return this.elementProperties.get(e)??Xr}static _$Ei(){if(this.hasOwnProperty(Ci("elementProperties")))return;const e=xd(this);e.finalize(),e.l!==void 0&&(this.l=[...e.l]),this.elementProperties=new Map(e.elementProperties)}static finalize(){if(this.hasOwnProperty(Ci("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(Ci("properties"))){const t=this.properties,i=[...Pd(t),...Rd(t)];for(const s of i)this.createProperty(s,t[s])}const e=this[Symbol.metadata];if(e!==null){const t=litPropertyMetadata.get(e);if(t!==void 0)for(const[i,s]of t)this.elementProperties.set(i,s)}this._$Eh=new Map;for(const[t,i]of this.elementProperties){const s=this._$Eu(t,i);s!==void 0&&this._$Eh.set(s,t)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(e){const t=[];if(Array.isArray(e)){const i=new Set(e.flat(1/0).reverse());for(const s of i)t.unshift(Yr(s))}else e!==void 0&&t.push(Yr(e));return t}static _$Eu(e,t){const i=t.attribute;return i===!1?void 0:typeof i=="string"?i:typeof e=="string"?e.toLowerCase():void 0}constructor(){super(),this._$Ep=void 0,this.isUpdatePending=!1,this.hasUpdated=!1,this._$Em=null,this._$Ev()}_$Ev(){var e;this._$ES=new Promise(t=>this.enableUpdating=t),this._$AL=new Map,this._$E_(),this.requestUpdate(),(e=this.constructor.l)==null||e.forEach(t=>t(this))}addController(e){var t;(this._$EO??(this._$EO=new Set)).add(e),this.renderRoot!==void 0&&this.isConnected&&((t=e.hostConnected)==null||t.call(e))}removeController(e){var t;(t=this._$EO)==null||t.delete(e)}_$E_(){const e=new Map,t=this.constructor.elementProperties;for(const i of t.keys())this.hasOwnProperty(i)&&(e.set(i,this[i]),delete this[i]);e.size>0&&(this._$Ep=e)}createRenderRoot(){const e=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return Cd(e,this.constructor.elementStyles),e}connectedCallback(){var e;this.renderRoot??(this.renderRoot=this.createRenderRoot()),this.enableUpdating(!0),(e=this._$EO)==null||e.forEach(t=>{var i;return(i=t.hostConnected)==null?void 0:i.call(t)})}enableUpdating(e){}disconnectedCallback(){var e;(e=this._$EO)==null||e.forEach(t=>{var i;return(i=t.hostDisconnected)==null?void 0:i.call(t)})}attributeChangedCallback(e,t,i){this._$AK(e,i)}_$ET(e,t){var r;const i=this.constructor.elementProperties.get(e),s=this.constructor._$Eu(e,i);if(s!==void 0&&i.reflect===!0){const a=(((r=i.converter)==null?void 0:r.toAttribute)!==void 0?i.converter:un).toAttribute(t,i.type);this._$Em=e,a==null?this.removeAttribute(s):this.setAttribute(s,a),this._$Em=null}}_$AK(e,t){var r,a;const i=this.constructor,s=i._$Eh.get(e);if(s!==void 0&&this._$Em!==s){const o=i.getPropertyOptions(s),c=typeof o.converter=="function"?{fromAttribute:o.converter}:((r=o.converter)==null?void 0:r.fromAttribute)!==void 0?o.converter:un;this._$Em=s,this[s]=c.fromAttribute(t,o.type)??((a=this._$Ej)==null?void 0:a.get(s))??null,this._$Em=null}}requestUpdate(e,t,i){var s;if(e!==void 0){const r=this.constructor,a=this[e];if(i??(i=r.getPropertyOptions(e)),!((i.hasChanged??fs)(a,t)||i.useDefault&&i.reflect&&a===((s=this._$Ej)==null?void 0:s.get(e))&&!this.hasAttribute(r._$Eu(e,i))))return;this.C(e,t,i)}this.isUpdatePending===!1&&(this._$ES=this._$EP())}C(e,t,{useDefault:i,reflect:s,wrapped:r},a){i&&!(this._$Ej??(this._$Ej=new Map)).has(e)&&(this._$Ej.set(e,a??t??this[e]),r!==!0||a!==void 0)||(this._$AL.has(e)||(this.hasUpdated||i||(t=void 0),this._$AL.set(e,t)),s===!0&&this._$Em!==e&&(this._$Eq??(this._$Eq=new Set)).add(e))}async _$EP(){this.isUpdatePending=!0;try{await this._$ES}catch(t){Promise.reject(t)}const e=this.scheduleUpdate();return e!=null&&await e,!this.isUpdatePending}scheduleUpdate(){return this.performUpdate()}performUpdate(){var i;if(!this.isUpdatePending)return;if(!this.hasUpdated){if(this.renderRoot??(this.renderRoot=this.createRenderRoot()),this._$Ep){for(const[r,a]of this._$Ep)this[r]=a;this._$Ep=void 0}const s=this.constructor.elementProperties;if(s.size>0)for(const[r,a]of s){const{wrapped:o}=a,c=this[r];o!==!0||this._$AL.has(r)||c===void 0||this.C(r,void 0,a,c)}}let e=!1;const t=this._$AL;try{e=this.shouldUpdate(t),e?(this.willUpdate(t),(i=this._$EO)==null||i.forEach(s=>{var r;return(r=s.hostUpdate)==null?void 0:r.call(s)}),this.update(t)):this._$EM()}catch(s){throw e=!1,this._$EM(),s}e&&this._$AE(t)}willUpdate(e){}_$AE(e){var t;(t=this._$EO)==null||t.forEach(i=>{var s;return(s=i.hostUpdated)==null?void 0:s.call(i)}),this.hasUpdated||(this.hasUpdated=!0,this.firstUpdated(e)),this.updated(e)}_$EM(){this._$AL=new Map,this.isUpdatePending=!1}get updateComplete(){return this.getUpdateComplete()}getUpdateComplete(){return this._$ES}shouldUpdate(e){return!0}update(e){this._$Eq&&(this._$Eq=this._$Eq.forEach(t=>this._$ET(t,this[t]))),this._$EM()}updated(e){}firstUpdated(e){}};_i.elementStyles=[],_i.shadowRootOptions={mode:"open"},_i[Ci("elementProperties")]=new Map,_i[Ci("finalized")]=new Map,hs==null||hs({ReactiveElement:_i}),(ht.reactiveElementVersions??(ht.reactiveElementVersions=[])).push("2.1.0");/**
67
+ */const{is:qw,defineProperty:Zw,getOwnPropertyDescriptor:zw,getOwnPropertyNames:ey,getOwnPropertySymbols:Ay,getPrototypeOf:ty}=Object,zA=globalThis,ah=zA.trustedTypes,ny=ah?ah.emptyScript:"",na=zA.reactiveElementPolyfillSupport,Nn=(n,e)=>n,Fr={toAttribute(n,e){switch(e){case Boolean:n=n?ny:null;break;case Object:case Array:n=n==null?n:JSON.stringify(n)}return n},fromAttribute(n,e){let A=n;switch(e){case Boolean:A=n!==null;break;case Number:A=n===null?null:Number(n);break;case Object:case Array:try{A=JSON.parse(n)}catch{A=null}}return A}},ia=(n,e)=>!qw(n,e),ch={attribute:!0,type:String,converter:Fr,reflect:!1,useDefault:!1,hasChanged:ia};Symbol.metadata??(Symbol.metadata=Symbol("metadata")),zA.litPropertyMetadata??(zA.litPropertyMetadata=new WeakMap);class Kn extends HTMLElement{static addInitializer(e){this._$Ei(),(this.l??(this.l=[])).push(e)}static get observedAttributes(){return this.finalize(),this._$Eh&&[...this._$Eh.keys()]}static createProperty(e,A=ch){if(A.state&&(A.attribute=!1),this._$Ei(),this.prototype.hasOwnProperty(e)&&((A=Object.create(A)).wrapped=!0),this.elementProperties.set(e,A),!A.noAccessor){const t=Symbol(),i=this.getPropertyDescriptor(e,t,A);i!==void 0&&Zw(this.prototype,e,i)}}static getPropertyDescriptor(e,A,t){const{get:i,set:r}=zw(this.prototype,e)??{get(){return this[A]},set(s){this[A]=s}};return{get:i,set(s){const o=i==null?void 0:i.call(this);r==null||r.call(this,s),this.requestUpdate(e,o,t)},configurable:!0,enumerable:!0}}static getPropertyOptions(e){return this.elementProperties.get(e)??ch}static _$Ei(){if(this.hasOwnProperty(Nn("elementProperties")))return;const e=ty(this);e.finalize(),e.l!==void 0&&(this.l=[...e.l]),this.elementProperties=new Map(e.elementProperties)}static finalize(){if(this.hasOwnProperty(Nn("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(Nn("properties"))){const A=this.properties,t=[...ey(A),...Ay(A)];for(const i of t)this.createProperty(i,A[i])}const e=this[Symbol.metadata];if(e!==null){const A=litPropertyMetadata.get(e);if(A!==void 0)for(const[t,i]of A)this.elementProperties.set(t,i)}this._$Eh=new Map;for(const[A,t]of this.elementProperties){const i=this._$Eu(A,t);i!==void 0&&this._$Eh.set(i,A)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(e){const A=[];if(Array.isArray(e)){const t=new Set(e.flat(1/0).reverse());for(const i of t)A.unshift(oh(i))}else e!==void 0&&A.push(oh(e));return A}static _$Eu(e,A){const t=A.attribute;return t===!1?void 0:typeof t=="string"?t:typeof e=="string"?e.toLowerCase():void 0}constructor(){super(),this._$Ep=void 0,this.isUpdatePending=!1,this.hasUpdated=!1,this._$Em=null,this._$Ev()}_$Ev(){var e;this._$ES=new Promise(A=>this.enableUpdating=A),this._$AL=new Map,this._$E_(),this.requestUpdate(),(e=this.constructor.l)==null||e.forEach(A=>A(this))}addController(e){var A;(this._$EO??(this._$EO=new Set)).add(e),this.renderRoot!==void 0&&this.isConnected&&((A=e.hostConnected)==null||A.call(e))}removeController(e){var A;(A=this._$EO)==null||A.delete(e)}_$E_(){const e=new Map,A=this.constructor.elementProperties;for(const t of A.keys())this.hasOwnProperty(t)&&(e.set(t,this[t]),delete this[t]);e.size>0&&(this._$Ep=e)}createRenderRoot(){const e=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return Yw(e,this.constructor.elementStyles),e}connectedCallback(){var e;this.renderRoot??(this.renderRoot=this.createRenderRoot()),this.enableUpdating(!0),(e=this._$EO)==null||e.forEach(A=>{var t;return(t=A.hostConnected)==null?void 0:t.call(A)})}enableUpdating(e){}disconnectedCallback(){var e;(e=this._$EO)==null||e.forEach(A=>{var t;return(t=A.hostDisconnected)==null?void 0:t.call(A)})}attributeChangedCallback(e,A,t){this._$AK(e,t)}_$ET(e,A){var r;const t=this.constructor.elementProperties.get(e),i=this.constructor._$Eu(e,t);if(i!==void 0&&t.reflect===!0){const s=(((r=t.converter)==null?void 0:r.toAttribute)!==void 0?t.converter:Fr).toAttribute(A,t.type);this._$Em=e,s==null?this.removeAttribute(i):this.setAttribute(i,s),this._$Em=null}}_$AK(e,A){var r,s;const t=this.constructor,i=t._$Eh.get(e);if(i!==void 0&&this._$Em!==i){const o=t.getPropertyOptions(i),a=typeof o.converter=="function"?{fromAttribute:o.converter}:((r=o.converter)==null?void 0:r.fromAttribute)!==void 0?o.converter:Fr;this._$Em=i,this[i]=a.fromAttribute(A,o.type)??((s=this._$Ej)==null?void 0:s.get(i))??null,this._$Em=null}}requestUpdate(e,A,t){var i;if(e!==void 0){const r=this.constructor,s=this[e];if(t??(t=r.getPropertyOptions(e)),!((t.hasChanged??ia)(s,A)||t.useDefault&&t.reflect&&s===((i=this._$Ej)==null?void 0:i.get(e))&&!this.hasAttribute(r._$Eu(e,t))))return;this.C(e,A,t)}this.isUpdatePending===!1&&(this._$ES=this._$EP())}C(e,A,{useDefault:t,reflect:i,wrapped:r},s){t&&!(this._$Ej??(this._$Ej=new Map)).has(e)&&(this._$Ej.set(e,s??A??this[e]),r!==!0||s!==void 0)||(this._$AL.has(e)||(this.hasUpdated||t||(A=void 0),this._$AL.set(e,A)),i===!0&&this._$Em!==e&&(this._$Eq??(this._$Eq=new Set)).add(e))}async _$EP(){this.isUpdatePending=!0;try{await this._$ES}catch(A){Promise.reject(A)}const e=this.scheduleUpdate();return e!=null&&await e,!this.isUpdatePending}scheduleUpdate(){return this.performUpdate()}performUpdate(){var t;if(!this.isUpdatePending)return;if(!this.hasUpdated){if(this.renderRoot??(this.renderRoot=this.createRenderRoot()),this._$Ep){for(const[r,s]of this._$Ep)this[r]=s;this._$Ep=void 0}const i=this.constructor.elementProperties;if(i.size>0)for(const[r,s]of i){const{wrapped:o}=s,a=this[r];o!==!0||this._$AL.has(r)||a===void 0||this.C(r,void 0,s,a)}}let e=!1;const A=this._$AL;try{e=this.shouldUpdate(A),e?(this.willUpdate(A),(t=this._$EO)==null||t.forEach(i=>{var r;return(r=i.hostUpdate)==null?void 0:r.call(i)}),this.update(A)):this._$EM()}catch(i){throw e=!1,this._$EM(),i}e&&this._$AE(A)}willUpdate(e){}_$AE(e){var A;(A=this._$EO)==null||A.forEach(t=>{var i;return(i=t.hostUpdated)==null?void 0:i.call(t)}),this.hasUpdated||(this.hasUpdated=!0,this.firstUpdated(e)),this.updated(e)}_$EM(){this._$AL=new Map,this.isUpdatePending=!1}get updateComplete(){return this.getUpdateComplete()}getUpdateComplete(){return this._$ES}shouldUpdate(e){return!0}update(e){this._$Eq&&(this._$Eq=this._$Eq.forEach(A=>this._$ET(A,this[A]))),this._$EM()}updated(e){}firstUpdated(e){}}Kn.elementStyles=[],Kn.shadowRootOptions={mode:"open"},Kn[Nn("elementProperties")]=new Map,Kn[Nn("finalized")]=new Map,na==null||na({ReactiveElement:Kn}),(zA.reactiveElementVersions??(zA.reactiveElementVersions=[])).push("2.1.0");/**
10
68
  * @license
11
69
  * Copyright 2017 Google LLC
12
70
  * SPDX-License-Identifier: BSD-3-Clause
13
- */const Ad={attribute:!0,type:String,converter:un,reflect:!1,hasChanged:fs},Od=(n=Ad,e,t)=>{const{kind:i,metadata:s}=t;let r=globalThis.litPropertyMetadata.get(s);if(r===void 0&&globalThis.litPropertyMetadata.set(s,r=new Map),i==="setter"&&((n=Object.create(n)).wrapped=!0),r.set(t.name,n),i==="accessor"){const{name:a}=t;return{set(o){const c=e.get.call(this);e.set.call(this,o),this.requestUpdate(a,c,n)},init(o){return o!==void 0&&this.C(a,void 0,n,o),o}}}if(i==="setter"){const{name:a}=t;return function(o){const c=this[a];e.call(this,o),this.requestUpdate(a,c,n)}}throw Error("Unsupported decorator location: "+i)};function ee(n){return(e,t)=>typeof t=="object"?Od(n,e,t):((i,s,r)=>{const a=s.hasOwnProperty(r);return s.constructor.createProperty(r,i),a?Object.getOwnPropertyDescriptor(s,r):void 0})(n,e,t)}/**
71
+ */const iy={attribute:!0,type:String,converter:Fr,reflect:!1,hasChanged:ia},ry=(n=iy,e,A)=>{const{kind:t,metadata:i}=A;let r=globalThis.litPropertyMetadata.get(i);if(r===void 0&&globalThis.litPropertyMetadata.set(i,r=new Map),t==="setter"&&((n=Object.create(n)).wrapped=!0),r.set(A.name,n),t==="accessor"){const{name:s}=A;return{set(o){const a=e.get.call(this);e.set.call(this,o),this.requestUpdate(s,a,n)},init(o){return o!==void 0&&this.C(s,void 0,n,o),o}}}if(t==="setter"){const{name:s}=A;return function(o){const a=this[s];e.call(this,o),this.requestUpdate(s,a,n)}}throw Error("Unsupported decorator location: "+t)};function z(n){return(e,A)=>typeof A=="object"?ry(n,e,A):((t,i,r)=>{const s=i.hasOwnProperty(r);return i.constructor.createProperty(r,t),s?Object.getOwnPropertyDescriptor(i,r):void 0})(n,e,A)}/**
14
72
  * @license
15
73
  * Copyright 2017 Google LLC
16
74
  * SPDX-License-Identifier: BSD-3-Clause
17
- */function Te(n){return ee({...n,state:!0,attribute:!1})}const Se=Symbol.for("@ts-pattern/matcher"),ea=Symbol.for("@ts-pattern/isVariadic"),hn="@ts-pattern/anonymous-select-key",ps=n=>!!(n&&typeof n=="object"),fn=n=>n&&!!n[Se],me=(n,e,t)=>{if(fn(n)){const i=n[Se](),{matched:s,selections:r}=i.match(e);return s&&r&&Object.keys(r).forEach(a=>t(a,r[a])),s}if(ps(n)){if(!ps(e))return!1;if(Array.isArray(n)){if(!Array.isArray(e))return!1;let i=[],s=[],r=[];for(const a of n.keys()){const o=n[a];fn(o)&&o[ea]?r.push(o):r.length?s.push(o):i.push(o)}if(r.length){if(r.length>1)throw new Error("Pattern error: Using `...P.array(...)` several times in a single pattern is not allowed.");if(e.length<i.length+s.length)return!1;const a=e.slice(0,i.length),o=s.length===0?[]:e.slice(-s.length),c=e.slice(i.length,s.length===0?1/0:-s.length);return i.every((d,l)=>me(d,a[l],t))&&s.every((d,l)=>me(d,o[l],t))&&(r.length===0||me(r[0],c,t))}return n.length===e.length&&n.every((a,o)=>me(a,e[o],t))}return Reflect.ownKeys(n).every(i=>{const s=n[i];return(i in e||fn(r=s)&&r[Se]().matcherType==="optional")&&me(s,e[i],t);var r})}return Object.is(e,n)},Re=n=>{var e,t,i;return ps(n)?fn(n)?(e=(t=(i=n[Se]()).getSelectionKeys)==null?void 0:t.call(i))!=null?e:[]:Array.isArray(n)?Ei(n,Re):Ei(Object.values(n),Re):[]},Ei=(n,e)=>n.reduce((t,i)=>t.concat(e(i)),[]);function Dd(...n){if(n.length===1){const[e]=n;return t=>me(e,t,()=>{})}if(n.length===2){const[e,t]=n;return me(e,t,()=>{})}throw new Error(`isMatching wasn't given the right number of arguments: expected 1 or 2, received ${n.length}.`)}function ge(n){return Object.assign(n,{optional:()=>gs(n),and:e=>ie(n,e),or:e=>ta(n,e),select:e=>e===void 0?wi(n):wi(e,n)})}function ms(n){return Object.assign((e=>Object.assign(e,{[Symbol.iterator](){let t=0;const i=[{value:Object.assign(e,{[ea]:!0}),done:!1},{done:!0,value:void 0}];return{next:()=>{var s;return(s=i[t++])!=null?s:i.at(-1)}}}}))(n),{optional:()=>ms(gs(n)),select:e=>ms(e===void 0?wi(n):wi(e,n))})}function gs(n){return ge({[Se]:()=>({match:e=>{let t={};const i=(s,r)=>{t[s]=r};return e===void 0?(Re(n).forEach(s=>i(s,void 0)),{matched:!0,selections:t}):{matched:me(n,e,i),selections:t}},getSelectionKeys:()=>Re(n),matcherType:"optional"})})}const Md=(n,e)=>{for(const t of n)if(!e(t))return!1;return!0},Nd=(n,e)=>{for(const[t,i]of n.entries())if(!e(i,t))return!1;return!0};function ie(...n){return ge({[Se]:()=>({match:e=>{let t={};const i=(s,r)=>{t[s]=r};return{matched:n.every(s=>me(s,e,i)),selections:t}},getSelectionKeys:()=>Ei(n,Re),matcherType:"and"})})}function ta(...n){return ge({[Se]:()=>({match:e=>{let t={};const i=(s,r)=>{t[s]=r};return Ei(n,Re).forEach(s=>i(s,void 0)),{matched:n.some(s=>me(s,e,i)),selections:t}},getSelectionKeys:()=>Ei(n,Re),matcherType:"or"})})}function K(n){return{[Se]:()=>({match:e=>({matched:!!n(e)})})}}function wi(...n){const e=typeof n[0]=="string"?n[0]:void 0,t=n.length===2?n[1]:typeof n[0]=="string"?void 0:n[0];return ge({[Se]:()=>({match:i=>{let s={[e??hn]:i};return{matched:t===void 0||me(t,i,(r,a)=>{s[r]=a}),selections:s}},getSelectionKeys:()=>[e??hn].concat(t===void 0?[]:Re(t))})})}function ze(n){return typeof n=="number"}function ft(n){return typeof n=="string"}function pt(n){return typeof n=="bigint"}const ia=ge(K(function(n){return!0})),Ld=ia,mt=n=>Object.assign(ge(n),{startsWith:e=>{return mt(ie(n,(t=e,K(i=>ft(i)&&i.startsWith(t)))));var t},endsWith:e=>{return mt(ie(n,(t=e,K(i=>ft(i)&&i.endsWith(t)))));var t},minLength:e=>mt(ie(n,(t=>K(i=>ft(i)&&i.length>=t))(e))),length:e=>mt(ie(n,(t=>K(i=>ft(i)&&i.length===t))(e))),maxLength:e=>mt(ie(n,(t=>K(i=>ft(i)&&i.length<=t))(e))),includes:e=>{return mt(ie(n,(t=e,K(i=>ft(i)&&i.includes(t)))));var t},regex:e=>{return mt(ie(n,(t=e,K(i=>ft(i)&&!!i.match(t)))));var t}}),Ud=mt(K(ft)),Ge=n=>Object.assign(ge(n),{between:(e,t)=>Ge(ie(n,((i,s)=>K(r=>ze(r)&&i<=r&&s>=r))(e,t))),lt:e=>Ge(ie(n,(t=>K(i=>ze(i)&&i<t))(e))),gt:e=>Ge(ie(n,(t=>K(i=>ze(i)&&i>t))(e))),lte:e=>Ge(ie(n,(t=>K(i=>ze(i)&&i<=t))(e))),gte:e=>Ge(ie(n,(t=>K(i=>ze(i)&&i>=t))(e))),int:()=>Ge(ie(n,K(e=>ze(e)&&Number.isInteger(e)))),finite:()=>Ge(ie(n,K(e=>ze(e)&&Number.isFinite(e)))),positive:()=>Ge(ie(n,K(e=>ze(e)&&e>0))),negative:()=>Ge(ie(n,K(e=>ze(e)&&e<0)))}),Fd=Ge(K(ze)),gt=n=>Object.assign(ge(n),{between:(e,t)=>gt(ie(n,((i,s)=>K(r=>pt(r)&&i<=r&&s>=r))(e,t))),lt:e=>gt(ie(n,(t=>K(i=>pt(i)&&i<t))(e))),gt:e=>gt(ie(n,(t=>K(i=>pt(i)&&i>t))(e))),lte:e=>gt(ie(n,(t=>K(i=>pt(i)&&i<=t))(e))),gte:e=>gt(ie(n,(t=>K(i=>pt(i)&&i>=t))(e))),positive:()=>gt(ie(n,K(e=>pt(e)&&e>0))),negative:()=>gt(ie(n,K(e=>pt(e)&&e<0)))}),jd=gt(K(pt)),$d=ge(K(function(n){return typeof n=="boolean"})),Bd=ge(K(function(n){return typeof n=="symbol"})),Vd=ge(K(function(n){return n==null})),qd=ge(K(function(n){return n!=null}));var zd={__proto__:null,matcher:Se,optional:gs,array:function(...n){return ms({[Se]:()=>({match:e=>{if(!Array.isArray(e))return{matched:!1};if(n.length===0)return{matched:!0};const t=n[0];let i={};if(e.length===0)return Re(t).forEach(r=>{i[r]=[]}),{matched:!0,selections:i};const s=(r,a)=>{i[r]=(i[r]||[]).concat([a])};return{matched:e.every(r=>me(t,r,s)),selections:i}},getSelectionKeys:()=>n.length===0?[]:Re(n[0])})})},set:function(...n){return ge({[Se]:()=>({match:e=>{if(!(e instanceof Set))return{matched:!1};let t={};if(e.size===0)return{matched:!0,selections:t};if(n.length===0)return{matched:!0};const i=(r,a)=>{t[r]=(t[r]||[]).concat([a])},s=n[0];return{matched:Md(e,r=>me(s,r,i)),selections:t}},getSelectionKeys:()=>n.length===0?[]:Re(n[0])})})},map:function(...n){return ge({[Se]:()=>({match:e=>{if(!(e instanceof Map))return{matched:!1};let t={};if(e.size===0)return{matched:!0,selections:t};const i=(o,c)=>{t[o]=(t[o]||[]).concat([c])};if(n.length===0)return{matched:!0};var s;if(n.length===1)throw new Error(`\`P.map\` wasn't given enough arguments. Expected (key, value), received ${(s=n[0])==null?void 0:s.toString()}`);const[r,a]=n;return{matched:Nd(e,(o,c)=>{const d=me(r,c,i),l=me(a,o,i);return d&&l}),selections:t}},getSelectionKeys:()=>n.length===0?[]:[...Re(n[0]),...Re(n[1])]})})},intersection:ie,union:ta,not:function(n){return ge({[Se]:()=>({match:e=>({matched:!me(n,e,()=>{})}),getSelectionKeys:()=>[],matcherType:"not"})})},when:K,select:wi,any:ia,_:Ld,string:Ud,number:Fd,bigint:jd,boolean:$d,symbol:Bd,nullish:Vd,nonNullable:qd,instanceOf:function(n){return ge(K(function(e){return t=>t instanceof e}(n)))},shape:function(n){return ge(K(Dd(n)))}};class Gd extends Error{constructor(e){let t;try{t=JSON.stringify(e)}catch{t=e}super(`Pattern matching error: no pattern matches value ${t}`),this.input=void 0,this.input=e}}const vs={matched:!1,value:void 0};function pn(n){return new Wd(n,vs)}let Wd=class Hr{constructor(e,t){this.input=void 0,this.state=void 0,this.input=e,this.state=t}with(...e){if(this.state.matched)return this;const t=e[e.length-1],i=[e[0]];let s;e.length===3&&typeof e[1]=="function"?s=e[1]:e.length>2&&i.push(...e.slice(1,e.length-1));let r=!1,a={};const o=(d,l)=>{r=!0,a[d]=l},c=!i.some(d=>me(d,this.input,o))||s&&!s(this.input)?vs:{matched:!0,value:t(r?hn in a?a[hn]:a:this.input,this.input)};return new Hr(this.input,c)}when(e,t){if(this.state.matched)return this;const i=!!e(this.input);return new Hr(this.input,i?{matched:!0,value:t(this.input,this.input)}:vs)}otherwise(e){return this.state.matched?this.state.value:e(this.input)}exhaustive(e=Kd){return this.state.matched?this.state.value:e(this.input)}run(){return this.exhaustive()}returnType(){return this}};function Kd(n){throw new Gd(n)}var na={exports:{}};(function(n){var e=Object.prototype.hasOwnProperty,t="~";function i(){}Object.create&&(i.prototype=Object.create(null),new i().__proto__||(t=!1));function s(c,d,l){this.fn=c,this.context=d,this.once=l||!1}function r(c,d,l,u,h){if(typeof l!="function")throw new TypeError("The listener must be a function");var f=new s(l,u||c,h),g=t?t+d:d;return c._events[g]?c._events[g].fn?c._events[g]=[c._events[g],f]:c._events[g].push(f):(c._events[g]=f,c._eventsCount++),c}function a(c,d){--c._eventsCount===0?c._events=new i:delete c._events[d]}function o(){this._events=new i,this._eventsCount=0}o.prototype.eventNames=function(){var d=[],l,u;if(this._eventsCount===0)return d;for(u in l=this._events)e.call(l,u)&&d.push(t?u.slice(1):u);return Object.getOwnPropertySymbols?d.concat(Object.getOwnPropertySymbols(l)):d},o.prototype.listeners=function(d){var l=t?t+d:d,u=this._events[l];if(!u)return[];if(u.fn)return[u.fn];for(var h=0,f=u.length,g=new Array(f);h<f;h++)g[h]=u[h].fn;return g},o.prototype.listenerCount=function(d){var l=t?t+d:d,u=this._events[l];return u?u.fn?1:u.length:0},o.prototype.emit=function(d,l,u,h,f,g){var m=t?t+d:d;if(!this._events[m])return!1;var v=this._events[m],T=arguments.length,x,P;if(v.fn){switch(v.once&&this.removeListener(d,v.fn,void 0,!0),T){case 1:return v.fn.call(v.context),!0;case 2:return v.fn.call(v.context,l),!0;case 3:return v.fn.call(v.context,l,u),!0;case 4:return v.fn.call(v.context,l,u,h),!0;case 5:return v.fn.call(v.context,l,u,h,f),!0;case 6:return v.fn.call(v.context,l,u,h,f,g),!0}for(P=1,x=new Array(T-1);P<T;P++)x[P-1]=arguments[P];v.fn.apply(v.context,x)}else{var y=v.length,b;for(P=0;P<y;P++)switch(v[P].once&&this.removeListener(d,v[P].fn,void 0,!0),T){case 1:v[P].fn.call(v[P].context);break;case 2:v[P].fn.call(v[P].context,l);break;case 3:v[P].fn.call(v[P].context,l,u);break;case 4:v[P].fn.call(v[P].context,l,u,h);break;default:if(!x)for(b=1,x=new Array(T-1);b<T;b++)x[b-1]=arguments[b];v[P].fn.apply(v[P].context,x)}}return!0},o.prototype.on=function(d,l,u){return r(this,d,l,u,!1)},o.prototype.once=function(d,l,u){return r(this,d,l,u,!0)},o.prototype.removeListener=function(d,l,u,h){var f=t?t+d:d;if(!this._events[f])return this;if(!l)return a(this,f),this;var g=this._events[f];if(g.fn)g.fn===l&&(!h||g.once)&&(!u||g.context===u)&&a(this,f);else{for(var m=0,v=[],T=g.length;m<T;m++)(g[m].fn!==l||h&&!g[m].once||u&&g[m].context!==u)&&v.push(g[m]);v.length?this._events[f]=v.length===1?v[0]:v:a(this,f)}return this},o.prototype.removeAllListeners=function(d){var l;return d?(l=t?t+d:d,this._events[l]&&a(this,l)):(this._events=new i,this._eventsCount=0),this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prefixed=t,o.EventEmitter=o,n.exports=o})(na);var Hd=na.exports;function Zd(n,e){return e.forEach(function(t){t&&typeof t!="string"&&!Array.isArray(t)&&Object.keys(t).forEach(function(i){if(i!=="default"&&!(i in n)){var s=Object.getOwnPropertyDescriptor(t,i);Object.defineProperty(n,i,s.get?s:{enumerable:!0,get:function(){return t[i]}})}})}),Object.freeze(n)}var Jd=Object.defineProperty,Yd=(n,e,t)=>e in n?Jd(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,sa=(n,e,t)=>Yd(n,typeof e!="symbol"?e+"":e,t);let Ce=class{constructor(){sa(this,"_locking"),sa(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()}),i=this._locking.then(()=>e);return this._locking=this._locking.then(()=>t),i}};function ae(n,e){if(!n)throw new Error(e)}const Qd=34028234663852886e22,Xd=-34028234663852886e22,el=4294967295,tl=2147483647,il=-2147483648;function mn(n){if(typeof n!="number")throw new Error("invalid int 32: "+typeof n);if(!Number.isInteger(n)||n>tl||n<il)throw new Error("invalid int 32: "+n)}function ys(n){if(typeof n!="number")throw new Error("invalid uint 32: "+typeof n);if(!Number.isInteger(n)||n>el||n<0)throw new Error("invalid uint 32: "+n)}function ra(n){if(typeof n!="number")throw new Error("invalid float 32: "+typeof n);if(Number.isFinite(n)&&(n>Qd||n<Xd))throw new Error("invalid float 32: "+n)}const aa=Symbol("@bufbuild/protobuf/enum-type");function nl(n){const e=n[aa];return ae(e,"missing enum type on enum object"),e}function oa(n,e,t,i){n[aa]=ca(e,t.map(s=>({no:s.no,name:s.name,localName:n[s.no]})))}function ca(n,e,t){const i=Object.create(null),s=Object.create(null),r=[];for(const a of e){const o=da(a);r.push(o),i[a.name]=o,s[a.no]=o}return{typeName:n,values:r,findName(a){return i[a]},findNumber(a){return s[a]}}}function sl(n,e,t){const i={};for(const s of e){const r=da(s);i[r.localName]=r.no,i[r.no]=r.localName}return oa(i,n,e),i}function da(n){return"localName"in n?n:Object.assign(Object.assign({},n),{localName:n.name})}class bs{equals(e){return this.getType().runtime.util.equals(this.getType(),this,e)}clone(){return this.getType().runtime.util.clone(this)}fromBinary(e,t){const i=this.getType(),s=i.runtime.bin,r=s.makeReadOptions(t);return s.readMessage(this,r.readerFactory(e),e.byteLength,r),this}fromJson(e,t){const i=this.getType(),s=i.runtime.json,r=s.makeReadOptions(t);return s.readMessage(i,e,r,this),this}fromJsonString(e,t){let i;try{i=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(i,t)}toBinary(e){const t=this.getType(),i=t.runtime.bin,s=i.makeWriteOptions(e),r=s.writerFactory();return i.writeMessage(this,r,s),r.finish()}toJson(e){const t=this.getType(),i=t.runtime.json,s=i.makeWriteOptions(e);return i.writeMessage(this,s)}toJsonString(e){var t;const i=this.toJson(e);return JSON.stringify(i,null,(t=e==null?void 0:e.prettySpaces)!==null&&t!==void 0?t:0)}toJSON(){return this.toJson({emitDefaultValues:!0})}getType(){return Object.getPrototypeOf(this).constructor}}function rl(n,e,t,i){var s;const r=(s=i==null?void 0:i.localName)!==null&&s!==void 0?s:e.substring(e.lastIndexOf(".")+1),a={[r]:function(o){n.util.initFields(this),n.util.initPartial(o,this)}}[r];return Object.setPrototypeOf(a.prototype,new bs),Object.assign(a,{runtime:n,typeName:e,fields:n.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 n.util.equals(a,o,c)}}),a}function al(){let n=0,e=0;for(let i=0;i<28;i+=7){let s=this.buf[this.pos++];if(n|=(s&127)<<i,!(s&128))return this.assertBounds(),[n,e]}let t=this.buf[this.pos++];if(n|=(t&15)<<28,e=(t&112)>>4,!(t&128))return this.assertBounds(),[n,e];for(let i=3;i<=31;i+=7){let s=this.buf[this.pos++];if(e|=(s&127)<<i,!(s&128))return this.assertBounds(),[n,e]}throw new Error("invalid varint")}function ks(n,e,t){for(let r=0;r<28;r=r+7){const a=n>>>r,o=!(!(a>>>7)&&e==0),c=(o?a|128:a)&255;if(t.push(c),!o)return}const i=n>>>28&15|(e&7)<<4,s=!!(e>>3);if(t.push((s?i|128:i)&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 gn=4294967296;function la(n){const e=n[0]==="-";e&&(n=n.slice(1));const t=1e6;let i=0,s=0;function r(a,o){const c=Number(n.slice(a,o));s*=t,i=i*t+c,i>=gn&&(s=s+(i/gn|0),i=i%gn)}return r(-24,-18),r(-18,-12),r(-12,-6),r(-6),e?ha(i,s):Ts(i,s)}function ol(n,e){let t=Ts(n,e);const i=t.hi&2147483648;i&&(t=ha(t.lo,t.hi));const s=ua(t.lo,t.hi);return i?"-"+s:s}function ua(n,e){if({lo:n,hi:e}=cl(n,e),e<=2097151)return String(gn*e+n);const t=n&16777215,i=(n>>>24|e<<8)&16777215,s=e>>16&65535;let r=t+i*6777216+s*6710656,a=i+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()+fa(a)+fa(r)}function cl(n,e){return{lo:n>>>0,hi:e>>>0}}function Ts(n,e){return{lo:n|0,hi:e|0}}function ha(n,e){return e=~e,n?n=~n+1:e+=1,Ts(n,e)}const fa=n=>{const e=String(n);return"0000000".slice(e.length)+e};function pa(n,e){if(n>=0){for(;n>127;)e.push(n&127|128),n=n>>>7;e.push(n)}else{for(let t=0;t<9;t++)e.push(n&127|128),n=n>>7;e.push(1)}}function dl(){let n=this.buf[this.pos++],e=n&127;if(!(n&128))return this.assertBounds(),e;if(n=this.buf[this.pos++],e|=(n&127)<<7,!(n&128))return this.assertBounds(),e;if(n=this.buf[this.pos++],e|=(n&127)<<14,!(n&128))return this.assertBounds(),e;if(n=this.buf[this.pos++],e|=(n&127)<<21,!(n&128))return this.assertBounds(),e;n=this.buf[this.pos++],e|=(n&15)<<28;for(let t=5;n&128&&t<10;t++)n=this.buf[this.pos++];if(n&128)throw new Error("invalid varint");return this.assertBounds(),e>>>0}function ll(){const n=new DataView(new ArrayBuffer(8));if(typeof BigInt=="function"&&typeof n.getBigInt64=="function"&&typeof n.getBigUint64=="function"&&typeof n.setBigInt64=="function"&&typeof n.setBigUint64=="function"&&(typeof process!="object"||typeof 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 d=typeof c=="bigint"?c:BigInt(c);if(d>r||d<s)throw new Error("int64 invalid: ".concat(c));return d},uParse(c){const d=typeof c=="bigint"?c:BigInt(c);if(d>o||d<a)throw new Error("uint64 invalid: ".concat(c));return d},enc(c){return n.setBigInt64(0,this.parse(c),!0),{lo:n.getInt32(0,!0),hi:n.getInt32(4,!0)}},uEnc(c){return n.setBigInt64(0,this.uParse(c),!0),{lo:n.getInt32(0,!0),hi:n.getInt32(4,!0)}},dec(c,d){return n.setInt32(0,c,!0),n.setInt32(4,d,!0),n.getBigInt64(0,!0)},uDec(c,d){return n.setInt32(0,c,!0),n.setInt32(4,d,!0),n.getBigUint64(0,!0)}}}const t=s=>ae(/^-?[0-9]+$/.test(s),"int64 invalid: ".concat(s)),i=s=>ae(/^[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()),i(s),s},enc(s){return typeof s!="string"&&(s=s.toString()),t(s),la(s)},uEnc(s){return typeof s!="string"&&(s=s.toString()),i(s),la(s)},dec(s,r){return ol(s,r)},uDec(s,r){return ua(s,r)}}}const se=ll();var C;(function(n){n[n.DOUBLE=1]="DOUBLE",n[n.FLOAT=2]="FLOAT",n[n.INT64=3]="INT64",n[n.UINT64=4]="UINT64",n[n.INT32=5]="INT32",n[n.FIXED64=6]="FIXED64",n[n.FIXED32=7]="FIXED32",n[n.BOOL=8]="BOOL",n[n.STRING=9]="STRING",n[n.BYTES=12]="BYTES",n[n.UINT32=13]="UINT32",n[n.SFIXED32=15]="SFIXED32",n[n.SFIXED64=16]="SFIXED64",n[n.SINT32=17]="SINT32",n[n.SINT64=18]="SINT64"})(C||(C={}));var vt;(function(n){n[n.BIGINT=0]="BIGINT",n[n.STRING=1]="STRING"})(vt||(vt={}));function yt(n,e,t){if(e===t)return!0;if(n==C.BYTES){if(!(e instanceof Uint8Array)||!(t instanceof Uint8Array)||e.length!==t.length)return!1;for(let i=0;i<e.length;i++)if(e[i]!==t[i])return!1;return!0}switch(n){case C.UINT64:case C.FIXED64:case C.INT64:case C.SFIXED64:case C.SINT64:return e==t}return!1}function Xt(n,e){switch(n){case C.BOOL:return!1;case C.UINT64:case C.FIXED64:case C.INT64:case C.SFIXED64:case C.SINT64:return e==0?se.zero:"0";case C.DOUBLE:case C.FLOAT:return 0;case C.BYTES:return new Uint8Array(0);case C.STRING:return"";default:return 0}}function ma(n,e){switch(n){case C.BOOL:return e===!1;case C.STRING:return e==="";case C.BYTES:return e instanceof Uint8Array&&!e.byteLength;default:return e==0}}var le;(function(n){n[n.Varint=0]="Varint",n[n.Bit64=1]="Bit64",n[n.LengthDelimited=2]="LengthDelimited",n[n.StartGroup=3]="StartGroup",n[n.EndGroup=4]="EndGroup",n[n.Bit32=5]="Bit32"})(le||(le={}));class ul{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),i=0;for(let s=0;s<this.chunks.length;s++)t.set(this.chunks[s],i),i+=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(ys(e);e>127;)this.buf.push(e&127|128),e=e>>>7;return this.buf.push(e),this}int32(e){return mn(e),pa(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){ra(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){ys(e);let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!0),this.raw(t)}sfixed32(e){mn(e);let t=new Uint8Array(4);return new DataView(t.buffer).setInt32(0,e,!0),this.raw(t)}sint32(e){return mn(e),e=(e<<1^e>>31)>>>0,pa(e,this.buf),this}sfixed64(e){let t=new Uint8Array(8),i=new DataView(t.buffer),s=se.enc(e);return i.setInt32(0,s.lo,!0),i.setInt32(4,s.hi,!0),this.raw(t)}fixed64(e){let t=new Uint8Array(8),i=new DataView(t.buffer),s=se.uEnc(e);return i.setInt32(0,s.lo,!0),i.setInt32(4,s.hi,!0),this.raw(t)}int64(e){let t=se.enc(e);return ks(t.lo,t.hi,this.buf),this}sint64(e){let t=se.enc(e),i=t.hi>>31,s=t.lo<<1^i,r=(t.hi<<1|t.lo>>>31)^i;return ks(s,r,this.buf),this}uint64(e){let t=se.uEnc(e);return ks(t.lo,t.hi,this.buf),this}}class hl{constructor(e,t){this.varint64=al,this.uint32=dl,this.buf=e,this.len=e.length,this.pos=0,this.view=new DataView(e.buffer,e.byteOffset,e.byteLength),this.textDecoder=t??new TextDecoder}tag(){let e=this.uint32(),t=e>>>3,i=e&7;if(t<=0||i<0||i>5)throw new Error("illegal tag: field no "+t+" wire type "+i);return[t,i]}skip(e,t){let i=this.pos;switch(e){case le.Varint:for(;this.buf[this.pos++]&128;);break;case le.Bit64:this.pos+=4;case le.Bit32:this.pos+=4;break;case le.LengthDelimited:let s=this.uint32();this.pos+=s;break;case le.StartGroup:for(;;){const[r,a]=this.tag();if(a===le.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(i,this.pos)}assertBounds(){if(this.pos>this.len)throw new RangeError("premature EOF")}int32(){return this.uint32()|0}sint32(){let e=this.uint32();return e>>>1^-(e&1)}int64(){return se.dec(...this.varint64())}uint64(){return se.uDec(...this.varint64())}sint64(){let[e,t]=this.varint64(),i=-(e&1);return e=(e>>>1|(t&1)<<31)^i,t=t>>>1^i,se.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 se.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return se.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 fl(n,e,t,i){let s;return{typeName:e,extendee:t,get field(){if(!s){const r=typeof i=="function"?i():i;r.name=e.split(".").pop(),r.jsonName="[".concat(e,"]"),s=n.util.newFieldList([r]).list()[0]}return s},runtime:n}}function ga(n){const e=n.field.localName,t=Object.create(null);return t[e]=pl(n),[t,()=>t[e]]}function pl(n){const e=n.field;if(e.repeated)return[];if(e.default!==void 0)return e.default;switch(e.kind){case"enum":return e.T.values[0].no;case"scalar":return Xt(e.T,e.L);case"message":const t=e.T,i=new t;return t.fieldWrapper?t.fieldWrapper.unwrapField(i):i;case"map":throw"map fields are not allowed to be extensions"}}function ml(n,e){if(!e.repeated&&(e.kind=="enum"||e.kind=="scalar")){for(let t=n.length-1;t>=0;--t)if(n[t].no==e.no)return[n[t]];return[]}return n.filter(t=>t.no===e.no)}let tt="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),vn=[];for(let n=0;n<tt.length;n++)vn[tt[n].charCodeAt(0)]=n;vn["-".charCodeAt(0)]=tt.indexOf("+"),vn["_".charCodeAt(0)]=tt.indexOf("/");const va={dec(n){let e=n.length*3/4;n[n.length-2]=="="?e-=2:n[n.length-1]=="="&&(e-=1);let t=new Uint8Array(e),i=0,s=0,r,a=0;for(let o=0;o<n.length;o++){if(r=vn[n.charCodeAt(o)],r===void 0)switch(n[o]){case"=":s=0;case`
18
- `:case"\r":case" ":case" ":continue;default:throw Error("invalid base64 string.")}switch(s){case 0:a=r,s=1;break;case 1:t[i++]=a<<2|(r&48)>>4,a=r,s=2;break;case 2:t[i++]=(a&15)<<4|(r&60)>>2,a=r,s=3;break;case 3:t[i++]=(a&3)<<6|r,s=0;break}}if(s==1)throw Error("invalid base64 string.");return t.subarray(0,i)},enc(n){let e="",t=0,i,s=0;for(let r=0;r<n.length;r++)switch(i=n[r],t){case 0:e+=tt[i>>2],s=(i&3)<<4,t=1;break;case 1:e+=tt[s|i>>4],s=(i&15)<<2,t=2;break;case 2:e+=tt[s|i>>6],e+=tt[i&63],t=0;break}return t&&(e+=tt[s],e+="=",t==1&&(e+="=")),e}};function gl(n,e,t){ba(e,n);const i=e.runtime.bin.makeReadOptions(t),s=ml(n.getType().runtime.bin.listUnknownFields(n),e.field),[r,a]=ga(e);for(const o of s)e.runtime.bin.readField(r,i.readerFactory(o.data),e.field,o.wireType,i);return a()}function vl(n,e,t,i){ba(e,n);const s=e.runtime.bin.makeReadOptions(i),r=e.runtime.bin.makeWriteOptions(i);if(ya(n,e)){const d=n.getType().runtime.bin.listUnknownFields(n).filter(l=>l.no!=e.field.no);n.getType().runtime.bin.discardUnknownFields(n);for(const l of d)n.getType().runtime.bin.onUnknownField(n,l.no,l.wireType,l.data)}const a=r.writerFactory();let o=e.field;!o.opt&&!o.repeated&&(o.kind=="enum"||o.kind=="scalar")&&(o=Object.assign(Object.assign({},e.field),{opt:!0})),e.runtime.bin.writeField(o,t,a,r);const c=s.readerFactory(a.finish());for(;c.pos<c.len;){const[d,l]=c.tag(),u=c.skip(l,d);n.getType().runtime.bin.onUnknownField(n,d,l,u)}}function ya(n,e){const t=n.getType();return e.extendee.typeName===t.typeName&&!!t.runtime.bin.listUnknownFields(n).find(i=>i.no==e.field.no)}function ba(n,e){ae(n.extendee.typeName==e.getType().typeName,"extension ".concat(n.typeName," can only be applied to message ").concat(n.extendee.typeName))}function ka(n,e){const t=n.localName;if(n.repeated)return e[t].length>0;if(n.oneof)return e[n.oneof.localName].case===t;switch(n.kind){case"enum":case"scalar":return n.opt||n.req?e[t]!==void 0:n.kind=="enum"?e[t]!==n.T.values[0].no:!ma(n.T,e[t]);case"message":return e[t]!==void 0;case"map":return Object.keys(e[t]).length>0}}function Ta(n,e){const t=n.localName,i=!n.opt&&!n.req;if(n.repeated)e[t]=[];else if(n.oneof)e[n.oneof.localName]={case:void 0};else switch(n.kind){case"map":e[t]={};break;case"enum":e[t]=i?n.T.values[0].no:void 0;break;case"scalar":e[t]=i?Xt(n.T,n.L):void 0;break;case"message":e[t]=void 0;break}}function Nt(n,e){if(n===null||typeof n!="object"||!Object.getOwnPropertyNames(bs.prototype).every(i=>i in n&&typeof n[i]=="function"))return!1;const t=n.getType();return t===null||typeof t!="function"||!("typeName"in t)||typeof t.typeName!="string"?!1:e===void 0?!0:t.typeName==e.typeName}function Sa(n,e){return Nt(e)||!n.fieldWrapper?e:n.fieldWrapper.wrapField(e)}C.DOUBLE,C.FLOAT,C.INT64,C.UINT64,C.INT32,C.UINT32,C.BOOL,C.STRING,C.BYTES;const Ca={ignoreUnknownFields:!1},_a={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0};function yl(n){return n?Object.assign(Object.assign({},Ca),n):Ca}function bl(n){return n?Object.assign(Object.assign({},_a),n):_a}const yn=Symbol(),bn=Symbol();function kl(){return{makeReadOptions:yl,makeWriteOptions:bl,readMessage(n,e,t,i){if(e==null||Array.isArray(e)||typeof e!="object")throw new Error("cannot decode message ".concat(n.typeName," from JSON: ").concat(We(e)));i=i??new n;const s=new Map,r=t.typeRegistry;for(const[a,o]of Object.entries(e)){const c=n.fields.findJsonName(a);if(c){if(c.oneof){if(o===null&&c.kind=="scalar")continue;const d=s.get(c.oneof);if(d!==void 0)throw new Error("cannot decode message ".concat(n.typeName,' from JSON: multiple keys for oneof "').concat(c.oneof.name,'" present: "').concat(d,'", "').concat(a,'"'));s.set(c.oneof,a)}Ea(i,o,c,t,n)}else{let d=!1;if(r!=null&&r.findExtension&&a.startsWith("[")&&a.endsWith("]")){const l=r.findExtension(a.substring(1,a.length-1));if(l&&l.extendee.typeName==n.typeName){d=!0;const[u,h]=ga(l);Ea(u,o,l.field,t,l),vl(i,l,h(),t)}}if(!d&&!t.ignoreUnknownFields)throw new Error("cannot decode message ".concat(n.typeName,' from JSON: key "').concat(a,'" is unknown'))}}return i},writeMessage(n,e){const t=n.getType(),i={};let s;try{for(s of t.fields.byNumber()){if(!ka(s,n)){if(s.req)throw"required field not set";if(!e.emitDefaultValues||!Sl(s))continue}const a=s.oneof?n[s.oneof.localName].value:n[s.localName],o=wa(s,a,e);o!==void 0&&(i[e.useProtoFieldName?s.name:s.jsonName]=o)}const r=e.typeRegistry;if(r!=null&&r.findExtensionFor)for(const a of t.runtime.bin.listUnknownFields(n)){const o=r.findExtensionFor(t.typeName,a.no);if(o&&ya(n,o)){const c=gl(n,o,e),d=wa(o.field,c,e);d!==void 0&&(i[o.field.jsonName]=d)}}}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 i},readScalar(n,e,t){return Pi(n,e,t??vt.BIGINT,!0)},writeScalar(n,e,t){if(e!==void 0&&(t||ma(n,e)))return kn(n,e)},debug:We}}function We(n){if(n===null)return"null";switch(typeof n){case"object":return Array.isArray(n)?"array":"object";case"string":return n.length>100?"string":'"'.concat(n.split('"').join('\\"'),'"');default:return String(n)}}function Ea(n,e,t,i,s){let r=t.localName;if(t.repeated){if(ae(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(We(e)));const a=n[r];for(const o of e){if(o===null)throw new Error("cannot decode field ".concat(s.typeName,".").concat(t.name," from JSON: ").concat(We(o)));switch(t.kind){case"message":a.push(t.T.fromJson(o,i));break;case"enum":const c=Ss(t.T,o,i.ignoreUnknownFields,!0);c!==bn&&a.push(c);break;case"scalar":try{a.push(Pi(t.T,o,t.L,!0))}catch(d){let l="cannot decode field ".concat(s.typeName,".").concat(t.name," from JSON: ").concat(We(o));throw d instanceof Error&&d.message.length>0&&(l+=": ".concat(d.message)),new Error(l)}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(We(e)));const a=n[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 d;try{d=Tl(t.K,o)}catch(l){let u="cannot decode map key for field ".concat(s.typeName,".").concat(t.name," from JSON: ").concat(We(e));throw l instanceof Error&&l.message.length>0&&(u+=": ".concat(l.message)),new Error(u)}switch(t.V.kind){case"message":a[d]=t.V.T.fromJson(c,i);break;case"enum":const l=Ss(t.V.T,c,i.ignoreUnknownFields,!0);l!==bn&&(a[d]=l);break;case"scalar":try{a[d]=Pi(t.V.T,c,vt.BIGINT,!0)}catch(u){let h="cannot decode map value for field ".concat(s.typeName,".").concat(t.name," from JSON: ").concat(We(e));throw u instanceof Error&&u.message.length>0&&(h+=": ".concat(u.message)),new Error(h)}break}}}else switch(t.oneof&&(n=n[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=n[r];Nt(o)?o.fromJson(e,i):(n[r]=o=a.fromJson(e,i),a.fieldWrapper&&!t.oneof&&(n[r]=a.fieldWrapper.unwrapField(o)));break;case"enum":const c=Ss(t.T,e,i.ignoreUnknownFields,!1);switch(c){case yn:Ta(t,n);break;case bn:break;default:n[r]=c;break}break;case"scalar":try{const d=Pi(t.T,e,t.L,!1);switch(d){case yn:Ta(t,n);break;default:n[r]=d;break}}catch(d){let l="cannot decode field ".concat(s.typeName,".").concat(t.name," from JSON: ").concat(We(e));throw d instanceof Error&&d.message.length>0&&(l+=": ".concat(d.message)),new Error(l)}break}}function Tl(n,e){if(n===C.BOOL)switch(e){case"true":e=!0;break;case"false":e=!1;break}return Pi(n,e,vt.BIGINT,!0).toString()}function Pi(n,e,t,i){if(e===null)return i?Xt(n,t):yn;switch(n){case C.DOUBLE:case C.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 n==C.FLOAT&&ra(s),s;case C.INT32:case C.FIXED32:case C.SFIXED32:case C.SINT32:case C.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 n==C.UINT32||n==C.FIXED32?ys(r):mn(r),r;case C.INT64:case C.SFIXED64:case C.SINT64:if(typeof e!="number"&&typeof e!="string")break;const a=se.parse(e);return t?a.toString():a;case C.FIXED64:case C.UINT64:if(typeof e!="number"&&typeof e!="string")break;const o=se.uParse(e);return t?o.toString():o;case C.BOOL:if(typeof e!="boolean")break;return e;case C.STRING:if(typeof e!="string")break;try{encodeURIComponent(e)}catch{throw new Error("invalid UTF8")}return e;case C.BYTES:if(e==="")return new Uint8Array(0);if(typeof e!="string")break;return va.dec(e)}throw new Error}function Ss(n,e,t,i){if(e===null)return n.typeName=="google.protobuf.NullValue"?0:i?n.values[0].no:yn;switch(typeof e){case"number":if(Number.isInteger(e))return e;break;case"string":const s=n.findName(e);if(s!==void 0)return s.no;if(t)return bn;break}throw new Error("cannot decode enum ".concat(n.typeName," from JSON: ").concat(We(e)))}function Sl(n){return n.repeated||n.kind=="map"?!0:!(n.oneof||n.kind=="message"||n.opt||n.req)}function wa(n,e,t){if(n.kind=="map"){ae(typeof e=="object"&&e!=null);const i={},s=Object.entries(e);switch(n.V.kind){case"scalar":for(const[a,o]of s)i[a.toString()]=kn(n.V.T,o);break;case"message":for(const[a,o]of s)i[a.toString()]=o.toJson(t);break;case"enum":const r=n.V.T;for(const[a,o]of s)i[a.toString()]=Cs(r,o,t.enumAsInteger);break}return t.emitDefaultValues||s.length>0?i:void 0}if(n.repeated){ae(Array.isArray(e));const i=[];switch(n.kind){case"scalar":for(let s=0;s<e.length;s++)i.push(kn(n.T,e[s]));break;case"enum":for(let s=0;s<e.length;s++)i.push(Cs(n.T,e[s],t.enumAsInteger));break;case"message":for(let s=0;s<e.length;s++)i.push(e[s].toJson(t));break}return t.emitDefaultValues||i.length>0?i:void 0}switch(n.kind){case"scalar":return kn(n.T,e);case"enum":return Cs(n.T,e,t.enumAsInteger);case"message":return Sa(n.T,e).toJson(t)}}function Cs(n,e,t){var i;if(ae(typeof e=="number"),n.typeName=="google.protobuf.NullValue")return null;if(t)return e;const s=n.findNumber(e);return(i=s==null?void 0:s.name)!==null&&i!==void 0?i:e}function kn(n,e){switch(n){case C.INT32:case C.SFIXED32:case C.SINT32:case C.FIXED32:case C.UINT32:return ae(typeof e=="number"),e;case C.FLOAT:case C.DOUBLE:return ae(typeof e=="number"),Number.isNaN(e)?"NaN":e===Number.POSITIVE_INFINITY?"Infinity":e===Number.NEGATIVE_INFINITY?"-Infinity":e;case C.STRING:return ae(typeof e=="string"),e;case C.BOOL:return ae(typeof e=="boolean"),e;case C.UINT64:case C.FIXED64:case C.INT64:case C.SFIXED64:case C.SINT64:return ae(typeof e=="bigint"||typeof e=="string"||typeof e=="number"),e.toString();case C.BYTES:return ae(e instanceof Uint8Array),va.enc(e)}}const ei=Symbol("@bufbuild/protobuf/unknown-fields"),Pa={readUnknownFields:!0,readerFactory:n=>new hl(n)},Ra={writeUnknownFields:!0,writerFactory:()=>new ul};function Cl(n){return n?Object.assign(Object.assign({},Pa),n):Pa}function _l(n){return n?Object.assign(Object.assign({},Ra),n):Ra}function El(){return{makeReadOptions:Cl,makeWriteOptions:_l,listUnknownFields(n){var e;return(e=n[ei])!==null&&e!==void 0?e:[]},discardUnknownFields(n){delete n[ei]},writeUnknownFields(n,e){const i=n[ei];if(i)for(const s of i)e.tag(s.no,s.wireType).raw(s.data)},onUnknownField(n,e,t,i){const s=n;Array.isArray(s[ei])||(s[ei]=[]),s[ei].push({no:e,wireType:t,data:i})},readMessage(n,e,t,i,s){const r=n.getType(),a=s?e.len:e.pos+t;let o,c;for(;e.pos<a&&([o,c]=e.tag(),!(s===!0&&c==le.EndGroup));){const d=r.fields.find(o);if(!d){const l=e.skip(c,o);i.readUnknownFields&&this.onUnknownField(n,o,c,l);continue}xa(n,e,d,c,i)}if(s&&(c!=le.EndGroup||o!==t))throw new Error("invalid end group tag")},readField:xa,writeMessage(n,e,t){const i=n.getType();for(const s of i.fields.byNumber()){if(!ka(s,n)){if(s.req)throw new Error("cannot encode field ".concat(i.typeName,".").concat(s.name," to binary: required field not set"));continue}const r=s.oneof?n[s.oneof.localName].value:n[s.localName];Ia(s,r,e,t)}return t.writeUnknownFields&&this.writeUnknownFields(n,e),e},writeField(n,e,t,i){e!==void 0&&Ia(n,e,t,i)}}}function xa(n,e,t,i,s){let{repeated:r,localName:a}=t;switch(t.oneof&&(n=n[t.oneof.localName],n.case!=a&&delete n.value,n.case=a,a="value"),t.kind){case"scalar":case"enum":const o=t.kind=="enum"?C.INT32:t.T;let c=Sn;if(t.kind=="scalar"&&t.L>0&&(c=Pl),r){let h=n[a];if(i==le.LengthDelimited&&o!=C.STRING&&o!=C.BYTES){let g=e.uint32()+e.pos;for(;e.pos<g;)h.push(c(e,o))}else h.push(c(e,o))}else n[a]=c(e,o);break;case"message":const d=t.T;r?n[a].push(Tn(e,new d,s,t)):Nt(n[a])?Tn(e,n[a],s,t):(n[a]=Tn(e,new d,s,t),d.fieldWrapper&&!t.oneof&&!t.repeated&&(n[a]=d.fieldWrapper.unwrapField(n[a])));break;case"map":let[l,u]=wl(t,e,s);n[a][l]=u;break}}function Tn(n,e,t,i){const s=e.getType().runtime.bin,r=i==null?void 0:i.delimited;return s.readMessage(e,n,r?i.no:n.uint32(),t,r),e}function wl(n,e,t){const i=e.uint32(),s=e.pos+i;let r,a;for(;e.pos<s;){const[o]=e.tag();switch(o){case 1:r=Sn(e,n.K);break;case 2:switch(n.V.kind){case"scalar":a=Sn(e,n.V.T);break;case"enum":a=e.int32();break;case"message":a=Tn(e,new n.V.T,t,void 0);break}break}}if(r===void 0&&(r=Xt(n.K,vt.BIGINT)),typeof r!="string"&&typeof r!="number"&&(r=r.toString()),a===void 0)switch(n.V.kind){case"scalar":a=Xt(n.V.T,vt.BIGINT);break;case"enum":a=n.V.T.values[0].no;break;case"message":a=new n.V.T;break}return[r,a]}function Pl(n,e){const t=Sn(n,e);return typeof t=="bigint"?t.toString():t}function Sn(n,e){switch(e){case C.STRING:return n.string();case C.BOOL:return n.bool();case C.DOUBLE:return n.double();case C.FLOAT:return n.float();case C.INT32:return n.int32();case C.INT64:return n.int64();case C.UINT64:return n.uint64();case C.FIXED64:return n.fixed64();case C.BYTES:return n.bytes();case C.FIXED32:return n.fixed32();case C.SFIXED32:return n.sfixed32();case C.SFIXED64:return n.sfixed64();case C.SINT64:return n.sint64();case C.UINT32:return n.uint32();case C.SINT32:return n.sint32()}}function Ia(n,e,t,i){ae(e!==void 0);const s=n.repeated;switch(n.kind){case"scalar":case"enum":let r=n.kind=="enum"?C.INT32:n.T;if(s)if(ae(Array.isArray(e)),n.packed)xl(t,r,n.no,e);else for(const a of e)Ri(t,r,n.no,a);else Ri(t,r,n.no,e);break;case"message":if(s){ae(Array.isArray(e));for(const a of e)Aa(t,i,n,a)}else Aa(t,i,n,e);break;case"map":ae(typeof e=="object"&&e!=null);for(const[a,o]of Object.entries(e))Rl(t,i,n,a,o);break}}function Rl(n,e,t,i,s){n.tag(t.no,le.LengthDelimited),n.fork();let r=i;switch(t.K){case C.INT32:case C.FIXED32:case C.UINT32:case C.SFIXED32:case C.SINT32:r=Number.parseInt(i);break;case C.BOOL:ae(i=="true"||i=="false"),r=i=="true";break}switch(Ri(n,t.K,1,r),t.V.kind){case"scalar":Ri(n,t.V.T,2,s);break;case"enum":Ri(n,C.INT32,2,s);break;case"message":ae(s!==void 0),n.tag(2,le.LengthDelimited).bytes(s.toBinary(e));break}n.join()}function Aa(n,e,t,i){const s=Sa(t.T,i);t.delimited?n.tag(t.no,le.StartGroup).raw(s.toBinary(e)).tag(t.no,le.EndGroup):n.tag(t.no,le.LengthDelimited).bytes(s.toBinary(e))}function Ri(n,e,t,i){ae(i!==void 0);let[s,r]=Oa(e);n.tag(t,s)[r](i)}function xl(n,e,t,i){if(!i.length)return;n.tag(t,le.LengthDelimited).fork();let[,s]=Oa(e);for(let r=0;r<i.length;r++)n[s](i[r]);n.join()}function Oa(n){let e=le.Varint;switch(n){case C.BYTES:case C.STRING:e=le.LengthDelimited;break;case C.DOUBLE:case C.FIXED64:case C.SFIXED64:e=le.Bit64;break;case C.FIXED32:case C.SFIXED32:case C.FLOAT:e=le.Bit32;break}const t=C[n].toLowerCase();return[e,t]}function Il(){return{setEnumType:oa,initPartial(n,e){if(n===void 0)return;const t=e.getType();for(const i of t.fields.byMember()){const s=i.localName,r=e,a=n;if(a[s]!=null)switch(i.kind){case"oneof":const o=a[s].case;if(o===void 0)continue;const c=i.findField(o);let d=a[s].value;c&&c.kind=="message"&&!Nt(d,c.T)?d=new c.T(d):c&&c.kind==="scalar"&&c.T===C.BYTES&&(d=xi(d)),r[s]={case:o,value:d};break;case"scalar":case"enum":let l=a[s];i.T===C.BYTES&&(l=i.repeated?l.map(xi):xi(l)),r[s]=l;break;case"map":switch(i.V.kind){case"scalar":case"enum":if(i.V.T===C.BYTES)for(const[f,g]of Object.entries(a[s]))r[s][f]=xi(g);else Object.assign(r[s],a[s]);break;case"message":const h=i.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=i.T;if(i.repeated)r[s]=a[s].map(h=>Nt(h,u)?h:new u(h));else{const h=a[s];u.fieldWrapper?u.typeName==="google.protobuf.BytesValue"?r[s]=xi(h):r[s]=h:r[s]=Nt(h,u)?h:new u(h)}break}}},equals(n,e,t){return e===t?!0:!e||!t?!1:n.fields.byMember().every(i=>{const s=e[i.localName],r=t[i.localName];if(i.repeated){if(s.length!==r.length)return!1;switch(i.kind){case"message":return s.every((a,o)=>i.T.equals(a,r[o]));case"scalar":return s.every((a,o)=>yt(i.T,a,r[o]));case"enum":return s.every((a,o)=>yt(C.INT32,a,r[o]))}throw new Error("repeated cannot contain ".concat(i.kind))}switch(i.kind){case"message":return i.T.equals(s,r);case"enum":return yt(C.INT32,s,r);case"scalar":return yt(i.T,s,r);case"oneof":if(s.case!==r.case)return!1;const a=i.findField(s.case);if(a===void 0)return!0;switch(a.kind){case"message":return a.T.equals(s.value,r.value);case"enum":return yt(C.INT32,s.value,r.value);case"scalar":return yt(a.T,s.value,r.value)}throw new Error("oneof cannot contain ".concat(a.kind));case"map":const o=Object.keys(s).concat(Object.keys(r));switch(i.V.kind){case"message":const c=i.V.T;return o.every(l=>c.equals(s[l],r[l]));case"enum":return o.every(l=>yt(C.INT32,s[l],r[l]));case"scalar":const d=i.V.T;return o.every(l=>yt(d,s[l],r[l]))}break}})},clone(n){const e=n.getType(),t=new e,i=t;for(const s of e.fields.byMember()){const r=n[s.localName];let a;if(s.repeated)a=r.map(Cn);else if(s.kind=="map"){a=i[s.localName];for(const[o,c]of Object.entries(r))a[o]=Cn(c)}else s.kind=="oneof"?a=s.findField(r.case)?{case:r.case,value:Cn(r.value)}:{case:void 0}:a=Cn(r);i[s.localName]=a}for(const s of e.runtime.bin.listUnknownFields(n))e.runtime.bin.onUnknownField(i,s.no,s.wireType,s.data);return t}}}function Cn(n){if(n===void 0)return n;if(Nt(n))return n.clone();if(n instanceof Uint8Array){const e=new Uint8Array(n.byteLength);return e.set(n),e}return n}function xi(n){return n instanceof Uint8Array?n:new Uint8Array(n)}function Al(n,e,t){return{syntax:n,json:kl(),bin:El(),util:Object.assign(Object.assign({},Il()),{newFieldList:e,initFields:t}),makeMessageType(i,s,r){return rl(this,i,s,r)},makeEnum:sl,makeEnumType:ca,getEnumType:nl,makeExtension(i,s,r){return fl(this,i,s,r)}}}class Ol{constructor(e,t){this._fields=e,this._normalizer=t}findJsonName(e){if(!this.jsonNames){const t={};for(const i of this.list())t[i.jsonName]=t[i.name]=i;this.jsonNames=t}return this.jsonNames[e]}find(e){if(!this.numbers){const t={};for(const i of this.list())t[i.no]=i;this.numbers=t}return this.numbers[e]}list(){return this.all||(this.all=this._normalizer(this._fields)),this.all}byNumber(){return this.numbersAsc||(this.numbersAsc=this.list().concat().sort((e,t)=>e.no-t.no)),this.numbersAsc}byMember(){if(!this.members){this.members=[];const e=this.members;let t;for(const i of this.list())i.oneof?i.oneof!==t&&(t=i.oneof,e.push(t)):e.push(i)}return this.members}}function Da(n,e){const t=Ma(n);return e?t:Fl(Ul(t))}function Dl(n){return Da(n,!1)}const Ml=Ma;function Ma(n){let e=!1;const t=[];for(let i=0;i<n.length;i++){let s=n.charAt(i);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 Nl=new Set(["constructor","toString","toJSON","valueOf"]),Ll=new Set(["getType","clone","equals","fromBinary","fromJson","fromJsonString","toBinary","toJson","toJsonString","toObject"]),Na=n=>"".concat(n,"$"),Ul=n=>Ll.has(n)?Na(n):n,Fl=n=>Nl.has(n)?Na(n):n;class jl{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=Dl(e)}addField(e){ae(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 $l(n,e){var t,i,s,r,a,o;const c=[];let d;for(const l of typeof n=="function"?n():n){const u=l;if(u.localName=Da(l.name,l.oneof!==void 0),u.jsonName=(t=l.jsonName)!==null&&t!==void 0?t:Ml(l.name),u.repeated=(i=l.repeated)!==null&&i!==void 0?i:!1,l.kind=="scalar"&&(u.L=(s=l.L)!==null&&s!==void 0?s:vt.BIGINT),u.delimited=(r=l.delimited)!==null&&r!==void 0?r:!1,u.req=(a=l.req)!==null&&a!==void 0?a:!1,u.opt=(o=l.opt)!==null&&o!==void 0?o:!1,l.packed===void 0&&(u.packed=l.kind=="enum"||l.kind=="scalar"&&l.T!=C.BYTES&&l.T!=C.STRING),l.oneof!==void 0){const h=typeof l.oneof=="string"?l.oneof:l.oneof.name;(!d||d.name!=h)&&(d=new jl(h)),u.oneof=d,d.addField(u)}c.push(u)}return c}const k=Al("proto3",n=>new Ol(n,e=>$l(e)),n=>{for(const e of n.getType().fields.byMember()){if(e.opt)continue;const t=e.localName,i=n;if(e.repeated){i[t]=[];continue}switch(e.kind){case"oneof":i[t]={case:void 0};break;case"enum":i[t]=0;break;case"map":i[t]={};break;case"scalar":i[t]=Xt(e.T,e.L);break}}});class _e extends bs{constructor(e){super(),this.seconds=se.zero,this.nanos=0,k.util.initPartial(e,this)}fromJson(e,t){if(typeof e!="string")throw new Error("cannot decode google.protobuf.Timestamp from JSON: ".concat(k.json.debug(e)));const i=e.match(/^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})(?:Z|\.([0-9]{3,9})Z|([+-][0-9][0-9]:[0-9][0-9]))$/);if(!i)throw new Error("cannot decode google.protobuf.Timestamp from JSON: invalid RFC 3339 string");const s=Date.parse(i[1]+"-"+i[2]+"-"+i[3]+"T"+i[4]+":"+i[5]+":"+i[6]+(i[8]?i[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=se.parse(s/1e3),this.nanos=0,i[7]&&(this.nanos=parseInt("1"+i[7]+"0".repeat(9-i[7].length))-1e9),this}toJson(e){const t=Number(this.seconds)*1e3;if(t<Date.parse("0001-01-01T00:00:00Z")||t>Date.parse("9999-12-31T23:59:59Z"))throw new Error("cannot encode google.protobuf.Timestamp to JSON: must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive");if(this.nanos<0)throw new Error("cannot encode google.protobuf.Timestamp to JSON: nanos must not be negative");let i="Z";if(this.nanos>0){const s=(this.nanos+1e9).toString().substring(1);s.substring(3)==="000000"?i="."+s.substring(0,3)+"Z":s.substring(6)==="000"?i="."+s.substring(0,6)+"Z":i="."+s+"Z"}return new Date(t).toISOString().replace(".000Z",i)}toDate(){return new Date(Number(this.seconds)*1e3+Math.ceil(this.nanos/1e6))}static now(){return _e.fromDate(new Date)}static fromDate(e){const t=e.getTime();return new _e({seconds:se.parse(Math.floor(t/1e3)),nanos:t%1e3*1e6})}static fromBinary(e,t){return new _e().fromBinary(e,t)}static fromJson(e,t){return new _e().fromJson(e,t)}static fromJsonString(e,t){return new _e().fromJsonString(e,t)}static equals(e,t){return k.util.equals(_e,e,t)}}_e.runtime=k,_e.typeName="google.protobuf.Timestamp",_e.fields=k.util.newFieldList(()=>[{no:1,name:"seconds",kind:"scalar",T:3},{no:2,name:"nanos",kind:"scalar",T:5}]);const Bl=k.makeMessageType("livekit.MetricsBatch",()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:_e},{no:3,name:"str_data",kind:"scalar",T:9,repeated:!0},{no:4,name:"time_series",kind:"message",T:Vl,repeated:!0},{no:5,name:"events",kind:"message",T:zl,repeated:!0}]),Vl=k.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:ql,repeated:!0},{no:5,name:"rid",kind:"scalar",T:13}]),ql=k.makeMessageType("livekit.MetricSample",()=>[{no:1,name:"timestamp_ms",kind:"scalar",T:3},{no:2,name:"normalized_timestamp",kind:"message",T:_e},{no:3,name:"value",kind:"scalar",T:2}]),zl=k.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:_e},{no:7,name:"normalized_end_timestamp",kind:"message",T:_e,opt:!0},{no:8,name:"metadata",kind:"scalar",T:9},{no:9,name:"rid",kind:"scalar",T:13}]),La=k.makeEnum("livekit.BackupCodecPolicy",[{no:0,name:"PREFER_REGRESSION"},{no:1,name:"SIMULCAST"},{no:2,name:"REGRESSION"}]),Oe=k.makeEnum("livekit.TrackType",[{no:0,name:"AUDIO"},{no:1,name:"VIDEO"},{no:2,name:"DATA"}]),ue=k.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"}]),ti=k.makeEnum("livekit.VideoQuality",[{no:0,name:"LOW"},{no:1,name:"MEDIUM"},{no:2,name:"HIGH"},{no:3,name:"OFF"}]),Ii=k.makeEnum("livekit.ConnectionQuality",[{no:0,name:"POOR"},{no:1,name:"GOOD"},{no:2,name:"EXCELLENT"},{no:3,name:"LOST"}]),Ai=k.makeEnum("livekit.ClientConfigSetting",[{no:0,name:"UNSET"},{no:1,name:"DISABLED"},{no:2,name:"ENABLED"}]),De=k.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"}]),ii=k.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"}]),Gl=k.makeEnum("livekit.SubscriptionError",[{no:0,name:"SE_UNKNOWN"},{no:1,name:"SE_CODEC_UNSUPPORTED"},{no:2,name:"SE_TRACK_NOTFOUND"}]),Ke=k.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"}]),_s=k.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:_n,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:Za}]),_n=k.makeMessageType("livekit.Codec",()=>[{no:1,name:"mime",kind:"scalar",T:9},{no:2,name:"fmtp_line",kind:"scalar",T:9}]),Wl=k.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:k.getEnumType(ue),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}]),Oi=k.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:k.getEnumType(Es)},{no:4,name:"tracks",kind:"message",T:ni,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:Wl},{no:12,name:"region",kind:"scalar",T:9},{no:13,name:"is_publisher",kind:"scalar",T:8},{no:14,name:"kind",kind:"enum",T:k.getEnumType(En)},{no:15,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:16,name:"disconnect_reason",kind:"enum",T:k.getEnumType(De)},{no:18,name:"kind_details",kind:"enum",T:k.getEnumType(Kl),repeated:!0}]),Es=k.makeEnum("livekit.ParticipantInfo.State",[{no:0,name:"JOINING"},{no:1,name:"JOINED"},{no:2,name:"ACTIVE"},{no:3,name:"DISCONNECTED"}]),En=k.makeEnum("livekit.ParticipantInfo.Kind",[{no:0,name:"STANDARD"},{no:1,name:"INGRESS"},{no:2,name:"EGRESS"},{no:3,name:"SIP"},{no:4,name:"AGENT"}]),Kl=k.makeEnum("livekit.ParticipantInfo.KindDetail",[{no:0,name:"CLOUD_AGENT"},{no:1,name:"FORWARDED"}]),xe=k.makeEnum("livekit.Encryption.Type",[{no:0,name:"NONE"},{no:1,name:"GCM"},{no:2,name:"CUSTOM"}]),Hl=k.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:Lt,repeated:!0}]),ni=k.makeMessageType("livekit.TrackInfo",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"type",kind:"enum",T:k.getEnumType(Oe)},{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:k.getEnumType(ue)},{no:10,name:"layers",kind:"message",T:Lt,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:Hl,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:k.getEnumType(xe)},{no:17,name:"stream",kind:"scalar",T:9},{no:18,name:"version",kind:"message",T:Za},{no:19,name:"audio_features",kind:"enum",T:k.getEnumType(Ke),repeated:!0},{no:20,name:"backup_codec_policy",kind:"enum",T:k.getEnumType(La)}]),Lt=k.makeMessageType("livekit.VideoLayer",()=>[{no:1,name:"quality",kind:"enum",T:k.getEnumType(ti)},{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}]),Ee=k.makeMessageType("livekit.DataPacket",()=>[{no:1,name:"kind",kind:"enum",T:k.getEnumType(J)},{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:Fa,oneof:"value"},{no:3,name:"speaker",kind:"message",T:Zl,oneof:"value"},{no:6,name:"sip_dtmf",kind:"message",T:ja,oneof:"value"},{no:7,name:"transcription",kind:"message",T:Jl,oneof:"value"},{no:8,name:"metrics",kind:"message",T:Bl,oneof:"value"},{no:9,name:"chat_message",kind:"message",T:ws,oneof:"value"},{no:10,name:"rpc_request",kind:"message",T:$a,oneof:"value"},{no:11,name:"rpc_ack",kind:"message",T:Ba,oneof:"value"},{no:12,name:"rpc_response",kind:"message",T:Va,oneof:"value"},{no:13,name:"stream_header",kind:"message",T:Rs,oneof:"value"},{no:14,name:"stream_chunk",kind:"message",T:xs,oneof:"value"},{no:15,name:"stream_trailer",kind:"message",T:Is,oneof:"value"}]),J=k.makeEnum("livekit.DataPacket.Kind",[{no:0,name:"RELIABLE"},{no:1,name:"LOSSY"}]),Zl=k.makeMessageType("livekit.ActiveSpeakerUpdate",()=>[{no:1,name:"speakers",kind:"message",T:Ua,repeated:!0}]),Ua=k.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}]),Fa=k.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}]),ja=k.makeMessageType("livekit.SipDTMF",()=>[{no:3,name:"code",kind:"scalar",T:13},{no:4,name:"digit",kind:"scalar",T:9}]),Jl=k.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:Yl,repeated:!0}]),Yl=k.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}]),ws=k.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}]),$a=k.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}]),Ba=k.makeMessageType("livekit.RpcAck",()=>[{no:1,name:"request_id",kind:"scalar",T:9}]),Va=k.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:qa,oneof:"value"}]),qa=k.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}]),za=k.makeMessageType("livekit.ParticipantTracks",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"track_sids",kind:"scalar",T:9,repeated:!0}]),Ql=k.makeMessageType("livekit.ServerInfo",()=>[{no:1,name:"edition",kind:"enum",T:k.getEnumType(Ga)},{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}]),Ga=k.makeEnum("livekit.ServerInfo.Edition",[{no:0,name:"Standard"},{no:1,name:"Cloud"}]),Xl=k.makeMessageType("livekit.ClientInfo",()=>[{no:1,name:"sdk",kind:"enum",T:k.getEnumType(Wa)},{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}]),Wa=k.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"}]),Ka=k.makeMessageType("livekit.ClientConfiguration",()=>[{no:1,name:"video",kind:"message",T:Ha},{no:2,name:"screen",kind:"message",T:Ha},{no:3,name:"resume_connection",kind:"enum",T:k.getEnumType(Ai)},{no:4,name:"disabled_codecs",kind:"message",T:eu},{no:5,name:"force_relay",kind:"enum",T:k.getEnumType(Ai)}]),Ha=k.makeMessageType("livekit.VideoConfiguration",()=>[{no:1,name:"hardware_encoder",kind:"enum",T:k.getEnumType(Ai)}]),eu=k.makeMessageType("livekit.DisabledCodecs",()=>[{no:1,name:"codecs",kind:"message",T:_n,repeated:!0},{no:2,name:"publish",kind:"message",T:_n,repeated:!0}]),Za=k.makeMessageType("livekit.TimedVersion",()=>[{no:1,name:"unix_micro",kind:"scalar",T:3},{no:2,name:"ticks",kind:"scalar",T:5}]),Ps=k.makeEnum("livekit.DataStream.OperationType",[{no:0,name:"CREATE"},{no:1,name:"UPDATE"},{no:2,name:"DELETE"},{no:3,name:"REACTION"}]),Ja=k.makeMessageType("livekit.DataStream.TextHeader",()=>[{no:1,name:"operation_type",kind:"enum",T:k.getEnumType(Ps)},{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"}),Ya=k.makeMessageType("livekit.DataStream.ByteHeader",()=>[{no:1,name:"name",kind:"scalar",T:9}],{localName:"DataStream_ByteHeader"}),Rs=k.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:k.getEnumType(xe)},{no:8,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:9,name:"text_header",kind:"message",T:Ja,oneof:"content_header"},{no:10,name:"byte_header",kind:"message",T:Ya,oneof:"content_header"}],{localName:"DataStream_Header"}),xs=k.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"}),Is=k.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"}),Me=k.makeEnum("livekit.SignalTarget",[{no:0,name:"PUBLISHER"},{no:1,name:"SUBSCRIBER"}]),As=k.makeEnum("livekit.StreamState",[{no:0,name:"ACTIVE"},{no:1,name:"PAUSED"}]),tu=k.makeEnum("livekit.CandidateProtocol",[{no:0,name:"UDP"},{no:1,name:"TCP"},{no:2,name:"TLS"}]),iu=k.makeMessageType("livekit.SignalRequest",()=>[{no:1,name:"offer",kind:"message",T:Ut,oneof:"message"},{no:2,name:"answer",kind:"message",T:Ut,oneof:"message"},{no:3,name:"trickle",kind:"message",T:Ms,oneof:"message"},{no:4,name:"add_track",kind:"message",T:Ds,oneof:"message"},{no:5,name:"mute",kind:"message",T:Ns,oneof:"message"},{no:6,name:"subscription",kind:"message",T:wn,oneof:"message"},{no:7,name:"track_setting",kind:"message",T:Xa,oneof:"message"},{no:8,name:"leave",kind:"message",T:Pn,oneof:"message"},{no:10,name:"update_layers",kind:"message",T:to,oneof:"message"},{no:11,name:"subscription_permission",kind:"message",T:ro,oneof:"message"},{no:12,name:"sync_state",kind:"message",T:ao,oneof:"message"},{no:13,name:"simulate",kind:"message",T:He,oneof:"message"},{no:14,name:"ping",kind:"scalar",T:3,oneof:"message"},{no:15,name:"update_metadata",kind:"message",T:io,oneof:"message"},{no:16,name:"ping_req",kind:"message",T:co,oneof:"message"},{no:17,name:"update_audio_track",kind:"message",T:eo,oneof:"message"},{no:18,name:"update_video_track",kind:"message",T:ou,oneof:"message"}]),Qa=k.makeMessageType("livekit.SignalResponse",()=>[{no:1,name:"join",kind:"message",T:nu,oneof:"message"},{no:2,name:"answer",kind:"message",T:Ut,oneof:"message"},{no:3,name:"offer",kind:"message",T:Ut,oneof:"message"},{no:4,name:"trickle",kind:"message",T:Ms,oneof:"message"},{no:5,name:"update",kind:"message",T:au,oneof:"message"},{no:6,name:"track_published",kind:"message",T:Ls,oneof:"message"},{no:8,name:"leave",kind:"message",T:Pn,oneof:"message"},{no:9,name:"mute",kind:"message",T:Ns,oneof:"message"},{no:10,name:"speakers_changed",kind:"message",T:cu,oneof:"message"},{no:11,name:"room_update",kind:"message",T:du,oneof:"message"},{no:12,name:"connection_quality",kind:"message",T:uu,oneof:"message"},{no:13,name:"stream_state_update",kind:"message",T:fu,oneof:"message"},{no:14,name:"subscribed_quality_update",kind:"message",T:mu,oneof:"message"},{no:15,name:"subscription_permission_update",kind:"message",T:gu,oneof:"message"},{no:16,name:"refresh_token",kind:"scalar",T:9,oneof:"message"},{no:17,name:"track_unpublished",kind:"message",T:ru,oneof:"message"},{no:18,name:"pong",kind:"scalar",T:3,oneof:"message"},{no:19,name:"reconnect",kind:"message",T:su,oneof:"message"},{no:20,name:"pong_resp",kind:"message",T:vu,oneof:"message"},{no:21,name:"subscription_response",kind:"message",T:ku,oneof:"message"},{no:22,name:"request_response",kind:"message",T:Tu,oneof:"message"},{no:23,name:"track_subscribed",kind:"message",T:Su,oneof:"message"}]),Os=k.makeMessageType("livekit.SimulcastCodec",()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"cid",kind:"scalar",T:9}]),Ds=k.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:k.getEnumType(Oe)},{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:k.getEnumType(ue)},{no:9,name:"layers",kind:"message",T:Lt,repeated:!0},{no:10,name:"simulcast_codecs",kind:"message",T:Os,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:k.getEnumType(xe)},{no:15,name:"stream",kind:"scalar",T:9},{no:16,name:"backup_codec_policy",kind:"enum",T:k.getEnumType(La)}]),Ms=k.makeMessageType("livekit.TrickleRequest",()=>[{no:1,name:"candidateInit",kind:"scalar",T:9},{no:2,name:"target",kind:"enum",T:k.getEnumType(Me)},{no:3,name:"final",kind:"scalar",T:8}]),Ns=k.makeMessageType("livekit.MuteTrackRequest",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"muted",kind:"scalar",T:8}]),nu=k.makeMessageType("livekit.JoinResponse",()=>[{no:1,name:"room",kind:"message",T:_s},{no:2,name:"participant",kind:"message",T:Oi},{no:3,name:"other_participants",kind:"message",T:Oi,repeated:!0},{no:4,name:"server_version",kind:"scalar",T:9},{no:5,name:"ice_servers",kind:"message",T:no,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:Ka},{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:Ql},{no:13,name:"sif_trailer",kind:"scalar",T:12},{no:14,name:"enabled_publish_codecs",kind:"message",T:_n,repeated:!0},{no:15,name:"fast_publish",kind:"scalar",T:8}]),su=k.makeMessageType("livekit.ReconnectResponse",()=>[{no:1,name:"ice_servers",kind:"message",T:no,repeated:!0},{no:2,name:"client_configuration",kind:"message",T:Ka}]),Ls=k.makeMessageType("livekit.TrackPublishedResponse",()=>[{no:1,name:"cid",kind:"scalar",T:9},{no:2,name:"track",kind:"message",T:ni}]),ru=k.makeMessageType("livekit.TrackUnpublishedResponse",()=>[{no:1,name:"track_sid",kind:"scalar",T:9}]),Ut=k.makeMessageType("livekit.SessionDescription",()=>[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"sdp",kind:"scalar",T:9}]),au=k.makeMessageType("livekit.ParticipantUpdate",()=>[{no:1,name:"participants",kind:"message",T:Oi,repeated:!0}]),wn=k.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:za,repeated:!0}]),Xa=k.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:k.getEnumType(ti)},{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}]),eo=k.makeMessageType("livekit.UpdateLocalAudioTrack",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"features",kind:"enum",T:k.getEnumType(Ke),repeated:!0}]),ou=k.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}]),Pn=k.makeMessageType("livekit.LeaveRequest",()=>[{no:1,name:"can_reconnect",kind:"scalar",T:8},{no:2,name:"reason",kind:"enum",T:k.getEnumType(De)},{no:3,name:"action",kind:"enum",T:k.getEnumType(si)},{no:4,name:"regions",kind:"message",T:yu}]),si=k.makeEnum("livekit.LeaveRequest.Action",[{no:0,name:"DISCONNECT"},{no:1,name:"RESUME"},{no:2,name:"RECONNECT"}]),to=k.makeMessageType("livekit.UpdateVideoLayers",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"layers",kind:"message",T:Lt,repeated:!0}]),io=k.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}]),no=k.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}]),cu=k.makeMessageType("livekit.SpeakersChanged",()=>[{no:1,name:"speakers",kind:"message",T:Ua,repeated:!0}]),du=k.makeMessageType("livekit.RoomUpdate",()=>[{no:1,name:"room",kind:"message",T:_s}]),lu=k.makeMessageType("livekit.ConnectionQualityInfo",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"quality",kind:"enum",T:k.getEnumType(Ii)},{no:3,name:"score",kind:"scalar",T:2}]),uu=k.makeMessageType("livekit.ConnectionQualityUpdate",()=>[{no:1,name:"updates",kind:"message",T:lu,repeated:!0}]),hu=k.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:k.getEnumType(As)}]),fu=k.makeMessageType("livekit.StreamStateUpdate",()=>[{no:1,name:"stream_states",kind:"message",T:hu,repeated:!0}]),Us=k.makeMessageType("livekit.SubscribedQuality",()=>[{no:1,name:"quality",kind:"enum",T:k.getEnumType(ti)},{no:2,name:"enabled",kind:"scalar",T:8}]),pu=k.makeMessageType("livekit.SubscribedCodec",()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"qualities",kind:"message",T:Us,repeated:!0}]),mu=k.makeMessageType("livekit.SubscribedQualityUpdate",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribed_qualities",kind:"message",T:Us,repeated:!0},{no:3,name:"subscribed_codecs",kind:"message",T:pu,repeated:!0}]),so=k.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}]),ro=k.makeMessageType("livekit.SubscriptionPermission",()=>[{no:1,name:"all_participants",kind:"scalar",T:8},{no:2,name:"track_permissions",kind:"message",T:so,repeated:!0}]),gu=k.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}]),ao=k.makeMessageType("livekit.SyncState",()=>[{no:1,name:"answer",kind:"message",T:Ut},{no:2,name:"subscription",kind:"message",T:wn},{no:3,name:"publish_tracks",kind:"message",T:Ls,repeated:!0},{no:4,name:"data_channels",kind:"message",T:oo,repeated:!0},{no:5,name:"offer",kind:"message",T:Ut},{no:6,name:"track_sids_disabled",kind:"scalar",T:9,repeated:!0}]),oo=k.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:k.getEnumType(Me)}]),He=k.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:k.getEnumType(tu),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"}]),co=k.makeMessageType("livekit.Ping",()=>[{no:1,name:"timestamp",kind:"scalar",T:3},{no:2,name:"rtt",kind:"scalar",T:3}]),vu=k.makeMessageType("livekit.Pong",()=>[{no:1,name:"last_ping_timestamp",kind:"scalar",T:3},{no:2,name:"timestamp",kind:"scalar",T:3}]),yu=k.makeMessageType("livekit.RegionSettings",()=>[{no:1,name:"regions",kind:"message",T:bu,repeated:!0}]),bu=k.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}]),ku=k.makeMessageType("livekit.SubscriptionResponse",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"err",kind:"enum",T:k.getEnumType(Gl)}]),Tu=k.makeMessageType("livekit.RequestResponse",()=>[{no:1,name:"request_id",kind:"scalar",T:13},{no:2,name:"reason",kind:"enum",T:k.getEnumType(Fs)},{no:3,name:"message",kind:"scalar",T:9}]),Fs=k.makeEnum("livekit.RequestResponse.Reason",[{no:0,name:"OK"},{no:1,name:"NOT_FOUND"},{no:2,name:"NOT_ALLOWED"},{no:3,name:"LIMIT_EXCEEDED"}]),Su=k.makeMessageType("livekit.TrackSubscribed",()=>[{no:1,name:"track_sid",kind:"scalar",T:9}]);function Cu(n){return n&&n.__esModule&&Object.prototype.hasOwnProperty.call(n,"default")?n.default:n}var Rn={exports:{}},_u=Rn.exports,lo;function Eu(){return lo||(lo=1,function(n){(function(e,t){n.exports?n.exports=t():e.log=t()})(_u,function(){var e=function(){},t="undefined",i=typeof window!==t&&typeof window.navigator!==t&&/Trident\/|MSIE /.test(window.navigator.userAgent),s=["trace","debug","info","warn","error"],r={},a=null;function o(m,v){var T=m[v];if(typeof T.bind=="function")return T.bind(m);try{return Function.prototype.bind.call(T,m)}catch{return function(){return Function.prototype.apply.apply(T,[m,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 d(m){return m==="debug"&&(m="log"),typeof console===t?!1:m==="trace"&&i?c:console[m]!==void 0?o(console,m):console.log!==void 0?o(console,"log"):e}function l(){for(var m=this.getLevel(),v=0;v<s.length;v++){var T=s[v];this[T]=v<m?e:this.methodFactory(T,m,this.name)}if(this.log=this.debug,typeof console===t&&m<this.levels.SILENT)return"No console available for logging"}function u(m){return function(){typeof console!==t&&(l.call(this),this[m].apply(this,arguments))}}function h(m,v,T){return d(m)||u.apply(this,arguments)}function f(m,v){var T=this,x,P,y,b="loglevel";typeof m=="string"?b+=":"+m:typeof m=="symbol"&&(b=void 0);function E(z){var de=(s[z]||"silent").toUpperCase();if(!(typeof window===t||!b)){try{window.localStorage[b]=de;return}catch{}try{window.document.cookie=encodeURIComponent(b)+"="+de+";"}catch{}}}function M(){var z;if(!(typeof window===t||!b)){try{z=window.localStorage[b]}catch{}if(typeof z===t)try{var de=window.document.cookie,Qt=encodeURIComponent(b),ls=de.indexOf(Qt+"=");ls!==-1&&(z=/^([^;]+)/.exec(de.slice(ls+Qt.length+1))[1])}catch{}return T.levels[z]===void 0&&(z=void 0),z}}function U(){if(!(typeof window===t||!b)){try{window.localStorage.removeItem(b)}catch{}try{window.document.cookie=encodeURIComponent(b)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}function W(z){var de=z;if(typeof de=="string"&&T.levels[de.toUpperCase()]!==void 0&&(de=T.levels[de.toUpperCase()]),typeof de=="number"&&de>=0&&de<=T.levels.SILENT)return de;throw new TypeError("log.setLevel() called with invalid level: "+z)}T.name=m,T.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},T.methodFactory=v||h,T.getLevel=function(){return y??P??x},T.setLevel=function(z,de){return y=W(z),de!==!1&&E(y),l.call(T)},T.setDefaultLevel=function(z){P=W(z),M()||T.setLevel(z,!1)},T.resetLevel=function(){y=null,U(),l.call(T)},T.enableAll=function(z){T.setLevel(T.levels.TRACE,z)},T.disableAll=function(z){T.setLevel(T.levels.SILENT,z)},T.rebuild=function(){if(a!==T&&(x=W(a.getLevel())),l.call(T),a===T)for(var z in r)r[z].rebuild()},x=W(a?a.getLevel():"WARN");var q=M();q!=null&&(y=W(q)),l.call(T)}a=new f,a.getLogger=function(v){if(typeof v!="symbol"&&typeof v!="string"||v==="")throw new TypeError("You must supply a name when creating a logger.");var T=r[v];return T||(T=r[v]=new f(v,a.methodFactory)),T};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})}(Rn)),Rn.exports}var xn=Eu(),js;(function(n){n[n.trace=0]="trace",n[n.debug=1]="debug",n[n.info=2]="info",n[n.warn=3]="warn",n[n.error=4]="error",n[n.silent=5]="silent"})(js||(js={}));var Ne;(function(n){n.Default="livekit",n.Room="livekit-room",n.Participant="livekit-participant",n.Track="livekit-track",n.Publication="livekit-track-publication",n.Engine="livekit-engine",n.Signal="livekit-signal",n.PCManager="livekit-pc-manager",n.PCTransport="livekit-pc-transport",n.E2EE="lk-e2ee"})(Ne||(Ne={}));let G=xn.getLogger("livekit");Object.values(Ne).map(n=>xn.getLogger(n)),G.setDefaultLevel(js.info);function it(n){const e=xn.getLogger(n);return e.setDefaultLevel(G.getLevel()),e}const wu=xn.getLogger("lk-e2ee"),Di=7e3,Pu=[0,300,2*2*300,3*3*300,4*4*300,Di,Di,Di,Di,Di];class Ru{constructor(e){this._retryDelays=e!==void 0?[...e]:Pu}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 xu(n,e){var t={};for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&e.indexOf(i)<0&&(t[i]=n[i]);if(n!=null&&typeof Object.getOwnPropertySymbols=="function")for(var s=0,i=Object.getOwnPropertySymbols(n);s<i.length;s++)e.indexOf(i[s])<0&&Object.prototype.propertyIsEnumerable.call(n,i[s])&&(t[i[s]]=n[i[s]]);return t}function p(n,e,t,i){function s(r){return r instanceof t?r:new t(function(a){a(r)})}return new(t||(t=Promise))(function(r,a){function o(l){try{d(i.next(l))}catch(u){a(u)}}function c(l){try{d(i.throw(l))}catch(u){a(u)}}function d(l){l.done?r(l.value):s(l.value).then(o,c)}d((i=i.apply(n,e||[])).next())})}function uo(n){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&n[e],i=0;if(t)return t.call(n);if(n&&typeof n.length=="number")return{next:function(){return n&&i>=n.length&&(n=void 0),{value:n&&n[i++],done:!n}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function bt(n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=n[Symbol.asyncIterator],t;return e?e.call(n):(n=typeof uo=="function"?uo(n):n[Symbol.iterator](),t={},i("next"),i("throw"),i("return"),t[Symbol.asyncIterator]=function(){return this},t);function i(r){t[r]=n[r]&&function(a){return new Promise(function(o,c){a=n[r](a),s(o,c,a.done,a.value)})}}function s(r,a,o,c){Promise.resolve(c).then(function(d){r({value:d,done:o})},a)}}typeof SuppressedError=="function"&&SuppressedError;var In={exports:{}},ho;function Iu(){if(ho)return In.exports;ho=1;var n=typeof Reflect=="object"?Reflect:null,e=n&&typeof n.apply=="function"?n.apply:function(b,E,M){return Function.prototype.apply.call(b,E,M)},t;n&&typeof n.ownKeys=="function"?t=n.ownKeys:Object.getOwnPropertySymbols?t=function(b){return Object.getOwnPropertyNames(b).concat(Object.getOwnPropertySymbols(b))}:t=function(b){return Object.getOwnPropertyNames(b)};function i(y){console&&console.warn&&console.warn(y)}var s=Number.isNaN||function(b){return b!==b};function r(){r.init.call(this)}In.exports=r,In.exports.once=T,r.EventEmitter=r,r.prototype._events=void 0,r.prototype._eventsCount=0,r.prototype._maxListeners=void 0;var a=10;function o(y){if(typeof y!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof y)}Object.defineProperty(r,"defaultMaxListeners",{enumerable:!0,get:function(){return a},set:function(y){if(typeof y!="number"||y<0||s(y))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+y+".");a=y}}),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(b){if(typeof b!="number"||b<0||s(b))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+b+".");return this._maxListeners=b,this};function c(y){return y._maxListeners===void 0?r.defaultMaxListeners:y._maxListeners}r.prototype.getMaxListeners=function(){return c(this)},r.prototype.emit=function(b){for(var E=[],M=1;M<arguments.length;M++)E.push(arguments[M]);var U=b==="error",W=this._events;if(W!==void 0)U=U&&W.error===void 0;else if(!U)return!1;if(U){var q;if(E.length>0&&(q=E[0]),q instanceof Error)throw q;var z=new Error("Unhandled error."+(q?" ("+q.message+")":""));throw z.context=q,z}var de=W[b];if(de===void 0)return!1;if(typeof de=="function")e(de,this,E);else for(var Qt=de.length,ls=g(de,Qt),M=0;M<Qt;++M)e(ls[M],this,E);return!0};function d(y,b,E,M){var U,W,q;if(o(E),W=y._events,W===void 0?(W=y._events=Object.create(null),y._eventsCount=0):(W.newListener!==void 0&&(y.emit("newListener",b,E.listener?E.listener:E),W=y._events),q=W[b]),q===void 0)q=W[b]=E,++y._eventsCount;else if(typeof q=="function"?q=W[b]=M?[E,q]:[q,E]:M?q.unshift(E):q.push(E),U=c(y),U>0&&q.length>U&&!q.warned){q.warned=!0;var z=new Error("Possible EventEmitter memory leak detected. "+q.length+" "+String(b)+" listeners added. Use emitter.setMaxListeners() to increase limit");z.name="MaxListenersExceededWarning",z.emitter=y,z.type=b,z.count=q.length,i(z)}return y}r.prototype.addListener=function(b,E){return d(this,b,E,!1)},r.prototype.on=r.prototype.addListener,r.prototype.prependListener=function(b,E){return d(this,b,E,!0)};function l(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function u(y,b,E){var M={fired:!1,wrapFn:void 0,target:y,type:b,listener:E},U=l.bind(M);return U.listener=E,M.wrapFn=U,U}r.prototype.once=function(b,E){return o(E),this.on(b,u(this,b,E)),this},r.prototype.prependOnceListener=function(b,E){return o(E),this.prependListener(b,u(this,b,E)),this},r.prototype.removeListener=function(b,E){var M,U,W,q,z;if(o(E),U=this._events,U===void 0)return this;if(M=U[b],M===void 0)return this;if(M===E||M.listener===E)--this._eventsCount===0?this._events=Object.create(null):(delete U[b],U.removeListener&&this.emit("removeListener",b,M.listener||E));else if(typeof M!="function"){for(W=-1,q=M.length-1;q>=0;q--)if(M[q]===E||M[q].listener===E){z=M[q].listener,W=q;break}if(W<0)return this;W===0?M.shift():m(M,W),M.length===1&&(U[b]=M[0]),U.removeListener!==void 0&&this.emit("removeListener",b,z||E)}return this},r.prototype.off=r.prototype.removeListener,r.prototype.removeAllListeners=function(b){var E,M,U;if(M=this._events,M===void 0)return this;if(M.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):M[b]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete M[b]),this;if(arguments.length===0){var W=Object.keys(M),q;for(U=0;U<W.length;++U)q=W[U],q!=="removeListener"&&this.removeAllListeners(q);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(E=M[b],typeof E=="function")this.removeListener(b,E);else if(E!==void 0)for(U=E.length-1;U>=0;U--)this.removeListener(b,E[U]);return this};function h(y,b,E){var M=y._events;if(M===void 0)return[];var U=M[b];return U===void 0?[]:typeof U=="function"?E?[U.listener||U]:[U]:E?v(U):g(U,U.length)}r.prototype.listeners=function(b){return h(this,b,!0)},r.prototype.rawListeners=function(b){return h(this,b,!1)},r.listenerCount=function(y,b){return typeof y.listenerCount=="function"?y.listenerCount(b):f.call(y,b)},r.prototype.listenerCount=f;function f(y){var b=this._events;if(b!==void 0){var E=b[y];if(typeof E=="function")return 1;if(E!==void 0)return E.length}return 0}r.prototype.eventNames=function(){return this._eventsCount>0?t(this._events):[]};function g(y,b){for(var E=new Array(b),M=0;M<b;++M)E[M]=y[M];return E}function m(y,b){for(;b+1<y.length;b++)y[b]=y[b+1];y.pop()}function v(y){for(var b=new Array(y.length),E=0;E<b.length;++E)b[E]=y[E].listener||y[E];return b}function T(y,b){return new Promise(function(E,M){function U(q){y.removeListener(b,W),M(q)}function W(){typeof y.removeListener=="function"&&y.removeListener("error",U),E([].slice.call(arguments))}P(y,b,W,{once:!0}),b!=="error"&&x(y,U,{once:!0})})}function x(y,b,E){typeof y.on=="function"&&P(y,"error",b,E)}function P(y,b,E,M){if(typeof y.on=="function")M.once?y.once(b,E):y.on(b,E);else if(typeof y.addEventListener=="function")y.addEventListener(b,function U(W){M.once&&y.removeEventListener(b,U),E(W)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof y)}return In.exports}var Ze=Iu();let fo=!0,po=!0;function An(n,e,t){const i=n.match(e);return i&&i.length>=t&&parseInt(i[t],10)}function Ft(n,e,t){if(!n.RTCPeerConnection)return;const i=n.RTCPeerConnection.prototype,s=i.addEventListener;i.addEventListener=function(a,o){if(a!==e)return s.apply(this,arguments);const c=d=>{const l=t(d);l&&(o.handleEvent?o.handleEvent(l):o(l))};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=i.removeEventListener;i.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(i,"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 Au(n){return typeof n!="boolean"?new Error("Argument type: "+typeof n+". Please use a boolean."):(fo=n,n?"adapter.js logging disabled":"adapter.js logging enabled")}function Ou(n){return typeof n!="boolean"?new Error("Argument type: "+typeof n+". Please use a boolean."):(po=!n,"adapter.js deprecation warnings "+(n?"disabled":"enabled"))}function mo(){if(typeof window=="object"){if(fo)return;typeof console<"u"&&typeof console.log=="function"&&console.log.apply(console,arguments)}}function $s(n,e){po&&console.warn(n+" is deprecated, please use "+e+" instead.")}function Du(n){const e={browser:null,version:null};if(typeof n>"u"||!n.navigator||!n.navigator.userAgent)return e.browser="Not a browser.",e;const{navigator:t}=n;if(t.userAgentData&&t.userAgentData.brands){const i=t.userAgentData.brands.find(s=>s.brand==="Chromium");if(i)return{browser:"chrome",version:parseInt(i.version,10)}}if(t.mozGetUserMedia)e.browser="firefox",e.version=An(t.userAgent,/Firefox\/(\d+)\./,1);else if(t.webkitGetUserMedia||n.isSecureContext===!1&&n.webkitRTCPeerConnection)e.browser="chrome",e.version=An(t.userAgent,/Chrom(e|ium)\/(\d+)\./,2);else if(n.RTCPeerConnection&&t.userAgent.match(/AppleWebKit\/(\d+)\./))e.browser="safari",e.version=An(t.userAgent,/AppleWebKit\/(\d+)\./,1),e.supportsUnifiedPlan=n.RTCRtpTransceiver&&"currentDirection"in n.RTCRtpTransceiver.prototype;else return e.browser="Not a supported browser.",e;return e}function go(n){return Object.prototype.toString.call(n)==="[object Object]"}function vo(n){return go(n)?Object.keys(n).reduce(function(e,t){const i=go(n[t]),s=i?vo(n[t]):n[t],r=i&&!Object.keys(s).length;return s===void 0||r?e:Object.assign(e,{[t]:s})},{}):n}function Bs(n,e,t){!e||t.has(e.id)||(t.set(e.id,e),Object.keys(e).forEach(i=>{i.endsWith("Id")?Bs(n,n.get(e[i]),t):i.endsWith("Ids")&&e[i].forEach(s=>{Bs(n,n.get(s),t)})}))}function yo(n,e,t){const i=t?"outbound-rtp":"inbound-rtp",s=new Map;if(e===null)return s;const r=[];return n.forEach(a=>{a.type==="track"&&a.trackIdentifier===e.id&&r.push(a)}),r.forEach(a=>{n.forEach(o=>{o.type===i&&o.trackId===a.id&&Bs(n,o,s)})}),s}const bo=mo;function ko(n,e){const t=n&&n.navigator;if(!t.mediaDevices)return;const i=function(o){if(typeof o!="object"||o.mandatory||o.optional)return o;const c={};return Object.keys(o).forEach(d=>{if(d==="require"||d==="advanced"||d==="mediaSource")return;const l=typeof o[d]=="object"?o[d]:{ideal:o[d]};l.exact!==void 0&&typeof l.exact=="number"&&(l.min=l.max=l.exact);const u=function(h,f){return h?h+f.charAt(0).toUpperCase()+f.slice(1):f==="deviceId"?"sourceId":f};if(l.ideal!==void 0){c.optional=c.optional||[];let h={};typeof l.ideal=="number"?(h[u("min",d)]=l.ideal,c.optional.push(h),h={},h[u("max",d)]=l.ideal,c.optional.push(h)):(h[u("",d)]=l.ideal,c.optional.push(h))}l.exact!==void 0&&typeof l.exact!="number"?(c.mandatory=c.mandatory||{},c.mandatory[u("",d)]=l.exact):["min","max"].forEach(h=>{l[h]!==void 0&&(c.mandatory=c.mandatory||{},c.mandatory[u(h,d)]=l[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 d=function(l,u,h){u in l&&!(h in l)&&(l[h]=l[u],delete l[u])};o=JSON.parse(JSON.stringify(o)),d(o.audio,"autoGainControl","googAutoGainControl"),d(o.audio,"noiseSuppression","googNoiseSuppression"),o.audio=i(o.audio)}if(o&&typeof o.video=="object"){let d=o.video.facingMode;d=d&&(typeof d=="object"?d:{ideal:d});const l=e.version<66;if(d&&(d.exact==="user"||d.exact==="environment"||d.ideal==="user"||d.ideal==="environment")&&!(t.mediaDevices.getSupportedConstraints&&t.mediaDevices.getSupportedConstraints().facingMode&&!l)){delete o.video.facingMode;let u;if(d.exact==="environment"||d.ideal==="environment"?u=["back","rear"]:(d.exact==="user"||d.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(m=>g.label.toLowerCase().includes(m)));return!f&&h.length&&u.includes("back")&&(f=h[h.length-1]),f&&(o.video.deviceId=d.exact?{exact:f.deviceId}:{ideal:f.deviceId}),o.video=i(o.video),bo("chrome: "+JSON.stringify(o)),c(o)})}o.video=i(o.video)}return bo("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,d){s(o,l=>{t.webkitGetUserMedia(l,c,u=>{d&&d(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,d=>o(d).then(l=>{if(d.audio&&!l.getAudioTracks().length||d.video&&!l.getVideoTracks().length)throw l.getTracks().forEach(u=>{u.stop()}),new DOMException("","NotFoundError");return l},l=>Promise.reject(r(l))))}}}function To(n){n.MediaStream=n.MediaStream||n.webkitMediaStream}function So(n){if(typeof n=="object"&&n.RTCPeerConnection&&!("ontrack"in n.RTCPeerConnection.prototype)){Object.defineProperty(n.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=n.RTCPeerConnection.prototype.setRemoteDescription;n.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=i=>{i.stream.addEventListener("addtrack",s=>{let r;n.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=[i.stream],this.dispatchEvent(a)}),i.stream.getTracks().forEach(s=>{let r;n.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=[i.stream],this.dispatchEvent(a)})},this.addEventListener("addstream",this._ontrackpoly)),e.apply(this,arguments)}}else Ft(n,"track",e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e))}function Co(n){if(typeof n=="object"&&n.RTCPeerConnection&&!("getSenders"in n.RTCPeerConnection.prototype)&&"createDTMFSender"in n.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(!n.RTCPeerConnection.prototype.getSenders){n.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};const s=n.RTCPeerConnection.prototype.addTrack;n.RTCPeerConnection.prototype.addTrack=function(o,c){let d=s.apply(this,arguments);return d||(d=e(this,o),this._senders.push(d)),d};const r=n.RTCPeerConnection.prototype.removeTrack;n.RTCPeerConnection.prototype.removeTrack=function(o){r.apply(this,arguments);const c=this._senders.indexOf(o);c!==-1&&this._senders.splice(c,1)}}const t=n.RTCPeerConnection.prototype.addStream;n.RTCPeerConnection.prototype.addStream=function(r){this._senders=this._senders||[],t.apply(this,[r]),r.getTracks().forEach(a=>{this._senders.push(e(this,a))})};const i=n.RTCPeerConnection.prototype.removeStream;n.RTCPeerConnection.prototype.removeStream=function(r){this._senders=this._senders||[],i.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 n=="object"&&n.RTCPeerConnection&&"getSenders"in n.RTCPeerConnection.prototype&&"createDTMFSender"in n.RTCPeerConnection.prototype&&n.RTCRtpSender&&!("dtmf"in n.RTCRtpSender.prototype)){const e=n.RTCPeerConnection.prototype.getSenders;n.RTCPeerConnection.prototype.getSenders=function(){const i=e.apply(this,[]);return i.forEach(s=>s._pc=this),i},Object.defineProperty(n.RTCRtpSender.prototype,"dtmf",{get(){return this._dtmf===void 0&&(this.track.kind==="audio"?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}})}}function _o(n){if(!(typeof n=="object"&&n.RTCPeerConnection&&n.RTCRtpSender&&n.RTCRtpReceiver))return;if(!("getStats"in n.RTCRtpSender.prototype)){const t=n.RTCPeerConnection.prototype.getSenders;t&&(n.RTCPeerConnection.prototype.getSenders=function(){const r=t.apply(this,[]);return r.forEach(a=>a._pc=this),r});const i=n.RTCPeerConnection.prototype.addTrack;i&&(n.RTCPeerConnection.prototype.addTrack=function(){const r=i.apply(this,arguments);return r._pc=this,r}),n.RTCRtpSender.prototype.getStats=function(){const r=this;return this._pc.getStats().then(a=>yo(a,r.track,!0))}}if(!("getStats"in n.RTCRtpReceiver.prototype)){const t=n.RTCPeerConnection.prototype.getReceivers;t&&(n.RTCPeerConnection.prototype.getReceivers=function(){const s=t.apply(this,[]);return s.forEach(r=>r._pc=this),s}),Ft(n,"track",i=>(i.receiver._pc=i.srcElement,i)),n.RTCRtpReceiver.prototype.getStats=function(){const s=this;return this._pc.getStats().then(r=>yo(r,s.track,!1))}}if(!("getStats"in n.RTCRtpSender.prototype&&"getStats"in n.RTCRtpReceiver.prototype))return;const e=n.RTCPeerConnection.prototype.getStats;n.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof n.MediaStreamTrack){const i=arguments[0];let s,r,a;return this.getSenders().forEach(o=>{o.track===i&&(s?a=!0:s=o)}),this.getReceivers().forEach(o=>(o.track===i&&(r?a=!0:r=o),o.track===i)),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 Eo(n){n.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map(a=>this._shimmedLocalStreams[a][0])};const e=n.RTCPeerConnection.prototype.addTrack;n.RTCPeerConnection.prototype.addTrack=function(a,o){if(!o)return e.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};const 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=n.RTCPeerConnection.prototype.addStream;n.RTCPeerConnection.prototype.addStream=function(a){this._shimmedLocalStreams=this._shimmedLocalStreams||{},a.getTracks().forEach(d=>{if(this.getSenders().find(u=>u.track===d))throw new DOMException("Track already exists.","InvalidAccessError")});const o=this.getSenders();t.apply(this,arguments);const c=this.getSenders().filter(d=>o.indexOf(d)===-1);this._shimmedLocalStreams[a.id]=[a].concat(c)};const i=n.RTCPeerConnection.prototype.removeStream;n.RTCPeerConnection.prototype.removeStream=function(a){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[a.id],i.apply(this,arguments)};const s=n.RTCPeerConnection.prototype.removeTrack;n.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 wo(n,e){if(!n.RTCPeerConnection)return;if(n.RTCPeerConnection.prototype.addTrack&&e.version>=65)return Eo(n);const t=n.RTCPeerConnection.prototype.getLocalStreams;n.RTCPeerConnection.prototype.getLocalStreams=function(){const l=t.apply(this);return this._reverseStreams=this._reverseStreams||{},l.map(u=>this._reverseStreams[u.id])};const i=n.RTCPeerConnection.prototype.addStream;n.RTCPeerConnection.prototype.addStream=function(l){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},l.getTracks().forEach(u=>{if(this.getSenders().find(f=>f.track===u))throw new DOMException("Track already exists.","InvalidAccessError")}),!this._reverseStreams[l.id]){const u=new n.MediaStream(l.getTracks());this._streams[l.id]=u,this._reverseStreams[u.id]=l,l=u}i.apply(this,[l])};const s=n.RTCPeerConnection.prototype.removeStream;n.RTCPeerConnection.prototype.removeStream=function(l){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},s.apply(this,[this._streams[l.id]||l]),delete this._reverseStreams[this._streams[l.id]?this._streams[l.id].id:l.id],delete this._streams[l.id]},n.RTCPeerConnection.prototype.addTrack=function(l,u){if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");const h=[].slice.call(arguments,1);if(h.length!==1||!h[0].getTracks().find(m=>m===l))throw new DOMException("The adapter.js addTrack polyfill only supports a single stream which is associated with the specified track.","NotSupportedError");if(this.getSenders().find(m=>m.track===l))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(l),Promise.resolve().then(()=>{this.dispatchEvent(new Event("negotiationneeded"))});else{const m=new n.MediaStream([l]);this._streams[u.id]=m,this._reverseStreams[m.id]=u,this.addStream(m)}return this.getSenders().find(m=>m.track===l)};function r(d,l){let u=l.sdp;return Object.keys(d._reverseStreams||[]).forEach(h=>{const f=d._reverseStreams[h],g=d._streams[f.id];u=u.replace(new RegExp(g.id,"g"),f.id)}),new RTCSessionDescription({type:l.type,sdp:u})}function a(d,l){let u=l.sdp;return Object.keys(d._reverseStreams||[]).forEach(h=>{const f=d._reverseStreams[h],g=d._streams[f.id];u=u.replace(new RegExp(f.id,"g"),g.id)}),new RTCSessionDescription({type:l.type,sdp:u})}["createOffer","createAnswer"].forEach(function(d){const l=n.RTCPeerConnection.prototype[d],u={[d](){const h=arguments;return arguments.length&&typeof arguments[0]=="function"?l.apply(this,[g=>{const m=r(this,g);h[0].apply(null,[m])},g=>{h[1]&&h[1].apply(null,g)},arguments[2]]):l.apply(this,arguments).then(g=>r(this,g))}};n.RTCPeerConnection.prototype[d]=u[d]});const o=n.RTCPeerConnection.prototype.setLocalDescription;n.RTCPeerConnection.prototype.setLocalDescription=function(){return!arguments.length||!arguments[0].type?o.apply(this,arguments):(arguments[0]=a(this,arguments[0]),o.apply(this,arguments))};const c=Object.getOwnPropertyDescriptor(n.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(n.RTCPeerConnection.prototype,"localDescription",{get(){const d=c.get.apply(this);return d.type===""?d:r(this,d)}}),n.RTCPeerConnection.prototype.removeTrack=function(l){if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!l._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(!(l._pc===this))throw new DOMException("Sender was not created by this connection.","InvalidAccessError");this._streams=this._streams||{};let h;Object.keys(this._streams).forEach(f=>{this._streams[f].getTracks().find(m=>l.track===m)&&(h=this._streams[f])}),h&&(h.getTracks().length===1?this.removeStream(this._reverseStreams[h.id]):h.removeTrack(l.track),this.dispatchEvent(new Event("negotiationneeded")))}}function Vs(n,e){!n.RTCPeerConnection&&n.webkitRTCPeerConnection&&(n.RTCPeerConnection=n.webkitRTCPeerConnection),n.RTCPeerConnection&&e.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(t){const i=n.RTCPeerConnection.prototype[t],s={[t](){return arguments[0]=new(t==="addIceCandidate"?n.RTCIceCandidate:n.RTCSessionDescription)(arguments[0]),i.apply(this,arguments)}};n.RTCPeerConnection.prototype[t]=s[t]})}function Po(n,e){Ft(n,"negotiationneeded",t=>{const i=t.target;if(!((e.version<72||i.getConfiguration&&i.getConfiguration().sdpSemantics==="plan-b")&&i.signalingState!=="stable"))return t})}var Ro=Object.freeze({__proto__:null,fixNegotiationNeeded:Po,shimAddTrackRemoveTrack:wo,shimAddTrackRemoveTrackWithNative:Eo,shimGetSendersWithDtmf:Co,shimGetUserMedia:ko,shimMediaStream:To,shimOnTrack:So,shimPeerConnection:Vs,shimSenderReceiverGetStats:_o});function xo(n,e){const t=n&&n.navigator,i=n&&n.MediaStreamTrack;if(t.getUserMedia=function(s,r,a){$s("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)},i&&i.prototype.getSettings){const a=i.prototype.getSettings;i.prototype.getSettings=function(){const o=a.apply(this,arguments);return s(o,"mozAutoGainControl","autoGainControl"),s(o,"mozNoiseSuppression","noiseSuppression"),o}}if(i&&i.prototype.applyConstraints){const a=i.prototype.applyConstraints;i.prototype.applyConstraints=function(o){return this.kind==="audio"&&typeof o=="object"&&(o=JSON.parse(JSON.stringify(o)),s(o,"autoGainControl","mozAutoGainControl"),s(o,"noiseSuppression","mozNoiseSuppression")),a.apply(this,[o])}}}}function Mu(n,e){n.navigator.mediaDevices&&"getDisplayMedia"in n.navigator.mediaDevices||n.navigator.mediaDevices&&(n.navigator.mediaDevices.getDisplayMedia=function(i){if(!(i&&i.video)){const s=new DOMException("getDisplayMedia without video constraints is undefined");return s.name="NotFoundError",s.code=8,Promise.reject(s)}return i.video===!0?i.video={mediaSource:e}:i.video.mediaSource=e,n.navigator.mediaDevices.getUserMedia(i)})}function Io(n){typeof n=="object"&&n.RTCTrackEvent&&"receiver"in n.RTCTrackEvent.prototype&&!("transceiver"in n.RTCTrackEvent.prototype)&&Object.defineProperty(n.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function qs(n,e){if(typeof n!="object"||!(n.RTCPeerConnection||n.mozRTCPeerConnection))return;!n.RTCPeerConnection&&n.mozRTCPeerConnection&&(n.RTCPeerConnection=n.mozRTCPeerConnection),e.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(s){const r=n.RTCPeerConnection.prototype[s],a={[s](){return arguments[0]=new(s==="addIceCandidate"?n.RTCIceCandidate:n.RTCSessionDescription)(arguments[0]),r.apply(this,arguments)}};n.RTCPeerConnection.prototype[s]=a[s]});const t={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},i=n.RTCPeerConnection.prototype.getStats;n.RTCPeerConnection.prototype.getStats=function(){const[r,a,o]=arguments;return i.apply(this,[r||null]).then(c=>{if(e.version<53&&!a)try{c.forEach(d=>{d.type=t[d.type]||d.type})}catch(d){if(d.name!=="TypeError")throw d;c.forEach((l,u)=>{c.set(u,Object.assign({},l,{type:t[l.type]||l.type}))})}return c}).then(a,o)}}function Ao(n){if(!(typeof n=="object"&&n.RTCPeerConnection&&n.RTCRtpSender)||n.RTCRtpSender&&"getStats"in n.RTCRtpSender.prototype)return;const e=n.RTCPeerConnection.prototype.getSenders;e&&(n.RTCPeerConnection.prototype.getSenders=function(){const s=e.apply(this,[]);return s.forEach(r=>r._pc=this),s});const t=n.RTCPeerConnection.prototype.addTrack;t&&(n.RTCPeerConnection.prototype.addTrack=function(){const s=t.apply(this,arguments);return s._pc=this,s}),n.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}function Oo(n){if(!(typeof n=="object"&&n.RTCPeerConnection&&n.RTCRtpSender)||n.RTCRtpSender&&"getStats"in n.RTCRtpReceiver.prototype)return;const e=n.RTCPeerConnection.prototype.getReceivers;e&&(n.RTCPeerConnection.prototype.getReceivers=function(){const i=e.apply(this,[]);return i.forEach(s=>s._pc=this),i}),Ft(n,"track",t=>(t.receiver._pc=t.srcElement,t)),n.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function Do(n){!n.RTCPeerConnection||"removeStream"in n.RTCPeerConnection.prototype||(n.RTCPeerConnection.prototype.removeStream=function(t){$s("removeStream","removeTrack"),this.getSenders().forEach(i=>{i.track&&t.getTracks().includes(i.track)&&this.removeTrack(i)})})}function Mo(n){n.DataChannel&&!n.RTCDataChannel&&(n.RTCDataChannel=n.DataChannel)}function No(n){if(!(typeof n=="object"&&n.RTCPeerConnection))return;const e=n.RTCPeerConnection.prototype.addTransceiver;e&&(n.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let i=arguments[1]&&arguments[1].sendEncodings;i===void 0&&(i=[]),i=[...i];const s=i.length>0;s&&i.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=i,a.sendEncodings=i,this.setParametersPromises.push(a.setParameters(o).then(()=>{delete a.sendEncodings}).catch(()=>{delete a.sendEncodings})))}return r})}function Lo(n){if(!(typeof n=="object"&&n.RTCRtpSender))return;const e=n.RTCRtpSender.prototype.getParameters;e&&(n.RTCRtpSender.prototype.getParameters=function(){const i=e.apply(this,arguments);return"encodings"in i||(i.encodings=[].concat(this.sendEncodings||[{}])),i})}function Uo(n){if(!(typeof n=="object"&&n.RTCPeerConnection))return;const e=n.RTCPeerConnection.prototype.createOffer;n.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 Fo(n){if(!(typeof n=="object"&&n.RTCPeerConnection))return;const e=n.RTCPeerConnection.prototype.createAnswer;n.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 jo=Object.freeze({__proto__:null,shimAddTransceiver:No,shimCreateAnswer:Fo,shimCreateOffer:Uo,shimGetDisplayMedia:Mu,shimGetParameters:Lo,shimGetUserMedia:xo,shimOnTrack:Io,shimPeerConnection:qs,shimRTCDataChannel:Mo,shimReceiverGetStats:Oo,shimRemoveStream:Do,shimSenderGetStats:Ao});function $o(n){if(!(typeof n!="object"||!n.RTCPeerConnection)){if("getLocalStreams"in n.RTCPeerConnection.prototype||(n.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in n.RTCPeerConnection.prototype)){const e=n.RTCPeerConnection.prototype.addTrack;n.RTCPeerConnection.prototype.addStream=function(i){this._localStreams||(this._localStreams=[]),this._localStreams.includes(i)||this._localStreams.push(i),i.getAudioTracks().forEach(s=>e.call(this,s,i)),i.getVideoTracks().forEach(s=>e.call(this,s,i))},n.RTCPeerConnection.prototype.addTrack=function(i){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 n.RTCPeerConnection.prototype||(n.RTCPeerConnection.prototype.removeStream=function(t){this._localStreams||(this._localStreams=[]);const i=this._localStreams.indexOf(t);if(i===-1)return;this._localStreams.splice(i,1);const s=t.getTracks();this.getSenders().forEach(r=>{s.includes(r.track)&&this.removeTrack(r)})})}}function Bo(n){if(!(typeof n!="object"||!n.RTCPeerConnection)&&("getRemoteStreams"in n.RTCPeerConnection.prototype||(n.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]}),!("onaddstream"in n.RTCPeerConnection.prototype))){Object.defineProperty(n.RTCPeerConnection.prototype,"onaddstream",{get(){return this._onaddstream},set(t){this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=t),this.addEventListener("track",this._onaddstreampoly=i=>{i.streams.forEach(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=n.RTCPeerConnection.prototype.setRemoteDescription;n.RTCPeerConnection.prototype.setRemoteDescription=function(){const i=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(s){s.streams.forEach(r=>{if(i._remoteStreams||(i._remoteStreams=[]),i._remoteStreams.indexOf(r)>=0)return;i._remoteStreams.push(r);const a=new Event("addstream");a.stream=r,i.dispatchEvent(a)})}),e.apply(i,arguments)}}}function Vo(n){if(typeof n!="object"||!n.RTCPeerConnection)return;const e=n.RTCPeerConnection.prototype,t=e.createOffer,i=e.createAnswer,s=e.setLocalDescription,r=e.setRemoteDescription,a=e.addIceCandidate;e.createOffer=function(d,l){const u=arguments.length>=2?arguments[2]:arguments[0],h=t.apply(this,[u]);return l?(h.then(d,l),Promise.resolve()):h},e.createAnswer=function(d,l){const u=arguments.length>=2?arguments[2]:arguments[0],h=i.apply(this,[u]);return l?(h.then(d,l),Promise.resolve()):h};let o=function(c,d,l){const u=s.apply(this,[c]);return l?(u.then(d,l),Promise.resolve()):u};e.setLocalDescription=o,o=function(c,d,l){const u=r.apply(this,[c]);return l?(u.then(d,l),Promise.resolve()):u},e.setRemoteDescription=o,o=function(c,d,l){const u=a.apply(this,[c]);return l?(u.then(d,l),Promise.resolve()):u},e.addIceCandidate=o}function qo(n){const e=n&&n.navigator;if(e.mediaDevices&&e.mediaDevices.getUserMedia){const t=e.mediaDevices,i=t.getUserMedia.bind(t);e.mediaDevices.getUserMedia=s=>i(zo(s))}!e.getUserMedia&&e.mediaDevices&&e.mediaDevices.getUserMedia&&(e.getUserMedia=(function(i,s,r){e.mediaDevices.getUserMedia(i).then(s,r)}).bind(e))}function zo(n){return n&&n.video!==void 0?Object.assign({},n,{video:vo(n.video)}):n}function Go(n){if(!n.RTCPeerConnection)return;const e=n.RTCPeerConnection;n.RTCPeerConnection=function(i,s){if(i&&i.iceServers){const r=[];for(let a=0;a<i.iceServers.length;a++){let o=i.iceServers[a];o.urls===void 0&&o.url?($s("RTCIceServer.url","RTCIceServer.urls"),o=JSON.parse(JSON.stringify(o)),o.urls=o.url,delete o.url,r.push(o)):r.push(i.iceServers[a])}i.iceServers=r}return new e(i,s)},n.RTCPeerConnection.prototype=e.prototype,"generateCertificate"in e&&Object.defineProperty(n.RTCPeerConnection,"generateCertificate",{get(){return e.generateCertificate}})}function Wo(n){typeof n=="object"&&n.RTCTrackEvent&&"receiver"in n.RTCTrackEvent.prototype&&!("transceiver"in n.RTCTrackEvent.prototype)&&Object.defineProperty(n.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function Ko(n){const e=n.RTCPeerConnection.prototype.createOffer;n.RTCPeerConnection.prototype.createOffer=function(i){if(i){typeof i.offerToReceiveAudio<"u"&&(i.offerToReceiveAudio=!!i.offerToReceiveAudio);const s=this.getTransceivers().find(a=>a.receiver.track.kind==="audio");i.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"):i.offerToReceiveAudio===!0&&!s&&this.addTransceiver("audio",{direction:"recvonly"}),typeof i.offerToReceiveVideo<"u"&&(i.offerToReceiveVideo=!!i.offerToReceiveVideo);const r=this.getTransceivers().find(a=>a.receiver.track.kind==="video");i.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"):i.offerToReceiveVideo===!0&&!r&&this.addTransceiver("video",{direction:"recvonly"})}return e.apply(this,arguments)}}function Ho(n){typeof n!="object"||n.AudioContext||(n.AudioContext=n.webkitAudioContext)}var Zo=Object.freeze({__proto__:null,shimAudioContext:Ho,shimCallbacksAPI:Vo,shimConstraints:zo,shimCreateOfferLegacy:Ko,shimGetUserMedia:qo,shimLocalStreamsAPI:$o,shimRTCIceServerUrls:Go,shimRemoteStreamsAPI:Bo,shimTrackEventTransceiver:Wo}),zs={exports:{}},Jo;function Nu(){return Jo||(Jo=1,function(n){const e={};e.generateIdentifier=function(){return Math.random().toString(36).substring(2,12)},e.localCName=e.generateIdentifier(),e.splitLines=function(t){return t.trim().split(`
19
- `).map(i=>i.trim())},e.splitSections=function(t){return t.split(`
20
- m=`).map((s,r)=>(r>0?"m="+s:s).trim()+`\r
21
- `)},e.getDescription=function(t){const i=e.splitSections(t);return i&&i[0]},e.getMediaSections=function(t){const i=e.splitSections(t);return i.shift(),i},e.matchPrefix=function(t,i){return e.splitLines(t).filter(s=>s.indexOf(i)===0)},e.parseCandidate=function(t){let i;t.indexOf("a=candidate:")===0?i=t.substring(12).split(" "):i=t.substring(10).split(" ");const s={foundation:i[0],component:{1:"rtp",2:"rtcp"}[i[1]]||i[1],protocol:i[2].toLowerCase(),priority:parseInt(i[3],10),ip:i[4],address:i[4],port:parseInt(i[5],10),type:i[7]};for(let r=8;r<i.length;r+=2)switch(i[r]){case"raddr":s.relatedAddress=i[r+1];break;case"rport":s.relatedPort=parseInt(i[r+1],10);break;case"tcptype":s.tcpType=i[r+1];break;case"ufrag":s.ufrag=i[r+1],s.usernameFragment=i[r+1];break;default:s[i[r]]===void 0&&(s[i[r]]=i[r+1]);break}return s},e.writeCandidate=function(t){const i=[];i.push(t.foundation);const s=t.component;s==="rtp"?i.push(1):s==="rtcp"?i.push(2):i.push(s),i.push(t.protocol.toUpperCase()),i.push(t.priority),i.push(t.address||t.ip),i.push(t.port);const r=t.type;return i.push("typ"),i.push(r),r!=="host"&&t.relatedAddress&&t.relatedPort&&(i.push("raddr"),i.push(t.relatedAddress),i.push("rport"),i.push(t.relatedPort)),t.tcpType&&t.protocol.toLowerCase()==="tcp"&&(i.push("tcptype"),i.push(t.tcpType)),(t.usernameFragment||t.ufrag)&&(i.push("ufrag"),i.push(t.usernameFragment||t.ufrag)),"candidate:"+i.join(" ")},e.parseIceOptions=function(t){return t.substring(14).split(" ")},e.parseRtpMap=function(t){let i=t.substring(9).split(" ");const s={payloadType:parseInt(i.shift(),10)};return i=i[0].split("/"),s.name=i[0],s.clockRate=parseInt(i[1],10),s.channels=i.length===3?parseInt(i[2],10):1,s.numChannels=s.channels,s},e.writeRtpMap=function(t){let i=t.payloadType;t.preferredPayloadType!==void 0&&(i=t.preferredPayloadType);const s=t.channels||t.numChannels||1;return"a=rtpmap:"+i+" "+t.name+"/"+t.clockRate+(s!==1?"/"+s:"")+`\r
22
- `},e.parseExtmap=function(t){const i=t.substring(9).split(" ");return{id:parseInt(i[0],10),direction:i[0].indexOf("/")>0?i[0].split("/")[1]:"sendrecv",uri:i[1],attributes:i.slice(2).join(" ")}},e.writeExtmap=function(t){return"a=extmap:"+(t.id||t.preferredId)+(t.direction&&t.direction!=="sendrecv"?"/"+t.direction:"")+" "+t.uri+(t.attributes?" "+t.attributes:"")+`\r
23
- `},e.parseFmtp=function(t){const i={};let s;const r=t.substring(t.indexOf(" ")+1).split(";");for(let a=0;a<r.length;a++)s=r[a].trim().split("="),i[s[0].trim()]=s[1];return i},e.writeFmtp=function(t){let i="",s=t.payloadType;if(t.preferredPayloadType!==void 0&&(s=t.preferredPayloadType),t.parameters&&Object.keys(t.parameters).length){const r=[];Object.keys(t.parameters).forEach(a=>{t.parameters[a]!==void 0?r.push(a+"="+t.parameters[a]):r.push(a)}),i+="a=fmtp:"+s+" "+r.join(";")+`\r
24
- `}return i},e.parseRtcpFb=function(t){const i=t.substring(t.indexOf(" ")+1).split(" ");return{type:i.shift(),parameter:i.join(" ")}},e.writeRtcpFb=function(t){let i="",s=t.payloadType;return t.preferredPayloadType!==void 0&&(s=t.preferredPayloadType),t.rtcpFeedback&&t.rtcpFeedback.length&&t.rtcpFeedback.forEach(r=>{i+="a=rtcp-fb:"+s+" "+r.type+(r.parameter&&r.parameter.length?" "+r.parameter:"")+`\r
25
- `}),i},e.parseSsrcMedia=function(t){const i=t.indexOf(" "),s={ssrc:parseInt(t.substring(7,i),10)},r=t.indexOf(":",i);return r>-1?(s.attribute=t.substring(i+1,r),s.value=t.substring(r+1)):s.attribute=t.substring(i+1),s},e.parseSsrcGroup=function(t){const i=t.substring(13).split(" ");return{semantics:i.shift(),ssrcs:i.map(s=>parseInt(s,10))}},e.getMid=function(t){const i=e.matchPrefix(t,"a=mid:")[0];if(i)return i.substring(6)},e.parseFingerprint=function(t){const i=t.substring(14).split(" ");return{algorithm:i[0].toLowerCase(),value:i[1].toUpperCase()}},e.getDtlsParameters=function(t,i){return{role:"auto",fingerprints:e.matchPrefix(t+i,"a=fingerprint:").map(e.parseFingerprint)}},e.writeDtlsParameters=function(t,i){let s="a=setup:"+i+`\r
26
- `;return t.fingerprints.forEach(r=>{s+="a=fingerprint:"+r.algorithm+" "+r.value+`\r
27
- `}),s},e.parseCryptoLine=function(t){const i=t.substring(9).split(" ");return{tag:parseInt(i[0],10),cryptoSuite:i[1],keyParams:i[2],sessionParams:i.slice(3)}},e.writeCryptoLine=function(t){return"a=crypto:"+t.tag+" "+t.cryptoSuite+" "+(typeof t.keyParams=="object"?e.writeCryptoKeyParams(t.keyParams):t.keyParams)+(t.sessionParams?" "+t.sessionParams.join(" "):"")+`\r
28
- `},e.parseCryptoKeyParams=function(t){if(t.indexOf("inline:")!==0)return null;const i=t.substring(7).split("|");return{keyMethod:"inline",keySalt:i[0],lifeTime:i[1],mkiValue:i[2]?i[2].split(":")[0]:void 0,mkiLength:i[2]?i[2].split(":")[1]:void 0}},e.writeCryptoKeyParams=function(t){return t.keyMethod+":"+t.keySalt+(t.lifeTime?"|"+t.lifeTime:"")+(t.mkiValue&&t.mkiLength?"|"+t.mkiValue+":"+t.mkiLength:"")},e.getCryptoParameters=function(t,i){return e.matchPrefix(t+i,"a=crypto:").map(e.parseCryptoLine)},e.getIceParameters=function(t,i){const s=e.matchPrefix(t+i,"a=ice-ufrag:")[0],r=e.matchPrefix(t+i,"a=ice-pwd:")[0];return s&&r?{usernameFragment:s.substring(12),password:r.substring(10)}:null},e.writeIceParameters=function(t){let i="a=ice-ufrag:"+t.usernameFragment+`\r
29
- a=ice-pwd:`+t.password+`\r
30
- `;return t.iceLite&&(i+=`a=ice-lite\r
31
- `),i},e.parseRtpParameters=function(t){const i={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},r=e.splitLines(t)[0].split(" ");i.profile=r[2];for(let o=3;o<r.length;o++){const c=r[o],d=e.matchPrefix(t,"a=rtpmap:"+c+" ")[0];if(d){const l=e.parseRtpMap(d),u=e.matchPrefix(t,"a=fmtp:"+c+" ");switch(l.parameters=u.length?e.parseFmtp(u[0]):{},l.rtcpFeedback=e.matchPrefix(t,"a=rtcp-fb:"+c+" ").map(e.parseRtcpFb),i.codecs.push(l),l.name.toUpperCase()){case"RED":case"ULPFEC":i.fecMechanisms.push(l.name.toUpperCase());break}}}e.matchPrefix(t,"a=extmap:").forEach(o=>{i.headerExtensions.push(e.parseExtmap(o))});const a=e.matchPrefix(t,"a=rtcp-fb:* ").map(e.parseRtcpFb);return i.codecs.forEach(o=>{a.forEach(c=>{o.rtcpFeedback.find(l=>l.type===c.type&&l.parameter===c.parameter)||o.rtcpFeedback.push(c)})}),i},e.writeRtpDescription=function(t,i){let s="";s+="m="+t+" ",s+=i.codecs.length>0?"9":"0",s+=" "+(i.profile||"UDP/TLS/RTP/SAVPF")+" ",s+=i.codecs.map(a=>a.preferredPayloadType!==void 0?a.preferredPayloadType:a.payloadType).join(" ")+`\r
32
- `,s+=`c=IN IP4 0.0.0.0\r
33
- `,s+=`a=rtcp:9 IN IP4 0.0.0.0\r
34
- `,i.codecs.forEach(a=>{s+=e.writeRtpMap(a),s+=e.writeFmtp(a),s+=e.writeRtcpFb(a)});let r=0;return i.codecs.forEach(a=>{a.maxptime>r&&(r=a.maxptime)}),r>0&&(s+="a=maxptime:"+r+`\r
35
- `),i.headerExtensions&&i.headerExtensions.forEach(a=>{s+=e.writeExtmap(a)}),s},e.parseRtpEncodingParameters=function(t){const i=[],s=e.parseRtpParameters(t),r=s.fecMechanisms.indexOf("RED")!==-1,a=s.fecMechanisms.indexOf("ULPFEC")!==-1,o=e.matchPrefix(t,"a=ssrc:").map(h=>e.parseSsrcMedia(h)).filter(h=>h.attribute==="cname"),c=o.length>0&&o[0].ssrc;let d;const l=e.matchPrefix(t,"a=ssrc-group:FID").map(h=>h.substring(17).split(" ").map(g=>parseInt(g,10)));l.length>0&&l[0].length>1&&l[0][0]===c&&(d=l[0][1]),s.codecs.forEach(h=>{if(h.name.toUpperCase()==="RTX"&&h.parameters.apt){let f={ssrc:c,codecPayloadType:parseInt(h.parameters.apt,10)};c&&d&&(f.rtx={ssrc:d}),i.push(f),r&&(f=JSON.parse(JSON.stringify(f)),f.fec={ssrc:c,mechanism:a?"red+ulpfec":"red"},i.push(f))}}),i.length===0&&c&&i.push({ssrc:c});let u=e.matchPrefix(t,"b=");return u.length&&(u[0].indexOf("b=TIAS:")===0?u=parseInt(u[0].substring(7),10):u[0].indexOf("b=AS:")===0?u=parseInt(u[0].substring(5),10)*1e3*.95-50*40*8:u=void 0,i.forEach(h=>{h.maxBitrate=u})),i},e.parseRtcpParameters=function(t){const i={},s=e.matchPrefix(t,"a=ssrc:").map(o=>e.parseSsrcMedia(o)).filter(o=>o.attribute==="cname")[0];s&&(i.cname=s.value,i.ssrc=s.ssrc);const r=e.matchPrefix(t,"a=rtcp-rsize");i.reducedSize=r.length>0,i.compound=r.length===0;const a=e.matchPrefix(t,"a=rtcp-mux");return i.mux=a.length>0,i},e.writeRtcpParameters=function(t){let i="";return t.reducedSize&&(i+=`a=rtcp-rsize\r
36
- `),t.mux&&(i+=`a=rtcp-mux\r
37
- `),t.ssrc!==void 0&&t.cname&&(i+="a=ssrc:"+t.ssrc+" cname:"+t.cname+`\r
38
- `),i},e.parseMsid=function(t){let i;const s=e.matchPrefix(t,"a=msid:");if(s.length===1)return i=s[0].substring(7).split(" "),{stream:i[0],track:i[1]};const r=e.matchPrefix(t,"a=ssrc:").map(a=>e.parseSsrcMedia(a)).filter(a=>a.attribute==="msid");if(r.length>0)return i=r[0].value.split(" "),{stream:i[0],track:i[1]}},e.parseSctpDescription=function(t){const i=e.parseMLine(t),s=e.matchPrefix(t,"a=max-message-size:");let r;s.length>0&&(r=parseInt(s[0].substring(19),10)),isNaN(r)&&(r=65536);const a=e.matchPrefix(t,"a=sctp-port:");if(a.length>0)return{port:parseInt(a[0].substring(12),10),protocol:i.fmt,maxMessageSize:r};const o=e.matchPrefix(t,"a=sctpmap:");if(o.length>0){const c=o[0].substring(10).split(" ");return{port:parseInt(c[0],10),protocol:c[1],maxMessageSize:r}}},e.writeSctpDescription=function(t,i){let s=[];return t.protocol!=="DTLS/SCTP"?s=["m="+t.kind+" 9 "+t.protocol+" "+i.protocol+`\r
39
- `,`c=IN IP4 0.0.0.0\r
40
- `,"a=sctp-port:"+i.port+`\r
41
- `]:s=["m="+t.kind+" 9 "+t.protocol+" "+i.port+`\r
42
- `,`c=IN IP4 0.0.0.0\r
43
- `,"a=sctpmap:"+i.port+" "+i.protocol+` 65535\r
44
- `],i.maxMessageSize!==void 0&&s.push("a=max-message-size:"+i.maxMessageSize+`\r
45
- `),s.join("")},e.generateSessionId=function(){return Math.random().toString().substr(2,22)},e.writeSessionBoilerplate=function(t,i,s){let r;const a=i!==void 0?i:2;return t?r=t:r=e.generateSessionId(),`v=0\r
46
- o=`+(s||"thisisadapterortc")+" "+r+" "+a+` IN IP4 127.0.0.1\r
47
- s=-\r
48
- t=0 0\r
49
- `},e.getDirection=function(t,i){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 i?e.getDirection(i):"sendrecv"},e.getKind=function(t){return e.splitLines(t)[0].split(" ")[0].substring(2)},e.isRejected=function(t){return t.split(" ",2)[1]==="0"},e.parseMLine=function(t){const 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 i=e.splitLines(t);for(let s=0;s<i.length;s++)if(i[s].length<2||i[s].charAt(1)!=="=")return!1;return!0},n.exports=e}(zs)),zs.exports}var Yo=Nu(),ri=Cu(Yo),Lu=Zd({__proto__:null,default:ri},[Yo]);function On(n){if(!n.RTCIceCandidate||n.RTCIceCandidate&&"foundation"in n.RTCIceCandidate.prototype)return;const e=n.RTCIceCandidate;n.RTCIceCandidate=function(i){if(typeof i=="object"&&i.candidate&&i.candidate.indexOf("a=")===0&&(i=JSON.parse(JSON.stringify(i)),i.candidate=i.candidate.substring(2)),i.candidate&&i.candidate.length){const s=new e(i),r=ri.parseCandidate(i.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(i)},n.RTCIceCandidate.prototype=e.prototype,Ft(n,"icecandidate",t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new n.RTCIceCandidate(t.candidate),writable:"false"}),t))}function Gs(n){!n.RTCIceCandidate||n.RTCIceCandidate&&"relayProtocol"in n.RTCIceCandidate.prototype||Ft(n,"icecandidate",e=>{if(e.candidate){const t=ri.parseCandidate(e.candidate.candidate);t.type==="relay"&&(e.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[t.priority>>24])}return e})}function Dn(n,e){if(!n.RTCPeerConnection)return;"sctp"in n.RTCPeerConnection.prototype||Object.defineProperty(n.RTCPeerConnection.prototype,"sctp",{get(){return typeof this._sctp>"u"?null:this._sctp}});const t=function(o){if(!o||!o.sdp)return!1;const c=ri.splitSections(o.sdp);return c.shift(),c.some(d=>{const l=ri.parseMLine(d);return l&&l.kind==="application"&&l.protocol.indexOf("SCTP")!==-1})},i=function(o){const c=o.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(c===null||c.length<2)return-1;const d=parseInt(c[1],10);return d!==d?-1:d},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 d=65536;e.browser==="firefox"&&e.version===57&&(d=65535);const l=ri.matchPrefix(o.sdp,"a=max-message-size:");return l.length>0?d=parseInt(l[0].substring(19),10):e.browser==="firefox"&&c!==-1&&(d=2147483637),d},a=n.RTCPeerConnection.prototype.setRemoteDescription;n.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=i(arguments[0]),d=s(c),l=r(arguments[0],c);let u;d===0&&l===0?u=Number.POSITIVE_INFINITY:d===0||l===0?u=Math.max(d,l):u=Math.min(d,l);const h={};Object.defineProperty(h,"maxMessageSize",{get(){return u}}),this._sctp=h}return a.apply(this,arguments)}}function Mn(n){if(!(n.RTCPeerConnection&&"createDataChannel"in n.RTCPeerConnection.prototype))return;function e(i,s){const r=i.send;i.send=function(){const o=arguments[0],c=o.length||o.size||o.byteLength;if(i.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(i,arguments)}}const t=n.RTCPeerConnection.prototype.createDataChannel;n.RTCPeerConnection.prototype.createDataChannel=function(){const s=t.apply(this,arguments);return e(s,this),s},Ft(n,"datachannel",i=>(e(i.channel,i.target),i))}function Ws(n){if(!n.RTCPeerConnection||"connectionState"in n.RTCPeerConnection.prototype)return;const e=n.RTCPeerConnection.prototype;Object.defineProperty(e,"connectionState",{get(){return{completed:"connected",checking:"connecting"}[this.iceConnectionState]||this.iceConnectionState},enumerable:!0,configurable:!0}),Object.defineProperty(e,"onconnectionstatechange",{get(){return this._onconnectionstatechange||null},set(t){this._onconnectionstatechange&&(this.removeEventListener("connectionstatechange",this._onconnectionstatechange),delete this._onconnectionstatechange),t&&this.addEventListener("connectionstatechange",this._onconnectionstatechange=t)},enumerable:!0,configurable:!0}),["setLocalDescription","setRemoteDescription"].forEach(t=>{const i=e[t];e[t]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=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)),i.apply(this,arguments)}})}function Ks(n,e){if(!n.RTCPeerConnection||e.browser==="chrome"&&e.version>=71||e.browser==="safari"&&e.version>=605)return;const t=n.RTCPeerConnection.prototype.setRemoteDescription;n.RTCPeerConnection.prototype.setRemoteDescription=function(s){if(s&&s.sdp&&s.sdp.indexOf(`
50
- a=extmap-allow-mixed`)!==-1){const r=s.sdp.split(`
51
- `).filter(a=>a.trim()!=="a=extmap-allow-mixed").join(`
52
- `);n.RTCSessionDescription&&s instanceof n.RTCSessionDescription?arguments[0]=new n.RTCSessionDescription({type:s.type,sdp:r}):s.sdp=r}return t.apply(this,arguments)}}function Nn(n,e){if(!(n.RTCPeerConnection&&n.RTCPeerConnection.prototype))return;const t=n.RTCPeerConnection.prototype.addIceCandidate;!t||t.length===0||(n.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?(e.browser==="chrome"&&e.version<78||e.browser==="firefox"&&e.version<68||e.browser==="safari")&&arguments[0]&&arguments[0].candidate===""?Promise.resolve():t.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}function Ln(n,e){if(!(n.RTCPeerConnection&&n.RTCPeerConnection.prototype))return;const t=n.RTCPeerConnection.prototype.setLocalDescription;!t||t.length===0||(n.RTCPeerConnection.prototype.setLocalDescription=function(){let 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 Uu=Object.freeze({__proto__:null,removeExtmapAllowMixed:Ks,shimAddIceCandidateNullOrEmpty:Nn,shimConnectionState:Ws,shimMaxMessageSize:Dn,shimParameterlessSetLocalDescription:Ln,shimRTCIceCandidate:On,shimRTCIceCandidateRelayProtocol:Gs,shimSendThrowTypeError:Mn});function Fu(){let{window:n}=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=mo,i=Du(n),s={browserDetails:i,commonShim:Uu,extractVersion:An,disableLog:Au,disableWarnings:Ou,sdp:Lu};switch(i.browser){case"chrome":if(!Ro||!Vs||!e.shimChrome)return t("Chrome shim is not included in this adapter release."),s;if(i.version===null)return t("Chrome shim can not determine version, not shimming."),s;t("adapter.js shimming chrome."),s.browserShim=Ro,Nn(n,i),Ln(n),ko(n,i),To(n),Vs(n,i),So(n),wo(n,i),Co(n),_o(n),Po(n,i),On(n),Gs(n),Ws(n),Dn(n,i),Mn(n),Ks(n,i);break;case"firefox":if(!jo||!qs||!e.shimFirefox)return t("Firefox shim is not included in this adapter release."),s;t("adapter.js shimming firefox."),s.browserShim=jo,Nn(n,i),Ln(n),xo(n,i),qs(n,i),Io(n),Do(n),Ao(n),Oo(n),Mo(n),No(n),Lo(n),Uo(n),Fo(n),On(n),Ws(n),Dn(n,i),Mn(n);break;case"safari":if(!Zo||!e.shimSafari)return t("Safari shim is not included in this adapter release."),s;t("adapter.js shimming safari."),s.browserShim=Zo,Nn(n,i),Ln(n),Go(n),Ko(n),Vo(n),$o(n),Bo(n),Wo(n),qo(n),Ho(n),On(n),Gs(n),Dn(n,i),Mn(n),Ks(n,i);break;default:t("Unsupported browser!");break}return s}Fu({window:typeof window>"u"?void 0:window});const ju=10,Un="lk_e2ee",$u={sharedKey:!1,ratchetSalt:"LKFrameEncryptionKey",ratchetWindowSize:8,failureTolerance:ju,keyringSize:16};var kt;(function(n){n.SetKey="setKey",n.RatchetRequest="ratchetRequest",n.KeyRatcheted="keyRatcheted"})(kt||(kt={}));var Qo;(function(n){n.KeyRatcheted="keyRatcheted"})(Qo||(Qo={}));var Tt;(function(n){n.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",n.EncryptionError="encryptionError"})(Tt||(Tt={}));var Xo;(function(n){n.Error="cryptorError"})(Xo||(Xo={}));function Bu(){return Vu()||Hs()}function Hs(){return typeof window.RTCRtpScriptTransform<"u"}function Vu(){return typeof window.RTCRtpSender<"u"&&typeof window.RTCRtpSender.prototype.createEncodedStreams<"u"}class Sm extends Ze.EventEmitter{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};super(),this.onKeyRatcheted=(t,i)=>{G.debug("key ratcheted event received",{material:t,keyIndex:i})},this.keyInfoMap=new Map,this.options=Object.assign(Object.assign({},$u),e),this.on(kt.KeyRatcheted,this.onKeyRatcheted)}onSetEncryptionKey(e,t,i){const s={key:e,participantIdentity:t,keyIndex:i};if(!this.options.sharedKey&&!t)throw new Error("participant identity needs to be passed for encryption key if sharedKey option is false");this.keyInfoMap.set("".concat(t??"shared","-").concat(i??0),s),this.emit(kt.SetKey,s)}getKeys(){return Array.from(this.keyInfoMap.values())}getOptions(){return this.options}ratchetKey(e,t){this.emit(kt.RatchetRequest,e,t)}}class St extends Error{constructor(e,t){super(t||"an error has occured"),this.name="LiveKitError",this.code=e}}var H;(function(n){n[n.NotAllowed=0]="NotAllowed",n[n.ServerUnreachable=1]="ServerUnreachable",n[n.InternalError=2]="InternalError",n[n.Cancelled=3]="Cancelled",n[n.LeaveRequest=4]="LeaveRequest"})(H||(H={}));class te extends St{constructor(e,t,i,s){super(1,e),this.name="ConnectionError",this.status=i,this.reason=t,this.context=s,this.reasonName=H[t]}}class Zs extends St{constructor(e){super(21,e??"device is unsupported"),this.name="DeviceUnsupportedError"}}class nt extends St{constructor(e){super(20,e??"track is invalid"),this.name="TrackInvalidError"}}class qu extends St{constructor(e){super(10,e??"unsupported server"),this.name="UnsupportedServer"}}class fe extends St{constructor(e){super(12,e??"unexpected connection state"),this.name="UnexpectedConnectionState"}}class Js extends St{constructor(e){super(13,e??"unable to negotiate"),this.name="NegotiationError"}}class Ys extends St{constructor(e,t){super(15,e),this.name="PublishTrackError",this.status=t}}class ec extends St{constructor(e,t){super(15,e),this.reason=t,this.reasonName=typeof t=="string"?t:Fs[t]}}var Fn;(function(n){n.PermissionDenied="PermissionDenied",n.NotFound="NotFound",n.DeviceInUse="DeviceInUse",n.Other="Other"})(Fn||(Fn={})),function(n){function e(t){if(t&&"name"in t)return t.name==="NotFoundError"||t.name==="DevicesNotFoundError"?n.NotFound:t.name==="NotAllowedError"||t.name==="PermissionDeniedError"?n.PermissionDenied:t.name==="NotReadableError"||t.name==="TrackStartError"?n.DeviceInUse:n.Other}n.getFailure=e}(Fn||(Fn={}));var tc;(function(n){n[n.InvalidKey=0]="InvalidKey",n[n.MissingKey=1]="MissingKey",n[n.InternalError=2]="InternalError"})(tc||(tc={}));var w;(function(n){n.Connected="connected",n.Reconnecting="reconnecting",n.SignalReconnecting="signalReconnecting",n.Reconnected="reconnected",n.Disconnected="disconnected",n.ConnectionStateChanged="connectionStateChanged",n.MediaDevicesChanged="mediaDevicesChanged",n.ParticipantConnected="participantConnected",n.ParticipantDisconnected="participantDisconnected",n.TrackPublished="trackPublished",n.TrackSubscribed="trackSubscribed",n.TrackSubscriptionFailed="trackSubscriptionFailed",n.TrackUnpublished="trackUnpublished",n.TrackUnsubscribed="trackUnsubscribed",n.TrackMuted="trackMuted",n.TrackUnmuted="trackUnmuted",n.LocalTrackPublished="localTrackPublished",n.LocalTrackUnpublished="localTrackUnpublished",n.LocalAudioSilenceDetected="localAudioSilenceDetected",n.ActiveSpeakersChanged="activeSpeakersChanged",n.ParticipantMetadataChanged="participantMetadataChanged",n.ParticipantNameChanged="participantNameChanged",n.ParticipantAttributesChanged="participantAttributesChanged",n.RoomMetadataChanged="roomMetadataChanged",n.DataReceived="dataReceived",n.SipDTMFReceived="sipDTMFReceived",n.TranscriptionReceived="transcriptionReceived",n.ConnectionQualityChanged="connectionQualityChanged",n.TrackStreamStateChanged="trackStreamStateChanged",n.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",n.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",n.AudioPlaybackStatusChanged="audioPlaybackChanged",n.VideoPlaybackStatusChanged="videoPlaybackChanged",n.MediaDevicesError="mediaDevicesError",n.ParticipantPermissionsChanged="participantPermissionsChanged",n.SignalConnected="signalConnected",n.RecordingStatusChanged="recordingStatusChanged",n.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",n.EncryptionError="encryptionError",n.DCBufferStatusChanged="dcBufferStatusChanged",n.ActiveDeviceChanged="activeDeviceChanged",n.ChatMessage="chatMessage",n.LocalTrackSubscribed="localTrackSubscribed",n.MetricsReceived="metricsReceived"})(w||(w={}));var O;(function(n){n.TrackPublished="trackPublished",n.TrackSubscribed="trackSubscribed",n.TrackSubscriptionFailed="trackSubscriptionFailed",n.TrackUnpublished="trackUnpublished",n.TrackUnsubscribed="trackUnsubscribed",n.TrackMuted="trackMuted",n.TrackUnmuted="trackUnmuted",n.LocalTrackPublished="localTrackPublished",n.LocalTrackUnpublished="localTrackUnpublished",n.ParticipantMetadataChanged="participantMetadataChanged",n.ParticipantNameChanged="participantNameChanged",n.DataReceived="dataReceived",n.SipDTMFReceived="sipDTMFReceived",n.TranscriptionReceived="transcriptionReceived",n.IsSpeakingChanged="isSpeakingChanged",n.ConnectionQualityChanged="connectionQualityChanged",n.TrackStreamStateChanged="trackStreamStateChanged",n.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",n.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",n.MediaDevicesError="mediaDevicesError",n.AudioStreamAcquired="audioStreamAcquired",n.ParticipantPermissionsChanged="participantPermissionsChanged",n.PCTrackAdded="pcTrackAdded",n.AttributesChanged="attributesChanged",n.LocalTrackSubscribed="localTrackSubscribed",n.ChatMessage="chatMessage"})(O||(O={}));var I;(function(n){n.TransportsCreated="transportsCreated",n.Connected="connected",n.Disconnected="disconnected",n.Resuming="resuming",n.Resumed="resumed",n.Restarting="restarting",n.Restarted="restarted",n.SignalResumed="signalResumed",n.SignalRestarted="signalRestarted",n.Closing="closing",n.MediaTrackAdded="mediaTrackAdded",n.ActiveSpeakersUpdate="activeSpeakersUpdate",n.DataPacketReceived="dataPacketReceived",n.RTPVideoMapUpdate="rtpVideoMapUpdate",n.DCBufferStatusChanged="dcBufferStatusChanged",n.ParticipantUpdate="participantUpdate",n.RoomUpdate="roomUpdate",n.SpeakersChanged="speakersChanged",n.StreamStateChanged="streamStateChanged",n.ConnectionQualityUpdate="connectionQualityUpdate",n.SubscriptionError="subscriptionError",n.SubscriptionPermissionUpdate="subscriptionPermissionUpdate",n.RemoteMute="remoteMute",n.SubscribedQualityUpdate="subscribedQualityUpdate",n.LocalTrackUnpublished="localTrackUnpublished",n.LocalTrackSubscribed="localTrackSubscribed",n.Offline="offline",n.SignalRequestResponse="signalRequestResponse",n.SignalConnected="signalConnected"})(I||(I={}));var R;(function(n){n.Message="message",n.Muted="muted",n.Unmuted="unmuted",n.Restarted="restarted",n.Ended="ended",n.Subscribed="subscribed",n.Unsubscribed="unsubscribed",n.UpdateSettings="updateSettings",n.UpdateSubscription="updateSubscription",n.AudioPlaybackStarted="audioPlaybackStarted",n.AudioPlaybackFailed="audioPlaybackFailed",n.AudioSilenceDetected="audioSilenceDetected",n.VisibilityChanged="visibilityChanged",n.VideoDimensionsChanged="videoDimensionsChanged",n.VideoPlaybackStarted="videoPlaybackStarted",n.VideoPlaybackFailed="videoPlaybackFailed",n.ElementAttached="elementAttached",n.ElementDetached="elementDetached",n.UpstreamPaused="upstreamPaused",n.UpstreamResumed="upstreamResumed",n.SubscriptionPermissionChanged="subscriptionPermissionChanged",n.SubscriptionStatusChanged="subscriptionStatusChanged",n.SubscriptionFailed="subscriptionFailed",n.TrackProcessorUpdate="trackProcessorUpdate",n.AudioTrackFeatureUpdate="audioTrackFeatureUpdate",n.TranscriptionReceived="transcriptionReceived",n.TimeSyncUpdate="timeSyncUpdate"})(R||(R={}));function zu(n){return typeof n>"u"?n:typeof structuredClone=="function"?structuredClone(n):JSON.parse(JSON.stringify(n))}const Gu=/version\/(\d+(\.?_?\d+)+)/i;let Qs;function Le(n){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;if(typeof n>"u"&&typeof navigator>"u")return;const t=(n??navigator.userAgent).toLowerCase();if(Qs===void 0||e){const i=Wu.find(s=>{let{test:r}=s;return r.test(t)});Qs=i==null?void 0:i.describe(t)}return Qs}const Wu=[{test:/firefox|iceweasel|fxios/i,describe(n){return{name:"Firefox",version:jn(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,n),os:n.toLowerCase().includes("fxios")?"iOS":void 0,osVersion:Xs(n)}}},{test:/chrom|crios|crmo/i,describe(n){return{name:"Chrome",version:jn(/(?:chrome|chromium|crios|crmo)\/(\d+(\.?_?\d+)+)/i,n),os:n.toLowerCase().includes("crios")?"iOS":void 0,osVersion:Xs(n)}}},{test:/safari|applewebkit/i,describe(n){return{name:"Safari",version:jn(Gu,n),os:n.includes("mobile/")?"iOS":"macOS",osVersion:Xs(n)}}}];function jn(n,e){let t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:1;const i=e.match(n);return i&&i.length>=t&&i[t]||""}function Xs(n){return n.includes("mac os")?jn(/\(.+?(\d+_\d+(:?_\d+)?)/,n,1).replace(/_/g,"."):void 0}var Ku="2.11.4";const Hu=Ku,Zu=15;class ve{}ve.setTimeout=function(){return setTimeout(...arguments)},ve.setInterval=function(){return setInterval(...arguments)},ve.clearTimeout=function(){return clearTimeout(...arguments)},ve.clearInterval=function(){return clearInterval(...arguments)};const Ju=5e3,Mi=[];var Ae;(function(n){n[n.LOW=0]="LOW",n[n.MEDIUM=1]="MEDIUM",n[n.HIGH=2]="HIGH"})(Ae||(Ae={}));class S extends Ze.EventEmitter{constructor(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};var s;super(),this.attachedElements=[],this.isMuted=!1,this.streamState=S.StreamState.Active,this.isInBackground=!1,this._currentBitrate=0,this.log=G,this.appVisibilityChangedListener=()=>{this.backgroundTimeout&&clearTimeout(this.backgroundTimeout),document.visibilityState==="hidden"?this.backgroundTimeout=setTimeout(()=>this.handleAppVisibilityChanged(),Ju):this.handleAppVisibilityChanged()},this.log=it((s=i.loggerName)!==null&&s!==void 0?s:Ne.Track),this.loggerContextCb=i.loggerContextCb,this.setMaxListeners(100),this.kind=t,this._mediaStreamTrack=e,this._mediaStreamID=e.id,this.source=S.Source.Unknown}get logContext(){var e;return Object.assign(Object.assign({},(e=this.loggerContextCb)===null||e===void 0?void 0:e.call(this)),Q(this))}get currentBitrate(){return this._currentBitrate}get mediaStreamTrack(){return this._mediaStreamTrack}get mediaStreamID(){return this._mediaStreamID}attach(e){let t="audio";this.kind===S.Kind.Video&&(t="video"),this.attachedElements.length===0&&this.kind===S.Kind.Video&&this.addAppVisibilityListener(),e||(t==="audio"&&(Mi.forEach(r=>{r.parentElement===null&&!e&&(e=r)}),e&&Mi.splice(Mi.indexOf(e),1)),e||(e=document.createElement(t))),this.attachedElements.includes(e)||this.attachedElements.push(e),ai(this.mediaStreamTrack,e);const i=e.srcObject.getTracks(),s=i.some(r=>r.kind==="audio");return e.play().then(()=>{this.emit(s?R.AudioPlaybackStarted:R.VideoPlaybackStarted)}).catch(r=>{r.name==="NotAllowedError"?this.emit(s?R.AudioPlaybackFailed:R.VideoPlaybackFailed,r):r.name==="AbortError"?G.debug("".concat(s?"audio":"video"," playback aborted, likely due to new play request")):G.warn("could not playback ".concat(s?"audio":"video"),r),s&&e&&i.some(a=>a.kind==="video")&&r.name==="NotAllowedError"&&(e.muted=!0,e.play().catch(()=>{}))}),this.emit(R.ElementAttached,e),e}detach(e){try{if(e){oi(this.mediaStreamTrack,e);const i=this.attachedElements.indexOf(e);return i>=0&&(this.attachedElements.splice(i,1),this.recycleElement(e),this.emit(R.ElementDetached,e)),e}const t=[];return this.attachedElements.forEach(i=>{oi(this.mediaStreamTrack,i),t.push(i),this.recycleElement(i),this.emit(R.ElementDetached,i)}),this.attachedElements=[],t}finally{this.attachedElements.length===0&&this.removeAppVisibilityListener()}}stop(){this.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=it(e.loggerName)),e.loggerContextCb&&(this.loggerContextCb=e.loggerContextCb)}recycleElement(e){if(e instanceof HTMLAudioElement){let t=!0;e.pause(),Mi.forEach(i=>{i.parentElement||(t=!1)}),t&&Mi.push(e)}}handleAppVisibilityChanged(){return p(this,void 0,void 0,function*(){this.isInBackground=document.visibilityState==="hidden",!this.isInBackground&&this.kind===S.Kind.Video&&setTimeout(()=>this.attachedElements.forEach(e=>e.play().catch(()=>{})),0)})}addAppVisibilityListener(){Pe()?(this.isInBackground=document.visibilityState==="hidden",document.addEventListener("visibilitychange",this.appVisibilityChangedListener)):this.isInBackground=!1}removeAppVisibilityListener(){Pe()&&document.removeEventListener("visibilitychange",this.appVisibilityChangedListener)}}function ai(n,e){let t;e.srcObject instanceof MediaStream?t=e.srcObject:t=new MediaStream;let i;n.kind==="audio"?i=t.getAudioTracks():i=t.getVideoTracks(),i.includes(n)||(i.forEach(s=>{t.removeTrack(s)}),t.addTrack(n)),(!Ct()||!(e instanceof HTMLVideoElement))&&(e.autoplay=!0),e.muted=t.getAudioTracks().length===0,e instanceof HTMLVideoElement&&(e.playsInline=!0),e.srcObject!==t&&(e.srcObject=t,(Ct()||ci())&&e instanceof HTMLVideoElement&&setTimeout(()=>{e.srcObject=t,e.play().catch(()=>{})},0))}function oi(n,e){if(e.srcObject instanceof MediaStream){const t=e.srcObject;t.removeTrack(n),t.getTracks().length>0?e.srcObject=t:e.srcObject=null}}(function(n){let e;(function(d){d.Audio="audio",d.Video="video",d.Unknown="unknown"})(e=n.Kind||(n.Kind={}));let t;(function(d){d.Camera="camera",d.Microphone="microphone",d.ScreenShare="screen_share",d.ScreenShareAudio="screen_share_audio",d.Unknown="unknown"})(t=n.Source||(n.Source={}));let i;(function(d){d.Active="active",d.Paused="paused",d.Unknown="unknown"})(i=n.StreamState||(n.StreamState={}));function s(d){switch(d){case e.Audio:return Oe.AUDIO;case e.Video:return Oe.VIDEO;default:return Oe.DATA}}n.kindToProto=s;function r(d){switch(d){case Oe.AUDIO:return e.Audio;case Oe.VIDEO:return e.Video;default:return e.Unknown}}n.kindFromProto=r;function a(d){switch(d){case t.Camera:return ue.CAMERA;case t.Microphone:return ue.MICROPHONE;case t.ScreenShare:return ue.SCREEN_SHARE;case t.ScreenShareAudio:return ue.SCREEN_SHARE_AUDIO;default:return ue.UNKNOWN}}n.sourceToProto=a;function o(d){switch(d){case ue.CAMERA:return t.Camera;case ue.MICROPHONE:return t.Microphone;case ue.SCREEN_SHARE:return t.ScreenShare;case ue.SCREEN_SHARE_AUDIO:return t.ScreenShareAudio;default:return t.Unknown}}n.sourceFromProto=o;function c(d){switch(d){case As.ACTIVE:return i.Active;case As.PAUSED:return i.Paused;default:return i.Unknown}}n.streamStateFromProto=c})(S||(S={}));class X{constructor(e,t,i,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&&i!==void 0)this.width=e,this.height=t,this.aspectRatio=e/t,this.encoding={maxBitrate:i,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 Yu=["vp8","h264"],Qu=["vp8","h264","vp9","av1"];function Xu(n){return!!Yu.find(e=>e===n)}var ic;(function(n){n[n.PREFER_REGRESSION=0]="PREFER_REGRESSION",n[n.SIMULCAST=1]="SIMULCAST",n[n.REGRESSION=2]="REGRESSION"})(ic||(ic={}));var er;(function(n){n.telephone={maxBitrate:12e3},n.speech={maxBitrate:24e3},n.music={maxBitrate:48e3},n.musicStereo={maxBitrate:64e3},n.musicHighQuality={maxBitrate:96e3},n.musicHighQualityStereo={maxBitrate:128e3}})(er||(er={}));const Ni={h90:new X(160,90,9e4,20),h180:new X(320,180,16e4,20),h216:new X(384,216,18e4,20),h360:new X(640,360,45e4,20),h540:new X(960,540,8e5,25),h720:new X(1280,720,17e5,30),h1080:new X(1920,1080,3e6,30),h1440:new X(2560,1440,5e6,30),h2160:new X(3840,2160,8e6,30)},tr={h120:new X(160,120,7e4,20),h180:new X(240,180,125e3,20),h240:new X(320,240,14e4,20),h360:new X(480,360,33e4,20),h480:new X(640,480,5e5,20),h540:new X(720,540,6e5,25),h720:new X(960,720,13e5,30),h1080:new X(1440,1080,23e5,30),h1440:new X(1920,1440,38e5,30)},ir={h360fps3:new X(640,360,2e5,3,"medium"),h360fps15:new X(640,360,4e5,15,"medium"),h720fps5:new X(1280,720,8e5,5,"medium"),h720fps15:new X(1280,720,15e5,15,"medium"),h720fps30:new X(1280,720,2e6,30,"medium"),h1080fps15:new X(1920,1080,25e5,15,"medium"),h1080fps30:new X(1920,1080,5e6,30,"medium"),original:new X(0,0,7e6,30,"medium")},eh="|",nc="https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension";function th(n){const e=n.split(eh);return e.length>1?[e[0],n.substr(e[0].length+1)]:[n,""]}function we(n){return p(this,void 0,void 0,function*(){return new Promise(e=>ve.setTimeout(e,n))})}function nr(){return"addTransceiver"in RTCPeerConnection.prototype}function sr(){return"addTrack"in RTCPeerConnection.prototype}function ih(){if(!("getCapabilities"in RTCRtpSender)||Ct())return!1;const n=RTCRtpSender.getCapabilities("video");let e=!1;if(n){for(const t of n.codecs)if(t.mimeType==="video/AV1"){e=!0;break}}return e}function nh(){if(!("getCapabilities"in RTCRtpSender)||ci())return!1;if(Ct()){const t=Le();if(t!=null&&t.version&&jt(t.version,"16")<0)return!1}const n=RTCRtpSender.getCapabilities("video");let e=!1;if(n){for(const t of n.codecs)if(t.mimeType==="video/VP9"){e=!0;break}}return e}function Li(n){return n==="av1"||n==="vp9"}function rr(n){return document?(n||(n=document.createElement("audio")),"setSinkId"in n):!1}function sh(){return typeof RTCPeerConnection>"u"?!1:nr()||sr()}function ci(){var n;return((n=Le())===null||n===void 0?void 0:n.name)==="Firefox"}function Ct(){var n;return((n=Le())===null||n===void 0?void 0:n.name)==="Safari"}function rh(){const n=Le();return(n==null?void 0:n.name)==="Safari"&&n.version.startsWith("17.")}function sc(){var n,e;return Pe()?(e=(n=navigator.userAgentData)===null||n===void 0?void 0:n.mobile)!==null&&e!==void 0?e:/Tablet|iPad|Mobile|Android|BlackBerry/.test(navigator.userAgent):!1}function ah(){const n=Le(),e="17.2";if(n)return n.name!=="Safari"&&n.os!=="iOS"||n.os==="iOS"&&n.osVersion&&jt(e,n.osVersion)>=0?!0:n.name==="Safari"&&jt(e,n.version)>=0}function Pe(){return typeof document<"u"}function Je(){return navigator.product=="ReactNative"}function ar(n){return n.hostname.endsWith(".livekit.cloud")||n.hostname.endsWith(".livekit.run")}function rc(){if(global&&global.LiveKitReactNativeGlobal)return global.LiveKitReactNativeGlobal}function ac(){if(!Je())return;let n=rc();if(n)return n.platform}function oc(){if(Pe())return window.devicePixelRatio;if(Je()){let n=rc();if(n)return n.devicePixelRatio}return 1}function jt(n,e){const t=n.split("."),i=e.split("."),s=Math.min(t.length,i.length);for(let r=0;r<s;++r){const a=parseInt(t[r],10),o=parseInt(i[r],10);if(a>o)return 1;if(a<o)return-1;if(r===s-1&&a===o)return 0}return n===""&&e!==""?-1:e===""?1:t.length==i.length?0:t.length<i.length?-1:1}function oh(n){for(const e of n)e.target.handleResize(e)}function ch(n){for(const e of n)e.target.handleVisibilityChanged(e)}let or=null;const cc=()=>(or||(or=new ResizeObserver(oh)),or);let cr=null;const dc=()=>(cr||(cr=new IntersectionObserver(ch,{root:null,rootMargin:"0px"})),cr);function dh(){var n;const e=new Xl({sdk:Wa.JS,protocol:Zu,version:Hu});return Je()&&(e.os=(n=ac())!==null&&n!==void 0?n:""),e}function lc(){let n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:16,e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:16,t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1,i=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1;const s=document.createElement("canvas");s.width=n,s.height=e;const r=s.getContext("2d");r==null||r.fillRect(0,0,s.width,s.height),i&&r&&(r.beginPath(),r.arc(n/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 Ui;function dr(){if(!Ui){const n=new AudioContext,e=n.createOscillator(),t=n.createGain();t.gain.setValueAtTime(0,0);const i=n.createMediaStreamDestination();if(e.connect(t),t.connect(i),e.start(),[Ui]=i.stream.getAudioTracks(),!Ui)throw Error("Could not get empty media stream audio track");Ui.enabled=!1}return Ui.clone()}class uc{constructor(e,t){this.onFinally=t,this.promise=new Promise((i,s)=>p(this,void 0,void 0,function*(){this.resolve=i,this.reject=s,e&&(yield e(i,s))})).finally(()=>{var i;return(i=this.onFinally)===null||i===void 0?void 0:i.call(this)})}}function lh(n){return Qu.includes(n)}function _t(n){if(typeof n=="string"||typeof n=="number")return n;if(Array.isArray(n))return n[0];if(n.exact)return Array.isArray(n.exact)?n.exact[0]:n.exact;if(n.ideal)return Array.isArray(n.ideal)?n.ideal[0]:n.ideal;throw Error("could not unwrap constraint")}function uh(n){return n.startsWith("http")?n.replace(/^(http)/,"ws"):n}function lr(n){return n.startsWith("ws")?n.replace(/^(ws)/,"http"):n}function hh(n,e){return n.segments.map(t=>{let{id:i,text:s,language:r,startTime:a,endTime:o,final:c}=t;var d;const l=(d=e.get(i))!==null&&d!==void 0?d:Date.now(),u=Date.now();return c?e.delete(i):e.set(i,l),{id:i,text:s,startTime:Number.parseInt(a.toString()),endTime:Number.parseInt(o.toString()),final:c,language:r,firstReceivedTime:l,lastReceivedTime:u}})}function fh(n){const{id:e,timestamp:t,message:i,editTimestamp:s}=n;return{id:e,timestamp:Number.parseInt(t.toString()),editTimestamp:s?Number.parseInt(s.toString()):void 0,message:i}}function hc(n){switch(n.reason){case H.LeaveRequest:return n.context;case H.Cancelled:return De.CLIENT_INITIATED;case H.NotAllowed:return De.USER_REJECTED;case H.ServerUnreachable:return De.JOIN_FAILURE;default:return De.UNKNOWN_REASON}}function $n(n){return n!==void 0?Number(n):void 0}function $t(n){return n!==void 0?BigInt(n):void 0}function di(n){return!!n&&!(n instanceof MediaStreamTrack)&&n.isLocal}function st(n){return!!n&&n.kind==S.Kind.Audio}function li(n){return!!n&&n.kind==S.Kind.Video}function Et(n){return di(n)&&li(n)}function Bt(n){return di(n)&&st(n)}function ur(n){return!!n&&!n.isLocal}function ph(n){return!!n&&!n.isLocal}function hr(n){return ur(n)&&li(n)}function mh(n){return n.isLocal}function gh(n,e){const t=[];let i=new TextEncoder().encode(n);for(;i.length>e;){let s=e;for(;s>0;){const r=i[s];if(r!==void 0&&(r&192)!==128)break;s--}t.push(i.slice(0,s)),i=i.slice(s)}return i.length>0&&t.push(i),t}function fc(n,e,t){var i,s,r,a;const{optionsWithoutProcessor:o,audioProcessor:c,videoProcessor:d}=vc(n??{}),l=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&&(fr(h.audio,e),(i=(r=h.audio).deviceId)!==null&&i!==void 0||(r.deviceId={ideal:"default"}),(c||l)&&(h.audio.processor=c??l)),h.video&&(fr(h.video,t),(s=(a=h.video).deviceId)!==null&&s!==void 0||(a.deviceId={ideal:"default"}),(d||u)&&(h.video.processor=d??u)),h}function fr(n,e){return Object.keys(e).forEach(t=>{n[t]===void 0&&(n[t]=e[t])}),n}function pr(n){var e,t,i,s;const r={};if(n.video)if(typeof n.video=="object"){const a={},o=a,c=n.video;Object.keys(c).forEach(d=>{switch(d){case"resolution":fr(o,c.resolution);break;default:o[d]=c[d]}}),r.video=a,(e=(i=r.video).deviceId)!==null&&e!==void 0||(i.deviceId={ideal:"default"})}else r.video=n.video?{deviceId:{ideal:"default"}}:!1;else r.video=!1;return n.audio?typeof n.audio=="object"?(r.audio=n.audio,(t=(s=r.audio).deviceId)!==null&&t!==void 0||(s.deviceId={ideal:"default"})):r.audio={deviceId:{ideal:"default"}}:r.audio=!1,r}function pc(n){return p(this,arguments,void 0,function(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:200;return function*(){const i=mc();if(i){const s=i.createAnalyser();s.fftSize=2048;const r=s.frequencyBinCount,a=new Uint8Array(r);i.createMediaStreamSource(new MediaStream([e.mediaStreamTrack])).connect(s),yield we(t),s.getByteTimeDomainData(a);const c=a.some(d=>d!==128&&d!==0);return i.close(),!c}return!1}()})}function mc(){var n;const e=typeof window<"u"&&(window.AudioContext||window.webkitAudioContext);if(e){const t=new e({latencyHint:"interactive"});if(t.state==="suspended"&&typeof window<"u"&&(!((n=window.document)===null||n===void 0)&&n.body)){const i=()=>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",i)});window.document.body.addEventListener("click",i)}return t}}function vh(n){return n==="audioinput"?S.Source.Microphone:n==="videoinput"?S.Source.Camera:S.Source.Unknown}function gc(n){return n===S.Source.Microphone?"audioinput":n===S.Source.Camera?"videoinput":void 0}function yh(n){var e,t;let i=(e=n.video)!==null&&e!==void 0?e:!0;return n.resolution&&n.resolution.width>0&&n.resolution.height>0&&(i=typeof i=="boolean"?{}:i,Ct()?i=Object.assign(Object.assign({},i),{width:{max:n.resolution.width},height:{max:n.resolution.height},frameRate:n.resolution.frameRate}):i=Object.assign(Object.assign({},i),{width:{ideal:n.resolution.width},height:{ideal:n.resolution.height},frameRate:n.resolution.frameRate})),{audio:(t=n.audio)!==null&&t!==void 0?t:!1,video:i,controller:n.controller,selfBrowserSurface:n.selfBrowserSurface,surfaceSwitching:n.surfaceSwitching,systemAudio:n.systemAudio,preferCurrentTab:n.preferCurrentTab}}function Bn(n){return n.split("/")[1].toLowerCase()}function bh(n){const e=[];return n.forEach(t=>{t.track!==void 0&&e.push(new Ls({cid:t.track.mediaStreamID,track:t.trackInfo}))}),e}function Q(n){return"mediaStreamTrack"in n?{trackID:n.sid,source:n.source,muted:n.isMuted,enabled:n.mediaStreamTrack.enabled,kind:n.kind,streamID:n.mediaStreamID,streamTrackID:n.mediaStreamTrack.id}:{trackID:n.trackSid,enabled:n.isEnabled,muted:n.isMuted,trackInfo:Object.assign({mimeType:n.mimeType,name:n.trackName,encrypted:n.isEncrypted,kind:n.kind,source:n.source},n.track?Q(n.track):{})}}function kh(){return typeof RTCRtpReceiver<"u"&&"getSynchronizationSources"in RTCRtpReceiver}function Th(n,e){var t;n===void 0&&(n={}),e===void 0&&(e={});const i=[...Object.keys(e),...Object.keys(n)],s={};for(const r of i)n[r]!==e[r]&&(s[r]=(t=e[r])!==null&&t!==void 0?t:"");return s}function vc(n){const e=Object.assign({},n);let t,i;return typeof e.audio=="object"&&e.audio.processor&&(t=e.audio.processor,e.audio=Object.assign(Object.assign({},e.audio),{processor:void 0})),typeof e.video=="object"&&e.video.processor&&(i=e.video.processor,e.video=Object.assign(Object.assign({},e.video),{processor:void 0})),{audioProcessor:t,videoProcessor:i,optionsWithoutProcessor:zu(e)}}function Sh(n){switch(n){case ue.CAMERA:return S.Source.Camera;case ue.MICROPHONE:return S.Source.Microphone;case ue.SCREEN_SHARE:return S.Source.ScreenShare;case ue.SCREEN_SHARE_AUDIO:return S.Source.ScreenShareAudio;default:return S.Source.Unknown}}class Ch extends Ze.EventEmitter{constructor(e){super(),this.onWorkerMessage=t=>{var i,s;const{kind:r,data:a}=t.data;switch(r){case"error":G.error(a.error.message),this.emit(Tt.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===((i=this.room)===null||i===void 0?void 0:i.localParticipant.identity))this.emit(Tt.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(Tt.ParticipantEncryptionStatusChanged,a.enabled,o)}break;case"ratchetKey":this.keyProvider.emit(kt.KeyRatcheted,a.material,a.keyIndex);break}},this.onWorkerError=t=>{G.error("e2ee worker encountered an error:",{error:t.error}),this.emit(Tt.EncryptionError,t.error)},this.keyProvider=e.keyProvider,this.worker=e.worker,this.encryptionEnabled=!1}setup(e){if(!Bu())throw new Zs("tried to setup end-to-end encryption on an unsupported browser");if(G.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:wu.getLevel()}};this.worker&&(G.info("initializing worker",{worker:this.worker}),this.worker.onmessage=this.onWorkerMessage,this.worker.onerror=this.onWorkerError,this.worker.postMessage(t))}}setParticipantCryptorEnabled(e,t){G.debug("set e2ee to ".concat(e," for participant ").concat(t)),this.postEnable(e,t)}setSifTrailer(e){!e||e.length===0?G.warn("ignoring server sent trailer as it's empty"):this.postSifTrailer(e)}setupEngine(e){e.on(I.RTPVideoMapUpdate,t=>{this.postRTPMap(t)})}setupEventListeners(e,t){e.on(w.TrackPublished,(i,s)=>this.setParticipantCryptorEnabled(i.trackInfo.encryption!==xe.NONE,s.identity)),e.on(w.ConnectionStateChanged,i=>{i===Y.Connected&&e.remoteParticipants.forEach(s=>{s.trackPublications.forEach(r=>{this.setParticipantCryptorEnabled(r.trackInfo.encryption!==xe.NONE,s.identity)})})}).on(w.TrackUnsubscribed,(i,s,r)=>{var a;const o={kind:"removeTransform",data:{participantIdentity:r.identity,trackId:i.mediaStreamID}};(a=this.worker)===null||a===void 0||a.postMessage(o)}).on(w.TrackSubscribed,(i,s,r)=>{this.setupE2EEReceiver(i,r.identity,s.trackInfo)}).on(w.SignalConnected,()=>{if(!this.room)throw new TypeError("expected room to be present on signal connect");t.getKeys().forEach(i=>{this.postKey(i)}),this.setParticipantCryptorEnabled(this.room.localParticipant.isE2EEEnabled,this.room.localParticipant.identity)}),e.localParticipant.on(O.LocalTrackPublished,i=>p(this,void 0,void 0,function*(){this.setupE2EESender(i.track,i.track.sender)})),t.on(kt.SetKey,i=>this.postKey(i)).on(kt.RatchetRequest,(i,s)=>this.postRatchetRequest(i,s))}postRatchetRequest(e,t){if(!this.worker)throw Error("could not ratchet key, worker is missing");const i={kind:"ratchetRequest",data:{participantIdentity:e,keyIndex:t}};this.worker.postMessage(i)}postKey(e){let{key:t,participantIdentity:i,keyIndex:s}=e;var r;if(!this.worker)throw Error("could not set key, worker is missing");const a={kind:"setKey",data:{participantIdentity:i,isPublisher:i===((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 i={kind:"enable",data:{enabled:e,participantIdentity:t}};this.worker.postMessage(i)}else throw new ReferenceError("failed to enable e2ee, worker is not ready")}postRTPMap(e){var t;if(!this.worker)throw TypeError("could not post rtp map, worker is missing");if(!(!((t=this.room)===null||t===void 0)&&t.localParticipant.identity))throw TypeError("could not post rtp map, local participant identity is missing");const i={kind:"setRTPMap",data:{map:e,participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(i)}postSifTrailer(e){if(!this.worker)throw Error("could not post SIF trailer, worker is missing");const t={kind:"setSifTrailer",data:{trailer:e}};this.worker.postMessage(t)}setupE2EEReceiver(e,t,i){if(e.receiver){if(!(i!=null&&i.mimeType)||i.mimeType==="")throw new TypeError("MimeType missing from trackInfo, cannot set up E2EE cryptor");this.handleReceiver(e.receiver,e.mediaStreamID,t,e.kind==="video"?Bn(i.mimeType):void 0)}}setupE2EESender(e,t){if(!di(e)||!t){t||G.warn("early return because sender is not ready");return}this.handleSender(t,e.mediaStreamID,void 0)}handleReceiver(e,t,i,s){return p(this,void 0,void 0,function*(){if(this.worker){if(Hs()){const r={kind:"decode",participantIdentity:i,trackId:t,codec:s};e.transform=new RTCRtpScriptTransform(this.worker,r)}else{if(Un in e&&s){const c={kind:"updateCodec",data:{trackId:t,codec:s,participantIdentity:i}};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:i}};this.worker.postMessage(o,[a,r])}e[Un]=!0}})}handleSender(e,t,i){var s;if(!(Un in e||!this.worker)){if(!(!((s=this.room)===null||s===void 0)&&s.localParticipant.identity)||this.room.localParticipant.identity==="")throw TypeError("local identity needs to be known in order to set up encrypted sender");if(Hs()){G.info("initialize script transform");const r={kind:"encode",participantIdentity:this.room.localParticipant.identity,trackId:t,codec:i};e.transform=new RTCRtpScriptTransform(this.worker,r)}else{G.info("initialize encoded streams");const r=e.createEncodedStreams(),a={kind:"encode",data:{readableStream:r.readable,writableStream:r.writable,codec:i,trackId:t,participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(a,[r.readable,r.writable])}e[Un]=!0}}}const mr="default";class pe{constructor(){this._previousDevices=[]}static getInstance(){return this.instance===void 0&&(this.instance=new pe),this.instance}get previousDevices(){return this._previousDevices}getDevices(e){return p(this,arguments,void 0,function(t){var i=this;let s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){var r;if(((r=pe.userMediaPromiseMap)===null||r===void 0?void 0:r.size)>0){G.debug("awaiting getUserMedia promise");try{t?yield pe.userMediaPromiseMap.get(t):yield Promise.all(pe.userMediaPromiseMap.values())}catch{G.warn("error waiting for media permissons")}}let a=yield navigator.mediaDevices.enumerateDevices();if(s&&!(Ct()&&i.hasDeviceInUse(t))&&(a.filter(c=>c.kind===t).length===0||a.some(c=>{const d=c.label==="",l=t?c.kind===t:!0;return d&&l}))){const c={video:t!=="audioinput"&&t!=="audiooutput",audio:t!=="videoinput"&&{deviceId:{ideal:"default"}}},d=yield navigator.mediaDevices.getUserMedia(c);a=yield navigator.mediaDevices.enumerateDevices(),d.getTracks().forEach(l=>{l.stop()})}return i._previousDevices=a,t&&(a=a.filter(o=>o.kind===t)),a}()})}normalizeDeviceId(e,t,i){return p(this,void 0,void 0,function*(){if(t!==mr)return t;const s=yield this.getDevices(e),r=s.find(o=>o.deviceId===mr);if(!r){G.warn("could not reliably determine default device");return}const a=s.find(o=>o.deviceId!==mr&&o.groupId===(i??r.groupId));if(!a){G.warn("could not reliably determine default device");return}return a==null?void 0:a.deviceId})}hasDeviceInUse(e){return e?pe.userMediaPromiseMap.has(e):pe.userMediaPromiseMap.size>0}}pe.mediaDeviceKinds=["audioinput","audiooutput","videoinput"],pe.userMediaPromiseMap=new Map;var Fi;(function(n){n[n.WAITING=0]="WAITING",n[n.RUNNING=1]="RUNNING",n[n.COMPLETED=2]="COMPLETED"})(Fi||(Fi={}));class _h{constructor(){this.pendingTasks=new Map,this.taskMutex=new Ce,this.nextTaskIndex=0}run(e){return p(this,void 0,void 0,function*(){const t={id:this.nextTaskIndex++,enqueuedAt:Date.now(),status:Fi.WAITING};this.pendingTasks.set(t.id,t);const i=yield this.taskMutex.lock();try{return t.executedAt=Date.now(),t.status=Fi.RUNNING,yield e()}finally{t.status=Fi.COMPLETED,this.pendingTasks.delete(t.id),i()}})}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 Eh(n,e){const t=new URL(uh(n));return e.forEach((i,s)=>{t.searchParams.set(s,i)}),yc(t,"rtc")}function wh(n){const e=new URL(lr(n));return yc(e,"validate")}function Ph(n){return n.endsWith("/")?n:"".concat(n,"/")}function yc(n,e){return n.pathname="".concat(Ph(n.pathname)).concat(e),n.toString()}const Rh=["syncState","trickle","offer","answer","simulate","leave"];function xh(n){const e=Rh.indexOf(n.case)>=0;return G.trace("request allowed to bypass queue:",{canPass:e,req:n}),e}var ne;(function(n){n[n.CONNECTING=0]="CONNECTING",n[n.CONNECTED=1]="CONNECTED",n[n.RECONNECTING=2]="RECONNECTING",n[n.DISCONNECTING=3]="DISCONNECTING",n[n.DISCONNECTED=4]="DISCONNECTED"})(ne||(ne={}));class gr{get currentState(){return this.state}get isDisconnected(){return this.state===ne.DISCONNECTING||this.state===ne.DISCONNECTED}get isEstablishingConnection(){return this.state===ne.CONNECTING||this.state===ne.RECONNECTING}getNextRequestId(){return this._requestId+=1,this._requestId}constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1,t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};var i;this.rtt=0,this.state=ne.DISCONNECTED,this.log=G,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=it((i=t.loggerName)!==null&&i!==void 0?i:Ne.Signal),this.loggerContextCb=t.loggerContextCb,this.useJSON=e,this.requestQueue=new _h,this.queuedRequests=[],this.closingLock=new Ce,this.connectionLock=new Ce,this.state=ne.DISCONNECTED}get logContext(){var e,t;return(t=(e=this.loggerContextCb)===null||e===void 0?void 0:e.call(this))!==null&&t!==void 0?t:{}}join(e,t,i,s){return p(this,void 0,void 0,function*(){return this.state=ne.CONNECTING,this.options=i,yield this.connect(e,t,i,s)})}reconnect(e,t,i,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=ne.RECONNECTING,this.clearPingInterval(),yield this.connect(e,t,Object.assign(Object.assign({},this.options),{reconnect:!0,sid:i,reconnectReason:s}))})}connect(e,t,i,s){this.connectOptions=i;const r=dh(),a=Ih(t,r,i),o=Eh(e,a),c=wh(o);return new Promise((d,l)=>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),l(new te("room connection has been cancelled (signal)",H.Cancelled))}),f=setTimeout(()=>{this.close(),l(new te("room connection has timed out (signal)",H.ServerUnreachable))},i.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:i.reconnect,reconnectReason:i.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=m=>p(this,void 0,void 0,function*(){if(this.state!==ne.CONNECTED){this.state=ne.DISCONNECTED,clearTimeout(f);try{const v=yield fetch(c);if(v.status.toFixed(0).startsWith("4")){const T=yield v.text();l(new te(T,H.NotAllowed,v.status))}else l(new te("Encountered unknown websocket error during connection: ".concat(m.toString()),H.InternalError,v.status))}catch(v){l(new te(v instanceof Error?v.message:"server was not reachable",H.ServerUnreachable))}return}this.handleWSError(m)}),this.ws.onmessage=m=>p(this,void 0,void 0,function*(){var v,T,x;let P;if(typeof m.data=="string"){const y=JSON.parse(m.data);P=Qa.fromJson(y,{ignoreUnknownFields:!0})}else if(m.data instanceof ArrayBuffer)P=Qa.fromBinary(new Uint8Array(m.data));else{this.log.error("could not decode websocket message: ".concat(typeof m.data),this.logContext);return}if(this.state!==ne.CONNECTED){let y=!1;if(((v=P.message)===null||v===void 0?void 0:v.case)==="join"?(this.state=ne.CONNECTED,s==null||s.removeEventListener("abort",h),this.pingTimeoutDuration=P.message.value.pingTimeout,this.pingIntervalDuration=P.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()),d(P.message.value)):this.state===ne.RECONNECTING&&P.message.case!=="leave"?(this.state=ne.CONNECTED,s==null||s.removeEventListener("abort",h),this.startPingInterval(),((T=P.message)===null||T===void 0?void 0:T.case)==="reconnect"?d(P.message.value):(this.log.debug("declaring signal reconnected without reconnect response received",this.logContext),d(void 0),y=!0)):this.isEstablishingConnection&&P.message.case==="leave"?l(new te("Received leave request while trying to (re)connect",H.LeaveRequest,void 0,P.message.value.reason)):i.reconnect||l(new te("did not receive join response, got ".concat((x=P.message)===null||x===void 0?void 0:x.case," instead"),H.InternalError)),!y)return}this.signalLatency&&(yield we(this.signalLatency)),this.handleSignalResponse(P)}),this.ws.onclose=m=>{this.isEstablishingConnection&&l(new te("Websocket got closed during a (re)connection attempt",H.InternalError)),this.log.warn("websocket closed",Object.assign(Object.assign({},this.logContext),{reason:m.reason,code:m.code,wasClean:m.wasClean,state:this.state})),this.handleOnClose(m.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 i=yield e.closingLock.lock();try{if(e.clearPingInterval(),t&&(e.state=ne.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,we(250)])),e.ws=void 0}}finally{t&&(e.state=ne.DISCONNECTED),i()}}()})}sendOffer(e){this.log.debug("sending offer",Object.assign(Object.assign({},this.logContext),{offerSdp:e.sdp})),this.sendRequest({case:"offer",value:Vn(e)})}sendAnswer(e){return this.log.debug("sending answer",Object.assign(Object.assign({},this.logContext),{answerSdp:e.sdp})),this.sendRequest({case:"answer",value:Vn(e)})}sendIceCandidate(e,t){return this.log.debug("sending ice candidate",Object.assign(Object.assign({},this.logContext),{candidate:e})),this.sendRequest({case:"trickle",value:new Ms({candidateInit:JSON.stringify(e),target:t})})}sendMuteTrack(e,t){return this.sendRequest({case:"mute",value:new Ns({sid:e,muted:t})})}sendAddTrack(e){return this.sendRequest({case:"addTrack",value:e})}sendUpdateLocalMetadata(e,t){return p(this,arguments,void 0,function(i,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 io({requestId:o,metadata:i,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 to({trackSid:e,layers:t})})}sendUpdateSubscriptionPermissions(e,t){return this.sendRequest({case:"subscriptionPermission",value:new ro({allParticipants:e,trackPermissions:t})})}sendSimulateScenario(e){return this.sendRequest({case:"simulate",value:e})}sendPing(){return Promise.all([this.sendRequest({case:"ping",value:se.parse(Date.now())}),this.sendRequest({case:"pingReq",value:new co({timestamp:se.parse(Date.now()),rtt:se.parse(this.rtt)})})])}sendUpdateLocalAudioTrack(e,t){return this.sendRequest({case:"updateAudioTrack",value:new eo({trackSid:e,features:t})})}sendLeave(){return this.sendRequest({case:"leave",value:new Pn({reason:De.CLIENT_INITIATED,action:si.DISCONNECT})})}sendRequest(e){return p(this,arguments,void 0,function(t){var i=this;let s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1;return function*(){if(!s&&!xh(t)&&i.state===ne.RECONNECTING){i.queuedRequests.push(()=>p(i,void 0,void 0,function*(){yield this.sendRequest(t,!0)}));return}if(s||(yield i.requestQueue.flush()),i.signalLatency&&(yield we(i.signalLatency)),!i.ws||i.ws.readyState!==i.ws.OPEN){i.log.error("cannot send signal request before connected, type: ".concat(t==null?void 0:t.case),i.logContext);return}const a=new iu({message:t});try{i.useJSON?i.ws.send(a.toJsonString()):i.ws.send(a.toBinary())}catch(o){i.log.error("error sending signal message",Object.assign(Object.assign({},i.logContext),{error:o}))}}()})}handleSignalResponse(e){var t,i;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=bc(s.value);this.onAnswer&&this.onAnswer(a)}else if(s.case==="offer"){const a=bc(s.value);this.onOffer&&this.onOffer(a)}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((i=s.value.speakers)!==null&&i!==void 0?i:[]):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):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===ne.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=ve.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&&ve.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=ve.setInterval(()=>{this.sendPing()},this.pingIntervalDuration*1e3)}clearPingInterval(){this.log.debug("clearing ping interval",this.logContext),this.clearPingTimeout(),this.pingInterval&&ve.clearInterval(this.pingInterval)}}function bc(n){const e={type:"offer",sdp:n.sdp};switch(n.type){case"answer":case"offer":case"pranswer":case"rollback":e.type=n.type;break}return e}function Vn(n){return new Ut({sdp:n.sdp,type:n.type})}function Ih(n,e,t){var i;const s=new URLSearchParams;return s.set("access_token",n),t.reconnect&&(s.set("reconnect","1"),t.sid&&s.set("sid",t.sid)),s.set("auto_subscribe",t.autoSubscribe?"1":"0"),s.set("sdk",Je()?"reactnative":"js"),s.set("version",e.version),s.set("protocol",e.protocol.toString()),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()),!((i=navigator.connection)===null||i===void 0)&&i.type&&s.set("network",navigator.connection.type),s}var Ue={},vr={},yr={exports:{}},kc;function br(){if(kc)return yr.exports;kc=1;var n=yr.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(n).forEach(function(e){var t=n[e];t.forEach(function(i){i.reg||(i.reg=/(.*)/),i.format||(i.format="%s")})}),yr.exports}var Tc;function Ah(){return Tc||(Tc=1,function(n){var e=function(o){return String(Number(o))===o?Number(o):o},t=function(o,c,d,l){if(l&&!d)c[l]=e(o[1]);else for(var u=0;u<d.length;u+=1)o[u+1]!=null&&(c[d[u]]=e(o[u+1]))},i=function(o,c,d){var l=o.name&&o.names;o.push&&!c[o.push]?c[o.push]=[]:l&&!c[o.name]&&(c[o.name]={});var u=o.push?{}:l?c[o.name]:c;t(d.match(o.reg),u,o.names,o.name),o.push&&c[o.push].push(u)},s=br(),r=RegExp.prototype.test.bind(/^([a-z])=(.*)/);n.parse=function(o){var c={},d=[],l=c;return o.split(/(\r\n|\r|\n)/).filter(r).forEach(function(u){var h=u[0],f=u.slice(2);h==="m"&&(d.push({rtp:[],fmtp:[]}),l=d[d.length-1]);for(var g=0;g<(s[h]||[]).length;g+=1){var m=s[h][g];if(m.reg.test(f))return i(m,l,f)}}),c.media=d,c};var a=function(o,c){var d=c.split(/=(.+)/,2);return d.length===2?o[d[0]]=e(d[1]):d.length===1&&c.length>1&&(o[d[0]]=void 0),o};n.parseParams=function(o){return o.split(/;\s?/).reduce(a,{})},n.parseFmtpConfig=n.parseParams,n.parsePayloads=function(o){return o.toString().split(" ").map(Number)},n.parseRemoteCandidates=function(o){for(var c=[],d=o.split(" ").map(e),l=0;l<d.length;l+=3)c.push({component:d[l],ip:d[l+1],port:d[l+2]});return c},n.parseImageAttributes=function(o){return o.split(" ").map(function(c){return c.substring(1,c.length-1).split(",").reduce(a,{})})},n.parseSimulcastStreamList=function(o){return o.split(";").map(function(c){return c.split(",").map(function(d){var l,u=!1;return d[0]!=="~"?l=e(d):(l=e(d.substring(1,d.length)),u=!0),{scid:l,paused:u}})})}}(vr)),vr}var kr,Sc;function Oh(){if(Sc)return kr;Sc=1;var n=br(),e=/%[sdv%]/g,t=function(a){var o=1,c=arguments,d=c.length;return a.replace(e,function(l){if(o>=d)return l;var u=c[o];switch(o+=1,l){case"%%":return"%";case"%s":return String(u);case"%d":return Number(u);case"%v":return""}})},i=function(a,o,c){var d=o.format instanceof Function?o.format(o.push?c:c[o.name]):o.format,l=[a+"="+d];if(o.names)for(var u=0;u<o.names.length;u+=1){var h=o.names[u];o.name?l.push(c[o.name][h]):l.push(c[o.names[u]])}else l.push(c[o.name]);return t.apply(null,l)},s=["v","o","s","i","u","e","p","c","b","t","r","z","a"],r=["i","c","b","a"];return kr=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,d=o.innerOrder||r,l=[];return c.forEach(function(u){n[u].forEach(function(h){h.name in a&&a[h.name]!=null?l.push(i(u,h,a)):h.push in a&&a[h.push]!=null&&a[h.push].forEach(function(f){l.push(i(u,h,f))})})}),a.media.forEach(function(u){l.push(i("m",n.m[0],u)),d.forEach(function(h){n[h].forEach(function(f){f.name in u&&u[f.name]!=null?l.push(i(h,f,u)):f.push in u&&u[f.push]!=null&&u[f.push].forEach(function(g){l.push(i(h,f,g))})})})}),l.join(`\r
53
- `)+`\r
54
- `},kr}var Cc;function Dh(){if(Cc)return Ue;Cc=1;var n=Ah(),e=Oh(),t=br();return Ue.grammar=t,Ue.write=e,Ue.parse=n.parse,Ue.parseParams=n.parseParams,Ue.parseFmtpConfig=n.parseFmtpConfig,Ue.parsePayloads=n.parsePayloads,Ue.parseRemoteCandidates=n.parseRemoteCandidates,Ue.parseImageAttributes=n.parseImageAttributes,Ue.parseSimulcastStreamList=n.parseSimulcastStreamList,Ue}var wt=Dh();function Tr(n,e,t){var i,s,r;e===void 0&&(e=50),t===void 0&&(t={});var a=(i=t.isImmediate)!=null&&i,o=(s=t.callback)!=null&&s,c=t.maxWait,d=Date.now(),l=[];function u(){if(c!==void 0){var f=Date.now()-d;if(f+e>=c)return c-f}return e}var h=function(){var f=[].slice.call(arguments),g=this;return new Promise(function(m,v){var T=a&&r===void 0;if(r!==void 0&&clearTimeout(r),r=setTimeout(function(){if(r=void 0,d=Date.now(),!a){var P=n.apply(g,f);o&&o(P),l.forEach(function(y){return(0,y.resolve)(P)}),l=[]}},u()),T){var x=n.apply(g,f);return o&&o(x),m(x)}l.push({resolve:m,reject:v})})};return h.cancel=function(f){r!==void 0&&clearTimeout(r),l.forEach(function(g){return(0,g.reject)(f)}),l=[]},h}const Mh=.7,Nh=20,ui={NegotiationStarted:"negotiationStarted",NegotiationComplete:"negotiationComplete",RTPVideoPayloadTypes:"rtpVideoPayloadTypes"};class _c extends Ze.EventEmitter{get pc(){return this._pc||(this._pc=this.createPC()),this._pc}constructor(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};var i;super(),this.log=G,this.ddExtID=0,this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate=!1,this.trackBitrates=[],this.remoteStereoMids=[],this.remoteNackMids=[],this.negotiate=Tr(s=>p(this,void 0,void 0,function*(){this.emit(ui.NegotiationStarted);try{yield this.createAndSendOffer()}catch(r){if(s)s(r);else throw r}}),Nh),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=it((i=t.loggerName)!==null&&i!==void 0?i:Ne.PCTransport),this.loggerOptions=t,this.config=e,this._pc=this.createPC()}createPC(){const e=new RTCPeerConnection(this.config);return e.onicecandidate=t=>{var i;t.candidate&&((i=this.onIceCandidate)===null||i===void 0||i.call(this,t.candidate))},e.onicecandidateerror=t=>{var i;(i=this.onIceCandidateError)===null||i===void 0||i.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 i;(i=this.onDataChannel)===null||i===void 0||i.call(this,t)},e.ontrack=t=>{var i;(i=this.onTrack)===null||i===void 0||i.call(this,t)},e}get logContext(){var e,t;return Object.assign({},(t=(e=this.loggerOptions).loggerContextCb)===null||t===void 0?void 0:t.call(e))}get isICEConnected(){return this._pc!==null&&(this.pc.iceConnectionState==="connected"||this.pc.iceConnectionState==="completed")}addIceCandidate(e){return p(this,void 0,void 0,function*(){if(this.pc.remoteDescription&&!this.restartingIce)return this.pc.addIceCandidate(e);this.pendingCandidates.push(e)})}setRemoteDescription(e){return p(this,void 0,void 0,function*(){var t;let i;if(e.type==="offer"){let{stereoMids:s,nackMids:r}=Lh(e);this.remoteStereoMids=s,this.remoteNackMids=r}else if(e.type==="answer"){const s=wt.parse((t=e.sdp)!==null&&t!==void 0?t:"");s.media.forEach(r=>{r.type==="audio"&&this.trackBitrates.some(a=>{if(!a.transceiver||r.mid!=a.transceiver.mid)return!1;let o=0;if(r.rtp.some(d=>d.codec.toUpperCase()===a.codec.toUpperCase()?(o=d.payload,!0):!1),o===0)return!0;let c=!1;for(const d of r.fmtp)if(d.payload===o){d.config=d.config.split(";").filter(l=>!l.includes("maxaveragebitrate")).join(";"),a.maxbr>0&&(d.config+=";maxaveragebitrate=".concat(a.maxbr*1e3)),c=!0;break}return c||a.maxbr>0&&r.fmtp.push({payload:o,config:"maxaveragebitrate=".concat(a.maxbr*1e3)}),!0})}),i=wt.write(s)}yield this.setMungedSDP(e,i,!0),this.pendingCandidates.forEach(s=>{this.pc.addIceCandidate(s)}),this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate?(this.renegotiate=!1,yield this.createAndSendOffer()):e.type==="answer"&&(this.emit(ui.NegotiationComplete),e.sdp&&wt.parse(e.sdp).media.forEach(r=>{r.type==="video"&&this.emit(ui.RTPVideoPayloadTypes,r.rtp)}))})}createAndSendOffer(e){return p(this,void 0,void 0,function*(){var t;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 r=this._pc.remoteDescription;if(e!=null&&e.iceRestart&&r)yield this._pc.setRemoteDescription(r);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 i=yield this.pc.createOffer(e);this.log.debug("original offer",Object.assign({sdp:i.sdp},this.logContext));const s=wt.parse((t=i.sdp)!==null&&t!==void 0?t:"");s.media.forEach(r=>{wc(r),r.type==="audio"?Ec(r,[],[]):r.type==="video"&&this.trackBitrates.some(a=>{if(!r.msid||!a.cid||!r.msid.includes(a.cid))return!1;let o=0;if(r.rtp.some(d=>d.codec.toUpperCase()===a.codec.toUpperCase()?(o=d.payload,!0):!1),o===0||(Li(a.codec)&&this.ensureVideoDDExtensionForSVC(r,s),a.codec!=="av1"))return!0;const c=Math.round(a.maxbr*Mh);for(const d of r.fmtp)if(d.payload===o){d.config.includes("x-google-start-bitrate")||(d.config+=";x-google-start-bitrate=".concat(c));break}return!0})}),yield this.setMungedSDP(i,wt.write(s)),this.onOffer(i)})}createAndSetAnswer(){return p(this,void 0,void 0,function*(){var e;const t=yield this.pc.createAnswer(),i=wt.parse((e=t.sdp)!==null&&e!==void 0?e:"");return i.media.forEach(s=>{wc(s),s.type==="audio"&&Ec(s,this.remoteStereoMids,this.remoteNackMids)}),yield this.setMungedSDP(t,wt.write(i)),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 fe("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 fe("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 i=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),i.set(o.id,o);break;case"remote-candidate":s.set(o.id,"".concat(o.address,":").concat(o.port));break}}),t==="")return;const a=(e=i.get(t))===null||e===void 0?void 0:e.remoteCandidateId;if(a!==void 0)return s.get(a)})}setMungedSDP(e,t,i){return p(this,void 0,void 0,function*(){if(t){const s=e.sdp;e.sdp=t;try{this.log.debug("setting munged ".concat(i?"remote":"local"," description"),this.logContext),i?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{i?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!i&&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 Js(r)}})}ensureVideoDDExtensionForSVC(e,t){var i,s;if(!((i=e.ext)===null||i===void 0?void 0:i.some(a=>a.uri===nc))){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(d=>{d.value>a&&(a=d.value)}))}),this.ddExtID=a+1}(s=e.ext)===null||s===void 0||s.push({value:this.ddExtID,uri:nc})}}}function Ec(n,e,t){let i=0;n.rtp.some(s=>s.codec==="opus"?(i=s.payload,!0):!1),i>0&&(n.rtcpFb||(n.rtcpFb=[]),t.includes(n.mid)&&!n.rtcpFb.some(s=>s.payload===i&&s.type==="nack")&&n.rtcpFb.push({payload:i,type:"nack"}),e.includes(n.mid)&&n.fmtp.some(s=>s.payload===i?(s.config.includes("stereo=1")||(s.config+=";stereo=1"),!0):!1))}function Lh(n){var e;const t=[],i=[],s=wt.parse((e=n.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")&&i.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:i}}function wc(n){if(n.connection){const e=n.connection.ip.indexOf(":")>=0;(n.connection.version===4&&e||n.connection.version===6&&!e)&&(n.connection.ip="0.0.0.0",n.connection.version=4)}}const Sr="vp8",Uh={audioPreset:er.music,dtx:!0,red:!0,forceStereo:!1,simulcast:!0,screenShareEncoding:ir.h1080fps15.encoding,stopMicTrackOnMute:!1,videoCodec:Sr,backupCodec:!0},Pc={deviceId:{ideal:"default"},autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0,voiceIsolation:!0},Rc={deviceId:{ideal:"default"},resolution:Ni.h720.resolution},Fh={adaptiveStream:!1,dynacast:!1,stopLocalTrackOnUnpublish:!0,reconnectPolicy:new Ru,disconnectOnPageLeave:!0,webAudioMix:!1},Cr={autoSubscribe:!0,maxRetries:1,peerConnectionTimeout:15e3,websocketTimeout:15e3};var oe;(function(n){n[n.NEW=0]="NEW",n[n.CONNECTING=1]="CONNECTING",n[n.CONNECTED=2]="CONNECTED",n[n.FAILED=3]="FAILED",n[n.CLOSING=4]="CLOSING",n[n.CLOSED=5]="CLOSED"})(oe||(oe={}));class jh{get needsPublisher(){return this.isPublisherConnectionRequired}get needsSubscriber(){return this.isSubscriberConnectionRequired}get currentState(){return this.state}constructor(e,t,i){var s;this.peerConnectionTimeout=Cr.peerConnectionTimeout,this.log=G,this.updateState=()=>{var r;const a=this.state,o=this.requiredTransports.map(c=>c.getConnectionState());o.every(c=>c==="connected")?this.state=oe.CONNECTED:o.some(c=>c==="failed")?this.state=oe.FAILED:o.some(c=>c==="connecting")?this.state=oe.CONNECTING:o.every(c=>c==="closed")?this.state=oe.CLOSED:o.some(c=>c==="closed")?this.state=oe.CLOSING:o.every(c=>c==="new")&&(this.state=oe.NEW),a!==this.state&&(this.log.debug("pc state change: from ".concat(oe[a]," to ").concat(oe[this.state]),this.logContext),(r=this.onStateChange)===null||r===void 0||r.call(this,this.state,this.publisher.getConnectionState(),this.subscriber.getConnectionState()))},this.log=it((s=i.loggerName)!==null&&s!==void 0?s:Ne.PCManager),this.loggerOptions=i,this.isPublisherConnectionRequired=!t,this.isSubscriberConnectionRequired=t,this.publisher=new _c(e,i),this.subscriber=new _c(e,i),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,Me.PUBLISHER)},this.subscriber.onIceCandidate=r=>{var a;(a=this.onIceCandidate)===null||a===void 0||a.call(this,r,Me.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=>{var a;(a=this.onPublisherOffer)===null||a===void 0||a.call(this,r)},this.state=oe.NEW,this.connectionLock=new Ce,this.remoteOfferLock=new Ce}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){return this.publisher.setRemoteDescription(e)}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(i){this.log.warn("could not removeTrack",Object.assign(Object.assign({},this.logContext),{error:i}))}}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===Me.PUBLISHER?yield this.publisher.addIceCandidate(e):yield this.subscriber.addIceCandidate(e)})}createSubscriberAnswerFromOffer(e){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 t=yield this.remoteOfferLock.lock();try{return yield this.subscriber.setRemoteDescription(e),yield this.subscriber.createAndSetAnswer()}finally{t()}})}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 i;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((i=this.requiredTransports)===null||i===void 0?void 0:i.map(r=>this.ensureTransportConnected(r,e,t)))}finally{s()}})}negotiate(e){return p(this,void 0,void 0,function*(){return new Promise((t,i)=>p(this,void 0,void 0,function*(){const s=setTimeout(()=>{i("negotiation timed out")},this.peerConnectionTimeout),r=()=>{clearTimeout(s),i("negotiation aborted")};e.signal.addEventListener("abort",r),this.publisher.once(ui.NegotiationStarted,()=>{e.signal.aborted||this.publisher.once(ui.NegotiationComplete,()=>{clearTimeout(s),t()})}),yield this.publisher.negotiate(a=>{clearTimeout(s),i(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===Me.PUBLISHER?this.publisher.getConnectedAddress():e===Me.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(i,s){var r=this;let a=arguments.length>2&&arguments[2]!==void 0?arguments[2]:this.peerConnectionTimeout;return function*(){if(i.getConnectionState()!=="connected")return new Promise((c,d)=>p(r,void 0,void 0,function*(){const l=()=>{this.log.warn("abort transport connection",this.logContext),ve.clearTimeout(u),d(new te("room connection has been cancelled",H.Cancelled))};s!=null&&s.signal.aborted&&l(),s==null||s.signal.addEventListener("abort",l);const u=ve.setTimeout(()=>{s==null||s.signal.removeEventListener("abort",l),d(new te("could not establish pc connection",H.InternalError))},a);for(;this.state!==oe.CONNECTED;)if(yield we(50),s!=null&&s.signal.aborted){d(new te("room connection has been cancelled",H.Cancelled));return}ve.clearTimeout(u),s==null||s.signal.removeEventListener("abort",l),c()}))}()})}}class ce extends Error{constructor(e,t,i){super(t),this.code=e,this.message=Ic(t,ce.MAX_MESSAGE_BYTES),this.data=i?Ic(i,ce.MAX_DATA_BYTES):void 0}static fromProto(e){return new ce(e.code,e.message,e.data)}toProto(){return new qa({code:this.code,message:this.message,data:this.data})}static builtIn(e,t){return new ce(ce.ErrorCode[e],ce.ErrorMessage[e],t)}}ce.MAX_MESSAGE_BYTES=256,ce.MAX_DATA_BYTES=15360,ce.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},ce.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 xc=15360;function _r(n){return new TextEncoder().encode(n).length}function Ic(n,e){if(_r(n)<=e)return n;let t=0,i=n.length;const s=new TextEncoder;for(;t<i;){const r=Math.floor((t+i+1)/2);s.encode(n.slice(0,r)).length<=e?t=r:i=r-1}return n.slice(0,t)}const Er=2e3;function qn(n,e){if(!e)return 0;let t,i;return"bytesReceived"in n?(t=n.bytesReceived,i=e.bytesReceived):"bytesSent"in n&&(t=n.bytesSent,i=e.bytesSent),t===void 0||i===void 0||n.timestamp===void 0||e.timestamp===void 0?0:(t-i)*8*1e3/(n.timestamp-e.timestamp)}const $h=1e3;class Ac extends S{get sender(){return this._sender}set sender(e){this._sender=e}get constraints(){return this._constraints}constructor(e,t,i){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=Tr(()=>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(R.Ended,this)},this.reacquireTrack=!1,this.providedByUser=s,this.muteLock=new Ce,this.pauseUpstreamLock=new Ce,this.processorLock=new Ce,this.restartLock=new Ce,this.setMediaStreamTrack(e,!0),this._constraints=e.getConstraints(),i&&(this._constraints=i)}get id(){return this._mediaStreamTrack.id}get dimensions(){if(this.kind!==S.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 i;if(e===this._mediaStreamTrack&&!t)return;this._mediaStreamTrack&&(this.attachedElements.forEach(r=>{oi(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){const r=yield this.processorLock.lock();try{if(this.log.debug("restarting processor",this.logContext),this.kind==="unknown")throw TypeError("cannot set processor on track of unknown kind");this.processorElement&&(ai(e,this.processorElement),this.processorElement.muted=!0),yield this.processor.restart({track:e,kind:this.kind,element:this.processorElement}),s=this.processor.processedTrack}finally{r()}}this.sender&&((i=this.sender.transport)===null||i===void 0?void 0:i.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=>{ai(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]:$h;return function*(){var i;if(e.kind===S.Kind.Audio)throw new Error("cannot get dimensions for audio tracks");((i=Le())===null||i===void 0?void 0:i.os)==="iOS"&&(yield we(10));const s=Date.now();for(;Date.now()-s<t;){const r=e.dimensions;if(r)return r;yield we(50)}throw new nt("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===_t(e)||(this._constraints.deviceId=e,this.isMuted)?!0:(yield this.restartTrack(),_t(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===S.Source.ScreenShare)return;const{deviceId:i,groupId:s}=e._mediaStreamTrack.getSettings(),r=e.kind===S.Kind.Audio?"audioinput":"videoinput";return t?pe.getInstance().normalizeDeviceId(r,i,s):i}()})}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*(){if(!this.sender)throw new nt("unable to replace an unpublished track");let i,s;return typeof t=="boolean"?i=t:t!==void 0&&(i=t.userProvidedTrack,s=t.stopProcessor),this.providedByUser=i??!0,this.log.debug("replace MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(e),s&&this.processor&&(yield this.stopProcessor()),this})}restart(e){return p(this,void 0,void 0,function*(){this.manuallyStopped=!1;const t=yield this.restartLock.lock();try{e||(e=this._constraints);const{deviceId:i,facingMode:s}=e,r=xu(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===S.Kind.Video?a.video=i||s?{deviceId:i,facingMode:s}:!0:a.audio=i?{deviceId:i}:!0,this.attachedElements.forEach(d=>{oi(this.mediaStreamTrack,d)}),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.stop();const c=(yield navigator.mediaDevices.getUserMedia(a)).getTracks()[0];return 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(R.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?R.Muted:R.Unmuted,this))}get needsReAcquisition(){return this._mediaStreamTrack.readyState!=="live"||this._mediaStreamTrack.muted||!this._mediaStreamTrack.enabled||this.reacquireTrack}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return p(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),sc()&&(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(R.UpstreamPaused,this);const i=Le();if((i==null?void 0:i.name)==="Safari"&&jt(i.version,"12.0")<0)throw new Zs("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(R.UpstreamResumed,this),((e=this.sender.transport)===null||e===void 0?void 0:e.state)!=="closed"&&(yield this.sender.replaceTrack(this.mediaStreamTrack))}finally{t()}})}getRTCStatsReport(){return 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 i=this;let s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){var r;const a=yield i.processorLock.lock();try{i.log.debug("setting up processor",i.logContext);const o=document.createElement(i.kind),c={kind:i.kind,track:i._mediaStreamTrack,element:o,audioContext:i.audioContext};if(yield t.init(c),i.log.debug("processor initialized",i.logContext),i.processor&&(yield i.stopProcessor()),i.kind==="unknown")throw TypeError("cannot set processor on track of unknown kind");if(ai(i._mediaStreamTrack,o),o.muted=!0,o.play().catch(d=>i.log.error("failed to play processor element",Object.assign(Object.assign({},i.logContext),{error:d}))),i.processor=t,i.processorElement=o,i.processor.processedTrack){for(const d of i.attachedElements)d!==i.processorElement&&s&&(oi(i._mediaStreamTrack,d),ai(i.processor.processedTrack,d));yield(r=i.sender)===null||r===void 0?void 0:r.replaceTrack(i.processor.processedTrack)}i.emit(R.TrackProcessorUpdate,i.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*(){var i,s;e.processor&&(e.log.debug("stopping processor",e.logContext),(i=e.processor.processedTrack)===null||i===void 0||i.stop(),yield e.processor.destroy(),e.processor=void 0,t||((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(R.TrackProcessorUpdate))}()})}}class zn extends Ac{get enhancedNoiseCancellation(){return this.isKrispNoiseFilterEnabled}constructor(e,t){let i=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,S.Kind.Audio,t,i,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=qn(a,this.prevStats)),this.prevStats=a}),this.handleKrispNoiseFilterEnable=()=>{this.isKrispNoiseFilterEnabled=!0,this.log.debug("Krisp noise filter enabled",this.logContext),this.emit(R.AudioTrackFeatureUpdate,this,Ke.TF_ENHANCED_NOISE_CANCELLATION,!0)},this.handleKrispNoiseFilterDisable=()=>{this.isKrispNoiseFilterEnabled=!1,this.log.debug("Krisp noise filter disabled",this.logContext),this.emit(R.AudioTrackFeatureUpdate,this,Ke.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===S.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 i=this._constraints.deviceId&&this._mediaStreamTrack.getSettings().deviceId!==_t(this._constraints.deviceId);return this.source===S.Source.Microphone&&(this.stopOnMute||this._mediaStreamTrack.readyState==="ended"||i)&&!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 i=pr({audio:e});typeof i.audio!="boolean"&&(t=i.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 i=yield t.restart.call(this,e);return this.checkForSilence(),i})}startMonitor(){Pe()&&(this.monitorInterval||(this.monitorInterval=setInterval(()=>{this.monitorSender()},Er)))}setProcessor(e){return p(this,void 0,void 0,function*(){var t;const i=yield this.processorLock.lock();try{if(!Je()&&!this.audioContext)throw Error("Audio context needs to be set on LocalAudioTrack in order to enable processors");this.processor&&(yield this.stopProcessor());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(R.TrackProcessorUpdate,this.processor)}finally{i()}})}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 i;return t.forEach(s=>{s.type==="outbound-rtp"&&(i={type:"audio",streamId:s.id,packetsSent:s.packetsSent,packetsLost:s.packetsLost,bytesSent:s.bytesSent,timestamp:s.timestamp,roundTripTime:s.roundTripTime,jitter:s.jitter})}),i})}checkForSilence(){return p(this,void 0,void 0,function*(){const e=yield pc(this);return e&&(this.isMuted||this.log.warn("silence detected on local audio track",this.logContext),this.emit(R.AudioSilenceDetected)),e})}}function Bh(n,e,t){switch(n.kind){case"audio":return new zn(n,e,!1,void 0,t);case"video":return new Wn(n,e,!1,t);default:throw new nt("unsupported track type: ".concat(n.kind))}}const Vh=Object.values(Ni),qh=Object.values(tr),zh=Object.values(ir),Gh=[Ni.h180,Ni.h360],Wh=[tr.h180,tr.h360],Kh=n=>[{scaleResolutionDownBy:2,fps:n.encoding.maxFramerate}].map(t=>{var i,s;return new X(Math.floor(n.width/t.scaleResolutionDownBy),Math.floor(n.height/t.scaleResolutionDownBy),Math.max(15e4,Math.floor(n.encoding.maxBitrate/(Math.pow(t.scaleResolutionDownBy,2)*(((i=n.encoding.maxFramerate)!==null&&i!==void 0?i:30)/((s=t.fps)!==null&&s!==void 0?s:30))))),t.fps,n.encoding.priority)}),wr=["q","h","f"];function Pr(n,e,t,i){var s,r;let a=i==null?void 0:i.videoEncoding;n&&(a=i==null?void 0:i.screenShareEncoding);const o=i==null?void 0:i.simulcast,c=i==null?void 0:i.scalabilityMode,d=i==null?void 0:i.videoCodec;if(!a&&!o&&!c||!e||!t)return[{}];a||(a=Zh(n,e,t,d),G.debug("using video encoding",a));const l=a.maxFramerate,u=new X(e,t,a.maxBitrate,a.maxFramerate,a.priority);if(c&&Li(d)){const g=new Gn(c),m=[];if(g.spatial>3)throw new Error("unsupported scalabilityMode: ".concat(c));const v=Le();if(Ct()||Je()||(v==null?void 0:v.name)==="Chrome"&&jt(v==null?void 0:v.version,"113")<0){const T=g.suffix=="h"?2:3;for(let x=0;x<g.spatial;x+=1)m.push({rid:wr[2-x],maxBitrate:a.maxBitrate/Math.pow(T,x),maxFramerate:u.encoding.maxFramerate});m[0].scalabilityMode=c}else m.push({maxBitrate:a.maxBitrate,maxFramerate:u.encoding.maxFramerate,scalabilityMode:c});return u.encoding.priority&&(m[0].priority=u.encoding.priority,m[0].networkPriority=u.encoding.priority),G.debug("using svc encoding",{encodings:m}),m}if(!o)return[a];let h=[];n?h=(s=Dc(i==null?void 0:i.screenShareSimulcastLayers))!==null&&s!==void 0?s:Oc(n,u):h=(r=Dc(i==null?void 0:i.videoSimulcastLayers))!==null&&r!==void 0?r:Oc(n,u);let f;if(h.length>0){const g=h[0];h.length>1&&([,f]=h);const m=Math.max(e,t);if(m>=960&&f)return Rr(e,t,[g,f,u],l);if(m>=480)return Rr(e,t,[g,u],l)}return Rr(e,t,[u])}function Hh(n,e,t){var i,s,r,a;if(!t.backupCodec||t.backupCodec===!0||t.backupCodec.codec===t.videoCodec)return;e!==t.backupCodec.codec&&G.warn("requested a different codec than specified as backup",{serverRequested:e,backup:t.backupCodec.codec}),t.videoCodec=e,t.videoEncoding=t.backupCodec.encoding;const o=n.mediaStreamTrack.getSettings(),c=(i=o.width)!==null&&i!==void 0?i:(s=n.dimensions)===null||s===void 0?void 0:s.width,d=(r=o.height)!==null&&r!==void 0?r:(a=n.dimensions)===null||a===void 0?void 0:a.height;return n.source===S.Source.ScreenShare&&t.simulcast&&(t.simulcast=!1),Pr(n.source===S.Source.ScreenShare,c,d,t)}function Zh(n,e,t,i){const s=Jh(n,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(i)switch(i){case"av1":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 Jh(n,e,t){if(n)return zh;const i=e>t?e/t:t/e;return Math.abs(i-16/9)<Math.abs(i-4/3)?Vh:qh}function Oc(n,e){if(n)return Kh(e);const{width:t,height:i}=e,s=t>i?t/i:i/t;return Math.abs(s-16/9)<Math.abs(s-4/3)?Gh:Wh}function Rr(n,e,t,i){const s=[];if(t.forEach((r,a)=>{if(a>=wr.length)return;const o=Math.min(n,e),d={rid:wr[a],scaleResolutionDownBy:Math.max(1,o/Math.min(r.width,r.height)),maxBitrate:r.encoding.maxBitrate},l=i&&r.encoding.maxFramerate?Math.min(i,r.encoding.maxFramerate):r.encoding.maxFramerate;l&&(d.maxFramerate=l);const u=ci()||a===0;r.encoding.priority&&u&&(d.priority=r.encoding.priority,d.networkPriority=r.encoding.priority),s.push(d)}),Je()&&ac()==="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,G.info("Simulcast on iOS React-Native requires all encodings to share the same framerate.")),G.info('Setting framerate of encoding "'.concat((c=o.rid)!==null&&c!==void 0?c:"",'" to ').concat(r)),o.maxFramerate=r)})}return s}function Dc(n){if(n)return n.sort((e,t)=>{const{encoding:i}=e,{encoding:s}=t;return i.maxBitrate>s.maxBitrate?1:i.maxBitrate<s.maxBitrate?-1:i.maxBitrate===s.maxBitrate&&i.maxFramerate&&s.maxFramerate?i.maxFramerate>s.maxFramerate?1:-1:0})}class Gn{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 Yh(n){return n.source===S.Source.ScreenShare||n.constraints.height&&_t(n.constraints.height)>=1080?"maintain-resolution":"balanced"}const Qh=5e3;class Wn extends Ac{get sender(){return this._sender}set sender(e){this._sender=e,this.degradationPreference&&this.setDegradationPreference(this.degradationPreference)}constructor(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,s=arguments.length>3?arguments[3]:void 0;super(e,S.Kind.Video,t,i,s),this.simulcastCodecs=new Map,this.degradationPreference="balanced",this.monitorSender=()=>p(this,void 0,void 0,function*(){if(!this.sender){this._currentBitrate=0;return}let r;try{r=yield this.getSenderStats()}catch(o){this.log.error("could not get audio sender stats",Object.assign(Object.assign({},this.logContext),{error:o}));return}const a=new Map(r.map(o=>[o.rid,o]));if(this.prevStats){let o=0;a.forEach((c,d)=>{var l;const u=(l=this.prevStats)===null||l===void 0?void 0:l.get(d);o+=qn(c,u)}),this._currentBitrate=o}this.prevStats=a}),this.senderLock=new Ce}get isSimulcast(){return!!(this.sender&&this.sender.getParameters().encodings.length>1)}startMonitor(e){var t;if(this.signalClient=e,!Pe())return;const i=(t=this.sender)===null||t===void 0?void 0:t.getParameters();i&&(this.encodings=i.encodings),!this.monitorInterval&&(this.monitorInterval=setInterval(()=>{this.monitorSender()},Er))}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,i,s,r,a;yield e.pauseUpstream.call(this);try{for(var o=!0,c=bt(this.simulcastCodecs.values()),d;d=yield c.next(),t=d.done,!t;o=!0)r=d.value,o=!1,yield(a=r.sender)===null||a===void 0?void 0:a.replaceTrack(null)}catch(l){i={error:l}}finally{try{!o&&!t&&(s=c.return)&&(yield s.call(c))}finally{if(i)throw i.error}}})}resumeUpstream(){const e=Object.create(null,{resumeUpstream:{get:()=>super.resumeUpstream}});return p(this,void 0,void 0,function*(){var t,i,s,r,a;yield e.resumeUpstream.call(this);try{for(var o=!0,c=bt(this.simulcastCodecs.values()),d;d=yield c.next(),t=d.done,!t;o=!0){r=d.value,o=!1;const l=r;yield(a=l.sender)===null||a===void 0?void 0:a.replaceTrack(l.mediaStreamTrack)}}catch(l){i={error:l}}finally{try{!o&&!t&&(s=c.return)&&(yield s.call(c))}finally{if(i)throw i.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===S.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===S.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=[],i=yield this.sender.getStats();return i.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=i.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 i=Ae.LOW;i<=Ae.HIGH;i+=1)t.push(new Us({quality:i,enabled:i<=e}));this.log.debug("setting publishing quality. max quality ".concat(e),this.logContext),this.setPublishingLayers(t)}restartTrack(e){return p(this,void 0,void 0,function*(){var t,i,s,r,a;let o;if(e){const u=pr({video:e});typeof u.video!="boolean"&&(o=u.video)}yield this.restart(o);try{for(var c=!0,d=bt(this.simulcastCodecs.values()),l;l=yield d.next(),t=l.done,!t;c=!0){r=l.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){i={error:u}}finally{try{!c&&!t&&(s=d.return)&&(yield s.call(d))}finally{if(i)throw i.error}}})}setProcessor(e){const t=Object.create(null,{setProcessor:{get:()=>super.setProcessor}});return p(this,arguments,void 0,function(i){var s=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){var a,o,c,d,l,u;if(yield t.setProcessor.call(s,i,r),!((l=s.processor)===null||l===void 0)&&l.processedTrack)try{for(var h=!0,f=bt(s.simulcastCodecs.values()),g;g=yield f.next(),a=g.done,!a;h=!0)d=g.value,h=!1,yield(u=d.sender)===null||u===void 0?void 0:u.replaceTrack(s.processor.processedTrack)}catch(m){o={error:m}}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 i={codec:e,mediaStreamTrack:this.mediaStreamTrack.clone(),sender:void 0,encodings:t};return this.simulcastCodecs.set(e,i),i}setSimulcastTrackSender(e,t){const i=this.simulcastCodecs.get(e);i&&(i.sender=t,setTimeout(()=>{this.subscribedCodecs&&this.setPublishingCodecs(this.subscribedCodecs)},Qh))}setPublishingCodecs(e){return p(this,void 0,void 0,function*(){var t,i,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(e[0].qualities),[];this.subscribedCodecs=e;const d=[];try{for(t=!0,i=bt(e);s=yield i.next(),r=s.done,!r;t=!0){c=s.value,t=!1;const l=c;if(!this.codec||this.codec===l.codec)yield this.setPublishingLayers(l.qualities);else{const u=this.simulcastCodecs.get(l.codec);if(this.log.debug("try setPublishingCodec for ".concat(l.codec),Object.assign(Object.assign({},this.logContext),{simulcastCodecInfo:u})),!u||!u.sender){for(const h of l.qualities)if(h.enabled){d.push(l.codec);break}}else u.encodings&&(this.log.debug("try setPublishingLayersForSender ".concat(l.codec),this.logContext),yield Mc(u.sender,u.encodings,l.qualities,this.senderLock,this.log,this.logContext))}}}catch(l){a={error:l}}finally{try{!t&&!r&&(o=i.return)&&(yield o.call(i))}finally{if(a)throw a.error}}return d})}setPublishingLayers(e){return p(this,void 0,void 0,function*(){this.log.debug("setting publishing layers",Object.assign(Object.assign({},this.logContext),{qualities:e})),!(!this.sender||!this.encodings)&&(yield Mc(this.sender,this.encodings,e,this.senderLock,this.log,this.logContext))})}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return p(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),sc()&&this.isInBackground&&this.source===S.Source.Camera&&(this._mediaStreamTrack.enabled=!1)})}}function Mc(n,e,t,i,s,r){return p(this,void 0,void 0,function*(){const a=yield i.lock();s.debug("setPublishingLayersForSender",Object.assign(Object.assign({},r),{sender:n,qualities:t,senderEncodings:e}));try{const o=n.getParameters(),{encodings:c}=o;if(!c)return;if(c.length!==e.length){s.warn("cannot set publishing layers, encodings mismatch",Object.assign(Object.assign({},r),{encodings:c,senderEncodings:e}));return}let d=!1;const l=Le();if((l==null?void 0:l.name)==="Chrome"&&jt(l==null?void 0:l.version,"133")>0&&c[0].scalabilityMode){const h=c[0],f=new Gn(h.scalabilityMode);let g=ti.OFF;if(t.forEach(m=>{m.enabled&&(g===ti.OFF||m.quality>g)&&(g=m.quality)}),g===ti.OFF)h.active&&(h.active=!1,d=!0);else if(!h.active||f.spatial!==g+1){d=!0,h.active=!0;const m=new Gn(e[0].scalabilityMode);f.spatial=g+1,f.suffix=m.suffix,f.spatial===1&&(f.suffix=void 0),h.scalabilityMode=f.toString(),h.scaleResolutionDownBy=Math.pow(2,2-g),e[0].maxBitrate&&(h.maxBitrate=e[0].maxBitrate/(h.scaleResolutionDownBy*h.scaleResolutionDownBy))}}else c.forEach((h,f)=>{var g;let m=(g=h.rid)!==null&&g!==void 0?g:"";m===""&&(m="q");const v=Nc(m),T=t.find(x=>x.quality===v);T&&h.active!==T.enabled&&(d=!0,h.active=T.enabled,s.debug("setting layer ".concat(T.quality," to ").concat(h.active?"enabled":"disabled"),r),ci()&&(T.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&&(o.encodings=c,s.debug("setting encodings",Object.assign(Object.assign({},r),{encodings:o.encodings})),yield n.setParameters(o))}finally{a()}})}function Nc(n){switch(n){case"f":return Ae.HIGH;case"h":return Ae.MEDIUM;case"q":return Ae.LOW;default:return Ae.HIGH}}function Lc(n,e,t,i){if(!t)return[new Lt({quality:Ae.HIGH,width:n,height:e,bitrate:0,ssrc:0})];if(i){const s=t[0].scalabilityMode,r=new Gn(s),a=[],o=r.suffix=="h"?1.5:2,c=r.suffix=="h"?2:3;for(let d=0;d<r.spatial;d+=1)a.push(new Lt({quality:Math.min(Ae.HIGH,r.spatial-1)-d,width:Math.ceil(n/Math.pow(o,d)),height:Math.ceil(e/Math.pow(o,d)),bitrate:t[0].maxBitrate?Math.ceil(t[0].maxBitrate/Math.pow(c,d)):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 d=Nc((a=s.rid)!==null&&a!==void 0?a:"");return new Lt({quality:d,width:Math.ceil(n/c),height:Math.ceil(e/c),bitrate:(o=s.maxBitrate)!==null&&o!==void 0?o:0,ssrc:0})})}const Uc="_lossy",Fc="_reliable",Xh=2*1e3,xr="leave-reconnect";var Fe;(function(n){n[n.New=0]="New",n[n.Connected=1]="Connected",n[n.Disconnected=2]="Disconnected",n[n.Reconnecting=3]="Reconnecting",n[n.Closed=4]="Closed"})(Fe||(Fe={}));class ef extends Ze.EventEmitter{get isClosed(){return this._isClosed}get pendingReconnect(){return!!this.reconnectTimeout}constructor(e){var t;super(),this.options=e,this.rtcConfig={},this.peerConnectionTimeout=Cr.peerConnectionTimeout,this.fullReconnectOnNext=!1,this.subscriberPrimary=!1,this.pcState=Fe.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=G,this.handleDataChannel=i=>p(this,[i],void 0,function(s){var r=this;let{channel:a}=s;return function*(){if(a){if(a.label===Fc)r.reliableDCSub=a;else if(a.label===Uc)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=i=>p(this,void 0,void 0,function*(){var s,r;const a=yield this.dataProcessLock.lock();try{let o;if(i.data instanceof ArrayBuffer)o=i.data;else if(i.data instanceof Blob)o=yield i.data.arrayBuffer();else{this.log.error("unsupported data type",Object.assign(Object.assign({},this.logContext),{data:i.data}));return}const c=Ee.fromBinary(new Uint8Array(o));((s=c.value)===null||s===void 0?void 0:s.case)==="speaker"?this.emit(I.ActiveSpeakersUpdate,c.value.value.speakers):(((r=c.value)===null||r===void 0?void 0:r.case)==="user"&&nf(c,c.value.value),this.emit(I.DataPacketReceived,c))}finally{a()}}),this.handleDataError=i=>{const r=i.currentTarget.maxRetransmits===0?"lossy":"reliable";if(i instanceof ErrorEvent&&i.error){const{error:a}=i.error;this.log.error("DataChannel error on ".concat(r,": ").concat(i.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:i}))},this.handleBufferedAmountLow=i=>{const r=i.currentTarget.maxRetransmits===0?J.LOSSY:J.RELIABLE;this.updateAndEmitDCBufferStatus(r)},this.handleDisconnect=(i,s)=>{if(this._isClosed)return;this.log.warn("".concat(i," 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(I.Disconnected),this.close()},a=Date.now()-this.reconnectStart;let o=this.getNextRetryDelay({elapsedMs:a,retryCount:this.reconnectAttempts});if(o===null){r(a);return}i===xr&&(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=ve.setTimeout(()=>this.attemptReconnect(s).finally(()=>this.reconnectTimeout=void 0),o)},this.waitForRestarted=()=>new Promise((i,s)=>{this.pcState===Fe.Connected&&i();const r=()=>{this.off(I.Disconnected,a),i()},a=()=>{this.off(I.Restarted,r),s()};this.once(I.Restarted,r),this.once(I.Disconnected,a)}),this.updateAndEmitDCBufferStatus=i=>{const s=this.isBufferStatusLow(i);typeof s<"u"&&s!==this.dcBufferStatus.get(i)&&(this.dcBufferStatus.set(i,s),this.emit(I.DCBufferStatusChanged,s,i))},this.isBufferStatusLow=i=>{const s=this.dataChannelForKind(i);if(s)return s.bufferedAmount<=s.bufferedAmountLowThreshold},this.handleBrowserOnLine=()=>{this.client.currentState===ne.RECONNECTING&&(this.clearReconnectTimeout(),this.attemptReconnect(ii.RR_SIGNAL_DISCONNECTED))},this.log=it((t=e.loggerName)!==null&&t!==void 0?t:Ne.Engine),this.loggerOptions={loggerName:e.loggerName,loggerContextCb:()=>this.logContext},this.client=new gr(void 0,this.loggerOptions),this.client.signalLatency=this.options.expSignalLatency,this.reconnectPolicy=this.options.reconnectPolicy,this.registerOnLineListener(),this.closingLock=new Ce,this.dataProcessLock=new Ce,this.dcBufferStatus=new Map([[J.LOSSY,!0],[J.RELIABLE,!0]]),this.client.onParticipantUpdate=i=>this.emit(I.ParticipantUpdate,i),this.client.onConnectionQuality=i=>this.emit(I.ConnectionQualityUpdate,i),this.client.onRoomUpdate=i=>this.emit(I.RoomUpdate,i),this.client.onSubscriptionError=i=>this.emit(I.SubscriptionError,i),this.client.onSubscriptionPermissionUpdate=i=>this.emit(I.SubscriptionPermissionUpdate,i),this.client.onSpeakersChanged=i=>this.emit(I.SpeakersChanged,i),this.client.onStreamStateUpdate=i=>this.emit(I.StreamStateChanged,i),this.client.onRequestResponse=i=>this.emit(I.SignalRequestResponse,i)}get logContext(){var e,t,i,s,r,a,o,c;return{room:(t=(e=this.latestJoinResponse)===null||e===void 0?void 0:e.room)===null||t===void 0?void 0:t.name,roomID:(s=(i=this.latestJoinResponse)===null||i===void 0?void 0:i.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:(c=(o=this.latestJoinResponse)===null||o===void 0?void 0:o.participant)===null||c===void 0?void 0:c.sid}}join(e,t,i,s){return p(this,void 0,void 0,function*(){this.url=e,this.token=t,this.signalOpts=i,this.maxJoinAttempts=i.maxRetries;try{this.joinAttempts+=1,this.setupSignalClientCallbacks();const r=yield this.client.join(e,t,i,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,setTimeout(()=>{this.emit(I.SignalConnected)},10),r}catch(r){if(r instanceof te&&r.reason===H.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,i,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(I.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=i=>{i&&(i.close(),i.onbufferedamountlow=null,i.onclose=null,i.onclosing=null,i.onerror=null,i.onmessage=null,i.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})}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 nt("a track with the same ID has already been published");return new Promise((t,i)=>{const s=setTimeout(()=>{delete this.pendingTrackResolvers[e.cid],i(new te("publication of local track timed out, no response from server",H.InternalError))},1e4);this.pendingTrackResolvers[e.cid]={resolve:r=>{clearTimeout(s),t(r)},reject:()=>{clearTimeout(s),i(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,i;if(this.pcManager&&this.pcManager.currentState!==oe.NEW)return;this.participantSid=(t=e.participant)===null||t===void 0?void 0:t.sid;const s=this.makeRTCConfiguration(e);this.pcManager=new jh(s,e.subscriberPrimary,this.loggerOptions),this.emit(I.TransportsCreated,this.pcManager.publisher,this.pcManager.subscriber),this.pcManager.onIceCandidate=(r,a)=>{this.client.sendIceCandidate(r,a)},this.pcManager.onPublisherOffer=r=>{this.client.sendOffer(r)},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===oe.CONNECTED){const l=this.pcState===Fe.New;this.pcState=Fe.Connected,l&&this.emit(I.Connected,e)}else r===oe.FAILED&&this.pcState===Fe.Connected&&(this.pcState=Fe.Disconnected,this.handleDisconnect("peerconnection failed",o==="failed"?ii.RR_SUBSCRIBER_FAILED:ii.RR_PUBLISHER_FAILED));const c=this.client.isDisconnected||this.client.currentState===ne.RECONNECTING,d=[oe.FAILED,oe.CLOSING,oe.CLOSED].includes(r);c&&d&&!this._isClosed&&this.emit(I.Offline)}),this.pcManager.onTrack=r=>{this.emit(I.MediaTrackAdded,r.track,r.streams[0],r.receiver)},tf((i=e.serverInfo)===null||i===void 0?void 0:i.protocol)||this.createDataChannels()})}setupSignalClientCallbacks(){this.client.onAnswer=e=>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))}),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=>p(this,void 0,void 0,function*(){if(!this.pcManager)return;const t=yield this.pcManager.createSubscriberAnswerFromOffer(e);this.client.sendAnswer(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:i}=this.pendingTrackResolvers[e.cid];delete this.pendingTrackResolvers[e.cid],i(e.track)},this.client.onLocalTrackUnpublished=e=>{this.emit(I.LocalTrackUnpublished,e)},this.client.onLocalTrackSubscribed=e=>{this.emit(I.LocalTrackSubscribed,e)},this.client.onTokenRefresh=e=>{this.token=e},this.client.onRemoteMuteChanged=(e,t)=>{this.emit(I.RemoteMute,e,t)},this.client.onSubscribedQualityUpdate=e=>{this.emit(I.SubscribedQualityUpdate,e)},this.client.onClose=()=>{this.handleDisconnect("signal",ii.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 si.DISCONNECT:this.emit(I.Disconnected,e==null?void 0:e.reason),this.close();break;case si.RECONNECT:this.fullReconnectOnNext=!0,this.handleDisconnect(xr);break;case si.RESUME:this.handleDisconnect(xr)}}}makeRTCConfiguration(e){var t;const i=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),i.encodedInsertableStreams=!0),e.iceServers&&!i.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)}),i.iceServers=s}return e.clientConfiguration&&e.clientConfiguration.forceRelay===Ai.ENABLED&&(i.iceTransportPolicy="relay"),i.sdpSemantics="unified-plan",i.continualGatheringPolicy="gather_continually",i}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(Uc,{ordered:!0,maxRetransmits:0}),this.reliableDC=this.pcManager.createPublisherDataChannel(Fc,{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,i){return p(this,void 0,void 0,function*(){if(nr())return yield this.createTransceiverRTCRtpSender(e,t,i);if(sr())return this.log.warn("using add-track fallback",this.logContext),yield this.createRTCRtpSender(e.mediaStreamTrack);throw new fe("Required webRTC APIs not supported on this device")})}createSimulcastSender(e,t,i,s){return p(this,void 0,void 0,function*(){if(nr())return this.createSimulcastTransceiverSender(e,t,i,s);if(sr())return this.log.debug("using add-track fallback",this.logContext),this.createRTCRtpSender(e.mediaStreamTrack);throw new fe("Cannot stream on this device")})}createTransceiverRTCRtpSender(e,t,i){return p(this,void 0,void 0,function*(){if(!this.pcManager)throw new fe("publisher is closed");const s=[];e.mediaStream&&s.push(e.mediaStream),li(e)&&(e.codec=t.videoCodec);const r={direction:"sendonly",streams:s};return i&&(r.sendEncodings=i),(yield this.pcManager.addPublisherTransceiver(e.mediaStreamTrack,r)).sender})}createSimulcastTransceiverSender(e,t,i,s){return p(this,void 0,void 0,function*(){if(!this.pcManager)throw new fe("publisher is closed");const r={direction:"sendonly"};s&&(r.sendEncodings=s);const a=yield this.pcManager.addPublisherTransceiver(t.mediaStreamTrack,r);if(i.videoCodec)return e.setSimulcastTrackSender(i.videoCodec,a.sender),a.sender})}createRTCRtpSender(e){return p(this,void 0,void 0,function*(){if(!this.pcManager)throw new fe("publisher is closed");return this.pcManager.addPublisherTrack(e)})}attemptReconnect(e){return p(this,void 0,void 0,function*(){var t,i,s;if(!this._isClosed){if(this.attemptingReconnect){G.warn("already attempting reconnect, returning early",this.logContext);return}(((t=this.clientConfiguration)===null||t===void 0?void 0:t.resumeConnection)===Ai.DISABLED||((s=(i=this.pcManager)===null||i===void 0?void 0:i.currentState)!==null&&s!==void 0?s:oe.NEW)===oe.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 fe?(this.log.debug("received unrecoverable error",Object.assign(Object.assign({},this.logContext),{error:r})),a=!1):r instanceof hi||(this.fullReconnectOnNext=!0),a?this.handleDisconnect("reconnect",ii.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(I.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,i,s;try{if(!this.url||!this.token)throw new fe("could not reconnect, url or token not saved");this.log.info("reconnecting, attempt: ".concat(this.reconnectAttempts),this.logContext),this.emit(I.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 hi;r=yield this.join(e??this.url,this.token,this.signalOpts)}catch(a){throw a instanceof te&&a.reason===H.NotAllowed?new fe("could not reconnect, token might be expired"):new hi}if(this.shouldFailNext)throw this.shouldFailNext=!1,new Error("simulated failure");if(this.client.setReconnected(),this.emit(I.SignalRestarted,r),yield this.waitForPCReconnected(),this.client.currentState!==ne.CONNECTED)throw new hi("Signal connection got severed during reconnect");(t=this.regionUrlProvider)===null||t===void 0||t.resetAttempts(),this.emit(I.Restarted)}catch(r){const a=yield(i=this.regionUrlProvider)===null||i===void 0?void 0:i.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 fe("could not reconnect, url or token not saved");if(!this.pcManager)throw new fe("publisher and subscriber connections unset");this.log.info("resuming signal connection, attempt ".concat(this.reconnectAttempts),this.logContext),this.emit(I.Resuming);let i;try{this.setupSignalClientCallbacks(),i=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 te&&s.reason===H.NotAllowed?new fe("could not reconnect, token might be expired"):s instanceof te&&s.reason===H.LeaveRequest?s:new hi(r)}if(this.emit(I.SignalResumed),i){const s=this.makeRTCConfiguration(i);this.pcManager.updateConfiguration(s)}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!==ne.CONNECTED)throw new hi("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(),this.emit(I.Resumed)})}waitForPCInitialConnection(e,t){return p(this,void 0,void 0,function*(){if(!this.pcManager)throw new fe("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(t,e)})}waitForPCReconnected(){return p(this,void 0,void 0,function*(){this.pcState=Fe.Reconnecting,this.log.debug("waiting for peer connection to reconnect",this.logContext);try{if(yield we(Xh),!this.pcManager)throw new fe("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(void 0,this.peerConnectionTimeout),this.pcState=Fe.Connected}catch(e){throw this.pcState=Fe.Disconnected,new te("could not establish PC connection, ".concat(e.message),H.InternalError)}})}publishRpcResponse(e,t,i,s){return p(this,void 0,void 0,function*(){const r=new Ee({destinationIdentities:[e],kind:J.RELIABLE,value:{case:"rpcResponse",value:new Va({requestId:t,value:s?{case:"error",value:s.toProto()}:{case:"payload",value:i??""}})}});yield this.sendDataPacket(r,J.RELIABLE)})}publishRpcAck(e,t){return p(this,void 0,void 0,function*(){const i=new Ee({destinationIdentities:[e],kind:J.RELIABLE,value:{case:"rpcAck",value:new Ba({requestId:t})}});yield this.sendDataPacket(i,J.RELIABLE)})}sendDataPacket(e,t){return p(this,void 0,void 0,function*(){const i=e.toBinary();yield this.ensurePublisherConnected(t);const s=this.dataChannelForKind(t);s&&s.send(i),this.updateAndEmitDCBufferStatus(t)})}waitForBufferStatusLow(e){return new Promise((t,i)=>p(this,void 0,void 0,function*(){if(this.isBufferStatusLow(e))t();else{const s=()=>i("Engine closed");for(this.once(I.Closing,s);!this.dcBufferStatus.get(e);)yield we(10);this.off(I.Closing,s),t()}}))}ensureDataTransportConnected(e){return p(this,arguments,void 0,function(t){var i=this;let s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.subscriberPrimary;return function*(){var r;if(!i.pcManager)throw new fe("PC manager is closed");const a=s?i.pcManager.subscriber:i.pcManager.publisher,o=s?"Subscriber":"Publisher";if(!a)throw new te("".concat(o," connection not set"),H.InternalError);let c=!1;!s&&!i.dataChannelForKind(t,s)&&(i.createDataChannels(),c=!0),!c&&!s&&!i.pcManager.publisher.isICEConnected&&i.pcManager.publisher.getICEConnectionState()!=="checking"&&(c=!0),c&&i.negotiate();const d=i.dataChannelForKind(t,s);if((d==null?void 0:d.readyState)==="open")return;const l=new Date().getTime()+i.peerConnectionTimeout;for(;new Date().getTime()<l;){if(a.isICEConnected&&((r=i.dataChannelForKind(t,s))===null||r===void 0?void 0:r.readyState)==="open")return;yield we(50)}throw new te("could not establish ".concat(o," connection, state: ").concat(a.getICEConnectionState()),H.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!==oe.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 Js("PC manager is closed"));return}this.pcManager.requirePublisher(),this.pcManager.publisher.getTransceivers().length==0&&!this.lossyDC&&!this.reliableDC&&this.createDataChannels();const i=new AbortController,s=()=>{i.abort(),this.log.debug("engine disconnected while negotiation was ongoing",this.logContext),e()};this.isClosed&&t("cannot negotiate on closed engine"),this.on(I.Closing,s),this.pcManager.publisher.once(ui.RTPVideoPayloadTypes,r=>{const a=new Map;r.forEach(o=>{const c=o.codec.toLowerCase();lh(c)&&a.set(o.payload,c)}),this.emit(I.RTPVideoMapUpdate,a)});try{yield this.pcManager.negotiate(i),e()}catch(r){r instanceof Js&&(this.fullReconnectOnNext=!0),this.handleDisconnect("negotiation",ii.RR_UNKNOWN),t(r)}finally{this.off(I.Closing,s)}}))})}dataChannelForKind(e,t){if(t){if(e===J.LOSSY)return this.lossyDCSub;if(e===J.RELIABLE)return this.reliableDCSub}else{if(e===J.LOSSY)return this.lossyDC;if(e===J.RELIABLE)return this.reliableDC}}sendSyncState(e,t){var i,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=(i=this.signalOpts)===null||i===void 0?void 0:i.autoSubscribe)!==null&&s!==void 0?s:!0,c=new Array,d=new Array;e.forEach(l=>{l.isDesired!==o&&c.push(l.trackSid),l.isEnabled||d.push(l.trackSid)}),this.client.sendSyncState(new ao({answer:r?Vn({sdp:r.sdp,type:r.type}):void 0,offer:a?Vn({sdp:a.sdp,type:a.type}):void 0,subscription:new wn({trackSids:c,subscribe:!o,participantTracks:[]}),publishTracks:bh(t),dataChannels:this.dataChannelsInfo(),trackSidsDisabled:d}))}failNext(){this.shouldFailNext=!0}dataChannelsInfo(){const e=[],t=(i,s)=>{(i==null?void 0:i.id)!==void 0&&i.id!==null&&e.push(new oo({label:i.label,id:i.id,target:s}))};return t(this.dataChannelForKind(J.LOSSY),Me.PUBLISHER),t(this.dataChannelForKind(J.RELIABLE),Me.PUBLISHER),t(this.dataChannelForKind(J.LOSSY,!0),Me.SUBSCRIBER),t(this.dataChannelForKind(J.RELIABLE,!0),Me.SUBSCRIBER),e}clearReconnectTimeout(){this.reconnectTimeout&&ve.clearTimeout(this.reconnectTimeout)}clearPendingReconnect(){this.clearReconnectTimeout(),this.reconnectAttempts=0}registerOnLineListener(){Pe()&&window.addEventListener("online",this.handleBrowserOnLine)}deregisterOnLineListener(){Pe()&&window.removeEventListener("online",this.handleBrowserOnLine)}}class hi extends Error{}function tf(n){return n!==void 0&&n>13}function nf(n,e){const t=n.participantIdentity?n.participantIdentity:e.participantIdentity;n.participantIdentity=t,e.participantIdentity=t;const i=n.destinationIdentities.length!==0?n.destinationIdentities:e.destinationIdentities;n.destinationIdentities=i,e.destinationIdentities=i}class Ir{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 ar(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(i=>!this.attemptedRegions.find(s=>s.url===i.url));if(t.length>0){const i=t[0];return this.attemptedRegions.push(i),G.debug("next region: ".concat(i.region)),i.url}else return null})}resetAttempts(){this.attemptedRegions=[]}fetchRegionSettings(e){return p(this,void 0,void 0,function*(){const t=yield fetch("".concat(sf(this.serverUrl),"/regions"),{headers:{authorization:"Bearer ".concat(this.token)},signal:e});if(t.ok){const i=yield t.json();return this.lastUpdateAt=Date.now(),i}else throw new te("Could not fetch region settings: ".concat(t.statusText),t.status===401?H.NotAllowed:H.InternalError,t.status)})}setServerReportedRegions(e){this.regionSettings=e,this.lastUpdateAt=Date.now()}}function sf(n){return"".concat(n.protocol.replace("ws","http"),"//").concat(n.host,"/settings")}class jc{get info(){return this._info}constructor(e,t,i){this.reader=t,this.totalByteSize=i,this._info=e,this.bytesReceived=0}}class rf extends jc{handleChunkReceived(e){var t;this.bytesReceived+=e.content.byteLength;const i=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;(t=this.onProgress)===null||t===void 0||t.call(this,i)}[Symbol.asyncIterator](){const e=this.reader.getReader();return{next:()=>p(this,void 0,void 0,function*(){try{const{done:t,value:i}=yield e.read();return t?{done:!0,value:void 0}:(this.handleChunkReceived(i),{done:!1,value:i.content})}catch{return{done:!0,value:void 0}}}),return(){return p(this,void 0,void 0,function*(){return e.releaseLock(),{done:!0,value:void 0}})}}}readAll(){return p(this,void 0,void 0,function*(){var e,t,i,s;let r=new Set;try{for(var a=!0,o=bt(this),c;c=yield o.next(),e=c.done,!e;a=!0){s=c.value,a=!1;const d=s;r.add(d)}}catch(d){t={error:d}}finally{try{!a&&!e&&(i=o.return)&&(yield i.call(o))}finally{if(t)throw t.error}}return Array.from(r)})}}class af extends jc{constructor(e,t,i){super(e,t,i),this.receivedChunks=new Map}handleChunkReceived(e){var t;const i=$n(e.chunkIndex),s=this.receivedChunks.get(i);if(s&&s.version>e.version)return;this.receivedChunks.set(i,e),this.bytesReceived+=e.content.byteLength;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;return{next:()=>p(this,void 0,void 0,function*(){try{const{done:i,value:s}=yield e.read();return i?{done:!0,value:void 0}:(this.handleChunkReceived(s),{done:!1,value:t.decode(s.content)})}catch{return{done:!0,value:void 0}}}),return(){return p(this,void 0,void 0,function*(){return e.releaseLock(),{done:!0,value:void 0}})}}}readAll(){return p(this,void 0,void 0,function*(){var e,t,i,s;let r="";try{for(var a=!0,o=bt(this),c;c=yield o.next(),e=c.done,!e;a=!0)s=c.value,a=!1,r+=s}catch(d){t={error:d}}finally{try{!a&&!e&&(i=o.return)&&(yield i.call(o))}finally{if(t)throw t.error}}return r})}}class $c{constructor(e,t,i){this.writableStream=e,this.defaultWriter=e.getWriter(),this.onClose=i,this.info=t}write(e){return this.defaultWriter.write(e)}close(){return 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 of extends $c{}class cf extends $c{}class Bc extends S{constructor(e,t,i,s,r){super(e,i,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?R.Muted:R.Unmuted,this))}setMediaStream(e){this.mediaStream=e;const t=i=>{i.track===this._mediaStreamTrack&&(e.removeEventListener("removetrack",t),this.receiver&&"playoutDelayHint"in this.receiver&&(this.receiver.playoutDelayHint=void 0),this.receiver=void 0,this._currentBitrate=0,this.emit(R.Ended,this))};e.addEventListener("removetrack",t)}start(){this.startMonitor(),super.enable()}stop(){this.stopMonitor(),super.disable()}getRTCStatsReport(){return 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(),Er)),kh()&&this.registerTimeSyncUpdate()}registerTimeSyncUpdate(){const e=()=>{var t;this.timeSyncHandle=requestAnimationFrame(()=>e());const i=(t=this.receiver)===null||t===void 0?void 0:t.getSynchronizationSources()[0];if(i){const{timestamp:s,rtpTimestamp:r}=i;r&&this.rtpTimestamp!==r&&(this.emit(R.TimeSyncUpdate,{timestamp:s,rtpTimestamp:r}),this.rtpTimestamp=r)}};e()}}class df extends Bc{constructor(e,t,i,s,r,a){super(e,t,S.Kind.Audio,i,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=qn(o,this.prevStats)),this.prevStats=o}),this.audioContext=s,this.webAudioPluginNodes=[],r&&(this.sinkId=r.deviceId)}setVolume(e){var t;for(const i of this.attachedElements)this.audioContext?(t=this.gainNode)===null||t===void 0||t.gain.setTargetAtTime(e,0,.1):i.volume=e;Je()&&this._mediaStreamTrack._setVolume(e),this.elementVolume=e}getVolume(){if(this.elementVolume)return this.elementVolume;if(Je())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(rr(t))return t.setSinkId(e)}))})}attach(e){const t=this.attachedElements.length===0;return e?super.attach(e):e=super.attach(),this.sinkId&&rr(e)&&e.setSinkId(this.sinkId),this.audioContext&&t&&(this.log.debug("using audio context mapping",this.logContext),this.connectWebAudio(this.audioContext,e),e.volume=0,e.muted=!0),this.elementVolume&&this.setVolume(this.elementVolume),e}detach(e){let t;return e?(t=super.detach(e),this.audioContext&&(this.attachedElements.length>0?this.connectWebAudio(this.audioContext,this.attachedElements[0]):this.disconnectWebAudio())):(t=super.detach(),this.disconnectWebAudio()),t}setAudioContext(e){this.audioContext=e,e&&this.attachedElements.length>0?this.connectWebAudio(e,this.attachedElements[0]):e||this.disconnectWebAudio()}setWebAudioPlugins(e){this.webAudioPluginNodes=e,this.attachedElements.length>0&&this.audioContext&&this.connectWebAudio(this.audioContext,this.attachedElements[0])}connectWebAudio(e,t){this.disconnectWebAudio(),this.sourceNode=e.createMediaStreamSource(t.srcObject);let i=this.sourceNode;this.webAudioPluginNodes.forEach(s=>{i.connect(s),i=s}),this.gainNode=e.createGain(),i.connect(this.gainNode),this.gainNode.connect(e.destination),this.elementVolume&&this.gainNode.gain.setTargetAtTime(this.elementVolume,0,.1),e.state!=="running"&&e.resume().then(()=>{e.state!=="running"&&this.emit(R.AudioPlaybackFailed,new Error("Audio Context couldn't be started automatically"))}).catch(s=>{this.emit(R.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(i=>{i.type==="inbound-rtp"&&(t={type:"audio",streamId:i.id,timestamp:i.timestamp,jitter:i.jitter,bytesReceived:i.bytesReceived,concealedSamples:i.concealedSamples,concealmentEvents:i.concealmentEvents,silentConcealedSamples:i.silentConcealedSamples,silentConcealmentEvents:i.silentConcealmentEvents,totalAudioEnergy:i.totalAudioEnergy,totalSamplesDuration:i.totalSamplesDuration})}),t})}}const Ar=100;class lf extends Bc{constructor(e,t,i,s,r){super(e,t,S.Kind.Video,i,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=qn(a,this.prevStats)),this.prevStats=a}),this.debouncedHandleResize=Tr(()=>{this.updateDimensions()},Ar),this.adaptiveStreamSettings=s}get isAdaptiveStream(){return this.adaptiveStreamSettings!==void 0}get mediaStreamTrack(){return this._mediaStreamTrack}setMuted(e){super.setMuted(e),this.attachedElements.forEach(t=>{e?oi(this._mediaStreamTrack,t):ai(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 uf(e);this.observeElementInfo(t)}return e}observeElementInfo(e){this.adaptiveStreamSettings&&this.elementInfos.find(t=>t===e)===void 0?(e.handleResize=()=>{this.debouncedHandleResize()},e.handleVisibilityChanged=()=>{this.updateVisibility()},this.elementInfos.push(e),e.observe(),this.debouncedHandleResize(),this.updateVisibility()):this.log.warn("visibility resize observer not triggered",this.logContext)}stopObservingElementInfo(e){if(!this.isAdaptiveStream){this.log.warn("stopObservingElementInfo ignored",this.logContext);return}const t=this.elementInfos.filter(i=>i===e);for(const i of t)i.stopObserving();this.elementInfos=this.elementInfos.filter(i=>i!==e),this.updateVisibility(),this.debouncedHandleResize()}detach(e){let t=[];if(e)return this.stopObservingElement(e),super.detach(e);t=super.detach();for(const i of t)this.stopObservingElement(i);return t}getDecoderImplementation(){var e;return(e=this.prevStats)===null||e===void 0?void 0:e.decoderImplementation}getReceiverStats(){return p(this,void 0,void 0,function*(){if(!this.receiver||!this.receiver.getStats)return;const e=yield this.receiver.getStats();let t,i="",s=new Map;return e.forEach(r=>{r.type==="inbound-rtp"?(i=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&&i!==""&&s.get(i)&&(t.mimeType=s.get(i).mimeType),t})}stopObservingElement(e){const t=this.elementInfos.filter(i=>i.element===e);for(const i of t)this.stopObservingElementInfo(i)}handleAppVisibilityChanged(){const e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return p(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),this.isAdaptiveStream&&this.updateVisibility()})}updateVisibility(){var e,t;const i=this.elementInfos.reduce((o,c)=>Math.max(o,c.visibilityChangedAt||0),0),s=!((t=(e=this.adaptiveStreamSettings)===null||e===void 0?void 0:e.pauseVideoInBackground)!==null&&t!==void 0)||t?this.isInBackground:!1,r=this.elementInfos.some(o=>o.pictureInPicture),a=this.elementInfos.some(o=>o.visible)&&!s||r;if(this.lastVisible!==a){if(!a&&Date.now()-i<Ar){ve.setTimeout(()=>{this.updateVisibility()},Ar);return}this.lastVisible=a,this.emit(R.VisibilityChanged,a,this)}}updateDimensions(){var e,t;let i=0,s=0;const r=this.getPixelDensity();for(const a of this.elementInfos){const o=a.width()*r,c=a.height()*r;o+c>i+s&&(i=o,s=c)}((e=this.lastDimensions)===null||e===void 0?void 0:e.width)===i&&((t=this.lastDimensions)===null||t===void 0?void 0:t.height)===s||(this.lastDimensions={width:i,height:s},this.emit(R.VideoDimensionsChanged,this.lastDimensions,this))}getPixelDensity(){var e;const t=(e=this.adaptiveStreamSettings)===null||e===void 0?void 0:e.pixelDensity;return t==="screen"?oc():t||(oc()>2?2:1)}}class uf{get visible(){return this.isPiP||this.isIntersecting}get pictureInPicture(){return this.isPiP}constructor(e,t){this.onVisibilityChanged=i=>{var s;const{target:r,isIntersecting:a}=i;r===this.element&&(this.isIntersecting=a,this.isPiP=ji(this.element),this.visibilityChangedAt=Date.now(),(s=this.handleVisibilityChanged)===null||s===void 0||s.call(this))},this.onEnterPiP=()=>{var i,s,r;(s=(i=window.documentPictureInPicture)===null||i===void 0?void 0:i.window)===null||s===void 0||s.addEventListener("pagehide",this.onLeavePiP),this.isPiP=ji(this.element),(r=this.handleVisibilityChanged)===null||r===void 0||r.call(this)},this.onLeavePiP=()=>{var i;this.isPiP=ji(this.element),(i=this.handleVisibilityChanged)===null||i===void 0||i.call(this)},this.element=e,this.isIntersecting=t??Or(e),this.isPiP=Pe()&&ji(e),this.visibilityChangedAt=0}width(){return this.element.clientWidth}height(){return this.element.clientHeight}observe(){var e,t,i;this.isIntersecting=Or(this.element),this.isPiP=ji(this.element),this.element.handleResize=()=>{var s;(s=this.handleResize)===null||s===void 0||s.call(this)},this.element.handleVisibilityChanged=this.onVisibilityChanged,dc().observe(this.element),cc().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),(i=(t=window.documentPictureInPicture)===null||t===void 0?void 0:t.window)===null||i===void 0||i.addEventListener("pagehide",this.onLeavePiP)}stopObserving(){var e,t,i,s,r;(e=dc())===null||e===void 0||e.unobserve(this.element),(t=cc())===null||t===void 0||t.unobserve(this.element),this.element.removeEventListener("enterpictureinpicture",this.onEnterPiP),this.element.removeEventListener("leavepictureinpicture",this.onLeavePiP),(i=window.documentPictureInPicture)===null||i===void 0||i.removeEventListener("enter",this.onEnterPiP),(r=(s=window.documentPictureInPicture)===null||s===void 0?void 0:s.window)===null||r===void 0||r.removeEventListener("pagehide",this.onLeavePiP)}}function ji(n){var e,t;return document.pictureInPictureElement===n?!0:!((e=window.documentPictureInPicture)===null||e===void 0)&&e.window?Or(n,(t=window.documentPictureInPicture)===null||t===void 0?void 0:t.window):!1}function Or(n,e){const t=e||window;let i=n.offsetTop,s=n.offsetLeft;const r=n.offsetWidth,a=n.offsetHeight,{hidden:o}=n,{display:c}=getComputedStyle(n);for(;n.offsetParent;)n=n.offsetParent,i+=n.offsetTop,s+=n.offsetLeft;return i<t.pageYOffset+t.innerHeight&&s<t.pageXOffset+t.innerWidth&&i+a>t.pageYOffset&&s+r>t.pageXOffset&&!o&&c!=="none"}class rt extends Ze.EventEmitter{constructor(e,t,i,s){var r;super(),this.metadataMuted=!1,this.encryption=xe.NONE,this.log=G,this.handleMuted=()=>{this.emit(R.Muted)},this.handleUnmuted=()=>{this.emit(R.Unmuted)},this.log=it((r=s==null?void 0:s.loggerName)!==null&&r!==void 0?r:Ne.Publication),this.loggerContextCb=this.loggerContextCb,this.setMaxListeners(100),this.kind=e,this.trackSid=t,this.trackName=i,this.source=S.Source.Unknown}setTrack(e){this.track&&(this.track.off(R.Muted,this.handleMuted),this.track.off(R.Unmuted,this.handleUnmuted)),this.track=e,e&&(e.on(R.Muted,this.handleMuted),e.on(R.Unmuted,this.handleUnmuted))}get logContext(){var e;return Object.assign(Object.assign({},(e=this.loggerContextCb)===null||e===void 0?void 0:e.call(this)),Q(this))}get isMuted(){return this.metadataMuted}get isEnabled(){return!0}get isSubscribed(){return this.track!==void 0}get isEncrypted(){return this.encryption!==xe.NONE}get audioTrack(){if(st(this.track))return this.track}get videoTrack(){if(li(this.track))return this.track}updateInfo(e){this.trackSid=e.sid,this.trackName=e.name,this.source=S.sourceFromProto(e.source),this.mimeType=e.mimeType,this.kind===S.Kind.Video&&e.width>0&&(this.dimensions={width:e.width,height:e.height},this.simulcasted=e.simulcast),this.encryption=e.encryption,this.trackInfo=e,this.log.debug("update publication info",Object.assign(Object.assign({},this.logContext),{info:e}))}}(function(n){(function(e){e.Desired="desired",e.Subscribed="subscribed",e.Unsubscribed="unsubscribed"})(n.SubscriptionStatus||(n.SubscriptionStatus={})),function(e){e.Allowed="allowed",e.NotAllowed="not_allowed"}(n.PermissionStatus||(n.PermissionStatus={}))})(rt||(rt={}));class Dr extends rt{get isUpstreamPaused(){var e;return(e=this.track)===null||e===void 0?void 0:e.isUpstreamPaused}constructor(e,t,i,s){super(e,t.sid,t.name,s),this.track=void 0,this.handleTrackEnded=()=>{this.emit(R.Ended)},this.updateInfo(t),this.setTrack(i)}setTrack(e){this.track&&this.track.off(R.Ended,this.handleTrackEnded),super.setTrack(e),e&&e.on(R.Ended,this.handleTrackEnded)}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(st(this.track)){const t=this.track.getSourceTrackSettings(),i=new Set;return t.autoGainControl&&i.add(Ke.TF_AUTO_GAIN_CONTROL),t.echoCancellation&&i.add(Ke.TF_ECHO_CANCELLATION),t.noiseSuppression&&i.add(Ke.TF_NOISE_SUPPRESSION),t.channelCount&&t.channelCount>1&&i.add(Ke.TF_STEREO),!((e=this.options)===null||e===void 0)&&e.dtx||i.add(Ke.TF_NO_DTX),this.track.enhancedNoiseCancellation&&i.add(Ke.TF_ENHANCED_NOISE_CANCELLATION),Array.from(i.values())}else return[]}}function Kn(n,e){return p(this,void 0,void 0,function*(){n??(n={});let t=!1;const{audioProcessor:i,videoProcessor:s,optionsWithoutProcessor:r}=vc(n);let a=r.audio,o=r.video;if(i&&typeof r.audio=="object"&&(r.audio.processor=i),s&&typeof r.video=="object"&&(r.video.processor=s),n.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||typeof r.video=="object"&&!r.video.deviceId)&&(r.video={deviceId:"default"});const c=fc(r,Pc,Rc),d=pr(c),l=navigator.mediaDevices.getUserMedia(d);r.audio&&(pe.userMediaPromiseMap.set("audioinput",l),l.catch(()=>pe.userMediaPromiseMap.delete("audioinput"))),r.video&&(pe.userMediaPromiseMap.set("videoinput",l),l.catch(()=>pe.userMediaPromiseMap.delete("videoinput")));try{const u=yield l;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 m;const v=f?d.audio:d.video;typeof v!="boolean"&&(m=v);const T=h.getSettings().deviceId;m!=null&&m.deviceId&&_t(m.deviceId)!==T?m.deviceId=T:m||(m={deviceId:T});const x=Bh(h,m,e);return x.kind===S.Kind.Video?x.source=S.Source.Camera:x.kind===S.Kind.Audio&&(x.source=S.Source.Microphone),x.mediaStream=u,st(x)&&i?yield x.setProcessor(i):li(x)&&s&&(yield x.setProcessor(s)),x})))}catch(u){if(!t)throw u;return Kn(Object.assign(Object.assign({},n),{audio:a,video:o}),e)}})}function hf(n){return p(this,void 0,void 0,function*(){return(yield Kn({audio:!1,video:n??!0}))[0]})}function ff(n){return p(this,void 0,void 0,function*(){return(yield Kn({audio:n??!0,video:!1}))[0]})}var Pt;(function(n){n.Excellent="excellent",n.Good="good",n.Poor="poor",n.Lost="lost",n.Unknown="unknown"})(Pt||(Pt={}));function pf(n){switch(n){case Ii.EXCELLENT:return Pt.Excellent;case Ii.GOOD:return Pt.Good;case Ii.POOR:return Pt.Poor;case Ii.LOST:return Pt.Lost;default:return Pt.Unknown}}class Vc extends Ze.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===En.AGENT}get kind(){return this._kind}get attributes(){return Object.freeze(Object.assign({},this._attributes))}constructor(e,t,i,s,r,a){let o=arguments.length>6&&arguments[6]!==void 0?arguments[6]:En.STANDARD;var c;super(),this.audioLevel=0,this.isSpeaking=!1,this._connectionQuality=Pt.Unknown,this.log=G,this.log=it((c=a==null?void 0:a.loggerName)!==null&&c!==void 0?c:Ne.Participant),this.loggerOptions=a,this.setMaxListeners(100),this.sid=e,this.identity=t,this.name=i,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}get connectionQuality(){return this._connectionQuality}get isCameraEnabled(){var e;const t=this.getTrackPublication(S.Source.Camera);return!(!((e=t==null?void 0:t.isMuted)!==null&&e!==void 0)||e)}get isMicrophoneEnabled(){var e;const t=this.getTrackPublication(S.Source.Microphone);return!(!((e=t==null?void 0:t.isMuted)!==null&&e!==void 0)||e)}get isScreenShareEnabled(){return!!this.getTrackPublication(S.Source.ScreenShare)}get isLocal(){return!1}get joinedAt(){return this.participantInfo?new Date(Number.parseInt(this.participantInfo.joinedAt.toString())*1e3):new Date}updateInfo(e){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.permission&&this.setPermissions(e.permission),this.participantInfo=e,this.log.trace("update participant info",Object.assign(Object.assign({},this.logContext),{info:e})),!0)}_setMetadata(e){const t=this.metadata!==e,i=this.metadata;this.metadata=e,t&&this.emit(O.ParticipantMetadataChanged,i)}_setName(e){const t=this.name!==e;this.name=e,t&&this.emit(O.ParticipantNameChanged,e)}_setAttributes(e){const t=Th(this.attributes,e);this._attributes=e,Object.keys(t).length>0&&this.emit(O.AttributesChanged,t)}setPermissions(e){var t,i,s,r,a,o;const c=this.permissions,d=e.canPublish!==((t=this.permissions)===null||t===void 0?void 0:t.canPublish)||e.canSubscribe!==((i=this.permissions)===null||i===void 0?void 0:i.canSubscribe)||e.canPublishData!==((s=this.permissions)===null||s===void 0?void 0:s.canPublishData)||e.hidden!==((r=this.permissions)===null||r===void 0?void 0:r.hidden)||e.recorder!==((a=this.permissions)===null||a===void 0?void 0:a.recorder)||e.canPublishSources.length!==this.permissions.canPublishSources.length||e.canPublishSources.some((l,u)=>{var h;return l!==((h=this.permissions)===null||h===void 0?void 0:h.canPublishSources[u])})||e.canSubscribeMetrics!==((o=this.permissions)===null||o===void 0?void 0:o.canSubscribeMetrics);return this.permissions=e,d&&this.emit(O.ParticipantPermissionsChanged,c),d}setIsSpeaking(e){e!==this.isSpeaking&&(this.isSpeaking=e,e&&(this.lastSpokeAt=new Date),this.emit(O.IsSpeakingChanged,e))}setConnectionQuality(e){const t=this._connectionQuality;this._connectionQuality=pf(e),t!==this._connectionQuality&&this.emit(O.ConnectionQualityChanged,this._connectionQuality)}setAudioContext(e){this.audioContext=e,this.audioTrackPublications.forEach(t=>st(t.track)&&t.track.setAudioContext(e))}addTrackPublication(e){e.on(R.Muted,()=>{this.emit(O.TrackMuted,e)}),e.on(R.Unmuted,()=>{this.emit(O.TrackUnmuted,e)});const t=e;switch(t.track&&(t.track.sid=e.trackSid),this.trackPublications.set(e.trackSid,e),e.kind){case S.Kind.Audio:this.audioTrackPublications.set(e.trackSid,e);break;case S.Kind.Video:this.videoTrackPublications.set(e.trackSid,e);break}}}function mf(n){var e,t,i;if(!n.participantSid&&!n.participantIdentity)throw new Error("Invalid track permission, must provide at least one of participantIdentity and participantSid");return new so({participantIdentity:(e=n.participantIdentity)!==null&&e!==void 0?e:"",participantSid:(t=n.participantSid)!==null&&t!==void 0?t:"",allTracks:(i=n.allowAll)!==null&&i!==void 0?i:!1,trackSids:n.allowedTrackSids||[]})}const qc=15e3;class gf extends Vc{constructor(e,t,i,s,r){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=xe.NONE,this.enabledPublishVideoCodecs=[],this.pendingAcks=new Map,this.pendingResponses=new Map,this.handleReconnecting=()=>{this.reconnectFuture||(this.reconnectFuture=new uc)},this.handleReconnected=()=>{var a,o;(o=(a=this.reconnectFuture)===null||a===void 0?void 0:a.resolve)===null||o===void 0||o.call(a),this.reconnectFuture=void 0,this.updateTrackSubscriptionPermissions()},this.handleDisconnected=()=>{var a,o;this.reconnectFuture&&(this.reconnectFuture.promise.catch(c=>this.log.warn(c.message,this.logContext)),(o=(a=this.reconnectFuture)===null||a===void 0?void 0:a.reject)===null||o===void 0||o.call(a,"Got disconnected during reconnection attempt"),this.reconnectFuture=void 0)},this.handleSignalRequestResponse=a=>{const{requestId:o,reason:c,message:d}=a,l=this.pendingSignalRequests.get(o);l&&(c!==Fs.OK&&l.reject(new ec(d,c)),this.pendingSignalRequests.delete(o))},this.handleDataPacket=a=>{switch(a.value.case){case"rpcResponse":let o=a.value.value,c=null,d=null;o.value.case==="payload"?c=o.value.value:o.value.case==="error"&&(d=ce.fromProto(o.value.value)),this.handleIncomingRpcResponse(o.requestId,c,d);break;case"rpcAck":let l=a.value.value;this.handleIncomingRpcAck(l.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(a=>mf(a)))},this.onTrackUnmuted=a=>{this.onTrackMuted(a,a.isUpstreamPaused)},this.onTrackMuted=(a,o)=>{if(o===void 0&&(o=!0),!a.sid){this.log.error("could not update mute status for unpublished track",Object.assign(Object.assign({},this.logContext),Q(a)));return}this.engine.updateMuteStatus(a.sid,o)},this.onTrackUpstreamPaused=a=>{this.log.debug("upstream paused",Object.assign(Object.assign({},this.logContext),Q(a))),this.onTrackMuted(a,!0)},this.onTrackUpstreamResumed=a=>{this.log.debug("upstream resumed",Object.assign(Object.assign({},this.logContext),Q(a))),this.onTrackMuted(a,a.isMuted)},this.onTrackFeatureUpdate=a=>{const o=this.audioTrackPublications.get(a.sid);if(!o){this.log.warn("Could not update local audio track settings, missing publication for track ".concat(a.sid),this.logContext);return}this.engine.client.sendUpdateLocalAudioTrack(o.trackSid,o.getTrackFeatures())},this.handleSubscribedQualityUpdate=a=>p(this,void 0,void 0,function*(){var o,c,d,l,u,h;if(!(!((u=this.roomOptions)===null||u===void 0)&&u.dynacast))return;const f=this.videoTrackPublications.get(a.trackSid);if(!f){this.log.warn("received subscribed quality update for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:a.trackSid}));return}if(a.subscribedCodecs.length>0){if(!f.videoTrack)return;const T=yield f.videoTrack.setPublishingCodecs(a.subscribedCodecs);try{for(var g=!0,m=bt(T),v;v=yield m.next(),o=v.done,!o;g=!0){l=v.value,g=!1;const x=l;Xu(x)&&(this.log.debug("publish ".concat(x," for ").concat(f.videoTrack.sid),Object.assign(Object.assign({},this.logContext),Q(f))),yield this.publishAdditionalCodecForTrack(f.videoTrack,x,f.options))}}catch(x){c={error:x}}finally{try{!g&&!o&&(d=m.return)&&(yield d.call(m))}finally{if(c)throw c.error}}}else a.subscribedQualities.length>0&&(yield(h=f.videoTrack)===null||h===void 0?void 0:h.setPublishingLayers(a.subscribedQualities))}),this.handleLocalTrackUnpublished=a=>{const o=this.trackPublications.get(a.trackSid);if(!o){this.log.warn("received unpublished event for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:a.trackSid}));return}this.unpublishTrack(o.track)},this.handleTrackEnded=a=>p(this,void 0,void 0,function*(){if(a.source===S.Source.ScreenShare||a.source===S.Source.ScreenShareAudio)this.log.debug("unpublishing local track due to TrackEnded",Object.assign(Object.assign({},this.logContext),Q(a))),this.unpublishTrack(a);else if(a.isUserProvided)yield a.mute();else if(Bt(a)||Et(a))try{if(Pe())try{const o=yield navigator==null?void 0:navigator.permissions.query({name:a.source===S.Source.Camera?"camera":"microphone"});if(o&&o.state==="denied")throw this.log.warn("user has revoked access to ".concat(a.source),Object.assign(Object.assign({},this.logContext),Q(a))),o.onchange=()=>{o.state!=="denied"&&(a.isMuted||a.restartTrack(),o.onchange=null)},new Error("GetUserMedia Permission denied")}catch{}a.isMuted||(this.log.debug("track ended, attempting to use a different device",Object.assign(Object.assign({},this.logContext),Q(a))),Bt(a)?yield a.restartTrack({deviceId:"default"}):yield a.restartTrack())}catch{this.log.warn("could not restart track, muting instead",Object.assign(Object.assign({},this.logContext),Q(a))),yield a.mute()}}),this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this.engine=i,this.roomOptions=s,this.setupEngine(i),this.activeDeviceMap=new Map([["audioinput","default"],["videoinput","default"],["audiooutput","default"]]),this.pendingSignalRequests=new Map,this.rpcHandlers=r}get lastCameraError(){return this.cameraError}get lastMicrophoneError(){return this.microphoneError}get isE2EEEnabled(){return this.encryptionType!==xe.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){this.engine=e,this.engine.on(I.RemoteMute,(t,i)=>{const s=this.trackPublications.get(t);!s||!s.track||(i?s.mute():s.unmute())}),this.engine.on(I.Connected,this.handleReconnected).on(I.SignalRestarted,this.handleReconnected).on(I.SignalResumed,this.handleReconnected).on(I.Restarting,this.handleReconnecting).on(I.Resuming,this.handleReconnecting).on(I.LocalTrackUnpublished,this.handleLocalTrackUnpublished).on(I.SubscribedQualityUpdate,this.handleSubscribedQualityUpdate).on(I.Disconnected,this.handleDisconnected).on(I.SignalRequestResponse,this.handleSignalRequestResponse).on(I.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 i=this;let{metadata:s,name:r,attributes:a}=t;return function*(){return new Promise((o,c)=>p(i,void 0,void 0,function*(){var d,l;try{let u=!1;const h=yield this.engine.client.sendUpdateLocalMetadata((d=s??this.metadata)!==null&&d!==void 0?d:"",(l=r??this.name)!==null&&l!==void 0?l:"",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[m,v]=g;return this.attributes[m]===v||v===""&&!this.attributes[m]}))){this.pendingSignalRequests.delete(h),o();return}yield we(50)}c(new ec("Request to update local metadata timed out","TimeoutError"))}catch(u){u instanceof Error&&c(u)}}))}()})}setCameraEnabled(e,t,i){return this.setTrackEnabled(S.Source.Camera,e,t,i)}setMicrophoneEnabled(e,t,i){return this.setTrackEnabled(S.Source.Microphone,e,t,i)}setScreenShareEnabled(e,t,i){return this.setTrackEnabled(S.Source.ScreenShare,e,t,i)}setPermissions(e){const t=this.permissions,i=super.setPermissions(e);return i&&t&&this.emit(O.ParticipantPermissionsChanged,t),i}setE2EEEnabled(e){return p(this,void 0,void 0,function*(){this.encryptionType=e?xe.GCM:xe.NONE,yield this.republishAllTracks(void 0,!1)})}setTrackEnabled(e,t,i,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 d=yield this.waitForPendingPublicationOfSource(e);return d||this.log.info("waiting for pending publication promise timed out",Object.assign(Object.assign({},this.logContext),{source:e})),yield d==null?void 0:d.unmute(),d}this.pendingPublishing.add(e);try{switch(e){case S.Source.Camera:c=yield this.createTracks({video:(r=i)!==null&&r!==void 0?r:!0});break;case S.Source.Microphone:c=yield this.createTracks({audio:(a=i)!==null&&a!==void 0?a:!0});break;case S.Source.ScreenShare:c=yield this.createScreenTracks(Object.assign({},i));break;default:throw new nt(e)}}catch(d){throw c==null||c.forEach(l=>{l.stop()}),d instanceof Error&&this.emit(O.MediaDevicesError,d),this.pendingPublishing.delete(e),d}try{const d=[];for(const u of c)this.log.info("publishing track",Object.assign(Object.assign({},this.logContext),Q(u))),d.push(this.publishTrack(u,s));[o]=yield Promise.all(d)}catch(d){throw c==null||c.forEach(l=>{l.stop()}),d}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===S.Source.ScreenShare){o=yield this.unpublishTrack(o.track);const c=this.getTrackPublication(S.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(S.Source.Camera)||this.pendingPublishing.has(S.Source.Microphone))){this.pendingPublishing.add(S.Source.Camera),this.pendingPublishing.add(S.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(S.Source.Camera),this.pendingPublishing.delete(S.Source.Microphone)}}})}createTracks(e){return p(this,void 0,void 0,function*(){var t,i;e??(e={});const s=fc(e,(t=this.roomOptions)===null||t===void 0?void 0:t.audioCaptureDefaults,(i=this.roomOptions)===null||i===void 0?void 0:i.videoCaptureDefaults);try{return(yield Kn(s,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext})).map(o=>(st(o)&&(this.microphoneError=void 0,o.setAudioContext(this.audioContext),o.source=S.Source.Microphone,this.emit(O.AudioStreamAcquired)),li(o)&&(this.cameraError=void 0,o.source=S.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 Zs("getDisplayMedia not supported");e.resolution===void 0&&!rh()&&(e.resolution=ir.h1080fps30.resolution);const t=yh(e),i=yield navigator.mediaDevices.getDisplayMedia(t),s=i.getVideoTracks();if(s.length===0)throw new nt("no video track found");const r=new Wn(s[0],void 0,!1,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});r.source=S.Source.ScreenShare,e.contentHint&&(r.mediaStreamTrack.contentHint=e.contentHint);const a=[r];if(i.getAudioTracks().length>0){this.emit(O.AudioStreamAcquired);const o=new zn(i.getAudioTracks()[0],void 0,!1,this.audioContext,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});o.source=S.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(i,s){var r=this;let a=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1;return function*(){var o,c,d,l;Bt(i)&&i.setAudioContext(r.audioContext),yield(o=r.reconnectFuture)===null||o===void 0?void 0:o.promise,r.republishPromise&&!a&&(yield r.republishPromise),di(i)&&r.pendingPublishPromises.has(i)&&(yield r.pendingPublishPromises.get(i));let u;if(i instanceof MediaStreamTrack)u=i.getConstraints();else{u=i.constraints;let T;switch(i.source){case S.Source.Microphone:T="audioinput";break;case S.Source.Camera:T="videoinput"}T&&r.activeDeviceMap.has(T)&&(u=Object.assign(Object.assign({},u),{deviceId:r.activeDeviceMap.get(T)}))}if(i instanceof MediaStreamTrack)switch(i.kind){case"audio":i=new zn(i,u,!0,r.audioContext,{loggerName:r.roomOptions.loggerName,loggerContextCb:()=>r.logContext});break;case"video":i=new Wn(i,u,!0,{loggerName:r.roomOptions.loggerName,loggerContextCb:()=>r.logContext});break;default:throw new nt("unsupported MediaStreamTrack kind ".concat(i.kind))}else i.updateLoggerOptions({loggerName:r.roomOptions.loggerName,loggerContextCb:()=>r.logContext});let h;if(r.trackPublications.forEach(T=>{T.track&&T.track===i&&(h=T)}),h)return r.log.warn("track has already been published, skipping",Object.assign(Object.assign({},r.logContext),Q(h))),h;const f="channelCount"in i.mediaStreamTrack.getSettings()&&i.mediaStreamTrack.getSettings().channelCount===2||i.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),Q(i))),s.red===void 0&&r.log.info("Opus RED will be disabled for stereo tracks by default. Enable them explicitly to make it work."),(d=s.dtx)!==null&&d!==void 0||(s.dtx=!1),(l=s.red)!==null&&l!==void 0||(s.red=!1));const m=Object.assign(Object.assign({},r.roomOptions.publishDefaults),s);!ah()&&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)),m.simulcast=!1),m.source&&(i.source=m.source);const v=new Promise((T,x)=>p(r,void 0,void 0,function*(){try{if(this.engine.client.currentState!==ne.CONNECTED){this.log.debug("deferring track publication until signal is connected",Object.assign(Object.assign({},this.logContext),{track:Q(i)}));const P=()=>p(this,void 0,void 0,function*(){try{const y=yield this.publish(i,m,g);T(y)}catch(y){x(y)}});setTimeout(()=>{this.engine.off(I.SignalConnected,P),x(new Ys("publishing rejected as engine not connected within timeout",408))},15e3),this.engine.once(I.SignalConnected,P),this.engine.on(I.Closing,()=>{this.engine.off(I.SignalConnected,P),x(new Ys("publishing rejected as engine closed",499))})}else try{const P=yield this.publish(i,m,g);T(P)}catch(P){x(P)}}catch(P){x(P)}}));r.pendingPublishPromises.set(i,v);try{return yield v}catch(T){throw T}finally{r.pendingPublishPromises.delete(i)}}()})}hasPermissionsToPublish(e){if(!this.permissions)return this.log.warn("no permissions present for publishing track",Object.assign(Object.assign({},this.logContext),Q(e))),!1;const{canPublish:t,canPublishSources:i}=this.permissions;return t&&(i.length===0||i.map(s=>Sh(s)).includes(e.source))?!0:(this.log.warn("insufficient permissions to publish",Object.assign(Object.assign({},this.logContext),Q(e))),!1)}publish(e,t,i){return p(this,void 0,void 0,function*(){var s,r,a,o,c,d,l,u,h,f;if(!this.hasPermissionsToPublish(e))throw new Ys("failed to publish track, insufficient permissions",403);Array.from(this.trackPublications.values()).find(b=>di(e)&&b.source===e.source)&&e.source!==S.Source.Unknown&&this.log.info("publishing a second track with the same source: ".concat(e.source),Object.assign(Object.assign({},this.logContext),Q(e))),t.stopMicTrackOnMute&&st(e)&&(e.stopOnMute=!0),e.source===S.Source.ScreenShare&&ci()&&(t.simulcast=!1),t.videoCodec==="av1"&&!ih()&&(t.videoCodec=void 0),t.videoCodec==="vp9"&&!nh()&&(t.videoCodec=void 0),t.videoCodec===void 0&&(t.videoCodec=Sr),this.enabledPublishVideoCodecs.length>0&&(this.enabledPublishVideoCodecs.some(b=>t.videoCodec===Bn(b.mime))||(t.videoCodec=Bn(this.enabledPublishVideoCodecs[0].mime)));const m=t.videoCodec;e.on(R.Muted,this.onTrackMuted),e.on(R.Unmuted,this.onTrackUnmuted),e.on(R.Ended,this.handleTrackEnded),e.on(R.UpstreamPaused,this.onTrackUpstreamPaused),e.on(R.UpstreamResumed,this.onTrackUpstreamResumed),e.on(R.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate);const v=new Ds({cid:e.mediaStreamTrack.id,name:t.name,type:S.kindToProto(e.kind),muted:e.isMuted,source:S.sourceToProto(e.source),disableDtx:!(!((s=t.dtx)!==null&&s!==void 0)||s),encryption:this.encryptionType,stereo:i,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});let T;if(e.kind===S.Kind.Video){let b={width:0,height:0};try{b=yield e.waitForDimensions()}catch{const M=(o=(a=this.roomOptions.videoCaptureDefaults)===null||a===void 0?void 0:a.resolution)!==null&&o!==void 0?o:Ni.h720.resolution;b={width:M.width,height:M.height},this.log.error("could not determine track dimensions, using defaults",Object.assign(Object.assign(Object.assign({},this.logContext),Q(e)),{dims:b}))}v.width=b.width,v.height=b.height,Et(e)&&(Li(m)&&(e.source===S.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),Q(e))))),t.scalabilityMode=(c=t.scalabilityMode)!==null&&c!==void 0?c:"L3T3_KEY"),v.simulcastCodecs=[new Os({codec:m,cid:e.mediaStreamTrack.id})],t.backupCodec===!0&&(t.backupCodec={codec:Sr}),t.backupCodec&&m!==t.backupCodec.codec&&v.encryption===xe.NONE&&(this.roomOptions.dynacast||(this.roomOptions.dynacast=!0),v.simulcastCodecs.push(new Os({codec:t.backupCodec.codec,cid:""})))),T=Pr(e.source===S.Source.ScreenShare,v.width,v.height,t),v.layers=Lc(v.width,v.height,T,Li(t.videoCodec))}else e.kind===S.Kind.Audio&&(T=[{maxBitrate:(d=t.audioPreset)===null||d===void 0?void 0:d.maxBitrate,priority:(u=(l=t.audioPreset)===null||l===void 0?void 0:l.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 fe("cannot publish track when not connected");const x=()=>p(this,void 0,void 0,function*(){var b,E,M;if(!this.engine.pcManager)throw new fe("pcManager is not ready");if(e.sender=yield this.engine.createSender(e,t,T),Et(e)&&((b=t.degradationPreference)!==null&&b!==void 0||(t.degradationPreference=Yh(e)),e.setDegradationPreference(t.degradationPreference)),T)if(ci()&&e.kind===S.Kind.Audio){let U;for(const W of this.engine.pcManager.publisher.getTransceivers())if(W.sender===e.sender){U=W;break}U&&this.engine.pcManager.publisher.setTrackCodecBitrate({transceiver:U,codec:"opus",maxbr:!((E=T[0])===null||E===void 0)&&E.maxBitrate?T[0].maxBitrate/1e3:0})}else e.codec&&Li(e.codec)&&(!((M=T[0])===null||M===void 0)&&M.maxBitrate)&&this.engine.pcManager.publisher.setTrackCodecBitrate({cid:v.cid,codec:e.codec,maxbr:T[0].maxBitrate/1e3});yield this.engine.negotiate()});let P;if(this.enabledPublishVideoCodecs.length>0)P=(yield Promise.all([this.engine.addTrack(v),x()]))[0];else{P=yield this.engine.addTrack(v);let b;if(P.codecs.forEach(E=>{b===void 0&&(b=E.mimeType)}),b&&e.kind===S.Kind.Video){const E=Bn(b);E!==m&&(this.log.debug("falling back to server selected codec",Object.assign(Object.assign(Object.assign({},this.logContext),Q(e)),{codec:E})),t.videoCodec=E,T=Pr(e.source===S.Source.ScreenShare,v.width,v.height,t))}yield x()}const y=new Dr(e.kind,P,e,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});return y.options=t,e.sid=P.sid,this.log.debug("publishing ".concat(e.kind," with encodings"),Object.assign(Object.assign({},this.logContext),{encodings:T,trackInfo:P})),Et(e)?e.startMonitor(this.engine.client):Bt(e)&&e.startMonitor(),this.addTrackPublication(y),this.emit(O.LocalTrackPublished,y),y})}get isLocal(){return!0}publishAdditionalCodecForTrack(e,t,i){return p(this,void 0,void 0,function*(){var s;if(this.encryptionType!==xe.NONE)return;let r;if(this.trackPublications.forEach(f=>{f.track&&f.track===e&&(r=f)}),!r)throw new nt("track is not published");if(!Et(e))throw new nt("track is not a video track");const a=Object.assign(Object.assign({},(s=this.roomOptions)===null||s===void 0?void 0:s.publishDefaults),i),o=Hh(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),Q(e)));return}const c=e.addSimulcastTrack(t,o);if(!c)return;const d=new Ds({cid:c.mediaStreamTrack.id,type:S.kindToProto(e.kind),muted:e.isMuted,source:S.sourceToProto(e.source),sid:e.sid,simulcastCodecs:[{codec:a.videoCodec,cid:c.mediaStreamTrack.id}]});if(d.layers=Lc(d.width,d.height,o),!this.engine||this.engine.isClosed)throw new fe("cannot publish track when not connected");const l=()=>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(d),l()]))[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 i,s;if(di(e)){const d=this.pendingPublishPromises.get(e);d&&(this.log.info("awaiting publish promise before attempting to unpublish",Object.assign(Object.assign({},this.logContext),Q(e))),yield d)}const r=this.getPublicationForTrack(e),a=r?Q(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(R.Muted,this.onTrackMuted),e.off(R.Unmuted,this.onTrackUnmuted),e.off(R.Ended,this.handleTrackEnded),e.off(R.UpstreamPaused,this.onTrackUpstreamPaused),e.off(R.UpstreamResumed,this.onTrackUpstreamResumed),e.off(R.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate),t===void 0&&(t=(s=(i=this.roomOptions)===null||i===void 0?void 0:i.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<oe.FAILED&&c)try{for(const d of this.engine.pcManager.publisher.getTransceivers())d.sender===c&&(d.direction="inactive",o=!0);if(this.engine.removeTrack(c)&&(o=!0),Et(e)){for(const[,d]of e.simulcastCodecs)d.sender&&(this.engine.removeTrack(d.sender)&&(o=!0),d.sender=void 0);e.simulcastCodecs.clear()}}catch(d){this.log.warn("failed to unpublish track",Object.assign(Object.assign(Object.assign({},this.logContext),a),{error:d}))}switch(this.trackPublications.delete(r.trackSid),r.kind){case S.Kind.Audio:this.audioTrackPublications.delete(r.trackSid);break;case S.Kind.Video:this.videoTrackPublications.delete(r.trackSid);break}return this.emit(O.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(i=>this.unpublishTrack(i)))).filter(i=>!!i)})}republishAllTracks(e){return p(this,arguments,void 0,function(t){var i=this;let s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){i.republishPromise&&(yield i.republishPromise),i.republishPromise=new Promise((r,a)=>p(i,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 d=c.track;yield this.unpublishTrack(d,!1),s&&!d.isMuted&&d.source!==S.Source.ScreenShare&&d.source!==S.Source.ScreenShareAudio&&(Bt(d)||Et(d))&&!d.isUserProvided&&(this.log.debug("restarting existing track",Object.assign(Object.assign({},this.logContext),{track:c.trackSid})),yield d.restartTrack()),yield this.publishOrRepublishTrack(d,c.options,!0)}))),r()}catch(o){a(o)}finally{this.republishPromise=void 0}})),yield i.republishPromise}()})}publishData(e){return p(this,arguments,void 0,function(t){var i=this;let s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return function*(){const r=s.reliable?J.RELIABLE:J.LOSSY,a=s.destinationIdentities,o=s.topic,c=new Ee({kind:r,value:{case:"user",value:new Fa({participantIdentity:i.identity,payload:t,destinationIdentities:a,topic:o})}});yield i.engine.sendDataPacket(c,r)}()})}publishDtmf(e,t){return p(this,void 0,void 0,function*(){const i=new Ee({kind:J.RELIABLE,value:{case:"sipDtmf",value:new ja({code:e,digit:t})}});yield this.engine.sendDataPacket(i,J.RELIABLE)})}sendChatMessage(e,t){return p(this,void 0,void 0,function*(){const i={id:crypto.randomUUID(),message:e,timestamp:Date.now(),attachedFiles:t==null?void 0:t.attachments},s=new Ee({value:{case:"chatMessage",value:new ws(Object.assign(Object.assign({},i),{timestamp:se.parse(i.timestamp)}))}});return yield this.engine.sendDataPacket(s,J.RELIABLE),this.emit(O.ChatMessage,i),i})}editChatMessage(e,t){return p(this,void 0,void 0,function*(){const i=Object.assign(Object.assign({},t),{message:e,editTimestamp:Date.now()}),s=new Ee({value:{case:"chatMessage",value:new ws(Object.assign(Object.assign({},i),{timestamp:se.parse(i.timestamp),editTimestamp:se.parse(i.editTimestamp)}))}});return yield this.engine.sendDataPacket(s,J.RELIABLE),this.emit(O.ChatMessage,i),i})}sendText(e,t){return p(this,void 0,void 0,function*(){var i;const s=crypto.randomUUID(),a=new TextEncoder().encode(e).byteLength,o=(i=t==null?void 0:t.attachments)===null||i===void 0?void 0:i.map(()=>crypto.randomUUID()),c=new Array(o?o.length+1:1).fill(0),d=(u,h)=>{var f;c[h]=u;const g=c.reduce((m,v)=>m+v,0);(f=t==null?void 0:t.onProgress)===null||f===void 0||f.call(t,g)},l=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 l.write(e),d(1,0),yield l.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=>{d(f,h+1)}})})))),l.info})}streamText(e){return p(this,void 0,void 0,function*(){var t,i;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:(i=e==null?void 0:e.topic)!==null&&i!==void 0?i:"",size:e==null?void 0:e.totalSize,attributes:e==null?void 0:e.attributes},a=new Rs({streamId:s,mimeType:r.mimeType,topic:r.topic,timestamp:$t(r.timestamp),totalLength:$t(e==null?void 0:e.totalSize),attributes:r.attributes,contentHeader:{case:"textHeader",value:new Ja({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"?Ps.UPDATE:Ps.CREATE})}}),o=e==null?void 0:e.destinationIdentities,c=new Ee({destinationIdentities:o,value:{case:"streamHeader",value:a}});yield this.engine.sendDataPacket(c,J.RELIABLE);let d=0;const l=this,u=new WritableStream({write(g){return p(this,void 0,void 0,function*(){for(const m of gh(g,qc)){yield l.engine.waitForBufferStatusLow(J.RELIABLE);const v=new xs({content:m,streamId:s,chunkIndex:$t(d)}),T=new Ee({destinationIdentities:o,value:{case:"streamChunk",value:v}});yield l.engine.sendDataPacket(T,J.RELIABLE),d+=1}})},close(){return p(this,void 0,void 0,function*(){const g=new Is({streamId:s}),m=new Ee({destinationIdentities:o,value:{case:"streamTrailer",value:g}});yield l.engine.sendDataPacket(m,J.RELIABLE)})},abort(g){console.log("Sink error:",g)}});let h=()=>p(this,void 0,void 0,function*(){yield f.close()});l.engine.once(I.Closing,h);const f=new of(u,r,()=>this.engine.off(I.Closing,h));return f})}sendFile(e,t){return p(this,void 0,void 0,function*(){const i=crypto.randomUUID();return yield this._sendFile(i,e,t),{id:i}})}_sendFile(e,t,i){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=i==null?void 0:i.mimeType)!==null&&s!==void 0?s:t.type,topic:i==null?void 0:i.topic,destinationIdentities:i==null?void 0:i.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,i,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,d={id:o,mimeType:(i=e==null?void 0:e.mimeType)!==null&&i!==void 0?i:"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"},l=new Rs({totalLength:$t((a=d.size)!==null&&a!==void 0?a:0),mimeType:d.mimeType,streamId:o,topic:d.topic,timestamp:$t(Date.now()),contentHeader:{case:"byteHeader",value:new Ya({name:d.name})}}),u=new Ee({destinationIdentities:c,value:{case:"streamHeader",value:l}});yield this.engine.sendDataPacket(u,J.RELIABLE);let h=0;const f=new Ce,g=this.engine,m=this.log,v=new WritableStream({write(x){return p(this,void 0,void 0,function*(){const P=yield f.lock();let y=0;try{for(;y<x.byteLength;){const b=x.slice(y,y+qc);yield g.waitForBufferStatusLow(J.RELIABLE);const E=new Ee({destinationIdentities:c,value:{case:"streamChunk",value:new xs({content:b,streamId:o,chunkIndex:$t(h)})}});yield g.sendDataPacket(E,J.RELIABLE),h+=1,y+=b.byteLength}}finally{P()}})},close(){return p(this,void 0,void 0,function*(){const x=new Is({streamId:o}),P=new Ee({destinationIdentities:c,value:{case:"streamTrailer",value:x}});yield g.sendDataPacket(P,J.RELIABLE)})},abort(x){m.error("Sink error:",x)}});return new cf(v,d)})}performRpc(e){return p(this,arguments,void 0,function(t){var i=this;let{destinationIdentity:s,method:r,payload:a,responseTimeout:o=1e4}=t;return function*(){return new Promise((d,l)=>p(i,void 0,void 0,function*(){var u,h,f,g;if(_r(a)>xc){l(ce.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&&jt((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){l(ce.builtIn("UNSUPPORTED_SERVER"));return}const m=crypto.randomUUID();yield this.publishRpcRequest(s,m,r,a,o-2e3);const v=setTimeout(()=>{this.pendingAcks.delete(m),l(ce.builtIn("CONNECTION_TIMEOUT")),this.pendingResponses.delete(m),clearTimeout(T)},2e3);this.pendingAcks.set(m,{resolve:()=>{clearTimeout(v)},participantIdentity:s});const T=setTimeout(()=>{this.pendingResponses.delete(m),l(ce.builtIn("RESPONSE_TIMEOUT"))},o);this.pendingResponses.set(m,{resolve:(x,P)=>{clearTimeout(T),this.pendingAcks.has(m)&&(console.warn("RPC response received before ack",m),this.pendingAcks.delete(m),clearTimeout(v)),P?l(P):d(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,i){const s=this.pendingResponses.get(e);s?(s.resolve(t,i),this.pendingResponses.delete(e)):console.error("Response received for unexpected RPC request",e)}publishRpcRequest(e,t,i,s,r){return p(this,void 0,void 0,function*(){const a=new Ee({destinationIdentities:[e],kind:J.RELIABLE,value:{case:"rpcRequest",value:new $a({id:t,method:i,payload:s,responseTimeoutMs:r,version:1})}});yield this.engine.sendDataPacket(a,J.RELIABLE)})}handleParticipantDisconnected(e){for(const[t,{participantIdentity:i}]of this.pendingAcks)i===e&&this.pendingAcks.delete(t);for(const[t,{participantIdentity:i,resolve:s}]of this.pendingResponses)i===e&&(s(null,ce.builtIn("RECIPIENT_DISCONNECTED")),this.pendingResponses.delete(t))}setEnabledPublishCodecs(e){this.enabledPublishVideoCodecs=e.filter(t=>t.mime.split("/")[0].toLowerCase()==="video")}updateInfo(e){return e.sid!==this.sid||!super.updateInfo(e)?!1:(e.tracks.forEach(t=>{var i,s;const r=this.trackPublications.get(t.sid);if(r){const a=r.isMuted||((s=(i=r.track)===null||i===void 0?void 0:i.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),Q(r)),{mutedOnServer:a})),this.engine.client.sendMuteTrack(t.sid,a))}}),!0)}getPublicationForTrack(e){let t;return this.trackPublications.forEach(i=>{const s=i.track;s&&(e instanceof MediaStreamTrack?(Bt(s)||Et(s))&&s.mediaStreamTrack===e&&(t=i):e===s&&(t=i))}),t}waitForPendingPublicationOfSource(e){return p(this,void 0,void 0,function*(){const i=Date.now();for(;Date.now()<i+1e4;){const s=Array.from(this.pendingPublishPromises.entries()).find(r=>{let[a]=r;return a.source===e});if(s)return s[1];yield we(20)}})}}class vf extends rt{constructor(e,t,i,s){super(e,t.sid,t.name,s),this.track=void 0,this.allowed=!0,this.disabled=!1,this.currentVideoQuality=Ae.HIGH,this.handleEnded=r=>{this.setTrack(void 0),this.emit(R.Ended,r)},this.handleVisibilityChange=r=>{this.log.debug("adaptivestream video visibility ".concat(this.trackSid,", visible=").concat(r),this.logContext),this.disabled=!r,this.emitTrackUpdate()},this.handleVideoDimensionsChange=r=>{this.log.debug("adaptivestream video dimensions ".concat(r.width,"x").concat(r.height),this.logContext),this.videoDimensions=r,this.emitTrackUpdate()},this.subscribed=i,this.updateInfo(t)}setSubscribed(e){const t=this.subscriptionStatus,i=this.permissionStatus;this.subscribed=e,e&&(this.allowed=!0);const s=new wn({trackSids:[this.trackSid],subscribe:this.subscribed,participantTracks:[new za({participantSid:"",trackSids:[this.trackSid]})]});this.emit(R.UpdateSubscription,s),this.emitSubscriptionUpdateIfChanged(t),this.emitPermissionUpdateIfChanged(i)}get subscriptionStatus(){return this.subscribed===!1?rt.SubscriptionStatus.Unsubscribed:super.isSubscribed?rt.SubscriptionStatus.Subscribed:rt.SubscriptionStatus.Desired}get permissionStatus(){return this.allowed?rt.PermissionStatus.Allowed:rt.PermissionStatus.NotAllowed}get isSubscribed(){return this.subscribed===!1?!1:super.isSubscribed}get isDesired(){return this.subscribed!==!1}get isEnabled(){return!this.disabled}get isLocal(){return!1}setEnabled(e){!this.isManualOperationAllowed()||this.disabled===!e||(this.disabled=!e,this.emitTrackUpdate())}setVideoQuality(e){!this.isManualOperationAllowed()||this.currentVideoQuality===e||(this.currentVideoQuality=e,this.videoDimensions=void 0,this.emitTrackUpdate())}setVideoDimensions(e){var t,i;this.isManualOperationAllowed()&&(((t=this.videoDimensions)===null||t===void 0?void 0:t.width)===e.width&&((i=this.videoDimensions)===null||i===void 0?void 0:i.height)===e.height||(hr(this.track)&&(this.videoDimensions=e),this.currentVideoQuality=void 0,this.emitTrackUpdate()))}setVideoFPS(e){this.isManualOperationAllowed()&&hr(this.track)&&this.fps!==e&&(this.fps=e,this.emitTrackUpdate())}get videoQuality(){return this.currentVideoQuality}setTrack(e){const t=this.subscriptionStatus,i=this.permissionStatus,s=this.track;s!==e&&(s&&(s.off(R.VideoDimensionsChanged,this.handleVideoDimensionsChange),s.off(R.VisibilityChanged,this.handleVisibilityChange),s.off(R.Ended,this.handleEnded),s.detach(),s.stopMonitor(),this.emit(R.Unsubscribed,s)),super.setTrack(e),e&&(e.sid=this.trackSid,e.on(R.VideoDimensionsChanged,this.handleVideoDimensionsChange),e.on(R.VisibilityChanged,this.handleVisibilityChange),e.on(R.Ended,this.handleEnded),this.emit(R.Subscribed,e)),this.emitPermissionUpdateIfChanged(i),this.emitSubscriptionUpdateIfChanged(t))}setAllowed(e){const t=this.subscriptionStatus,i=this.permissionStatus;this.allowed=e,this.emitPermissionUpdateIfChanged(i),this.emitSubscriptionUpdateIfChanged(t)}setSubscriptionError(e){this.emit(R.SubscriptionFailed,e)}updateInfo(e){super.updateInfo(e);const t=this.metadataMuted;this.metadataMuted=e.muted,this.track?this.track.setMuted(e.muted):t!==e.muted&&this.emit(e.muted?R.Muted:R.Unmuted)}emitSubscriptionUpdateIfChanged(e){const t=this.subscriptionStatus;e!==t&&this.emit(R.SubscriptionStatusChanged,t,e)}emitPermissionUpdateIfChanged(e){this.permissionStatus!==e&&this.emit(R.SubscriptionPermissionChanged,this.permissionStatus,e)}isManualOperationAllowed(){return this.kind===S.Kind.Video&&this.isAdaptiveStream?(this.log.warn("adaptive stream is enabled, cannot change video track settings",this.logContext),!1):this.isDesired?!0:(this.log.warn("cannot update track settings when not subscribed",this.logContext),!1)}get isAdaptiveStream(){return hr(this.track)&&this.track.isAdaptiveStream}emitTrackUpdate(){const e=new Xa({trackSids:[this.trackSid],disabled:this.disabled,fps:this.fps});this.videoDimensions?(e.width=Math.ceil(this.videoDimensions.width),e.height=Math.ceil(this.videoDimensions.height)):this.currentVideoQuality!==void 0?e.quality=this.currentVideoQuality:e.quality=Ae.HIGH,this.emit(R.UpdateSettings,e)}}class Hn extends Vc{static fromParticipantInfo(e,t,i){return new Hn(e,t.sid,t.identity,t.name,t.metadata,t.attributes,i,t.kind)}get logContext(){return Object.assign(Object.assign({},super.logContext),{rpID:this.sid,remoteParticipant:this.identity})}constructor(e,t,i,s,r,a,o){let c=arguments.length>7&&arguments[7]!==void 0?arguments[7]:En.STANDARD;super(t,i||"",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(R.UpdateSettings,t=>{this.log.debug("send update settings",Object.assign(Object.assign({},this.logContext),Q(e))),this.signalClient.sendUpdateTrackSettings(t)}),e.on(R.UpdateSubscription,t=>{t.participantTracks.forEach(i=>{i.participantSid=this.sid}),this.signalClient.sendUpdateSubscription(t)}),e.on(R.SubscriptionPermissionChanged,t=>{this.emit(O.TrackSubscriptionPermissionChanged,e,t)}),e.on(R.SubscriptionStatusChanged,t=>{this.emit(O.TrackSubscriptionStatusChanged,e,t)}),e.on(R.Subscribed,t=>{this.emit(O.TrackSubscribed,t,e)}),e.on(R.Unsubscribed,t=>{this.emit(O.TrackUnsubscribed,t,e)}),e.on(R.SubscriptionFailed,t=>{this.emit(O.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]:S.Source.Microphone;this.volumeMap.set(t,e);const i=this.getTrackPublication(t);i&&i.track&&i.track.setVolume(e)}getVolume(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:S.Source.Microphone;const t=this.getTrackPublication(e);return t&&t.track?t.track.getVolume():this.volumeMap.get(e)}addSubscribedMediaTrack(e,t,i,s,r,a){let o=this.getTrackPublicationBySid(t);if(o||t.startsWith("TR")||this.trackPublications.forEach(l=>{!o&&e.kind===l.kind.toString()&&(o=l)}),!o){if(a===0){this.log.error("could not find published track",Object.assign(Object.assign({},this.logContext),{trackSid:t})),this.emit(O.TrackSubscriptionFailed,t);return}a===void 0&&(a=20),setTimeout(()=>{this.addSubscribedMediaTrack(e,t,i,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),Q(o))),this.emit(O.TrackSubscriptionFailed,t);return}const c=e.kind==="video";let d;return c?d=new lf(e,t,s,r):d=new df(e,t,s,this.audioContext,this.audioOutput),d.source=o.source,d.isMuted=o.isMuted,d.setMediaStream(i),d.start(),o.setTrack(d),this.volumeMap.has(o.source)&&ur(d)&&st(d)&&d.setVolume(this.volumeMap.get(o.source)),o}get hasMetadata(){return!!this.participantInfo}getTrackPublicationBySid(e){return this.trackPublications.get(e)}updateInfo(e){if(!super.updateInfo(e))return!1;const t=new Map,i=new Map;return e.tracks.forEach(s=>{var r,a;let o=this.getTrackPublicationBySid(s.sid);if(o)o.updateInfo(s);else{const c=S.kindFromProto(s.type);if(!c)return;o=new vf(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),i.set(s.sid,o);const d=Array.from(this.trackPublications.values()).find(l=>l.source===(o==null?void 0:o.source));d&&o.source!==S.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:Q(d),newTrack:Q(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),Q(s))),this.unpublishTrack(s.trackSid,!0))}),i.forEach(s=>{this.emit(O.TrackPublished,s)}),!0}unpublishTrack(e,t){const i=this.trackPublications.get(e);if(!i)return;const{track:s}=i;switch(s&&(s.stop(),i.setTrack(void 0)),this.trackPublications.delete(e),i.kind){case S.Kind.Audio:this.audioTrackPublications.delete(e);break;case S.Kind.Video:this.videoTrackPublications.delete(e);break}t&&this.emit(O.TrackUnpublished,i)}setAudioOutput(e){return p(this,void 0,void 0,function*(){this.audioOutput=e;const t=[];this.audioTrackPublications.forEach(i=>{var s;st(i.track)&&ur(i.track)&&t.push(i.track.setSinkId((s=e.deviceId)!==null&&s!==void 0?s:"default"))}),yield Promise.all(t)})}emit(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),s=1;s<t;s++)i[s-1]=arguments[s];return this.log.trace("participant event",Object.assign(Object.assign({},this.logContext),{event:e,args:i})),super.emit(e,...i)}}var Y;(function(n){n.Disconnected="disconnected",n.Connecting="connecting",n.Connected="connected",n.Reconnecting="reconnecting",n.SignalReconnecting="signalReconnecting"})(Y||(Y={}));const yf=4*1e3;class Vt extends Ze.EventEmitter{constructor(e){var t,i,s,r;if(super(),t=this,this.state=Y.Disconnected,this.activeSpeakers=[],this.isE2EEEnabled=!1,this.audioEnabled=!0,this.isVideoPlaybackBlocked=!1,this.log=G,this.bufferedEvents=[],this.isResuming=!1,this.byteStreamControllers=new Map,this.textStreamControllers=new Map,this.byteStreamHandlers=new Map,this.textStreamHandlers=new Map,this.rpcHandlers=new Map,this.connect=(a,o,c)=>p(this,void 0,void 0,function*(){var d;if(!sh())throw Je()?Error("WebRTC isn't detected, have you called registerGlobals?"):Error("LiveKit doesn't seem to be supported on this browser. Try to update your browser and make sure no browser extensions are disabling webRTC.");const l=yield this.disconnectLock.lock();if(this.state===Y.Connected)return this.log.info("already connected to room ".concat(this.name),this.logContext),l(),Promise.resolve();if(this.connectFuture)return l(),this.connectFuture.promise;this.setAndEmitConnectionState(Y.Connecting),((d=this.regionUrlProvider)===null||d===void 0?void 0:d.getServerUrl().toString())!==a&&(this.regionUrl=void 0,this.regionUrlProvider=void 0),ar(new URL(a))&&(this.regionUrlProvider===void 0?this.regionUrlProvider=new Ir(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,m)=>p(this,void 0,void 0,function*(){var v,T;this.abortController&&this.abortController.abort();const x=new AbortController;this.abortController=x,l==null||l();try{yield this.attemptConnection(m??a,o,c,x),this.abortController=void 0,f()}catch(P){if(this.regionUrlProvider&&P instanceof te&&P.reason!==H.Cancelled&&P.reason!==H.NotAllowed){let y=null;try{y=yield this.regionUrlProvider.getNextBestRegionUrl((v=this.abortController)===null||v===void 0?void 0:v.signal)}catch(b){if(b instanceof te&&(b.status===401||b.reason===H.Cancelled)){this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),g(b);return}}y&&!(!((T=this.abortController)===null||T===void 0)&&T.signal.aborted)?(this.log.info("Initial connection failed with ConnectionError: ".concat(P.message,". Retrying with another region: ").concat(y),this.logContext),this.recreateEngine(),yield u(f,g,y)):(this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,hc(P)),g(P))}else{let y=De.UNKNOWN_REASON;P instanceof te&&(y=hc(P)),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,y),g(P)}}}),h=this.regionUrl;return this.regionUrl=void 0,this.connectFuture=new uc((f,g)=>{u(f,g,h)},()=>{this.clearConnectionFutures()}),this.connectFuture.promise}),this.connectSignal=(a,o,c,d,l,u)=>p(this,void 0,void 0,function*(){var h,f,g;const m=yield c.join(a,o,{autoSubscribe:d.autoSubscribe,adaptiveStream:typeof l.adaptiveStream=="object"?!0:l.adaptiveStream,maxRetries:d.maxRetries,e2eeEnabled:!!this.e2eeManager,websocketTimeout:d.websocketTimeout},u.signal);let v=m.serverInfo;if(v||(v={version:m.serverVersion,region:m.serverRegion}),this.serverInfo=v,this.log.debug("connected to Livekit Server ".concat(Object.entries(v).map(T=>{let[x,P]=T;return"".concat(x,": ").concat(P)}).join(", ")),{room:(h=m.room)===null||h===void 0?void 0:h.name,roomSid:(f=m.room)===null||f===void 0?void 0:f.sid,identity:(g=m.participant)===null||g===void 0?void 0:g.identity}),!v.version)throw new qu("unknown server version");return v.version==="0.15.1"&&this.options.dynacast&&(this.log.debug("disabling dynacast due to server version",this.logContext),l.dynacast=!1),m}),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,d)=>p(this,void 0,void 0,function*(){var l,u;this.state===Y.Reconnecting||this.isResuming||!((l=this.engine)===null||l===void 0)&&l.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({},Cr),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,d);this.applyJoinResponse(h),this.setupLocalParticipantEvents(),this.emit(w.SignalConnected)}catch(h){yield this.engine.close(),this.recreateEngine();const f=new te("could not establish signal connection",H.ServerUnreachable);throw h instanceof Error&&(f.message="".concat(f.message,": ").concat(h.message)),h instanceof te&&(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(d.signal.aborted)throw yield this.engine.close(),this.recreateEngine(),new te("Connection attempt aborted",H.Cancelled);try{yield this.engine.waitForPCInitialConnection(this.connOptions.peerConnectionTimeout,d)}catch(h){throw yield this.engine.close(),this.recreateEngine(),h}Pe()&&this.options.disconnectOnPageLeave&&(window.addEventListener("pagehide",this.onPageLeave),window.addEventListener("beforeunload",this.onPageLeave)),Pe()&&document.addEventListener("freeze",this.onPageLeave),this.setAndEmitConnectionState(Y.Connected),this.emit(w.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 d=this;let l=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){var u,h,f,g;const m=yield d.disconnectLock.lock();try{if(d.state===Y.Disconnected){d.log.debug("already disconnected",d.logContext);return}d.log.info("disconnect from room",Object.assign({},d.logContext)),(d.state===Y.Connecting||d.state===Y.Reconnecting||d.isResuming)&&(d.log.warn("abort connection attempt",d.logContext),(u=d.abortController)===null||u===void 0||u.abort(),(f=(h=d.connectFuture)===null||h===void 0?void 0:h.reject)===null||f===void 0||f.call(h,new te("Client initiated disconnect",H.Cancelled)),d.connectFuture=void 0),!((g=d.engine)===null||g===void 0)&&g.client.isDisconnected||(yield d.engine.client.sendLeave()),d.engine&&(yield d.engine.close()),d.handleDisconnect(l,De.CLIENT_INITIATED),d.engine=void 0}finally{m()}}()})},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=Le();if(o&&o.os==="iOS"){const c="livekit-dummy-audio-el";let d=document.getElementById(c);if(!d){d=document.createElement("audio"),d.id=c,d.autoplay=!0,d.hidden=!0;const l=dr();l.enabled=!0;const u=new MediaStream([l]);d.srcObject=u,document.addEventListener("visibilitychange",()=>{d&&(d.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(d),this.once(w.Disconnected,()=>{d==null||d.remove(),d=null})}a.push(d)}this.remoteParticipants.forEach(c=>{c.audioTrackPublications.forEach(d=>{d.track&&d.track.attachedElements.forEach(l=>{a.push(l)})})});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 d;(d=c.track)===null||d===void 0||d.attachedElements.forEach(l=>{a.includes(l)||a.push(l)})});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(Y.Reconnecting)&&this.emit(w.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(Y.Connected),this.emit(w.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 d=this.remoteParticipants.get(o.identity);o.state===Es.DISCONNECTED?this.handleParticipantDisconnected(o.identity,d):d=this.getOrCreateParticipant(o.identity,o)})},this.handleActiveSpeakersUpdate=a=>{const o=[],c={};a.forEach(d=>{if(c[d.sid]=!0,d.sid===this.localParticipant.sid)this.localParticipant.audioLevel=d.level,this.localParticipant.setIsSpeaking(!0),o.push(this.localParticipant);else{const l=this.getRemoteParticipantBySid(d.sid);l&&(l.audioLevel=d.level,l.setIsSpeaking(!0),o.push(l))}}),c[this.localParticipant.sid]||(this.localParticipant.audioLevel=0,this.localParticipant.setIsSpeaking(!1)),this.remoteParticipants.forEach(d=>{c[d.sid]||(d.audioLevel=0,d.setIsSpeaking(!1))}),this.activeSpeakers=o,this.emitWhenConnected(w.ActiveSpeakersChanged,o)},this.handleSpeakersChanged=a=>{const o=new Map;this.activeSpeakers.forEach(d=>{const l=this.remoteParticipants.get(d.identity);l&&l.sid!==d.sid||o.set(d.sid,d)}),a.forEach(d=>{let l=this.getRemoteParticipantBySid(d.sid);d.sid===this.localParticipant.sid&&(l=this.localParticipant),l&&(l.audioLevel=d.level,l.setIsSpeaking(d.active),d.active?o.set(d.sid,l):o.delete(d.sid))});const c=Array.from(o.values());c.sort((d,l)=>l.audioLevel-d.audioLevel),this.activeSpeakers=c,this.emitWhenConnected(w.ActiveSpeakersChanged,c)},this.handleStreamStateUpdate=a=>{a.streamStates.forEach(o=>{const c=this.getRemoteParticipantBySid(o.participantSid);if(!c)return;const d=c.getTrackPublicationBySid(o.trackSid);if(!d||!d.track)return;const l=S.streamStateFromProto(o.state);l!==d.track.streamState&&(d.track.streamState=l,c.emit(O.TrackStreamStateChanged,d,d.track.streamState),this.emitWhenConnected(w.TrackStreamStateChanged,d,d.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(d=>d.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")this.handleStreamHeader(a.value.value,a.participantIdentity);else if(a.value.case==="streamChunk")this.handleStreamChunk(a.value.value);else if(a.value.case==="streamTrailer")this.handleStreamTrailer(a.value.value);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(w.DataReceived,o.payload,a,c,o.topic),a==null||a.emit(O.DataReceived,o.payload,c)},this.handleSipDtmf=(a,o)=>{this.emit(w.SipDTMFReceived,o,a),a==null||a.emit(O.SipDTMFReceived,o)},this.bufferedSegments=new Map,this.handleTranscription=(a,o)=>{const c=o.transcribedParticipantIdentity===this.localParticipant.identity?this.localParticipant:this.getParticipantByIdentity(o.transcribedParticipantIdentity),d=c==null?void 0:c.trackPublications.get(o.trackId),l=hh(o,this.transcriptionReceivedTimes);d==null||d.emit(R.TranscriptionReceived,l),c==null||c.emit(O.TranscriptionReceived,l,d),this.emit(w.TranscriptionReceived,l,c,d)},this.handleChatMessage=(a,o)=>{const c=fh(o);this.emit(w.ChatMessage,c,a)},this.handleMetrics=(a,o)=>{this.emit(w.MetricsReceived,a,o)},this.handleAudioPlaybackStarted=()=>{this.canPlaybackAudio||(this.audioEnabled=!0,this.emit(w.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(w.AudioPlaybackStatusChanged,!1))},this.handleVideoPlaybackStarted=()=>{this.isVideoPlaybackBlocked&&(this.isVideoPlaybackBlocked=!1,this.emit(w.VideoPlaybackStatusChanged,!0))},this.handleVideoPlaybackFailed=()=>{this.isVideoPlaybackBlocked||(this.isVideoPlaybackBlocked=!0,this.emit(w.VideoPlaybackStatusChanged,!1))},this.handleDeviceChange=()=>p(this,void 0,void 0,function*(){var a,o,c;const d=pe.getInstance().previousDevices,l=yield pe.getInstance().getDevices(void 0,!1),u=Le();if((u==null?void 0:u.name)==="Chrome"&&u.os!=="iOS")for(let f of l){const g=d.find(m=>m.deviceId===f.deviceId);g&&g.label!==""&&g.kind===f.kind&&g.label!==f.label&&this.getActiveDevice(f.kind)==="default"&&this.emit(w.ActiveDeviceChanged,f.kind,f.deviceId)}const h=["audiooutput","audioinput","videoinput"];for(let f of h){const g=vh(f),m=this.localParticipant.getTrackPublication(g);if(m&&(!((a=m.track)===null||a===void 0)&&a.isUserProvided))continue;const v=l.filter(x=>x.kind===f),T=this.getActiveDevice(f);if(T===((o=d.filter(x=>x.kind===f)[0])===null||o===void 0?void 0:o.deviceId)&&v.length>0&&((c=v[0])===null||c===void 0?void 0:c.deviceId)!==T){yield this.switchActiveDevice(f,v[0].deviceId);continue}f==="audioinput"&&!Ct()||f==="videoinput"||v.length>0&&!v.find(x=>x.deviceId===this.getActiveDevice(f))&&(yield this.switchActiveDevice(f,v[0].deviceId))}this.emit(w.MediaDevicesChanged)}),this.handleRoomUpdate=a=>{const o=this.roomInfo;this.roomInfo=a,o&&o.metadata!==a.metadata&&this.emitWhenConnected(w.RoomMetadataChanged,a.metadata),(o==null?void 0:o.activeRecording)!==a.activeRecording&&this.emitWhenConnected(w.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(w.ParticipantMetadataChanged,a,this.localParticipant)},this.onLocalParticipantNameChanged=a=>{this.emit(w.ParticipantNameChanged,a,this.localParticipant)},this.onLocalAttributesChanged=a=>{this.emit(w.ParticipantAttributesChanged,a,this.localParticipant)},this.onLocalTrackMuted=a=>{this.emit(w.TrackMuted,a,this.localParticipant)},this.onLocalTrackUnmuted=a=>{this.emit(w.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,d,l,u,h;(o=a.track)===null||o===void 0||o.on(R.TrackProcessorUpdate,this.onTrackProcessorUpdate),(c=a.track)===null||c===void 0||c.on(R.Restarted,this.onLocalTrackRestarted),(u=(l=(d=a.track)===null||d===void 0?void 0:d.getProcessor())===null||l===void 0?void 0:l.onPublish)===null||u===void 0||u.call(l,this),this.emit(w.LocalTrackPublished,a,this.localParticipant),Bt(a.track)&&(yield a.track.checkForSilence())&&this.emit(w.LocalAudioSilenceDetected,a);const f=yield(h=a.track)===null||h===void 0?void 0:h.getDeviceId(!1),g=gc(a.source);g&&f&&f!==this.localParticipant.activeDeviceMap.get(g)&&(this.localParticipant.activeDeviceMap.set(g,f),this.emit(w.ActiveDeviceChanged,g,f))}),this.onLocalTrackUnpublished=a=>{var o,c;(o=a.track)===null||o===void 0||o.off(R.TrackProcessorUpdate,this.onTrackProcessorUpdate),(c=a.track)===null||c===void 0||c.off(R.Restarted,this.onLocalTrackRestarted),this.emit(w.LocalTrackUnpublished,a,this.localParticipant)},this.onLocalTrackRestarted=a=>p(this,void 0,void 0,function*(){const o=yield a.getDeviceId(!1),c=gc(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(w.ActiveDeviceChanged,c,o))}),this.onLocalConnectionQualityChanged=a=>{this.emit(w.ConnectionQualityChanged,a,this.localParticipant)},this.onMediaDevicesError=a=>{this.emit(w.MediaDevicesError,a)},this.onLocalParticipantPermissionsChanged=a=>{this.emit(w.ParticipantPermissionsChanged,a,this.localParticipant)},this.onLocalChatMessageSent=a=>{this.emit(w.ChatMessage,a,this.localParticipant)},this.setMaxListeners(100),this.remoteParticipants=new Map,this.sidToIdentity=new Map,this.options=Object.assign(Object.assign({},Fh),e),this.log=it((i=this.options.loggerName)!==null&&i!==void 0?i:Ne.Room),this.transcriptionReceivedTimes=new Map,this.options.audioCaptureDefaults=Object.assign(Object.assign({},Pc),e==null?void 0:e.audioCaptureDefaults),this.options.videoCaptureDefaults=Object.assign(Object.assign({},Rc),e==null?void 0:e.videoCaptureDefaults),this.options.publishDefaults=Object.assign(Object.assign({},Uh),e==null?void 0:e.publishDefaults),this.maybeCreateEngine(),this.disconnectLock=new Ce,this.localParticipant=new gf("","",this.engine,this.options,this.rpcHandlers),this.options.videoCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("videoinput",_t(this.options.videoCaptureDefaults.deviceId)),this.options.audioCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("audioinput",_t(this.options.audioCaptureDefaults.deviceId)),!((s=this.options.audioOutput)===null||s===void 0)&&s.deviceId&&this.switchActiveDevice("audiooutput",_t(this.options.audioOutput.deviceId)).catch(a=>this.log.warn("Could not set audio output: ".concat(a.message),this.logContext)),this.options.e2ee&&this.setupE2EE(),Pe()){const a=new AbortController;(r=navigator.mediaDevices)===null||r===void 0||r.addEventListener("devicechange",this.handleDeviceChange,{signal:a.signal}),Vt.cleanupRegistry&&Vt.cleanupRegistry.register(this,()=>{a.abort()})}}registerTextStreamHandler(e,t){if(this.textStreamHandlers.has(e))throw new TypeError('A text stream handler for topic "'.concat(e,'" has already been set.'));this.textStreamHandlers.set(e,t)}unregisterTextStreamHandler(e){this.textStreamHandlers.delete(e)}registerByteStreamHandler(e,t){if(this.byteStreamHandlers.has(e))throw new TypeError('A byte stream handler for topic "'.concat(e,'" has already been set.'));this.byteStreamHandlers.set(e,t)}unregisterByteStreamHandler(e){this.byteStreamHandlers.delete(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)}handleIncomingRpcRequest(e,t,i,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,ce.builtIn("UNSUPPORTED_VERSION"));return}const o=this.rpcHandlers.get(i);if(!o){yield this.engine.publishRpcResponse(e,t,null,ce.builtIn("UNSUPPORTED_METHOD"));return}let c=null,d=null;try{const l=yield o({requestId:t,callerIdentity:e,payload:s,responseTimeout:r});_r(l)>xc?(c=ce.builtIn("RESPONSE_PAYLOAD_TOO_LARGE"),console.warn("RPC Response payload too large for ".concat(i))):d=l}catch(l){l instanceof ce?c=l:(console.warn("Uncaught error returned by RPC handler for ".concat(i,". Returning APPLICATION_ERROR instead."),l),c=ce.builtIn("APPLICATION_ERROR"))}yield this.engine.publishRpcResponse(e,t,d,c)})}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 Ch(this.options.e2ee),this.e2eeManager.on(Tt.ParticipantEncryptionStatusChanged,(t,i)=>{mh(i)&&(this.isE2EEEnabled=t),this.emit(w.ParticipantEncryptionStatusChanged,t,i)}),this.e2eeManager.on(Tt.EncryptionError,t=>this.emit(w.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===Y.Disconnected?"":this.roomInfo&&this.roomInfo.sid!==""?this.roomInfo.sid:new Promise((e,t)=>{const i=s=>{s.sid!==""&&(this.engine.off(I.RoomUpdate,i),e(s.sid))};this.engine.on(I.RoomUpdate,i),this.once(w.Disconnected,()=>{this.engine.off(I.RoomUpdate,i),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 ef(this.options),this.engine.on(I.ParticipantUpdate,this.handleParticipantUpdates).on(I.RoomUpdate,this.handleRoomUpdate).on(I.SpeakersChanged,this.handleSpeakersChanged).on(I.StreamStateChanged,this.handleStreamStateUpdate).on(I.ConnectionQualityUpdate,this.handleConnectionQualityUpdate).on(I.SubscriptionError,this.handleSubscriptionError).on(I.SubscriptionPermissionUpdate,this.handleSubscriptionPermissionUpdate).on(I.MediaTrackAdded,(e,t,i)=>{this.onTrackAdded(e,t,i)}).on(I.Disconnected,e=>{this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e)}).on(I.ActiveSpeakersUpdate,this.handleActiveSpeakersUpdate).on(I.DataPacketReceived,this.handleDataPacket).on(I.Resuming,()=>{this.clearConnectionReconcile(),this.isResuming=!0,this.log.info("Resuming signal connection",this.logContext),this.setAndEmitConnectionState(Y.SignalReconnecting)&&this.emit(w.SignalReconnecting)}).on(I.Resumed,()=>{this.registerConnectionReconcile(),this.isResuming=!1,this.log.info("Resumed signal connection",this.logContext),this.updateSubscriptions(),this.emitBufferedEvents(),this.setAndEmitConnectionState(Y.Connected)&&this.emit(w.Reconnected)}).on(I.SignalResumed,()=>{this.bufferedEvents=[],(this.state===Y.Reconnecting||this.isResuming)&&this.sendSyncState()}).on(I.Restarting,this.handleRestarting).on(I.SignalRestarted,this.handleSignalRestarted).on(I.Offline,()=>{this.setAndEmitConnectionState(Y.Reconnecting)&&this.emit(w.Reconnecting)}).on(I.DCBufferStatusChanged,(e,t)=>{this.emit(w.DCBufferStatusChanged,e,t)}).on(I.LocalTrackSubscribed,e=>{const t=this.localParticipant.getTrackPublications().find(i=>{let{trackSid:s}=i;return s===e});if(!t){this.log.warn("could not find local track subscription for subscribed event",this.logContext);return}this.localParticipant.emit(O.LocalTrackSubscribed,t),this.emitWhenConnected(w.LocalTrackSubscribed,t,this.localParticipant)}),this.localParticipant&&this.localParticipant.setupEngine(this.engine),this.e2eeManager&&this.e2eeManager.setupEngine(this.engine))}static getLocalDevices(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return pe.getInstance().getDevices(e,t)}prepareConnection(e,t){return p(this,void 0,void 0,function*(){if(this.state===Y.Disconnected){this.log.debug("prepareConnection to ".concat(e),this.logContext);try{if(ar(new URL(e))&&t){this.regionUrlProvider=new Ir(e,t);const i=yield this.regionUrlProvider.getNextBestRegionUrl();i&&this.state===Y.Disconnected&&(this.regionUrl=i,yield fetch(lr(i),{method:"HEAD"}),this.log.debug("prepared connection to ".concat(i),this.logContext))}else yield fetch(lr(e),{method:"HEAD"})}catch(i){this.log.warn("could not prepare connection",Object.assign(Object.assign({},this.logContext),{error:i}))}}})}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 i=()=>{},s;switch(e){case"signal-reconnect":yield this.engine.client.handleOnClose("simulate disconnect");break;case"speaker":s=new He({scenario:{case:"speakerUpdate",value:3}});break;case"node-failure":s=new He({scenario:{case:"nodeFailure",value:!0}});break;case"server-leave":s=new He({scenario:{case:"serverLeave",value:!0}});break;case"migration":s=new He({scenario:{case:"migration",value:!0}});break;case"resume-reconnect":this.engine.failNext(),yield this.engine.client.handleOnClose("simulate resume-disconnect");break;case"disconnect-signal-on-resume":i=()=>p(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),s=new He({scenario:{case:"disconnectSignalOnResume",value:!0}});break;case"disconnect-signal-on-resume-no-messages":i=()=>p(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),s=new He({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 He({scenario:{case:"switchCandidateProtocol",value:e==="force-tls"?2:1}}),i=()=>p(this,void 0,void 0,function*(){const r=this.engine.client.onLeave;r&&r(new Pn({reason:De.CLIENT_INITIATED,action:si.RECONNECT}))});break;case"subscriber-bandwidth":if(t===void 0||typeof t!="number")throw new Error("subscriber-bandwidth requires a number as argument");s=new He({scenario:{case:"subscriberBandwidth",value:$t(t)}});break;case"leave-full-reconnect":s=new He({scenario:{case:"leaveRequestFullReconnect",value:!0}})}s&&(yield this.engine.client.sendSimulateScenario(s),yield i())})}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(i,s){var r=this;let a=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0;return function*(){var o,c,d,l,u,h,f,g;let m=!0,v=!1;const T=a?{exact:s}:s;if(i==="audioinput"){v=r.localParticipant.audioTrackPublications.size===0;const x=(o=r.getActiveDevice(i))!==null&&o!==void 0?o:r.options.audioCaptureDefaults.deviceId;r.options.audioCaptureDefaults.deviceId=T;const P=Array.from(r.localParticipant.audioTrackPublications.values()).filter(y=>y.source===S.Source.Microphone);try{m=(yield Promise.all(P.map(y=>{var b;return(b=y.audioTrack)===null||b===void 0?void 0:b.setDeviceId(T)}))).every(y=>y===!0)}catch(y){throw r.options.audioCaptureDefaults.deviceId=x,y}}else if(i==="videoinput"){v=r.localParticipant.videoTrackPublications.size===0;const x=(c=r.getActiveDevice(i))!==null&&c!==void 0?c:r.options.videoCaptureDefaults.deviceId;r.options.videoCaptureDefaults.deviceId=T;const P=Array.from(r.localParticipant.videoTrackPublications.values()).filter(y=>y.source===S.Source.Camera);try{m=(yield Promise.all(P.map(y=>{var b;return(b=y.videoTrack)===null||b===void 0?void 0:b.setDeviceId(T)}))).every(y=>y===!0)}catch(y){throw r.options.videoCaptureDefaults.deviceId=x,y}}else if(i==="audiooutput"){if(!rr()&&!r.options.webAudioMix||r.options.webAudioMix&&r.audioContext&&!("setSinkId"in r.audioContext))throw new Error("cannot switch audio output, setSinkId not supported");r.options.webAudioMix&&(s=(d=yield pe.getInstance().normalizeDeviceId("audiooutput",s))!==null&&d!==void 0?d:""),(l=(g=r.options).audioOutput)!==null&&l!==void 0||(g.audioOutput={});const x=(u=r.getActiveDevice(i))!==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(P=>P.setAudioOutput({deviceId:s})))}catch(P){throw r.options.audioOutput.deviceId=x,P}}return(v||i==="audiooutput")&&(r.localParticipant.activeDeviceMap.set(i,i==="audiooutput"&&((f=r.options.audioOutput)===null||f===void 0?void 0:f.deviceId)||s),r.emit(w.ActiveDeviceChanged,i,s)),m}()})}setupLocalParticipantEvents(){this.localParticipant.on(O.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).on(O.ParticipantNameChanged,this.onLocalParticipantNameChanged).on(O.AttributesChanged,this.onLocalAttributesChanged).on(O.TrackMuted,this.onLocalTrackMuted).on(O.TrackUnmuted,this.onLocalTrackUnmuted).on(O.LocalTrackPublished,this.onLocalTrackPublished).on(O.LocalTrackUnpublished,this.onLocalTrackUnpublished).on(O.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).on(O.MediaDevicesError,this.onMediaDevicesError).on(O.AudioStreamAcquired,this.startAudio).on(O.ChatMessage,this.onLocalChatMessageSent).on(O.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,i){if(this.state===Y.Connecting||this.state===Y.Reconnecting){const l=()=>{this.onTrackAdded(e,t,i),u()},u=()=>{this.off(w.Reconnected,l),this.off(w.Connected,l),this.off(w.Disconnected,u)};this.once(w.Reconnected,l),this.once(w.Connected,l),this.once(w.Disconnected,u);return}if(this.state===Y.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=th(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(l=>l.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 d;this.options.adaptiveStream&&(typeof this.options.adaptiveStream=="object"?d=this.options.adaptiveStream:d={}),c.addSubscribedMediaTrack(e,o,t,i,d)}handleDisconnect(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0,t=arguments.length>1?arguments[1]:void 0;var i;if(this.clearConnectionReconcile(),this.isResuming=!1,this.bufferedEvents=[],this.transcriptionReceivedTimes.clear(),this.state!==Y.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(O.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).off(O.ParticipantNameChanged,this.onLocalParticipantNameChanged).off(O.AttributesChanged,this.onLocalAttributesChanged).off(O.TrackMuted,this.onLocalTrackMuted).off(O.TrackUnmuted,this.onLocalTrackUnmuted).off(O.LocalTrackPublished,this.onLocalTrackPublished).off(O.LocalTrackUnpublished,this.onLocalTrackUnpublished).off(O.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).off(O.MediaDevicesError,this.onMediaDevicesError).off(O.AudioStreamAcquired,this.startAudio).off(O.ChatMessage,this.onLocalChatMessageSent).off(O.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),Pe()&&(window.removeEventListener("beforeunload",this.onPageLeave),window.removeEventListener("pagehide",this.onPageLeave),window.removeEventListener("freeze",this.onPageLeave),(i=navigator.mediaDevices)===null||i===void 0||i.removeEventListener("devicechange",this.handleDeviceChange))}finally{this.setAndEmitConnectionState(Y.Disconnected),this.emit(w.Disconnected,t)}}}handleParticipantDisconnected(e,t){var i;this.remoteParticipants.delete(e),t&&(t.trackPublications.forEach(s=>{t.unpublishTrack(s.trackSid,!0)}),this.emit(w.ParticipantDisconnected,t),(i=this.localParticipant)===null||i===void 0||i.handleParticipantDisconnected(t.identity))}handleStreamHeader(e,t){return p(this,void 0,void 0,function*(){var i;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={id:e.streamId,name:(i=e.contentHeader.value.name)!==null&&i!==void 0?i:"unknown",mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:$n(e.timestamp),attributes:e.attributes},o=new ReadableStream({start:c=>{r=c,this.byteStreamControllers.set(e.streamId,{info:a,controller:r,startTime:Date.now()})}});s(new rf(a,o,$n(e.totalLength)),{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={id:e.streamId,mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:Number(e.timestamp),attributes:e.attributes},o=new ReadableStream({start:c=>{r=c,this.textStreamControllers.set(e.streamId,{info:a,controller:r,startTime:Date.now()})}});s(new af(a,o,$n(e.totalLength)),{identity:t})}})}handleStreamChunk(e){const t=this.byteStreamControllers.get(e.streamId);t&&e.content.length>0&&t.controller.enqueue(e);const i=this.textStreamControllers.get(e.streamId);i&&e.content.length>0&&i.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 i=this.byteStreamControllers.get(e.streamId);i&&(i.info.attributes=Object.assign(Object.assign({},i.info.attributes),e.attributes),i.controller.close(),this.byteStreamControllers.delete(e.streamId))}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=mc())!==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(),we(200)])}catch(s){this.log.warn("Could not resume audio context",Object.assign(Object.assign({},this.logContext),{error:s}))}const i=((t=this.audioContext)===null||t===void 0?void 0:t.state)==="running";i!==this.canPlaybackAudio&&(this.audioEnabled=i,this.emit(w.AudioPlaybackStatusChanged,i))})}createParticipant(e,t){var i;let s;return t?s=Hn.fromParticipantInfo(this.engine.client,t,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}):s=new Hn(this.engine.client,"",e,void 0,void 0,void 0,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}),this.options.webAudioMix&&s.setAudioContext(this.audioContext),!((i=this.options.audioOutput)===null||i===void 0)&&i.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 i=this.createParticipant(e,t);return this.remoteParticipants.set(e,i),this.sidToIdentity.set(t.sid,t.identity),this.emitWhenConnected(w.ParticipantConnected,i),i.on(O.TrackPublished,s=>{this.emitWhenConnected(w.TrackPublished,s,i)}).on(O.TrackSubscribed,(s,r)=>{s.kind===S.Kind.Audio?(s.on(R.AudioPlaybackStarted,this.handleAudioPlaybackStarted),s.on(R.AudioPlaybackFailed,this.handleAudioPlaybackFailed)):s.kind===S.Kind.Video&&(s.on(R.VideoPlaybackFailed,this.handleVideoPlaybackFailed),s.on(R.VideoPlaybackStarted,this.handleVideoPlaybackStarted)),this.emit(w.TrackSubscribed,s,r,i)}).on(O.TrackUnpublished,s=>{this.emit(w.TrackUnpublished,s,i)}).on(O.TrackUnsubscribed,(s,r)=>{this.emit(w.TrackUnsubscribed,s,r,i)}).on(O.TrackMuted,s=>{this.emitWhenConnected(w.TrackMuted,s,i)}).on(O.TrackUnmuted,s=>{this.emitWhenConnected(w.TrackUnmuted,s,i)}).on(O.ParticipantMetadataChanged,s=>{this.emitWhenConnected(w.ParticipantMetadataChanged,s,i)}).on(O.ParticipantNameChanged,s=>{this.emitWhenConnected(w.ParticipantNameChanged,s,i)}).on(O.AttributesChanged,s=>{this.emitWhenConnected(w.ParticipantAttributesChanged,s,i)}).on(O.ConnectionQualityChanged,s=>{this.emitWhenConnected(w.ConnectionQualityChanged,s,i)}).on(O.ParticipantPermissionsChanged,s=>{this.emitWhenConnected(w.ParticipantPermissionsChanged,s,i)}).on(O.TrackSubscriptionStatusChanged,(s,r)=>{this.emitWhenConnected(w.TrackSubscriptionStatusChanged,s,r,i)}).on(O.TrackSubscriptionFailed,(s,r)=>{this.emit(w.TrackSubscriptionFailed,s,i,r)}).on(O.TrackSubscriptionPermissionChanged,(s,r)=>{this.emitWhenConnected(w.TrackSubscriptionPermissionChanged,s,r,i)}),t&&i.updateInfo(t),i}sendSyncState(){const e=Array.from(this.remoteParticipants.values()).reduce((i,s)=>(i.push(...s.getTrackPublications()),i),[]),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&&ph(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=ve.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,De.STATE_MISMATCH))):e=0},yf)}clearConnectionReconcile(){this.connectionReconcileInterval&&ve.clearInterval(this.connectionReconcileInterval)}setAndEmitConnectionState(e){return e===this.state?!1:(this.state=e,this.emit(w.ConnectionStateChanged,this.state),!0)}emitBufferedEvents(){this.bufferedEvents.forEach(e=>{let[t,i]=e;this.emit(t,...i)}),this.bufferedEvents=[]}emitWhenConnected(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),s=1;s<t;s++)i[s-1]=arguments[s];if(this.state===Y.Reconnecting||this.isResuming||!this.engine||this.engine.pendingReconnect)this.bufferedEvents.push([e,i]);else if(this.state===Y.Connected)return this.emit(e,...i);return!1}simulateParticipants(e){return p(this,void 0,void 0,function*(){var t,i;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 _s({sid:"RM_SIMULATED",name:"simulated-room",emptyTimeout:0,maxParticipants:0,creationTime:se.parse(new Date().getTime()),metadata:"",numParticipants:1,numPublishers:1,turnPassword:"",enabledCodecs:[],activeRecording:!1}),this.localParticipant.updateInfo(new Oi({identity:"simulated-local",name:"local-name"})),this.setupLocalParticipantEvents(),this.emit(w.SignalConnected),this.emit(w.Connected),this.setAndEmitConnectionState(Y.Connected),s.video){const a=new Dr(S.Kind.Video,new ni({source:ue.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:Oe.AUDIO,name:"video-dummy"}),new Wn(s.useRealTracks?(yield window.navigator.mediaDevices.getUserMedia({video:!0})).getVideoTracks()[0]:lc(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(O.LocalTrackPublished,a)}if(s.audio){const a=new Dr(S.Kind.Audio,new ni({source:ue.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:Oe.AUDIO}),new zn(s.useRealTracks?(yield navigator.mediaDevices.getUserMedia({audio:!0})).getAudioTracks()[0]:dr(),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(O.LocalTrackPublished,a)}for(let a=0;a<r.count-1;a+=1){let o=new Oi({sid:Math.floor(Math.random()*1e4).toString(),identity:"simulated-".concat(a),state:Es.ACTIVE,tracks:[],joinedAt:se.parse(Date.now())});const c=this.getOrCreateParticipant(o.identity,o);if(r.video){const d=lc(160*((i=r.aspectRatios[a%r.aspectRatios.length])!==null&&i!==void 0?i:1),160,!1,!0),l=new ni({source:ue.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:Oe.AUDIO});c.addSubscribedMediaTrack(d,l.sid,new MediaStream([d]),new RTCRtpReceiver),o.tracks=[...o.tracks,l]}if(r.audio){const d=dr(),l=new ni({source:ue.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:Oe.AUDIO});c.addSubscribedMediaTrack(d,l.sid,new MediaStream([d]),new RTCRtpReceiver),o.tracks=[...o.tracks,l]}c.updateInfo(o)}})}emit(e){for(var t=arguments.length,i=new Array(t>1?t-1:0),s=1;s<t;s++)i[s-1]=arguments[s];if(e!==w.ActiveSpeakersChanged&&e!==w.TranscriptionReceived){const r=zc(i).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,...i)}}Vt.cleanupRegistry=typeof FinalizationRegistry<"u"&&new FinalizationRegistry(n=>{n()});function zc(n){return n.map(e=>{if(e)return Array.isArray(e)?zc(e):typeof e=="object"?"logContext"in e?e.logContext:void 0:e})}var je;(function(n){n[n.IDLE=0]="IDLE",n[n.RUNNING=1]="RUNNING",n[n.SKIPPED=2]="SKIPPED",n[n.SUCCESS=3]="SUCCESS",n[n.FAILED=4]="FAILED"})(je||(je={}));class Rt extends Ze.EventEmitter{constructor(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.status=je.IDLE,this.logs=[],this.options={},this.url=e,this.token=t,this.name=this.constructor.name,this.room=new Vt(i.roomOptions),this.connectOptions=i.connectOptions,this.options=i}run(e){return p(this,void 0,void 0,function*(){if(this.status!==je.IDLE)throw Error("check is running already");this.setStatus(je.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!==je.SKIPPED&&this.setStatus(this.isSuccess()?je.SUCCESS:je.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===Y.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!==Y.Disconnected&&(yield this.room.disconnect(),yield new Promise(e=>setTimeout(e,500)))})}skip(){this.setStatus(je.SKIPPED)}switchProtocol(e){return p(this,void 0,void 0,function*(){let t=!1,i=!1;if(this.room.on(w.Reconnecting,()=>{t=!0}),this.room.once(w.Reconnected,()=>{i=!0}),this.room.simulateScenario("force-".concat(e)),yield new Promise(r=>setTimeout(r,1e3)),!t)return;const s=Date.now()+1e4;for(;Date.now()<s;){if(i)return;yield we(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 bf extends Rt{get description(){return"Cloud regions"}perform(){return p(this,void 0,void 0,function*(){const e=new Ir(this.url,this.token);if(!e.isCloud()){this.skip();return}const t=[],i=new Set;for(let r=0;r<3;r++){const a=yield e.getNextBestRegionUrl();if(!a)break;if(i.has(a))continue;i.add(a);const o=yield this.checkCloudRegion(a);this.appendMessage("".concat(o.region," RTT: ").concat(o.rtt,"ms, duration: ").concat(o.duration,"ms")),t.push(o)}t.sort((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,i;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,d="A".repeat(a),l=Date.now();for(let g=0;g<c;g++)yield r.write(d);yield r.close();const u=Date.now(),h=yield(i=this.room.engine.pcManager)===null||i===void 0?void 0:i.publisher.getStats(),f={region:s,rtt:1e4,duration:u-l};return h==null||h.forEach(g=>{g.type==="candidate-pair"&&g.nominated&&(f.rtt=g.currentRoundTripTime*1e3)}),yield this.disconnect(),f})}}const Mr=1e4;class kf extends Rt{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 i=this.bestStats;this.appendMessage("upstream bitrate: ".concat((i.bitrateTotal/i.count/1e3/1e3).toFixed(2)," mbps")),this.appendMessage("RTT: ".concat((i.rttTotal/i.count*1e3).toFixed(2)," ms")),this.appendMessage("jitter: ".concat((i.jitterTotal/i.count*1e3).toFixed(2)," ms")),i.packetsLost>0&&this.appendWarning("packets lost: ".concat((i.packetsLost/i.packetsSent*100).toFixed(2),"%")),i.qualityLimitationDurations.bandwidth>1&&this.appendWarning("bandwidth limited ".concat((i.qualityLimitationDurations.bandwidth/(Mr/1e3)*100).toFixed(2),"%")),i.qualityLimitationDurations.cpu>0&&this.appendWarning("cpu limited ".concat((i.qualityLimitationDurations.cpu/(Mr/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 i=t.getContext("2d");if(!i)throw new Error("Could not get canvas context");let s=0;const r=()=>{s=(s+1)%360,i.fillStyle="hsl(".concat(s,", 100%, 50%)"),i.fillRect(0,0,t.width,t.height),requestAnimationFrame(r)};r();const o=t.captureStream(30).getVideoTracks()[0],d=(yield this.room.localParticipant.publishTrack(o,{simulcast:!1,degradationPreference:"maintain-resolution",videoEncoding:{maxBitrate:2e6}})).track,l={protocol:e,packetsLost:0,packetsSent:0,qualityLimitationDurations:{},rttTotal:0,jitterTotal:0,bitrateTotal:0,count:0},u=setInterval(()=>p(this,void 0,void 0,function*(){const h=yield d.getRTCStatsReport();h==null||h.forEach(f=>{f.type==="outbound-rtp"?(l.packetsSent=f.packetsSent,l.qualityLimitationDurations=f.qualityLimitationDurations,l.bitrateTotal+=f.targetBitrate,l.count++):f.type==="remote-inbound-rtp"&&(l.packetsLost=f.packetsLost,l.rttTotal+=f.roundTripTime,l.jitterTotal+=f.jitter)})}),1e3);return yield new Promise(h=>setTimeout(h,Mr)),clearInterval(u),o.stop(),t.remove(),yield this.disconnect(),l})}}class Tf extends Rt{get description(){return"Can publish audio"}perform(){return p(this,void 0,void 0,function*(){var e;const t=yield this.connect(),i=yield ff();if(yield pc(i,1e3))throw new Error("unable to detect audio from microphone");this.appendMessage("detected audio from microphone"),t.localParticipant.publishTrack(i),yield new Promise(o=>setTimeout(o,3e3));const r=yield(e=i.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 Sf extends Rt{get description(){return"Can publish video"}perform(){return p(this,void 0,void 0,function*(){var e;const t=yield this.connect(),i=yield hf();yield this.checkForVideo(i.mediaStreamTrack),t.localParticipant.publishTrack(i),yield new Promise(a=>setTimeout(a,5e3));const s=yield(e=i.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 i=document.createElement("video");i.srcObject=t,i.muted=!0,yield new Promise(s=>{i.onplay=()=>{setTimeout(()=>{var r,a,o,c;const d=document.createElement("canvas"),l=e.getSettings(),u=(a=(r=l.width)!==null&&r!==void 0?r:i.videoWidth)!==null&&a!==void 0?a:1280,h=(c=(o=l.height)!==null&&o!==void 0?o:i.videoHeight)!==null&&c!==void 0?c:720;d.width=u,d.height=h;const f=d.getContext("2d");f.drawImage(i,0,0);const m=f.getImageData(0,0,d.width,d.height).data;let v=!0;for(let T=0;T<m.length;T+=4)if(m[T]!==0||m[T+1]!==0||m[T+2]!==0){v=!1;break}v?this.appendError("camera appears to be producing only black frames"):this.appendMessage("received video frames"),s()},1e3)},i.play()}),i.remove()})}}class Cf extends Rt{get description(){return"Resuming connection after interruption"}perform(){return p(this,void 0,void 0,function*(){var e;const t=yield this.connect();let i=!1,s=!1,r;const a=new Promise(d=>{setTimeout(d,5e3),r=d}),o=()=>{i=!0};t.on(w.SignalReconnecting,o).on(w.Reconnecting,o).on(w.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,i){if(!s||t.state!==Y.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 _f extends Rt{get description(){return"Can connect via TURN"}perform(){return p(this,void 0,void 0,function*(){var e,t;const i=new gr,s=yield i.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 d of c.urls)d.startsWith("turn:")?(a=!0,o=!0):d.startsWith("turns:")&&(a=!0,o=!0,r=!0),d.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 i.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 Ef extends Rt{get description(){return"Establishing WebRTC connection"}perform(){return p(this,void 0,void 0,function*(){let e=!1,t=!1;this.room.on(w.SignalConnected,()=>{const i=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&&(wf(a.address)?o+=" (private)":a.protocol==="tcp"&&a.tcpType==="passive"?(e=!0,o+=" (passive)"):a.protocol==="udp"&&(t=!0)),this.appendMessage(o)}i&&i(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(),G.info("now the room is connected")}catch(i){throw this.appendWarning("ports need to be open on firewall in order to connect."),i}e||this.appendWarning("Server is not configured for ICE/TCP"),t||this.appendWarning("No public IPv4 UDP candidates were found. Your server is likely not configured correctly")})}}function wf(n){const e=n.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 Pf extends Rt{get description(){return"Connecting to signal connection via WebSocket"}perform(){return p(this,void 0,void 0,function*(){var e,t,i;(this.url.startsWith("ws:")||this.url.startsWith("http:"))&&this.appendWarning("Server is insecure, clients may block connections to it");let s=new gr;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)===Ga.Cloud&&(!((t=r.serverInfo)===null||t===void 0)&&t.region)&&this.appendMessage("LiveKit Cloud: ".concat((i=r.serverInfo)===null||i===void 0?void 0:i.region)),yield s.close()})}}class Cm extends Ze.EventEmitter{constructor(e,t){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.options={},this.checkResults=new Map,this.url=e,this.token=t,this.options=i}getNextCheckId(){const e=this.checkResults.size;return this.checkResults.set(e,{logs:[],status:je.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!==je.FAILED)}getResults(){return Array.from(this.checkResults.values())}createAndRunCheck(e){return p(this,void 0,void 0,function*(){const t=this.getNextCheckId(),i=new e(this.url,this.token,this.options),s=a=>{this.updateCheck(t,a)};i.on("update",s);const r=yield i.run();return i.off("update",s),r})}checkWebsocket(){return p(this,void 0,void 0,function*(){return this.createAndRunCheck(Pf)})}checkWebRTC(){return p(this,void 0,void 0,function*(){return this.createAndRunCheck(Ef)})}checkTURN(){return p(this,void 0,void 0,function*(){return this.createAndRunCheck(_f)})}checkReconnect(){return p(this,void 0,void 0,function*(){return this.createAndRunCheck(Cf)})}checkPublishAudio(){return p(this,void 0,void 0,function*(){return this.createAndRunCheck(Tf)})}checkPublishVideo(){return p(this,void 0,void 0,function*(){return this.createAndRunCheck(Sf)})}checkConnectionProtocol(){return p(this,void 0,void 0,function*(){const e=yield this.createAndRunCheck(kf);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(bf)})}}const Gc="https://iamobi.ai/api";var Z;(function(n){n.assertEqual=s=>s;function e(s){}n.assertIs=e;function t(s){throw new Error}n.assertNever=t,n.arrayToEnum=s=>{const r={};for(const a of s)r[a]=a;return r},n.getValidEnumValues=s=>{const r=n.objectKeys(s).filter(o=>typeof s[s[o]]!="number"),a={};for(const o of r)a[o]=s[o];return n.objectValues(a)},n.objectValues=s=>n.objectKeys(s).map(function(r){return s[r]}),n.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{const r=[];for(const a in s)Object.prototype.hasOwnProperty.call(s,a)&&r.push(a);return r},n.find=(s,r)=>{for(const a of s)if(r(a))return a},n.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&isFinite(s)&&Math.floor(s)===s;function i(s,r=" | "){return s.map(a=>typeof a=="string"?`'${a}'`:a).join(r)}n.joinValues=i,n.jsonStringifyReplacer=(s,r)=>typeof r=="bigint"?r.toString():r})(Z||(Z={}));var Nr;(function(n){n.mergeShapes=(e,t)=>({...e,...t})})(Nr||(Nr={}));const D=Z.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),at=n=>{switch(typeof n){case"undefined":return D.undefined;case"string":return D.string;case"number":return isNaN(n)?D.nan:D.number;case"boolean":return D.boolean;case"function":return D.function;case"bigint":return D.bigint;case"symbol":return D.symbol;case"object":return Array.isArray(n)?D.array:n===null?D.null:n.then&&typeof n.then=="function"&&n.catch&&typeof n.catch=="function"?D.promise:typeof Map<"u"&&n instanceof Map?D.map:typeof Set<"u"&&n instanceof Set?D.set:typeof Date<"u"&&n instanceof Date?D.date:D.object;default:return D.unknown}},_=Z.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),Rf=n=>JSON.stringify(n,null,2).replace(/"([^"]+)":/g,"$1:");class Ie extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=i=>{this.issues=[...this.issues,i]},this.addIssues=(i=[])=>{this.issues=[...this.issues,...i]};const t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){const t=e||function(r){return r.message},i={_errors:[]},s=r=>{for(const a of r.issues)if(a.code==="invalid_union")a.unionErrors.map(s);else if(a.code==="invalid_return_type")s(a.returnTypeError);else if(a.code==="invalid_arguments")s(a.argumentsError);else if(a.path.length===0)i._errors.push(t(a));else{let o=i,c=0;for(;c<a.path.length;){const d=a.path[c];c===a.path.length-1?(o[d]=o[d]||{_errors:[]},o[d]._errors.push(t(a))):o[d]=o[d]||{_errors:[]},o=o[d],c++}}};return s(this),i}static assert(e){if(!(e instanceof Ie))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,Z.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=t=>t.message){const t={},i=[];for(const s of this.issues)s.path.length>0?(t[s.path[0]]=t[s.path[0]]||[],t[s.path[0]].push(e(s))):i.push(e(s));return{formErrors:i,fieldErrors:t}}get formErrors(){return this.flatten()}}Ie.create=n=>new Ie(n);const fi=(n,e)=>{let t;switch(n.code){case _.invalid_type:n.received===D.undefined?t="Required":t=`Expected ${n.expected}, received ${n.received}`;break;case _.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(n.expected,Z.jsonStringifyReplacer)}`;break;case _.unrecognized_keys:t=`Unrecognized key(s) in object: ${Z.joinValues(n.keys,", ")}`;break;case _.invalid_union:t="Invalid input";break;case _.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${Z.joinValues(n.options)}`;break;case _.invalid_enum_value:t=`Invalid enum value. Expected ${Z.joinValues(n.options)}, received '${n.received}'`;break;case _.invalid_arguments:t="Invalid function arguments";break;case _.invalid_return_type:t="Invalid function return type";break;case _.invalid_date:t="Invalid date";break;case _.invalid_string:typeof n.validation=="object"?"includes"in n.validation?(t=`Invalid input: must include "${n.validation.includes}"`,typeof n.validation.position=="number"&&(t=`${t} at one or more positions greater than or equal to ${n.validation.position}`)):"startsWith"in n.validation?t=`Invalid input: must start with "${n.validation.startsWith}"`:"endsWith"in n.validation?t=`Invalid input: must end with "${n.validation.endsWith}"`:Z.assertNever(n.validation):n.validation!=="regex"?t=`Invalid ${n.validation}`:t="Invalid";break;case _.too_small:n.type==="array"?t=`Array must contain ${n.exact?"exactly":n.inclusive?"at least":"more than"} ${n.minimum} element(s)`:n.type==="string"?t=`String must contain ${n.exact?"exactly":n.inclusive?"at least":"over"} ${n.minimum} character(s)`:n.type==="number"?t=`Number must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${n.minimum}`:n.type==="date"?t=`Date must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(n.minimum))}`:t="Invalid input";break;case _.too_big:n.type==="array"?t=`Array must contain ${n.exact?"exactly":n.inclusive?"at most":"less than"} ${n.maximum} element(s)`:n.type==="string"?t=`String must contain ${n.exact?"exactly":n.inclusive?"at most":"under"} ${n.maximum} character(s)`:n.type==="number"?t=`Number must be ${n.exact?"exactly":n.inclusive?"less than or equal to":"less than"} ${n.maximum}`:n.type==="bigint"?t=`BigInt must be ${n.exact?"exactly":n.inclusive?"less than or equal to":"less than"} ${n.maximum}`:n.type==="date"?t=`Date must be ${n.exact?"exactly":n.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(n.maximum))}`:t="Invalid input";break;case _.custom:t="Invalid input";break;case _.invalid_intersection_types:t="Intersection results could not be merged";break;case _.not_multiple_of:t=`Number must be a multiple of ${n.multipleOf}`;break;case _.not_finite:t="Number must be finite";break;default:t=e.defaultError,Z.assertNever(n)}return{message:t}};let Wc=fi;function xf(n){Wc=n}function Zn(){return Wc}const Jn=n=>{const{data:e,path:t,errorMaps:i,issueData:s}=n,r=[...t,...s.path||[]],a={...s,path:r};if(s.message!==void 0)return{...s,path:r,message:s.message};let o="";const c=i.filter(d=>!!d).slice().reverse();for(const d of c)o=d(a,{data:e,defaultError:o}).message;return{...s,path:r,message:o}},If=[];function A(n,e){const t=Zn(),i=Jn({issueData:e,data:n.data,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,t,t===fi?void 0:fi].filter(s=>!!s)});n.common.issues.push(i)}class ye{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,t){const i=[];for(const s of t){if(s.status==="aborted")return j;s.status==="dirty"&&e.dirty(),i.push(s.value)}return{status:e.value,value:i}}static async mergeObjectAsync(e,t){const i=[];for(const s of t){const r=await s.key,a=await s.value;i.push({key:r,value:a})}return ye.mergeObjectSync(e,i)}static mergeObjectSync(e,t){const i={};for(const s of t){const{key:r,value:a}=s;if(r.status==="aborted"||a.status==="aborted")return j;r.status==="dirty"&&e.dirty(),a.status==="dirty"&&e.dirty(),r.value!=="__proto__"&&(typeof a.value<"u"||s.alwaysSet)&&(i[r.value]=a.value)}return{status:e.value,value:i}}}const j=Object.freeze({status:"aborted"}),pi=n=>({status:"dirty",value:n}),be=n=>({status:"valid",value:n}),Lr=n=>n.status==="aborted",Ur=n=>n.status==="dirty",qt=n=>n.status==="valid",$i=n=>typeof Promise<"u"&&n instanceof Promise;function Yn(n,e,t,i){if(t==="a"&&!i)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?n!==e||!i:!e.has(n))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?i:t==="a"?i.call(n):i?i.value:e.get(n)}function Kc(n,e,t,i,s){if(i==="m")throw new TypeError("Private method is not writable");if(i==="a"&&!s)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?n!==e||!s:!e.has(n))throw new TypeError("Cannot write private member to an object whose class did not declare it");return i==="a"?s.call(n,t):s?s.value=t:e.set(n,t),t}typeof SuppressedError=="function"&&SuppressedError;var N;(function(n){n.errToObj=e=>typeof e=="string"?{message:e}:e||{},n.toString=e=>typeof e=="string"?e:e==null?void 0:e.message})(N||(N={}));var Bi,Vi;class Ye{constructor(e,t,i,s){this._cachedPath=[],this.parent=e,this.data=t,this._path=i,this._key=s}get path(){return this._cachedPath.length||(this._key instanceof Array?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const Hc=(n,e)=>{if(qt(e))return{success:!0,data:e.value};if(!n.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const t=new Ie(n.common.issues);return this._error=t,this._error}}};function B(n){if(!n)return{};const{errorMap:e,invalid_type_error:t,required_error:i,description:s}=n;if(e&&(t||i))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:s}:{errorMap:(a,o)=>{var c,d;const{message:l}=n;return a.code==="invalid_enum_value"?{message:l??o.defaultError}:typeof o.data>"u"?{message:(c=l??i)!==null&&c!==void 0?c:o.defaultError}:a.code!=="invalid_type"?{message:o.defaultError}:{message:(d=l??t)!==null&&d!==void 0?d:o.defaultError}},description:s}}class V{get description(){return this._def.description}_getType(e){return at(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:at(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new ye,ctx:{common:e.parent.common,data:e.data,parsedType:at(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if($i(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){const t=this._parse(e);return Promise.resolve(t)}parse(e,t){const i=this.safeParse(e,t);if(i.success)return i.data;throw i.error}safeParse(e,t){var i;const s={common:{issues:[],async:(i=t==null?void 0:t.async)!==null&&i!==void 0?i:!1,contextualErrorMap:t==null?void 0:t.errorMap},path:(t==null?void 0:t.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:at(e)},r=this._parseSync({data:e,path:s.path,parent:s});return Hc(s,r)}"~validate"(e){var t,i;const s={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:at(e)};if(!this["~standard"].async)try{const r=this._parseSync({data:e,path:[],parent:s});return qt(r)?{value:r.value}:{issues:s.common.issues}}catch(r){!((i=(t=r==null?void 0:r.message)===null||t===void 0?void 0:t.toLowerCase())===null||i===void 0)&&i.includes("encountered")&&(this["~standard"].async=!0),s.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:s}).then(r=>qt(r)?{value:r.value}:{issues:s.common.issues})}async parseAsync(e,t){const i=await this.safeParseAsync(e,t);if(i.success)return i.data;throw i.error}async safeParseAsync(e,t){const i={common:{issues:[],contextualErrorMap:t==null?void 0:t.errorMap,async:!0},path:(t==null?void 0:t.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:at(e)},s=this._parse({data:e,path:i.path,parent:i}),r=await($i(s)?s:Promise.resolve(s));return Hc(i,r)}refine(e,t){const i=s=>typeof t=="string"||typeof t>"u"?{message:t}:typeof t=="function"?t(s):t;return this._refinement((s,r)=>{const a=e(s),o=()=>r.addIssue({code:_.custom,...i(s)});return typeof Promise<"u"&&a instanceof Promise?a.then(c=>c?!0:(o(),!1)):a?!0:(o(),!1)})}refinement(e,t){return this._refinement((i,s)=>e(i)?!0:(s.addIssue(typeof t=="function"?t(i,s):t),!1))}_refinement(e){return new Ve({schema:this,typeName:F.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:t=>this["~validate"](t)}}optional(){return Xe.create(this,this._def)}nullable(){return Ot.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Be.create(this)}promise(){return yi.create(this,this._def)}or(e){return Wi.create([this,e],this._def)}and(e){return Ki.create(this,e,this._def)}transform(e){return new Ve({...B(this._def),schema:this,typeName:F.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t=typeof e=="function"?e:()=>e;return new Qi({...B(this._def),innerType:this,defaultValue:t,typeName:F.ZodDefault})}brand(){return new $r({typeName:F.ZodBranded,type:this,...B(this._def)})}catch(e){const t=typeof e=="function"?e:()=>e;return new Xi({...B(this._def),innerType:this,catchValue:t,typeName:F.ZodCatch})}describe(e){const t=this.constructor;return new t({...this._def,description:e})}pipe(e){return en.create(this,e)}readonly(){return tn.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const Af=/^c[^\s-]{8,}$/i,Of=/^[0-9a-z]+$/,Df=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Mf=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,Nf=/^[a-z0-9_-]{21}$/i,Lf=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Uf=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,Ff=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,jf="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let Fr;const $f=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Bf=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,Vf=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,qf=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,zf=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Gf=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Zc="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",Wf=new RegExp(`^${Zc}$`);function Jc(n){let e="([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d";return n.precision?e=`${e}\\.\\d{${n.precision}}`:n.precision==null&&(e=`${e}(\\.\\d+)?`),e}function Kf(n){return new RegExp(`^${Jc(n)}$`)}function Yc(n){let e=`${Zc}T${Jc(n)}`;const t=[];return t.push(n.local?"Z?":"Z"),n.offset&&t.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${t.join("|")})`,new RegExp(`^${e}$`)}function Hf(n,e){return!!((e==="v4"||!e)&&$f.test(n)||(e==="v6"||!e)&&Vf.test(n))}function Zf(n,e){if(!Lf.test(n))return!1;try{const[t]=n.split("."),i=t.replace(/-/g,"+").replace(/_/g,"/").padEnd(t.length+(4-t.length%4)%4,"="),s=JSON.parse(atob(i));return!(typeof s!="object"||s===null||!s.typ||!s.alg||e&&s.alg!==e)}catch{return!1}}function Jf(n,e){return!!((e==="v4"||!e)&&Bf.test(n)||(e==="v6"||!e)&&qf.test(n))}class $e extends V{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==D.string){const r=this._getOrReturnCtx(e);return A(r,{code:_.invalid_type,expected:D.string,received:r.parsedType}),j}const i=new ye;let s;for(const r of this._def.checks)if(r.kind==="min")e.data.length<r.value&&(s=this._getOrReturnCtx(e,s),A(s,{code:_.too_small,minimum:r.value,type:"string",inclusive:!0,exact:!1,message:r.message}),i.dirty());else if(r.kind==="max")e.data.length>r.value&&(s=this._getOrReturnCtx(e,s),A(s,{code:_.too_big,maximum:r.value,type:"string",inclusive:!0,exact:!1,message:r.message}),i.dirty());else if(r.kind==="length"){const a=e.data.length>r.value,o=e.data.length<r.value;(a||o)&&(s=this._getOrReturnCtx(e,s),a?A(s,{code:_.too_big,maximum:r.value,type:"string",inclusive:!0,exact:!0,message:r.message}):o&&A(s,{code:_.too_small,minimum:r.value,type:"string",inclusive:!0,exact:!0,message:r.message}),i.dirty())}else if(r.kind==="email")Ff.test(e.data)||(s=this._getOrReturnCtx(e,s),A(s,{validation:"email",code:_.invalid_string,message:r.message}),i.dirty());else if(r.kind==="emoji")Fr||(Fr=new RegExp(jf,"u")),Fr.test(e.data)||(s=this._getOrReturnCtx(e,s),A(s,{validation:"emoji",code:_.invalid_string,message:r.message}),i.dirty());else if(r.kind==="uuid")Mf.test(e.data)||(s=this._getOrReturnCtx(e,s),A(s,{validation:"uuid",code:_.invalid_string,message:r.message}),i.dirty());else if(r.kind==="nanoid")Nf.test(e.data)||(s=this._getOrReturnCtx(e,s),A(s,{validation:"nanoid",code:_.invalid_string,message:r.message}),i.dirty());else if(r.kind==="cuid")Af.test(e.data)||(s=this._getOrReturnCtx(e,s),A(s,{validation:"cuid",code:_.invalid_string,message:r.message}),i.dirty());else if(r.kind==="cuid2")Of.test(e.data)||(s=this._getOrReturnCtx(e,s),A(s,{validation:"cuid2",code:_.invalid_string,message:r.message}),i.dirty());else if(r.kind==="ulid")Df.test(e.data)||(s=this._getOrReturnCtx(e,s),A(s,{validation:"ulid",code:_.invalid_string,message:r.message}),i.dirty());else if(r.kind==="url")try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),A(s,{validation:"url",code:_.invalid_string,message:r.message}),i.dirty()}else r.kind==="regex"?(r.regex.lastIndex=0,r.regex.test(e.data)||(s=this._getOrReturnCtx(e,s),A(s,{validation:"regex",code:_.invalid_string,message:r.message}),i.dirty())):r.kind==="trim"?e.data=e.data.trim():r.kind==="includes"?e.data.includes(r.value,r.position)||(s=this._getOrReturnCtx(e,s),A(s,{code:_.invalid_string,validation:{includes:r.value,position:r.position},message:r.message}),i.dirty()):r.kind==="toLowerCase"?e.data=e.data.toLowerCase():r.kind==="toUpperCase"?e.data=e.data.toUpperCase():r.kind==="startsWith"?e.data.startsWith(r.value)||(s=this._getOrReturnCtx(e,s),A(s,{code:_.invalid_string,validation:{startsWith:r.value},message:r.message}),i.dirty()):r.kind==="endsWith"?e.data.endsWith(r.value)||(s=this._getOrReturnCtx(e,s),A(s,{code:_.invalid_string,validation:{endsWith:r.value},message:r.message}),i.dirty()):r.kind==="datetime"?Yc(r).test(e.data)||(s=this._getOrReturnCtx(e,s),A(s,{code:_.invalid_string,validation:"datetime",message:r.message}),i.dirty()):r.kind==="date"?Wf.test(e.data)||(s=this._getOrReturnCtx(e,s),A(s,{code:_.invalid_string,validation:"date",message:r.message}),i.dirty()):r.kind==="time"?Kf(r).test(e.data)||(s=this._getOrReturnCtx(e,s),A(s,{code:_.invalid_string,validation:"time",message:r.message}),i.dirty()):r.kind==="duration"?Uf.test(e.data)||(s=this._getOrReturnCtx(e,s),A(s,{validation:"duration",code:_.invalid_string,message:r.message}),i.dirty()):r.kind==="ip"?Hf(e.data,r.version)||(s=this._getOrReturnCtx(e,s),A(s,{validation:"ip",code:_.invalid_string,message:r.message}),i.dirty()):r.kind==="jwt"?Zf(e.data,r.alg)||(s=this._getOrReturnCtx(e,s),A(s,{validation:"jwt",code:_.invalid_string,message:r.message}),i.dirty()):r.kind==="cidr"?Jf(e.data,r.version)||(s=this._getOrReturnCtx(e,s),A(s,{validation:"cidr",code:_.invalid_string,message:r.message}),i.dirty()):r.kind==="base64"?zf.test(e.data)||(s=this._getOrReturnCtx(e,s),A(s,{validation:"base64",code:_.invalid_string,message:r.message}),i.dirty()):r.kind==="base64url"?Gf.test(e.data)||(s=this._getOrReturnCtx(e,s),A(s,{validation:"base64url",code:_.invalid_string,message:r.message}),i.dirty()):Z.assertNever(r);return{status:i.value,value:e.data}}_regex(e,t,i){return this.refinement(s=>e.test(s),{validation:t,code:_.invalid_string,...N.errToObj(i)})}_addCheck(e){return new $e({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...N.errToObj(e)})}url(e){return this._addCheck({kind:"url",...N.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...N.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...N.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...N.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...N.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...N.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...N.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...N.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...N.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...N.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...N.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...N.errToObj(e)})}datetime(e){var t,i;return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof(e==null?void 0:e.precision)>"u"?null:e==null?void 0:e.precision,offset:(t=e==null?void 0:e.offset)!==null&&t!==void 0?t:!1,local:(i=e==null?void 0:e.local)!==null&&i!==void 0?i:!1,...N.errToObj(e==null?void 0:e.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof(e==null?void 0:e.precision)>"u"?null:e==null?void 0:e.precision,...N.errToObj(e==null?void 0:e.message)})}duration(e){return this._addCheck({kind:"duration",...N.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...N.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t==null?void 0:t.position,...N.errToObj(t==null?void 0:t.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...N.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...N.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...N.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...N.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...N.errToObj(t)})}nonempty(e){return this.min(1,N.errToObj(e))}trim(){return new $e({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new $e({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new $e({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}}$e.create=n=>{var e;return new $e({checks:[],typeName:F.ZodString,coerce:(e=n==null?void 0:n.coerce)!==null&&e!==void 0?e:!1,...B(n)})};function Yf(n,e){const t=(n.toString().split(".")[1]||"").length,i=(e.toString().split(".")[1]||"").length,s=t>i?t:i,r=parseInt(n.toFixed(s).replace(".","")),a=parseInt(e.toFixed(s).replace(".",""));return r%a/Math.pow(10,s)}class xt extends V{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==D.number){const r=this._getOrReturnCtx(e);return A(r,{code:_.invalid_type,expected:D.number,received:r.parsedType}),j}let i;const s=new ye;for(const r of this._def.checks)r.kind==="int"?Z.isInteger(e.data)||(i=this._getOrReturnCtx(e,i),A(i,{code:_.invalid_type,expected:"integer",received:"float",message:r.message}),s.dirty()):r.kind==="min"?(r.inclusive?e.data<r.value:e.data<=r.value)&&(i=this._getOrReturnCtx(e,i),A(i,{code:_.too_small,minimum:r.value,type:"number",inclusive:r.inclusive,exact:!1,message:r.message}),s.dirty()):r.kind==="max"?(r.inclusive?e.data>r.value:e.data>=r.value)&&(i=this._getOrReturnCtx(e,i),A(i,{code:_.too_big,maximum:r.value,type:"number",inclusive:r.inclusive,exact:!1,message:r.message}),s.dirty()):r.kind==="multipleOf"?Yf(e.data,r.value)!==0&&(i=this._getOrReturnCtx(e,i),A(i,{code:_.not_multiple_of,multipleOf:r.value,message:r.message}),s.dirty()):r.kind==="finite"?Number.isFinite(e.data)||(i=this._getOrReturnCtx(e,i),A(i,{code:_.not_finite,message:r.message}),s.dirty()):Z.assertNever(r);return{status:s.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,N.toString(t))}gt(e,t){return this.setLimit("min",e,!1,N.toString(t))}lte(e,t){return this.setLimit("max",e,!0,N.toString(t))}lt(e,t){return this.setLimit("max",e,!1,N.toString(t))}setLimit(e,t,i,s){return new xt({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:i,message:N.toString(s)}]})}_addCheck(e){return new xt({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:N.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:N.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:N.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:N.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:N.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:N.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:N.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:N.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:N.toString(e)})}get minValue(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&Z.isInteger(e.value))}get isFinite(){let e=null,t=null;for(const i of this._def.checks){if(i.kind==="finite"||i.kind==="int"||i.kind==="multipleOf")return!0;i.kind==="min"?(t===null||i.value>t)&&(t=i.value):i.kind==="max"&&(e===null||i.value<e)&&(e=i.value)}return Number.isFinite(t)&&Number.isFinite(e)}}xt.create=n=>new xt({checks:[],typeName:F.ZodNumber,coerce:(n==null?void 0:n.coerce)||!1,...B(n)});class It extends V{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==D.bigint)return this._getInvalidInput(e);let i;const s=new ye;for(const r of this._def.checks)r.kind==="min"?(r.inclusive?e.data<r.value:e.data<=r.value)&&(i=this._getOrReturnCtx(e,i),A(i,{code:_.too_small,type:"bigint",minimum:r.value,inclusive:r.inclusive,message:r.message}),s.dirty()):r.kind==="max"?(r.inclusive?e.data>r.value:e.data>=r.value)&&(i=this._getOrReturnCtx(e,i),A(i,{code:_.too_big,type:"bigint",maximum:r.value,inclusive:r.inclusive,message:r.message}),s.dirty()):r.kind==="multipleOf"?e.data%r.value!==BigInt(0)&&(i=this._getOrReturnCtx(e,i),A(i,{code:_.not_multiple_of,multipleOf:r.value,message:r.message}),s.dirty()):Z.assertNever(r);return{status:s.value,value:e.data}}_getInvalidInput(e){const t=this._getOrReturnCtx(e);return A(t,{code:_.invalid_type,expected:D.bigint,received:t.parsedType}),j}gte(e,t){return this.setLimit("min",e,!0,N.toString(t))}gt(e,t){return this.setLimit("min",e,!1,N.toString(t))}lte(e,t){return this.setLimit("max",e,!0,N.toString(t))}lt(e,t){return this.setLimit("max",e,!1,N.toString(t))}setLimit(e,t,i,s){return new It({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:i,message:N.toString(s)}]})}_addCheck(e){return new It({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:N.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:N.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:N.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:N.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:N.toString(t)})}get minValue(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}}It.create=n=>{var e;return new It({checks:[],typeName:F.ZodBigInt,coerce:(e=n==null?void 0:n.coerce)!==null&&e!==void 0?e:!1,...B(n)})};class qi extends V{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==D.boolean){const i=this._getOrReturnCtx(e);return A(i,{code:_.invalid_type,expected:D.boolean,received:i.parsedType}),j}return be(e.data)}}qi.create=n=>new qi({typeName:F.ZodBoolean,coerce:(n==null?void 0:n.coerce)||!1,...B(n)});class zt extends V{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==D.date){const r=this._getOrReturnCtx(e);return A(r,{code:_.invalid_type,expected:D.date,received:r.parsedType}),j}if(isNaN(e.data.getTime())){const r=this._getOrReturnCtx(e);return A(r,{code:_.invalid_date}),j}const i=new ye;let s;for(const r of this._def.checks)r.kind==="min"?e.data.getTime()<r.value&&(s=this._getOrReturnCtx(e,s),A(s,{code:_.too_small,message:r.message,inclusive:!0,exact:!1,minimum:r.value,type:"date"}),i.dirty()):r.kind==="max"?e.data.getTime()>r.value&&(s=this._getOrReturnCtx(e,s),A(s,{code:_.too_big,message:r.message,inclusive:!0,exact:!1,maximum:r.value,type:"date"}),i.dirty()):Z.assertNever(r);return{status:i.value,value:new Date(e.data.getTime())}}_addCheck(e){return new zt({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:N.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:N.toString(t)})}get minDate(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e!=null?new Date(e):null}}zt.create=n=>new zt({checks:[],coerce:(n==null?void 0:n.coerce)||!1,typeName:F.ZodDate,...B(n)});class Qn extends V{_parse(e){if(this._getType(e)!==D.symbol){const i=this._getOrReturnCtx(e);return A(i,{code:_.invalid_type,expected:D.symbol,received:i.parsedType}),j}return be(e.data)}}Qn.create=n=>new Qn({typeName:F.ZodSymbol,...B(n)});class zi extends V{_parse(e){if(this._getType(e)!==D.undefined){const i=this._getOrReturnCtx(e);return A(i,{code:_.invalid_type,expected:D.undefined,received:i.parsedType}),j}return be(e.data)}}zi.create=n=>new zi({typeName:F.ZodUndefined,...B(n)});class Gi extends V{_parse(e){if(this._getType(e)!==D.null){const i=this._getOrReturnCtx(e);return A(i,{code:_.invalid_type,expected:D.null,received:i.parsedType}),j}return be(e.data)}}Gi.create=n=>new Gi({typeName:F.ZodNull,...B(n)});class mi extends V{constructor(){super(...arguments),this._any=!0}_parse(e){return be(e.data)}}mi.create=n=>new mi({typeName:F.ZodAny,...B(n)});class Gt extends V{constructor(){super(...arguments),this._unknown=!0}_parse(e){return be(e.data)}}Gt.create=n=>new Gt({typeName:F.ZodUnknown,...B(n)});class ot extends V{_parse(e){const t=this._getOrReturnCtx(e);return A(t,{code:_.invalid_type,expected:D.never,received:t.parsedType}),j}}ot.create=n=>new ot({typeName:F.ZodNever,...B(n)});class Xn extends V{_parse(e){if(this._getType(e)!==D.undefined){const i=this._getOrReturnCtx(e);return A(i,{code:_.invalid_type,expected:D.void,received:i.parsedType}),j}return be(e.data)}}Xn.create=n=>new Xn({typeName:F.ZodVoid,...B(n)});class Be extends V{_parse(e){const{ctx:t,status:i}=this._processInputParams(e),s=this._def;if(t.parsedType!==D.array)return A(t,{code:_.invalid_type,expected:D.array,received:t.parsedType}),j;if(s.exactLength!==null){const a=t.data.length>s.exactLength.value,o=t.data.length<s.exactLength.value;(a||o)&&(A(t,{code:a?_.too_big:_.too_small,minimum:o?s.exactLength.value:void 0,maximum:a?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),i.dirty())}if(s.minLength!==null&&t.data.length<s.minLength.value&&(A(t,{code:_.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),i.dirty()),s.maxLength!==null&&t.data.length>s.maxLength.value&&(A(t,{code:_.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),i.dirty()),t.common.async)return Promise.all([...t.data].map((a,o)=>s.type._parseAsync(new Ye(t,a,t.path,o)))).then(a=>ye.mergeArray(i,a));const r=[...t.data].map((a,o)=>s.type._parseSync(new Ye(t,a,t.path,o)));return ye.mergeArray(i,r)}get element(){return this._def.type}min(e,t){return new Be({...this._def,minLength:{value:e,message:N.toString(t)}})}max(e,t){return new Be({...this._def,maxLength:{value:e,message:N.toString(t)}})}length(e,t){return new Be({...this._def,exactLength:{value:e,message:N.toString(t)}})}nonempty(e){return this.min(1,e)}}Be.create=(n,e)=>new Be({type:n,minLength:null,maxLength:null,exactLength:null,typeName:F.ZodArray,...B(e)});function gi(n){if(n instanceof re){const e={};for(const t in n.shape){const i=n.shape[t];e[t]=Xe.create(gi(i))}return new re({...n._def,shape:()=>e})}else return n instanceof Be?new Be({...n._def,type:gi(n.element)}):n instanceof Xe?Xe.create(gi(n.unwrap())):n instanceof Ot?Ot.create(gi(n.unwrap())):n instanceof Qe?Qe.create(n.items.map(e=>gi(e))):n}class re extends V{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const e=this._def.shape(),t=Z.objectKeys(e);return this._cached={shape:e,keys:t}}_parse(e){if(this._getType(e)!==D.object){const d=this._getOrReturnCtx(e);return A(d,{code:_.invalid_type,expected:D.object,received:d.parsedType}),j}const{status:i,ctx:s}=this._processInputParams(e),{shape:r,keys:a}=this._getCached(),o=[];if(!(this._def.catchall instanceof ot&&this._def.unknownKeys==="strip"))for(const d in s.data)a.includes(d)||o.push(d);const c=[];for(const d of a){const l=r[d],u=s.data[d];c.push({key:{status:"valid",value:d},value:l._parse(new Ye(s,u,s.path,d)),alwaysSet:d in s.data})}if(this._def.catchall instanceof ot){const d=this._def.unknownKeys;if(d==="passthrough")for(const l of o)c.push({key:{status:"valid",value:l},value:{status:"valid",value:s.data[l]}});else if(d==="strict")o.length>0&&(A(s,{code:_.unrecognized_keys,keys:o}),i.dirty());else if(d!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const d=this._def.catchall;for(const l of o){const u=s.data[l];c.push({key:{status:"valid",value:l},value:d._parse(new Ye(s,u,s.path,l)),alwaysSet:l in s.data})}}return s.common.async?Promise.resolve().then(async()=>{const d=[];for(const l of c){const u=await l.key,h=await l.value;d.push({key:u,value:h,alwaysSet:l.alwaysSet})}return d}).then(d=>ye.mergeObjectSync(i,d)):ye.mergeObjectSync(i,c)}get shape(){return this._def.shape()}strict(e){return N.errToObj,new re({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,i)=>{var s,r,a,o;const c=(a=(r=(s=this._def).errorMap)===null||r===void 0?void 0:r.call(s,t,i).message)!==null&&a!==void 0?a:i.defaultError;return t.code==="unrecognized_keys"?{message:(o=N.errToObj(e).message)!==null&&o!==void 0?o:c}:{message:c}}}:{}})}strip(){return new re({...this._def,unknownKeys:"strip"})}passthrough(){return new re({...this._def,unknownKeys:"passthrough"})}extend(e){return new re({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new re({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:F.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new re({...this._def,catchall:e})}pick(e){const t={};return Z.objectKeys(e).forEach(i=>{e[i]&&this.shape[i]&&(t[i]=this.shape[i])}),new re({...this._def,shape:()=>t})}omit(e){const t={};return Z.objectKeys(this.shape).forEach(i=>{e[i]||(t[i]=this.shape[i])}),new re({...this._def,shape:()=>t})}deepPartial(){return gi(this)}partial(e){const t={};return Z.objectKeys(this.shape).forEach(i=>{const s=this.shape[i];e&&!e[i]?t[i]=s:t[i]=s.optional()}),new re({...this._def,shape:()=>t})}required(e){const t={};return Z.objectKeys(this.shape).forEach(i=>{if(e&&!e[i])t[i]=this.shape[i];else{let r=this.shape[i];for(;r instanceof Xe;)r=r._def.innerType;t[i]=r}}),new re({...this._def,shape:()=>t})}keyof(){return Qc(Z.objectKeys(this.shape))}}re.create=(n,e)=>new re({shape:()=>n,unknownKeys:"strip",catchall:ot.create(),typeName:F.ZodObject,...B(e)}),re.strictCreate=(n,e)=>new re({shape:()=>n,unknownKeys:"strict",catchall:ot.create(),typeName:F.ZodObject,...B(e)}),re.lazycreate=(n,e)=>new re({shape:n,unknownKeys:"strip",catchall:ot.create(),typeName:F.ZodObject,...B(e)});class Wi extends V{_parse(e){const{ctx:t}=this._processInputParams(e),i=this._def.options;function s(r){for(const o of r)if(o.result.status==="valid")return o.result;for(const o of r)if(o.result.status==="dirty")return t.common.issues.push(...o.ctx.common.issues),o.result;const a=r.map(o=>new Ie(o.ctx.common.issues));return A(t,{code:_.invalid_union,unionErrors:a}),j}if(t.common.async)return Promise.all(i.map(async r=>{const a={...t,common:{...t.common,issues:[]},parent:null};return{result:await r._parseAsync({data:t.data,path:t.path,parent:a}),ctx:a}})).then(s);{let r;const a=[];for(const c of i){const d={...t,common:{...t.common,issues:[]},parent:null},l=c._parseSync({data:t.data,path:t.path,parent:d});if(l.status==="valid")return l;l.status==="dirty"&&!r&&(r={result:l,ctx:d}),d.common.issues.length&&a.push(d.common.issues)}if(r)return t.common.issues.push(...r.ctx.common.issues),r.result;const o=a.map(c=>new Ie(c));return A(t,{code:_.invalid_union,unionErrors:o}),j}}get options(){return this._def.options}}Wi.create=(n,e)=>new Wi({options:n,typeName:F.ZodUnion,...B(e)});const ct=n=>n instanceof Zi?ct(n.schema):n instanceof Ve?ct(n.innerType()):n instanceof Ji?[n.value]:n instanceof At?n.options:n instanceof Yi?Z.objectValues(n.enum):n instanceof Qi?ct(n._def.innerType):n instanceof zi?[void 0]:n instanceof Gi?[null]:n instanceof Xe?[void 0,...ct(n.unwrap())]:n instanceof Ot?[null,...ct(n.unwrap())]:n instanceof $r||n instanceof tn?ct(n.unwrap()):n instanceof Xi?ct(n._def.innerType):[];class es extends V{_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==D.object)return A(t,{code:_.invalid_type,expected:D.object,received:t.parsedType}),j;const i=this.discriminator,s=t.data[i],r=this.optionsMap.get(s);return r?t.common.async?r._parseAsync({data:t.data,path:t.path,parent:t}):r._parseSync({data:t.data,path:t.path,parent:t}):(A(t,{code:_.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[i]}),j)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,i){const s=new Map;for(const r of t){const a=ct(r.shape[e]);if(!a.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(const o of a){if(s.has(o))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(o)}`);s.set(o,r)}}return new es({typeName:F.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:s,...B(i)})}}function jr(n,e){const t=at(n),i=at(e);if(n===e)return{valid:!0,data:n};if(t===D.object&&i===D.object){const s=Z.objectKeys(e),r=Z.objectKeys(n).filter(o=>s.indexOf(o)!==-1),a={...n,...e};for(const o of r){const c=jr(n[o],e[o]);if(!c.valid)return{valid:!1};a[o]=c.data}return{valid:!0,data:a}}else if(t===D.array&&i===D.array){if(n.length!==e.length)return{valid:!1};const s=[];for(let r=0;r<n.length;r++){const a=n[r],o=e[r],c=jr(a,o);if(!c.valid)return{valid:!1};s.push(c.data)}return{valid:!0,data:s}}else return t===D.date&&i===D.date&&+n==+e?{valid:!0,data:n}:{valid:!1}}class Ki extends V{_parse(e){const{status:t,ctx:i}=this._processInputParams(e),s=(r,a)=>{if(Lr(r)||Lr(a))return j;const o=jr(r.value,a.value);return o.valid?((Ur(r)||Ur(a))&&t.dirty(),{status:t.value,value:o.data}):(A(i,{code:_.invalid_intersection_types}),j)};return i.common.async?Promise.all([this._def.left._parseAsync({data:i.data,path:i.path,parent:i}),this._def.right._parseAsync({data:i.data,path:i.path,parent:i})]).then(([r,a])=>s(r,a)):s(this._def.left._parseSync({data:i.data,path:i.path,parent:i}),this._def.right._parseSync({data:i.data,path:i.path,parent:i}))}}Ki.create=(n,e,t)=>new Ki({left:n,right:e,typeName:F.ZodIntersection,...B(t)});class Qe extends V{_parse(e){const{status:t,ctx:i}=this._processInputParams(e);if(i.parsedType!==D.array)return A(i,{code:_.invalid_type,expected:D.array,received:i.parsedType}),j;if(i.data.length<this._def.items.length)return A(i,{code:_.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),j;!this._def.rest&&i.data.length>this._def.items.length&&(A(i,{code:_.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());const r=[...i.data].map((a,o)=>{const c=this._def.items[o]||this._def.rest;return c?c._parse(new Ye(i,a,i.path,o)):null}).filter(a=>!!a);return i.common.async?Promise.all(r).then(a=>ye.mergeArray(t,a)):ye.mergeArray(t,r)}get items(){return this._def.items}rest(e){return new Qe({...this._def,rest:e})}}Qe.create=(n,e)=>{if(!Array.isArray(n))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Qe({items:n,typeName:F.ZodTuple,rest:null,...B(e)})};class Hi extends V{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:i}=this._processInputParams(e);if(i.parsedType!==D.object)return A(i,{code:_.invalid_type,expected:D.object,received:i.parsedType}),j;const s=[],r=this._def.keyType,a=this._def.valueType;for(const o in i.data)s.push({key:r._parse(new Ye(i,o,i.path,o)),value:a._parse(new Ye(i,i.data[o],i.path,o)),alwaysSet:o in i.data});return i.common.async?ye.mergeObjectAsync(t,s):ye.mergeObjectSync(t,s)}get element(){return this._def.valueType}static create(e,t,i){return t instanceof V?new Hi({keyType:e,valueType:t,typeName:F.ZodRecord,...B(i)}):new Hi({keyType:$e.create(),valueType:e,typeName:F.ZodRecord,...B(t)})}}class ts extends V{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:i}=this._processInputParams(e);if(i.parsedType!==D.map)return A(i,{code:_.invalid_type,expected:D.map,received:i.parsedType}),j;const s=this._def.keyType,r=this._def.valueType,a=[...i.data.entries()].map(([o,c],d)=>({key:s._parse(new Ye(i,o,i.path,[d,"key"])),value:r._parse(new Ye(i,c,i.path,[d,"value"]))}));if(i.common.async){const o=new Map;return Promise.resolve().then(async()=>{for(const c of a){const d=await c.key,l=await c.value;if(d.status==="aborted"||l.status==="aborted")return j;(d.status==="dirty"||l.status==="dirty")&&t.dirty(),o.set(d.value,l.value)}return{status:t.value,value:o}})}else{const o=new Map;for(const c of a){const d=c.key,l=c.value;if(d.status==="aborted"||l.status==="aborted")return j;(d.status==="dirty"||l.status==="dirty")&&t.dirty(),o.set(d.value,l.value)}return{status:t.value,value:o}}}}ts.create=(n,e,t)=>new ts({valueType:e,keyType:n,typeName:F.ZodMap,...B(t)});class Wt extends V{_parse(e){const{status:t,ctx:i}=this._processInputParams(e);if(i.parsedType!==D.set)return A(i,{code:_.invalid_type,expected:D.set,received:i.parsedType}),j;const s=this._def;s.minSize!==null&&i.data.size<s.minSize.value&&(A(i,{code:_.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),t.dirty()),s.maxSize!==null&&i.data.size>s.maxSize.value&&(A(i,{code:_.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),t.dirty());const r=this._def.valueType;function a(c){const d=new Set;for(const l of c){if(l.status==="aborted")return j;l.status==="dirty"&&t.dirty(),d.add(l.value)}return{status:t.value,value:d}}const o=[...i.data.values()].map((c,d)=>r._parse(new Ye(i,c,i.path,d)));return i.common.async?Promise.all(o).then(c=>a(c)):a(o)}min(e,t){return new Wt({...this._def,minSize:{value:e,message:N.toString(t)}})}max(e,t){return new Wt({...this._def,maxSize:{value:e,message:N.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}Wt.create=(n,e)=>new Wt({valueType:n,minSize:null,maxSize:null,typeName:F.ZodSet,...B(e)});class vi extends V{constructor(){super(...arguments),this.validate=this.implement}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==D.function)return A(t,{code:_.invalid_type,expected:D.function,received:t.parsedType}),j;function i(o,c){return Jn({data:o,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,Zn(),fi].filter(d=>!!d),issueData:{code:_.invalid_arguments,argumentsError:c}})}function s(o,c){return Jn({data:o,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,Zn(),fi].filter(d=>!!d),issueData:{code:_.invalid_return_type,returnTypeError:c}})}const r={errorMap:t.common.contextualErrorMap},a=t.data;if(this._def.returns instanceof yi){const o=this;return be(async function(...c){const d=new Ie([]),l=await o._def.args.parseAsync(c,r).catch(f=>{throw d.addIssue(i(c,f)),d}),u=await Reflect.apply(a,this,l);return await o._def.returns._def.type.parseAsync(u,r).catch(f=>{throw d.addIssue(s(u,f)),d})})}else{const o=this;return be(function(...c){const d=o._def.args.safeParse(c,r);if(!d.success)throw new Ie([i(c,d.error)]);const l=Reflect.apply(a,this,d.data),u=o._def.returns.safeParse(l,r);if(!u.success)throw new Ie([s(l,u.error)]);return u.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new vi({...this._def,args:Qe.create(e).rest(Gt.create())})}returns(e){return new vi({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,i){return new vi({args:e||Qe.create([]).rest(Gt.create()),returns:t||Gt.create(),typeName:F.ZodFunction,...B(i)})}}class Zi extends V{get schema(){return this._def.getter()}_parse(e){const{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}}Zi.create=(n,e)=>new Zi({getter:n,typeName:F.ZodLazy,...B(e)});class Ji extends V{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return A(t,{received:t.data,code:_.invalid_literal,expected:this._def.value}),j}return{status:"valid",value:e.data}}get value(){return this._def.value}}Ji.create=(n,e)=>new Ji({value:n,typeName:F.ZodLiteral,...B(e)});function Qc(n,e){return new At({values:n,typeName:F.ZodEnum,...B(e)})}class At extends V{constructor(){super(...arguments),Bi.set(this,void 0)}_parse(e){if(typeof e.data!="string"){const t=this._getOrReturnCtx(e),i=this._def.values;return A(t,{expected:Z.joinValues(i),received:t.parsedType,code:_.invalid_type}),j}if(Yn(this,Bi,"f")||Kc(this,Bi,new Set(this._def.values),"f"),!Yn(this,Bi,"f").has(e.data)){const t=this._getOrReturnCtx(e),i=this._def.values;return A(t,{received:t.data,code:_.invalid_enum_value,options:i}),j}return be(e.data)}get options(){return this._def.values}get enum(){const e={};for(const t of this._def.values)e[t]=t;return e}get Values(){const e={};for(const t of this._def.values)e[t]=t;return e}get Enum(){const e={};for(const t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return At.create(e,{...this._def,...t})}exclude(e,t=this._def){return At.create(this.options.filter(i=>!e.includes(i)),{...this._def,...t})}}Bi=new WeakMap,At.create=Qc;class Yi extends V{constructor(){super(...arguments),Vi.set(this,void 0)}_parse(e){const t=Z.getValidEnumValues(this._def.values),i=this._getOrReturnCtx(e);if(i.parsedType!==D.string&&i.parsedType!==D.number){const s=Z.objectValues(t);return A(i,{expected:Z.joinValues(s),received:i.parsedType,code:_.invalid_type}),j}if(Yn(this,Vi,"f")||Kc(this,Vi,new Set(Z.getValidEnumValues(this._def.values)),"f"),!Yn(this,Vi,"f").has(e.data)){const s=Z.objectValues(t);return A(i,{received:i.data,code:_.invalid_enum_value,options:s}),j}return be(e.data)}get enum(){return this._def.values}}Vi=new WeakMap,Yi.create=(n,e)=>new Yi({values:n,typeName:F.ZodNativeEnum,...B(e)});class yi extends V{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==D.promise&&t.common.async===!1)return A(t,{code:_.invalid_type,expected:D.promise,received:t.parsedType}),j;const i=t.parsedType===D.promise?t.data:Promise.resolve(t.data);return be(i.then(s=>this._def.type.parseAsync(s,{path:t.path,errorMap:t.common.contextualErrorMap})))}}yi.create=(n,e)=>new yi({type:n,typeName:F.ZodPromise,...B(e)});class Ve extends V{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===F.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:t,ctx:i}=this._processInputParams(e),s=this._def.effect||null,r={addIssue:a=>{A(i,a),a.fatal?t.abort():t.dirty()},get path(){return i.path}};if(r.addIssue=r.addIssue.bind(r),s.type==="preprocess"){const a=s.transform(i.data,r);if(i.common.async)return Promise.resolve(a).then(async o=>{if(t.value==="aborted")return j;const c=await this._def.schema._parseAsync({data:o,path:i.path,parent:i});return c.status==="aborted"?j:c.status==="dirty"||t.value==="dirty"?pi(c.value):c});{if(t.value==="aborted")return j;const o=this._def.schema._parseSync({data:a,path:i.path,parent:i});return o.status==="aborted"?j:o.status==="dirty"||t.value==="dirty"?pi(o.value):o}}if(s.type==="refinement"){const a=o=>{const c=s.refinement(o,r);if(i.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return o};if(i.common.async===!1){const o=this._def.schema._parseSync({data:i.data,path:i.path,parent:i});return o.status==="aborted"?j:(o.status==="dirty"&&t.dirty(),a(o.value),{status:t.value,value:o.value})}else return this._def.schema._parseAsync({data:i.data,path:i.path,parent:i}).then(o=>o.status==="aborted"?j:(o.status==="dirty"&&t.dirty(),a(o.value).then(()=>({status:t.value,value:o.value}))))}if(s.type==="transform")if(i.common.async===!1){const a=this._def.schema._parseSync({data:i.data,path:i.path,parent:i});if(!qt(a))return a;const o=s.transform(a.value,r);if(o instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:o}}else return this._def.schema._parseAsync({data:i.data,path:i.path,parent:i}).then(a=>qt(a)?Promise.resolve(s.transform(a.value,r)).then(o=>({status:t.value,value:o})):a);Z.assertNever(s)}}Ve.create=(n,e,t)=>new Ve({schema:n,typeName:F.ZodEffects,effect:e,...B(t)}),Ve.createWithPreprocess=(n,e,t)=>new Ve({schema:e,effect:{type:"preprocess",transform:n},typeName:F.ZodEffects,...B(t)});class Xe extends V{_parse(e){return this._getType(e)===D.undefined?be(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Xe.create=(n,e)=>new Xe({innerType:n,typeName:F.ZodOptional,...B(e)});class Ot extends V{_parse(e){return this._getType(e)===D.null?be(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Ot.create=(n,e)=>new Ot({innerType:n,typeName:F.ZodNullable,...B(e)});class Qi extends V{_parse(e){const{ctx:t}=this._processInputParams(e);let i=t.data;return t.parsedType===D.undefined&&(i=this._def.defaultValue()),this._def.innerType._parse({data:i,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}Qi.create=(n,e)=>new Qi({innerType:n,typeName:F.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...B(e)});class Xi extends V{_parse(e){const{ctx:t}=this._processInputParams(e),i={...t,common:{...t.common,issues:[]}},s=this._def.innerType._parse({data:i.data,path:i.path,parent:{...i}});return $i(s)?s.then(r=>({status:"valid",value:r.status==="valid"?r.value:this._def.catchValue({get error(){return new Ie(i.common.issues)},input:i.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new Ie(i.common.issues)},input:i.data})}}removeCatch(){return this._def.innerType}}Xi.create=(n,e)=>new Xi({innerType:n,typeName:F.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...B(e)});class is extends V{_parse(e){if(this._getType(e)!==D.nan){const i=this._getOrReturnCtx(e);return A(i,{code:_.invalid_type,expected:D.nan,received:i.parsedType}),j}return{status:"valid",value:e.data}}}is.create=n=>new is({typeName:F.ZodNaN,...B(n)});const Qf=Symbol("zod_brand");class $r extends V{_parse(e){const{ctx:t}=this._processInputParams(e),i=t.data;return this._def.type._parse({data:i,path:t.path,parent:t})}unwrap(){return this._def.type}}class en extends V{_parse(e){const{status:t,ctx:i}=this._processInputParams(e);if(i.common.async)return(async()=>{const r=await this._def.in._parseAsync({data:i.data,path:i.path,parent:i});return r.status==="aborted"?j:r.status==="dirty"?(t.dirty(),pi(r.value)):this._def.out._parseAsync({data:r.value,path:i.path,parent:i})})();{const s=this._def.in._parseSync({data:i.data,path:i.path,parent:i});return s.status==="aborted"?j:s.status==="dirty"?(t.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:i.path,parent:i})}}static create(e,t){return new en({in:e,out:t,typeName:F.ZodPipeline})}}class tn extends V{_parse(e){const t=this._def.innerType._parse(e),i=s=>(qt(s)&&(s.value=Object.freeze(s.value)),s);return $i(t)?t.then(s=>i(s)):i(t)}unwrap(){return this._def.innerType}}tn.create=(n,e)=>new tn({innerType:n,typeName:F.ZodReadonly,...B(e)});function Xc(n,e){const t=typeof n=="function"?n(e):typeof n=="string"?{message:n}:n;return typeof t=="string"?{message:t}:t}function ed(n,e={},t){return n?mi.create().superRefine((i,s)=>{var r,a;const o=n(i);if(o instanceof Promise)return o.then(c=>{var d,l;if(!c){const u=Xc(e,i),h=(l=(d=u.fatal)!==null&&d!==void 0?d:t)!==null&&l!==void 0?l:!0;s.addIssue({code:"custom",...u,fatal:h})}});if(!o){const c=Xc(e,i),d=(a=(r=c.fatal)!==null&&r!==void 0?r:t)!==null&&a!==void 0?a:!0;s.addIssue({code:"custom",...c,fatal:d})}}):mi.create()}const Xf={object:re.lazycreate};var F;(function(n){n.ZodString="ZodString",n.ZodNumber="ZodNumber",n.ZodNaN="ZodNaN",n.ZodBigInt="ZodBigInt",n.ZodBoolean="ZodBoolean",n.ZodDate="ZodDate",n.ZodSymbol="ZodSymbol",n.ZodUndefined="ZodUndefined",n.ZodNull="ZodNull",n.ZodAny="ZodAny",n.ZodUnknown="ZodUnknown",n.ZodNever="ZodNever",n.ZodVoid="ZodVoid",n.ZodArray="ZodArray",n.ZodObject="ZodObject",n.ZodUnion="ZodUnion",n.ZodDiscriminatedUnion="ZodDiscriminatedUnion",n.ZodIntersection="ZodIntersection",n.ZodTuple="ZodTuple",n.ZodRecord="ZodRecord",n.ZodMap="ZodMap",n.ZodSet="ZodSet",n.ZodFunction="ZodFunction",n.ZodLazy="ZodLazy",n.ZodLiteral="ZodLiteral",n.ZodEnum="ZodEnum",n.ZodEffects="ZodEffects",n.ZodNativeEnum="ZodNativeEnum",n.ZodOptional="ZodOptional",n.ZodNullable="ZodNullable",n.ZodDefault="ZodDefault",n.ZodCatch="ZodCatch",n.ZodPromise="ZodPromise",n.ZodBranded="ZodBranded",n.ZodPipeline="ZodPipeline",n.ZodReadonly="ZodReadonly"})(F||(F={}));const ep=(n,e={message:`Input not instance of ${n.name}`})=>ed(t=>t instanceof n,e),td=$e.create,id=xt.create,tp=is.create,ip=It.create,nd=qi.create,np=zt.create,sp=Qn.create,rp=zi.create,ap=Gi.create,op=mi.create,cp=Gt.create,dp=ot.create,lp=Xn.create,up=Be.create,hp=re.create,fp=re.strictCreate,pp=Wi.create,mp=es.create,gp=Ki.create,vp=Qe.create,yp=Hi.create,bp=ts.create,kp=Wt.create,Tp=vi.create,Sp=Zi.create,Cp=Ji.create,_p=At.create,Ep=Yi.create,wp=yi.create,sd=Ve.create,Pp=Xe.create,Rp=Ot.create,xp=Ve.createWithPreprocess,Ip=en.create;var dt=Object.freeze({__proto__:null,defaultErrorMap:fi,setErrorMap:xf,getErrorMap:Zn,makeIssue:Jn,EMPTY_PATH:If,addIssueToContext:A,ParseStatus:ye,INVALID:j,DIRTY:pi,OK:be,isAborted:Lr,isDirty:Ur,isValid:qt,isAsync:$i,get util(){return Z},get objectUtil(){return Nr},ZodParsedType:D,getParsedType:at,ZodType:V,datetimeRegex:Yc,ZodString:$e,ZodNumber:xt,ZodBigInt:It,ZodBoolean:qi,ZodDate:zt,ZodSymbol:Qn,ZodUndefined:zi,ZodNull:Gi,ZodAny:mi,ZodUnknown:Gt,ZodNever:ot,ZodVoid:Xn,ZodArray:Be,ZodObject:re,ZodUnion:Wi,ZodDiscriminatedUnion:es,ZodIntersection:Ki,ZodTuple:Qe,ZodRecord:Hi,ZodMap:ts,ZodSet:Wt,ZodFunction:vi,ZodLazy:Zi,ZodLiteral:Ji,ZodEnum:At,ZodNativeEnum:Yi,ZodPromise:yi,ZodEffects:Ve,ZodTransformer:Ve,ZodOptional:Xe,ZodNullable:Ot,ZodDefault:Qi,ZodCatch:Xi,ZodNaN:is,BRAND:Qf,ZodBranded:$r,ZodPipeline:en,ZodReadonly:tn,custom:ed,Schema:V,ZodSchema:V,late:Xf,get ZodFirstPartyTypeKind(){return F},coerce:{string:n=>$e.create({...n,coerce:!0}),number:n=>xt.create({...n,coerce:!0}),boolean:n=>qi.create({...n,coerce:!0}),bigint:n=>It.create({...n,coerce:!0}),date:n=>zt.create({...n,coerce:!0})},any:op,array:up,bigint:ip,boolean:nd,date:np,discriminatedUnion:mp,effect:sd,enum:_p,function:Tp,instanceof:ep,intersection:gp,lazy:Sp,literal:Cp,map:bp,nan:tp,nativeEnum:Ep,never:dp,null:ap,nullable:Rp,number:id,object:hp,oboolean:()=>nd().optional(),onumber:()=>id().optional(),optional:Pp,ostring:()=>td().optional(),pipeline:Ip,preprocess:xp,promise:wp,record:yp,set:kp,strictObject:fp,string:td,symbol:sp,transformer:sd,tuple:vp,undefined:rp,union:pp,unknown:cp,void:lp,NEVER:j,ZodIssueCode:_,quotelessJson:Rf,ZodError:Ie});dt.object({apiKey:dt.string().optional(),enableVoice:dt.boolean().default(!0),enableScreenCapture:dt.boolean().default(!0),debug:dt.boolean().default(!1),user:dt.object({id:dt.string(),email:dt.string().optional(),metadata:dt.any().optional()}).optional()});var rd=(n=>(n.READY="ready",n.ERROR="error",n.VOICE_START="voice:start",n.VOICE_STOP="voice:stop",n.SCREEN_CAPTURE_START="screen:start",n.SCREEN_CAPTURE_STOP="screen:stop",n.STATE_CHANGE="state:change",n))(rd||{}),$=(n=>(n.READY="ready",n.ERROR="error",n.PAUSED="paused",n.LOADING="loading",n.THINKING="thinking",n.RESEARCHING="researching",n.AGENT_SPEAKING="agent_speaking",n.USER_SPEAKING="user_speaking",n.AWAITING_USER_INPUT="awaiting_user_input",n))($||{});class ad{constructor({sessionId:e}){this.currentState=$.READY,this.assistantAudioContext=null,this.userAudioContext=null,this.emitter=new Hd.EventEmitter,this.sessionId=e}on(e,t){this.emitter.on(e,t)}off(e,t){this.emitter.off(e,t)}setupRoomEventListeners(){this.room&&(this.room.on(w.LocalTrackUnpublished,e=>{e.source===S.Source.ScreenShare&&(this.screenStream=void 0)}),this.room.on(w.Disconnected,()=>{console.log("Room disconnected"),this.disconnect()}),this.room.on(w.ParticipantDisconnected,()=>{this.disconnect()}),this.room.on(w.TrackSubscribed,(e,t,i)=>{if(e.kind==="audio"&&e.attach(),e.source===S.Source.Microphone&&i.identity.includes("agent-")){const s=e.mediaStream;if(!s){console.error("No media stream available for assistant track");return}const r=new AudioContext,a=r.createAnalyser();r.createMediaStreamSource(s).connect(a),a.fftSize=2048;const c=new Uint8Array(a.frequencyBinCount);this.analyzeAudio(a,c,"ASSISTANT"),this.assistantAudioContext=r}}),this.room.on(w.ParticipantAttributesChanged,e=>{if(!e["lk.agent.state"]||this.currentState===$.RESEARCHING||this.currentState===$.PAUSED)return;const t=e["lk.agent.state"],i=pn(t).with("listening",()=>$.USER_SPEAKING).with("speaking",()=>$.AGENT_SPEAKING).with("thinking",()=>$.AGENT_SPEAKING).otherwise(()=>{});i&&this.setState(i)}),this.room.on(w.DataReceived,async e=>{try{const t=JSON.parse(new TextDecoder().decode(e)),i=t.status||t.request;pn(i).with("using_tool",()=>{this.currentState=$.RESEARCHING,this.emitter.emit("stateChanged",{newState:this.currentState})}).with("using_tool_ended",()=>{this.currentState=$.AGENT_SPEAKING,this.emitter.emit("stateChanged",{newState:this.currentState})}).with("share_screen",()=>{this.shareScreen()}).with("prompt_user",()=>{this.promptContinue()}).with("capture_page_html",()=>{this.emitter.emit("capturePageHTML",{})}).otherwise(()=>{console.warn("Unknown data received:",t)})}catch(t){console.error("Error parsing data:",t)}}))}async connect(){if(!this.sessionId){console.error("No session ID found"),this.emitter.emit("error",{error:new Error("No session ID provided")});return}await this.requestMicrophone();try{this.room=new Vt({adaptiveStream:!0,dynacast:!0}),this.setupRoomEventListeners();const e=`${Gc}/join-token?token=${this.sessionId}`,t=await fetch(e).then(i=>i.json());if(await this.room.connect(t.url,t.token),this.microphoneStream){const i=this.microphoneStream.getAudioTracks()[0];await this.room.localParticipant.publishTrack(i,{name:"microphone",source:S.Source.Microphone})}return{url:t.url,token:t.token}}catch(e){throw console.error("Failed to connect to LiveKit:",e),this.disconnect(),this.emitter.emit("error",{error:e instanceof Error?e:new Error(String(e))}),e}}disconnect(){var e;this.room&&this.room.disconnect(!0),(e=this.screenStream)!=null&&e.track&&this.screenStream.track.stop(),this.microphoneStream&&this.microphoneStream.getTracks().forEach(t=>t.stop()),this.setState($.READY)}setState(e){e!==this.currentState&&(this.currentState=e,this.emitter.emit("stateChanged",{newState:e}))}async requestMicrophone(){try{const e=await navigator.mediaDevices.getUserMedia({audio:!0});this.microphoneStream=e;const t=new AudioContext;this.userAudioContext=t;const i=t.createAnalyser(),s=t.createMediaStreamSource(e),r=t.createGain();r.gain.value=1.5,s.connect(r),r.connect(i),i.fftSize=2048;const a=new Uint8Array(i.frequencyBinCount);this.analyzeAudio(i,a,"USER")}catch(e){throw console.error("Microphone permission denied:",e),new Error("Microphone permission denied")}}async shareScreen(){this.emitter.emit("preScreenShare",{});try{if(this.screenStream=await this.room.localParticipant.setScreenShareEnabled(!0,{video:{displaySurface:"window"}}),!this.screenStream){console.warn("Failed to share screen");return}await this.room.localParticipant.publishData(new TextEncoder().encode(JSON.stringify({request:"share_screen",success:!0})),{reliable:!0})}catch(e){console.error("Error sharing screen:",e),this.emitter.emit("error",{error:e instanceof Error?e:new Error(String(e))})}}pauseRecording(){var e,t,i;this.room&&(this.setState($.PAUSED),this.room.localParticipant.getTrackPublications().forEach(s=>{var r,a;s.handleMuted(),(a=(r=s.track)==null?void 0:r.mediaStream)==null||a.getTracks().forEach(o=>o.enabled=!1)}),(e=this.microphoneStream)==null||e.getTracks().forEach(s=>s.enabled=!1),(i=(t=this.screenStream)==null?void 0:t.track)==null||i.mute(),this.userAudioContext&&this.userAudioContext.resume(),this.assistantAudioContext&&this.assistantAudioContext.resume())}resumeRecording(){var e,t,i;this.room&&(this.setState($.USER_SPEAKING),this.room.localParticipant.getTrackPublications().forEach(s=>{var r,a;s.handleUnmuted(),(a=(r=s.track)==null?void 0:r.mediaStream)==null||a.getTracks().forEach(o=>o.enabled=!0)}),(e=this.microphoneStream)==null||e.getTracks().forEach(s=>s.enabled=!0),(i=(t=this.screenStream)==null?void 0:t.track)==null||i.unmute())}async promptContinue(){await this.room.localParticipant.publishData(new TextEncoder().encode(JSON.stringify({request:"prompt_user",success:!0})),{reliable:!0})}async analyzeAudio(e,t,i){e.getByteFrequencyData(t);const s=t.reduce((a,o)=>a+o,0)/t.length,r=Math.max(.01,Math.min(1,s/128));i==="USER"&&this.currentState===$.USER_SPEAKING?this.emitter.emit("volume",{speaker:"USER",spectrum:Array.from(t),volume:r}):i==="ASSISTANT"&&this.currentState===$.AGENT_SPEAKING&&this.emitter.emit("volume",{speaker:"ASSISTANT",spectrum:Array.from(t),volume:r}),setTimeout(()=>this.analyzeAudio(e,t,i),50)}async sendHTML(e){if(!this.room){console.log("Cannot send HTML: Not connected to room");return}try{const t={type:"page_content",html:e,timestamp:new Date().toISOString()},i=JSON.stringify(t),r=new TextEncoder().encode(i);await this.room.localParticipant.publishData(r,{reliable:!0})}catch(t){console.error("Error sending HTML to LiveKit:",t),this.emitter.emit("error",{error:t instanceof Error?t:new Error(String(t))})}}async reconnect(e,t,i){try{if(!e||!t)return console.error("Missing room URL or token for reconnection"),this.emitter.emit("error",{error:new Error("Missing room URL or token for reconnection")}),!1;if(await this.requestMicrophone(),this.room=new Vt({adaptiveStream:!0,dynacast:!0}),this.setupRoomEventListeners(),await this.room.connect(e,t),this.microphoneStream){const s=this.microphoneStream.getAudioTracks()[0];await this.room.localParticipant.publishTrack(s,{name:"microphone",source:S.Source.Microphone})}return this.setState(i),i===$.PAUSED&&this.pauseRecording(),!0}catch(s){return console.error("Failed to reconnect to room:",s),this.disconnect(),this.emitter.emit("error",{error:s instanceof Error?s:new Error(String(s))}),!1}}}class Ap{constructor(e){this.namespace=e}getItem(e){return localStorage.getItem(`${this.namespace}.${e}`)}setItem(e,t){localStorage.setItem(`${this.namespace}.${e}`,t)}removeItem(e){localStorage.removeItem(`${this.namespace}.${e}`)}clear(){for(let e=0;e<localStorage.length;e++){const t=localStorage.key(e);t&&t.startsWith(`${this.namespace}.`)&&localStorage.removeItem(t)}}}const Br={SESSION_DATA:"session_data"},Vr=new Ap("io.obi.widget");var Op=Object.defineProperty,Dp=Object.getOwnPropertyDescriptor,ns=(n,e,t,i)=>{for(var s=i>1?void 0:i?Dp(e,t):e,r=n.length-1,a;r>=0;r--)(a=n[r])&&(s=(i?a(e,t,s):a(s))||s);return i&&s&&Op(e,t,s),s};class bi extends L.LitElement{constructor(){super(...arguments),this.id="",this.isActive=!1,this.isSpecial=!1}handleClick(e){e.preventDefault(),e.stopPropagation();const t=new CustomEvent("click",{detail:{id:this.id,isActive:!this.isActive},bubbles:!0,composed:!0});this.dispatchEvent(t),this.onClick&&this.onClick(this.id,!this.isActive)}render(){return L.html`
75
+ */function Le(n){return z({...n,state:!0,attribute:!1})}class sy{constructor(e){this.namespace=e}getItem(e){return localStorage.getItem(`${this.namespace}.${e}`)}setItem(e,A){localStorage.setItem(`${this.namespace}.${e}`,A)}removeItem(e){localStorage.removeItem(`${this.namespace}.${e}`)}clear(){for(let e=0;e<localStorage.length;e++){const A=localStorage.key(e);A&&A.startsWith(`${this.namespace}.`)&&localStorage.removeItem(A)}}}const ra={SESSION_DATA:"session_data"},sa=new sy("io.obi.widget");var oy=Object.defineProperty,ay=Object.getOwnPropertyDescriptor,kr=(n,e,A,t)=>{for(var i=t>1?void 0:t?ay(e,A):e,r=n.length-1,s;r>=0;r--)(s=n[r])&&(i=(t?s(e,A,i):s(i))||i);return t&&i&&oy(e,A,i),i};class en extends _.LitElement{constructor(){super(...arguments),this.id="",this.isActive=!1,this.isSpecial=!1}handleClick(e){e.preventDefault(),e.stopPropagation();const A=new CustomEvent("click",{detail:{id:this.id,isActive:!this.isActive},bubbles:!0,composed:!0});this.dispatchEvent(A),this.onClick&&this.onClick(this.id,!this.isActive)}render(){return _.html`
55
76
  <button
56
77
  id="obi-nav-${this.id}"
57
78
  class=${this.isSpecial?"special":""}
@@ -61,7 +82,7 @@ a=extmap-allow-mixed`)!==-1){const r=s.sdp.split(`
61
82
  >
62
83
  <slot></slot>
63
84
  </button>
64
- `}}bi.styles=L.css`
85
+ `}}en.styles=_.css`
65
86
  :host {
66
87
  display: block;
67
88
  }
@@ -113,7 +134,7 @@ a=extmap-allow-mixed`)!==-1){const r=s.sdp.split(`
113
134
  width: 18px;
114
135
  height: 18px;
115
136
  }
116
- `,ns([ee({type:String})],bi.prototype,"id",2),ns([ee({type:Boolean})],bi.prototype,"isActive",2),ns([ee({type:Boolean})],bi.prototype,"isSpecial",2),ns([ee({type:Function})],bi.prototype,"onClick",2),customElements.get("obi-nav-icon")||customElements.define("obi-nav-icon",bi);const nn=n=>L.html`
137
+ `,kr([z({type:String})],en.prototype,"id",2),kr([z({type:Boolean})],en.prototype,"isActive",2),kr([z({type:Boolean})],en.prototype,"isSpecial",2),kr([z({type:Function})],en.prototype,"onClick",2),customElements.get("obi-nav-icon")||customElements.define("obi-nav-icon",en);const Vn=n=>_.html`
117
138
  <svg
118
139
  xmlns="http://www.w3.org/2000/svg"
119
140
  width="24"
@@ -129,18 +150,18 @@ a=extmap-allow-mixed`)!==-1){const r=s.sdp.split(`
129
150
  >
130
151
  ${n}
131
152
  </svg>
132
- `,Mp=nn(L.svg`
153
+ `,cy=Vn(_.svg`
133
154
  <rect x="14" y="4" width="4" height="16" rx="1"/><rect x="6" y="4" width="4" height="16" rx="1"/>
134
- `),Np=nn(L.svg`<polygon points="6 3 20 12 6 21 6 3"/>`),Lp=nn(L.svg`
155
+ `),ly=Vn(_.svg`<polygon points="6 3 20 12 6 21 6 3"/>`),uy=Vn(_.svg`
135
156
  <path d="M12 2v10"/><path d="M18.4 6.6a9 9 0 1 1-12.77.04"/>
136
- `),Up=nn(L.svg`
157
+ `),dy=Vn(_.svg`
137
158
  <path d="M18 6 6 18"/><path d="m6 6 12 12"/>
138
- `),Fp=nn(L.svg`
159
+ `),hy=Vn(_.svg`
139
160
  <path d="M12 7v14" />
140
161
  <path
141
162
  d="M3 18a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h5a4 4 0 0 1 4 4 4 4 0 0 1 4-4h5a1 1 0 0 1 1 1v13a1 1 0 0 1-1 1h-6a3 3 0 0 0-3 3 3 3 0 0 0-3-3z"
142
163
  />
143
- `),od=L.html`
164
+ `),lh=_.html`
144
165
  <img
145
166
  class="widget-icon"
146
167
  src="data:image/svg+xml;base64,${btoa(`<?xml version="1.0" encoding="UTF-8"?>
@@ -161,14 +182,14 @@ a=extmap-allow-mixed`)!==-1){const r=s.sdp.split(`
161
182
  </svg>`)}"
162
183
  alt="Obi Icon"
163
184
  />
164
- `;var jp=Object.defineProperty,$p=Object.getOwnPropertyDescriptor,ki=(n,e,t,i)=>{for(var s=i>1?void 0:i?$p(e,t):e,r=n.length-1,a;r>=0;r--)(a=n[r])&&(s=(i?a(e,t,s):a(s))||s);return i&&s&&jp(e,t,s),s};class Dt extends L.LitElement{constructor(){super(),this.isActive=!1,this.isScreenActive=!1,this.position={top:0,left:0},this.currentState=$.READY,this.direction="up"}connectedCallback(){super.connectedCallback()}handleIconClick(e,t){this.onItemSelect&&this.onItemSelect(e,t)}render(){return L.html`
165
- ${this.isActive?L.html`
185
+ `;var fy=Object.defineProperty,gy=Object.getOwnPropertyDescriptor,An=(n,e,A,t)=>{for(var i=t>1?void 0:t?gy(e,A):e,r=n.length-1,s;r>=0;r--)(s=n[r])&&(i=(t?s(e,A,i):s(i))||i);return t&&i&&fy(e,A,i),i};class et extends _.LitElement{constructor(){super(),this.isActive=!1,this.isScreenActive=!1,this.position={top:0,left:0},this.currentState=O.READY,this.direction="up"}connectedCallback(){super.connectedCallback()}handleIconClick(e,A){this.onItemSelect&&this.onItemSelect(e,A)}render(){return _.html`
186
+ ${this.isActive?_.html`
166
187
  <obi-nav-icon
167
188
  id="pause"
168
- ?isActive=${this.currentState===$.PAUSED}
169
- @click=${()=>this.handleIconClick("pause",this.currentState!==$.PAUSED)}
189
+ ?isActive=${this.currentState===O.PAUSED}
190
+ @click=${()=>this.handleIconClick("pause",this.currentState!==O.PAUSED)}
170
191
  >
171
- ${this.currentState===$.PAUSED?Np:Mp}
192
+ ${this.currentState===O.PAUSED?ly:cy}
172
193
  </obi-nav-icon>
173
194
  <obi-nav-icon
174
195
  id="activate"
@@ -176,17 +197,17 @@ a=extmap-allow-mixed`)!==-1){const r=s.sdp.split(`
176
197
  ?isSpecial=${!0}
177
198
  @click=${()=>this.handleIconClick("activate",!this.isActive)}
178
199
  >
179
- ${this.isActive?Up:Lp}
200
+ ${this.isActive?dy:uy}
180
201
  </obi-nav-icon>
181
- `:L.html`
202
+ `:_.html`
182
203
  <obi-nav-icon
183
204
  id="experiences"
184
205
  @click=${()=>this.handleIconClick("experiences",!0)}
185
206
  >
186
- ${Fp}
207
+ ${hy}
187
208
  </obi-nav-icon>
188
209
  `}
189
- `}}Dt.styles=L.css`
210
+ `}}et.styles=_.css`
190
211
  :host {
191
212
  display: flex;
192
213
  position: absolute;
@@ -210,13 +231,13 @@ a=extmap-allow-mixed`)!==-1){const r=s.sdp.split(`
210
231
  bottom: auto;
211
232
  flex-direction: column;
212
233
  }
213
- `,ki([ee({type:Boolean})],Dt.prototype,"isActive",2),ki([ee({type:Boolean})],Dt.prototype,"isScreenActive",2),ki([ee({type:Object})],Dt.prototype,"position",2),ki([ee({type:String})],Dt.prototype,"currentState",2),ki([ee({type:String})],Dt.prototype,"direction",2),ki([ee({type:Function})],Dt.prototype,"onItemSelect",2),customElements.get("obi-navigation-bar")||customElements.define("obi-navigation-bar",Dt);var Bp=Object.defineProperty,Vp=Object.getOwnPropertyDescriptor,lt=(n,e,t,i)=>{for(var s=i>1?void 0:i?Vp(e,t):e,r=n.length-1,a;r>=0;r--)(a=n[r])&&(s=(i?a(e,t,s):a(s))||s);return i&&s&&Bp(e,t,s),s};class Kt extends L.LitElement{constructor(){super(...arguments),this.id="",this.name="",this.description="",this.imageSrc=""}handleClick(){this.onSelect&&this.onSelect(this.id),this.dispatchEvent(new CustomEvent("course-select",{detail:{id:this.id},bubbles:!0,composed:!0}))}render(){return L.html`
234
+ `,An([z({type:Boolean})],et.prototype,"isActive",2),An([z({type:Boolean})],et.prototype,"isScreenActive",2),An([z({type:Object})],et.prototype,"position",2),An([z({type:String})],et.prototype,"currentState",2),An([z({type:String})],et.prototype,"direction",2),An([z({type:Function})],et.prototype,"onItemSelect",2),customElements.get("obi-navigation-bar")||customElements.define("obi-navigation-bar",et);var py=Object.defineProperty,my=Object.getOwnPropertyDescriptor,UA=(n,e,A,t)=>{for(var i=t>1?void 0:t?my(e,A):e,r=n.length-1,s;r>=0;r--)(s=n[r])&&(i=(t?s(e,A,i):s(i))||i);return t&&i&&py(e,A,i),i};class Bt extends _.LitElement{constructor(){super(...arguments),this.id="",this.name="",this.description="",this.imageSrc=""}handleClick(){this.onSelect&&this.onSelect(this.id),this.dispatchEvent(new CustomEvent("course-select",{detail:{id:this.id},bubbles:!0,composed:!0}))}render(){return _.html`
214
235
  <div class="course-container" @click=${this.handleClick}>
215
236
  <img src=${this.imageSrc} alt="Course Preview" class="course-image" />
216
237
  <h2 class="course-title">${this.name}</h2>
217
- ${this.description?L.html`<p class="course-description">${this.description}</p>`:""}
238
+ ${this.description?_.html`<p class="course-description">${this.description}</p>`:""}
218
239
  </div>
219
- `}}Kt.styles=L.css`
240
+ `}}Bt.styles=_.css`
220
241
  :host {
221
242
  display: block;
222
243
  }
@@ -261,19 +282,19 @@ a=extmap-allow-mixed`)!==-1){const r=s.sdp.split(`
261
282
  color: #71717a;
262
283
  margin: 0;
263
284
  }
264
- `,lt([ee({type:String})],Kt.prototype,"id",2),lt([ee({type:String})],Kt.prototype,"name",2),lt([ee({type:String})],Kt.prototype,"description",2),lt([ee({type:String})],Kt.prototype,"imageSrc",2),lt([ee({type:Function})],Kt.prototype,"onSelect",2);class Ti extends L.LitElement{constructor(){super(...arguments),this.courses=[],this.loading=!1,this.error=""}handleCourseSelect(e){this.onCourseSelect&&this.onCourseSelect(e.detail.id)}render(){if(this.loading)return L.html`<div class="loading">Loading...</div>`;if(this.error)return L.html`<div class="error">${this.error}</div>`;if(!this.courses||this.courses.length===0)return L.html`<div class="empty">No courses available</div>`;const e=this.courses.length===1?"grid-cols-1":this.courses.length===2?"grid-cols-2":"grid-cols-3";return L.html`
285
+ `,UA([z({type:String})],Bt.prototype,"id",2),UA([z({type:String})],Bt.prototype,"name",2),UA([z({type:String})],Bt.prototype,"description",2),UA([z({type:String})],Bt.prototype,"imageSrc",2),UA([z({type:Function})],Bt.prototype,"onSelect",2);class tn extends _.LitElement{constructor(){super(...arguments),this.courses=[],this.loading=!1,this.error=""}handleCourseSelect(e){this.onCourseSelect&&this.onCourseSelect(e.detail.id)}render(){if(this.loading)return _.html`<div class="loading">Loading...</div>`;if(this.error)return _.html`<div class="error">${this.error}</div>`;if(!this.courses||this.courses.length===0)return _.html`<div class="empty">No courses available</div>`;const e=this.courses.length===1?"grid-cols-1":this.courses.length===2?"grid-cols-2":"grid-cols-3";return _.html`
265
286
  <div class="course-grid ${e}">
266
- ${this.courses.map(t=>L.html`
287
+ ${this.courses.map(A=>_.html`
267
288
  <obi-course
268
- id=${t.id}
269
- name=${t.name}
270
- description=${t.description||""}
271
- imageSrc=${t.imageSrc}
289
+ id=${A.id}
290
+ name=${A.name}
291
+ description=${A.description||""}
292
+ imageSrc=${A.imageSrc}
272
293
  @course-select=${this.handleCourseSelect}
273
294
  ></obi-course>
274
295
  `)}
275
296
  </div>
276
- `}}Ti.styles=L.css`
297
+ `}}tn.styles=_.css`
277
298
  :host {
278
299
  display: block;
279
300
  }
@@ -308,7 +329,7 @@ a=extmap-allow-mixed`)!==-1){const r=s.sdp.split(`
308
329
  .error {
309
330
  color: #ef4444;
310
331
  }
311
- `,lt([ee({type:Array})],Ti.prototype,"courses",2),lt([ee({type:Boolean})],Ti.prototype,"loading",2),lt([ee({type:String})],Ti.prototype,"error",2),lt([ee({type:Function})],Ti.prototype,"onCourseSelect",2),customElements.get("obi-course")||customElements.define("obi-course",Kt),customElements.get("obi-course-list")||customElements.define("obi-course-list",Ti);var qp=Object.defineProperty,zp=Object.getOwnPropertyDescriptor,Ht=(n,e,t,i)=>{for(var s=i>1?void 0:i?zp(e,t):e,r=n.length-1,a;r>=0;r--)(a=n[r])&&(s=(i?a(e,t,s):a(s))||s);return i&&s&&qp(e,t,s),s};class ut extends L.LitElement{constructor(){super(...arguments),this.courses=[],this.loading=!0,this.error="",this.apiKey="",this.apiBaseUrl=""}handleCourseSelect(e){this.onCourseSelect&&this.onCourseSelect(e.detail.id)}handleClose(){this.onClose&&this.onClose()}async fetchCourses(){try{this.loading=!0;const s=(await(await fetch(`${this.apiBaseUrl}/sessions?token=${this.apiKey}`)).json()).map(r=>({id:r.uuid,name:r.onboarding_plan.name,description:r.onboarding_plan.description,imageSrc:r.onboarding_plan.screen_url||"https://corproductionsydney-storagebucket5cb7c8ea-atg4gmftc6sk.s3.amazonaws.com/static/generic-course.png"})).filter(r=>!!r.name);this.courses=[...s],this.requestUpdate()}catch(e){console.error("Fetch error:",e),this.error="Failed to fetch courses"}finally{this.loading=!1,this.requestUpdate()}}connectedCallback(){var e;super.connectedCallback(),(e=window.obiWidgetConfig)!=null&&e.apiKey&&(this.apiKey=window.obiWidgetConfig.apiKey),this.apiBaseUrl=Gc,this.apiBaseUrl&&this.apiKey?this.fetchCourses():(this.loading=!1,this.error="API base URL or API key is missing")}render(){return L.html`
332
+ `,UA([z({type:Array})],tn.prototype,"courses",2),UA([z({type:Boolean})],tn.prototype,"loading",2),UA([z({type:String})],tn.prototype,"error",2),UA([z({type:Function})],tn.prototype,"onCourseSelect",2),customElements.get("obi-course")||customElements.define("obi-course",Bt),customElements.get("obi-course-list")||customElements.define("obi-course-list",tn);var By=Object.defineProperty,vy=Object.getOwnPropertyDescriptor,vt=(n,e,A,t)=>{for(var i=t>1?void 0:t?vy(e,A):e,r=n.length-1,s;r>=0;r--)(s=n[r])&&(i=(t?s(e,A,i):s(i))||i);return t&&i&&By(e,A,i),i};class QA extends _.LitElement{constructor(){super(...arguments),this.courses=[],this.loading=!0,this.error="",this.apiKey="",this.apiBaseUrl=""}handleCourseSelect(e){this.onCourseSelect&&this.onCourseSelect(e.detail.id)}handleClose(){this.onClose&&this.onClose()}async fetchCourses(){try{this.loading=!0;const i=(await(await fetch(`${this.apiBaseUrl}/sessions?token=${this.apiKey}`)).json()).map(r=>({id:r.uuid,name:r.onboarding_plan.name,description:r.onboarding_plan.description,imageSrc:r.onboarding_plan.screen_url||"https://corproductionsydney-storagebucket5cb7c8ea-atg4gmftc6sk.s3.amazonaws.com/static/generic-course.png"})).filter(r=>!!r.name);this.courses=[...i],this.requestUpdate()}catch(e){console.error("Fetch error:",e),this.error="Failed to fetch courses"}finally{this.loading=!1,this.requestUpdate()}}connectedCallback(){var e;super.connectedCallback(),(e=window.obiWidgetConfig)!=null&&e.apiKey&&(this.apiKey=window.obiWidgetConfig.apiKey),this.apiBaseUrl=_r,this.apiBaseUrl&&this.apiKey?this.fetchCourses():(this.loading=!1,this.error="API base URL or API key is missing")}render(){return _.html`
312
333
  <div class="backdrop" @click=${this.handleClose}></div>
313
334
  <div class="container">
314
335
  <button class="close-button" @click=${this.handleClose}>×</button>
@@ -324,7 +345,7 @@ a=extmap-allow-mixed`)!==-1){const r=s.sdp.split(`
324
345
  @course-select=${this.handleCourseSelect}
325
346
  ></obi-course-list>
326
347
  </div>
327
- `}}ut.styles=L.css`
348
+ `}}QA.styles=_.css`
328
349
  :host {
329
350
  display: block;
330
351
  font-family: "Syne", sans-serif;
@@ -407,29 +428,29 @@ a=extmap-allow-mixed`)!==-1){const r=s.sdp.split(`
407
428
  font-size: 24px;
408
429
  color: #6b7280;
409
430
  }
410
- `,Ht([ee({type:Array})],ut.prototype,"courses",2),Ht([ee({type:Boolean})],ut.prototype,"loading",2),Ht([ee({type:String})],ut.prototype,"error",2),Ht([ee({type:String})],ut.prototype,"apiKey",2),Ht([ee({type:Function})],ut.prototype,"onCourseSelect",2),Ht([ee({type:Function})],ut.prototype,"onClose",2),Ht([Te()],ut.prototype,"apiBaseUrl",2),customElements.get("obi-course-modal")||customElements.define("obi-course-modal",ut);/**
431
+ `,vt([z({type:Array})],QA.prototype,"courses",2),vt([z({type:Boolean})],QA.prototype,"loading",2),vt([z({type:String})],QA.prototype,"error",2),vt([z({type:String})],QA.prototype,"apiKey",2),vt([z({type:Function})],QA.prototype,"onCourseSelect",2),vt([z({type:Function})],QA.prototype,"onClose",2),vt([Le()],QA.prototype,"apiBaseUrl",2),customElements.get("obi-course-modal")||customElements.define("obi-course-modal",QA);/**
411
432
  * @license
412
433
  * Copyright 2017 Google LLC
413
434
  * SPDX-License-Identifier: BSD-3-Clause
414
- */const sn=globalThis,ss=sn.trustedTypes,cd=ss?ss.createPolicy("lit-html",{createHTML:n=>n}):void 0,dd="$lit$",Mt=`lit$${Math.random().toFixed(9).slice(2)}$`,ld="?"+Mt,Gp=`<${ld}>`,Zt=document,rs=()=>Zt.createComment(""),rn=n=>n===null||typeof n!="object"&&typeof n!="function",qr=Array.isArray,Wp=n=>qr(n)||typeof(n==null?void 0:n[Symbol.iterator])=="function",zr=`[
415
- \f\r]`,an=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,ud=/-->/g,hd=/>/g,Jt=RegExp(`>|${zr}(?:([^\\s"'>=/]+)(${zr}*=${zr}*(?:[^
416
- \f\r"'\`<>=]|("|')|))|$)`,"g"),fd=/'/g,pd=/"/g,md=/^(?:script|style|textarea|title)$/i,on=Symbol.for("lit-noChange"),he=Symbol.for("lit-nothing"),gd=new WeakMap,Yt=Zt.createTreeWalker(Zt,129);function vd(n,e){if(!qr(n)||!n.hasOwnProperty("raw"))throw Error("invalid template strings array");return cd!==void 0?cd.createHTML(e):e}const Kp=(n,e)=>{const t=n.length-1,i=[];let s,r=e===2?"<svg>":e===3?"<math>":"",a=an;for(let o=0;o<t;o++){const c=n[o];let d,l,u=-1,h=0;for(;h<c.length&&(a.lastIndex=h,l=a.exec(c),l!==null);)h=a.lastIndex,a===an?l[1]==="!--"?a=ud:l[1]!==void 0?a=hd:l[2]!==void 0?(md.test(l[2])&&(s=RegExp("</"+l[2],"g")),a=Jt):l[3]!==void 0&&(a=Jt):a===Jt?l[0]===">"?(a=s??an,u=-1):l[1]===void 0?u=-2:(u=a.lastIndex-l[2].length,d=l[1],a=l[3]===void 0?Jt:l[3]==='"'?pd:fd):a===pd||a===fd?a=Jt:a===ud||a===hd?a=an:(a=Jt,s=void 0);const f=a===Jt&&n[o+1].startsWith("/>")?" ":"";r+=a===an?c+Gp:u>=0?(i.push(d),c.slice(0,u)+dd+c.slice(u)+Mt+f):c+Mt+(u===-2?o:f)}return[vd(n,r+(n[t]||"<?>")+(e===2?"</svg>":e===3?"</math>":"")),i]};class cn{constructor({strings:e,_$litType$:t},i){let s;this.parts=[];let r=0,a=0;const o=e.length-1,c=this.parts,[d,l]=Kp(e,t);if(this.el=cn.createElement(d,i),Yt.currentNode=this.el.content,t===2||t===3){const u=this.el.content.firstChild;u.replaceWith(...u.childNodes)}for(;(s=Yt.nextNode())!==null&&c.length<o;){if(s.nodeType===1){if(s.hasAttributes())for(const u of s.getAttributeNames())if(u.endsWith(dd)){const h=l[a++],f=s.getAttribute(u).split(Mt),g=/([.?@])?(.*)/.exec(h);c.push({type:1,index:r,name:g[2],strings:f,ctor:g[1]==="."?Zp:g[1]==="?"?Jp:g[1]==="@"?Yp:os}),s.removeAttribute(u)}else u.startsWith(Mt)&&(c.push({type:6,index:r}),s.removeAttribute(u));if(md.test(s.tagName)){const u=s.textContent.split(Mt),h=u.length-1;if(h>0){s.textContent=ss?ss.emptyScript:"";for(let f=0;f<h;f++)s.append(u[f],rs()),Yt.nextNode(),c.push({type:2,index:++r});s.append(u[h],rs())}}}else if(s.nodeType===8)if(s.data===ld)c.push({type:2,index:r});else{let u=-1;for(;(u=s.data.indexOf(Mt,u+1))!==-1;)c.push({type:7,index:r}),u+=Mt.length-1}r++}}static createElement(e,t){const i=Zt.createElement("template");return i.innerHTML=e,i}}function Si(n,e,t=n,i){var a,o;if(e===on)return e;let s=i!==void 0?(a=t._$Co)==null?void 0:a[i]:t._$Cl;const r=rn(e)?void 0:e._$litDirective$;return(s==null?void 0:s.constructor)!==r&&((o=s==null?void 0:s._$AO)==null||o.call(s,!1),r===void 0?s=void 0:(s=new r(n),s._$AT(n,t,i)),i!==void 0?(t._$Co??(t._$Co=[]))[i]=s:t._$Cl=s),s!==void 0&&(e=Si(n,s._$AS(n,e.values),s,i)),e}class Hp{constructor(e,t){this._$AV=[],this._$AN=void 0,this._$AD=e,this._$AM=t}get parentNode(){return this._$AM.parentNode}get _$AU(){return this._$AM._$AU}u(e){const{el:{content:t},parts:i}=this._$AD,s=((e==null?void 0:e.creationScope)??Zt).importNode(t,!0);Yt.currentNode=s;let r=Yt.nextNode(),a=0,o=0,c=i[0];for(;c!==void 0;){if(a===c.index){let d;c.type===2?d=new as(r,r.nextSibling,this,e):c.type===1?d=new c.ctor(r,c.name,c.strings,this,e):c.type===6&&(d=new Qp(r,this,e)),this._$AV.push(d),c=i[++o]}a!==(c==null?void 0:c.index)&&(r=Yt.nextNode(),a++)}return Yt.currentNode=Zt,s}p(e){let t=0;for(const i of this._$AV)i!==void 0&&(i.strings!==void 0?(i._$AI(e,i,t),t+=i.strings.length-2):i._$AI(e[t])),t++}}class as{get _$AU(){var e;return((e=this._$AM)==null?void 0:e._$AU)??this._$Cv}constructor(e,t,i,s){this.type=2,this._$AH=he,this._$AN=void 0,this._$AA=e,this._$AB=t,this._$AM=i,this.options=s,this._$Cv=(s==null?void 0:s.isConnected)??!0}get parentNode(){let e=this._$AA.parentNode;const t=this._$AM;return t!==void 0&&(e==null?void 0:e.nodeType)===11&&(e=t.parentNode),e}get startNode(){return this._$AA}get endNode(){return this._$AB}_$AI(e,t=this){e=Si(this,e,t),rn(e)?e===he||e==null||e===""?(this._$AH!==he&&this._$AR(),this._$AH=he):e!==this._$AH&&e!==on&&this._(e):e._$litType$!==void 0?this.$(e):e.nodeType!==void 0?this.T(e):Wp(e)?this.k(e):this._(e)}O(e){return this._$AA.parentNode.insertBefore(e,this._$AB)}T(e){this._$AH!==e&&(this._$AR(),this._$AH=this.O(e))}_(e){this._$AH!==he&&rn(this._$AH)?this._$AA.nextSibling.data=e:this.T(Zt.createTextNode(e)),this._$AH=e}$(e){var r;const{values:t,_$litType$:i}=e,s=typeof i=="number"?this._$AC(e):(i.el===void 0&&(i.el=cn.createElement(vd(i.h,i.h[0]),this.options)),i);if(((r=this._$AH)==null?void 0:r._$AD)===s)this._$AH.p(t);else{const a=new Hp(s,this),o=a.u(this.options);a.p(t),this.T(o),this._$AH=a}}_$AC(e){let t=gd.get(e.strings);return t===void 0&&gd.set(e.strings,t=new cn(e)),t}k(e){qr(this._$AH)||(this._$AH=[],this._$AR());const t=this._$AH;let i,s=0;for(const r of e)s===t.length?t.push(i=new as(this.O(rs()),this.O(rs()),this,this.options)):i=t[s],i._$AI(r),s++;s<t.length&&(this._$AR(i&&i._$AB.nextSibling,s),t.length=s)}_$AR(e=this._$AA.nextSibling,t){var i;for((i=this._$AP)==null?void 0:i.call(this,!1,!0,t);e&&e!==this._$AB;){const s=e.nextSibling;e.remove(),e=s}}setConnected(e){var t;this._$AM===void 0&&(this._$Cv=e,(t=this._$AP)==null||t.call(this,e))}}class os{get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}constructor(e,t,i,s,r){this.type=1,this._$AH=he,this._$AN=void 0,this.element=e,this.name=t,this._$AM=s,this.options=r,i.length>2||i[0]!==""||i[1]!==""?(this._$AH=Array(i.length-1).fill(new String),this.strings=i):this._$AH=he}_$AI(e,t=this,i,s){const r=this.strings;let a=!1;if(r===void 0)e=Si(this,e,t,0),a=!rn(e)||e!==this._$AH&&e!==on,a&&(this._$AH=e);else{const o=e;let c,d;for(e=r[0],c=0;c<r.length-1;c++)d=Si(this,o[i+c],t,c),d===on&&(d=this._$AH[c]),a||(a=!rn(d)||d!==this._$AH[c]),d===he?e=he:e!==he&&(e+=(d??"")+r[c+1]),this._$AH[c]=d}a&&!s&&this.j(e)}j(e){e===he?this.element.removeAttribute(this.name):this.element.setAttribute(this.name,e??"")}}class Zp extends os{constructor(){super(...arguments),this.type=3}j(e){this.element[this.name]=e===he?void 0:e}}class Jp extends os{constructor(){super(...arguments),this.type=4}j(e){this.element.toggleAttribute(this.name,!!e&&e!==he)}}class Yp extends os{constructor(e,t,i,s,r){super(e,t,i,s,r),this.type=5}_$AI(e,t=this){if((e=Si(this,e,t,0)??he)===on)return;const i=this._$AH,s=e===he&&i!==he||e.capture!==i.capture||e.once!==i.once||e.passive!==i.passive,r=e!==he&&(i===he||s);s&&this.element.removeEventListener(this.name,this,i),r&&this.element.addEventListener(this.name,this,e),this._$AH=e}handleEvent(e){var t;typeof this._$AH=="function"?this._$AH.call(((t=this.options)==null?void 0:t.host)??this.element,e):this._$AH.handleEvent(e)}}class Qp{constructor(e,t,i){this.element=e,this.type=6,this._$AN=void 0,this._$AM=t,this.options=i}get _$AU(){return this._$AM._$AU}_$AI(e){Si(this,e)}}const Gr=sn.litHtmlPolyfillSupport;Gr==null||Gr(cn,as),(sn.litHtmlVersions??(sn.litHtmlVersions=[])).push("3.3.0");/**
435
+ */const Gn=globalThis,Ir=Gn.trustedTypes,uh=Ir?Ir.createPolicy("lit-html",{createHTML:n=>n}):void 0,dh="$lit$",At=`lit$${Math.random().toFixed(9).slice(2)}$`,hh="?"+At,Cy=`<${hh}>`,Ct=document,Rr=()=>Ct.createComment(""),jn=n=>n===null||typeof n!="object"&&typeof n!="function",oa=Array.isArray,wy=n=>oa(n)||typeof(n==null?void 0:n[Symbol.iterator])=="function",aa=`[
436
+ \f\r]`,Jn=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,fh=/-->/g,gh=/>/g,wt=RegExp(`>|${aa}(?:([^\\s"'>=/]+)(${aa}*=${aa}*(?:[^
437
+ \f\r"'\`<>=]|("|')|))|$)`,"g"),ph=/'/g,mh=/"/g,Bh=/^(?:script|style|textarea|title)$/i,Wn=Symbol.for("lit-noChange"),fe=Symbol.for("lit-nothing"),vh=new WeakMap,yt=Ct.createTreeWalker(Ct,129);function Ch(n,e){if(!oa(n)||!n.hasOwnProperty("raw"))throw Error("invalid template strings array");return uh!==void 0?uh.createHTML(e):e}const yy=(n,e)=>{const A=n.length-1,t=[];let i,r=e===2?"<svg>":e===3?"<math>":"",s=Jn;for(let o=0;o<A;o++){const a=n[o];let c,l,u=-1,d=0;for(;d<a.length&&(s.lastIndex=d,l=s.exec(a),l!==null);)d=s.lastIndex,s===Jn?l[1]==="!--"?s=fh:l[1]!==void 0?s=gh:l[2]!==void 0?(Bh.test(l[2])&&(i=RegExp("</"+l[2],"g")),s=wt):l[3]!==void 0&&(s=wt):s===wt?l[0]===">"?(s=i??Jn,u=-1):l[1]===void 0?u=-2:(u=s.lastIndex-l[2].length,c=l[1],s=l[3]===void 0?wt:l[3]==='"'?mh:ph):s===mh||s===ph?s=wt:s===fh||s===gh?s=Jn:(s=wt,i=void 0);const h=s===wt&&n[o+1].startsWith("/>")?" ":"";r+=s===Jn?a+Cy:u>=0?(t.push(c),a.slice(0,u)+dh+a.slice(u)+At+h):a+At+(u===-2?o:h)}return[Ch(n,r+(n[A]||"<?>")+(e===2?"</svg>":e===3?"</math>":"")),t]};class Xn{constructor({strings:e,_$litType$:A},t){let i;this.parts=[];let r=0,s=0;const o=e.length-1,a=this.parts,[c,l]=yy(e,A);if(this.el=Xn.createElement(c,t),yt.currentNode=this.el.content,A===2||A===3){const u=this.el.content.firstChild;u.replaceWith(...u.childNodes)}for(;(i=yt.nextNode())!==null&&a.length<o;){if(i.nodeType===1){if(i.hasAttributes())for(const u of i.getAttributeNames())if(u.endsWith(dh)){const d=l[s++],h=i.getAttribute(u).split(At),f=/([.?@])?(.*)/.exec(d);a.push({type:1,index:r,name:f[2],strings:h,ctor:f[1]==="."?Uy:f[1]==="?"?Qy:f[1]==="@"?Ey:Pr}),i.removeAttribute(u)}else u.startsWith(At)&&(a.push({type:6,index:r}),i.removeAttribute(u));if(Bh.test(i.tagName)){const u=i.textContent.split(At),d=u.length-1;if(d>0){i.textContent=Ir?Ir.emptyScript:"";for(let h=0;h<d;h++)i.append(u[h],Rr()),yt.nextNode(),a.push({type:2,index:++r});i.append(u[d],Rr())}}}else if(i.nodeType===8)if(i.data===hh)a.push({type:2,index:r});else{let u=-1;for(;(u=i.data.indexOf(At,u+1))!==-1;)a.push({type:7,index:r}),u+=At.length-1}r++}}static createElement(e,A){const t=Ct.createElement("template");return t.innerHTML=e,t}}function nn(n,e,A=n,t){var s,o;if(e===Wn)return e;let i=t!==void 0?(s=A._$Co)==null?void 0:s[t]:A._$Cl;const r=jn(e)?void 0:e._$litDirective$;return(i==null?void 0:i.constructor)!==r&&((o=i==null?void 0:i._$AO)==null||o.call(i,!1),r===void 0?i=void 0:(i=new r(n),i._$AT(n,A,t)),t!==void 0?(A._$Co??(A._$Co=[]))[t]=i:A._$Cl=i),i!==void 0&&(e=nn(n,i._$AS(n,e.values),i,t)),e}class by{constructor(e,A){this._$AV=[],this._$AN=void 0,this._$AD=e,this._$AM=A}get parentNode(){return this._$AM.parentNode}get _$AU(){return this._$AM._$AU}u(e){const{el:{content:A},parts:t}=this._$AD,i=((e==null?void 0:e.creationScope)??Ct).importNode(A,!0);yt.currentNode=i;let r=yt.nextNode(),s=0,o=0,a=t[0];for(;a!==void 0;){if(s===a.index){let c;a.type===2?c=new xr(r,r.nextSibling,this,e):a.type===1?c=new a.ctor(r,a.name,a.strings,this,e):a.type===6&&(c=new Sy(r,this,e)),this._$AV.push(c),a=t[++o]}s!==(a==null?void 0:a.index)&&(r=yt.nextNode(),s++)}return yt.currentNode=Ct,i}p(e){let A=0;for(const t of this._$AV)t!==void 0&&(t.strings!==void 0?(t._$AI(e,t,A),A+=t.strings.length-2):t._$AI(e[A])),A++}}class xr{get _$AU(){var e;return((e=this._$AM)==null?void 0:e._$AU)??this._$Cv}constructor(e,A,t,i){this.type=2,this._$AH=fe,this._$AN=void 0,this._$AA=e,this._$AB=A,this._$AM=t,this.options=i,this._$Cv=(i==null?void 0:i.isConnected)??!0}get parentNode(){let e=this._$AA.parentNode;const A=this._$AM;return A!==void 0&&(e==null?void 0:e.nodeType)===11&&(e=A.parentNode),e}get startNode(){return this._$AA}get endNode(){return this._$AB}_$AI(e,A=this){e=nn(this,e,A),jn(e)?e===fe||e==null||e===""?(this._$AH!==fe&&this._$AR(),this._$AH=fe):e!==this._$AH&&e!==Wn&&this._(e):e._$litType$!==void 0?this.$(e):e.nodeType!==void 0?this.T(e):wy(e)?this.k(e):this._(e)}O(e){return this._$AA.parentNode.insertBefore(e,this._$AB)}T(e){this._$AH!==e&&(this._$AR(),this._$AH=this.O(e))}_(e){this._$AH!==fe&&jn(this._$AH)?this._$AA.nextSibling.data=e:this.T(Ct.createTextNode(e)),this._$AH=e}$(e){var r;const{values:A,_$litType$:t}=e,i=typeof t=="number"?this._$AC(e):(t.el===void 0&&(t.el=Xn.createElement(Ch(t.h,t.h[0]),this.options)),t);if(((r=this._$AH)==null?void 0:r._$AD)===i)this._$AH.p(A);else{const s=new by(i,this),o=s.u(this.options);s.p(A),this.T(o),this._$AH=s}}_$AC(e){let A=vh.get(e.strings);return A===void 0&&vh.set(e.strings,A=new Xn(e)),A}k(e){oa(this._$AH)||(this._$AH=[],this._$AR());const A=this._$AH;let t,i=0;for(const r of e)i===A.length?A.push(t=new xr(this.O(Rr()),this.O(Rr()),this,this.options)):t=A[i],t._$AI(r),i++;i<A.length&&(this._$AR(t&&t._$AB.nextSibling,i),A.length=i)}_$AR(e=this._$AA.nextSibling,A){var t;for((t=this._$AP)==null?void 0:t.call(this,!1,!0,A);e&&e!==this._$AB;){const i=e.nextSibling;e.remove(),e=i}}setConnected(e){var A;this._$AM===void 0&&(this._$Cv=e,(A=this._$AP)==null||A.call(this,e))}}class Pr{get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}constructor(e,A,t,i,r){this.type=1,this._$AH=fe,this._$AN=void 0,this.element=e,this.name=A,this._$AM=i,this.options=r,t.length>2||t[0]!==""||t[1]!==""?(this._$AH=Array(t.length-1).fill(new String),this.strings=t):this._$AH=fe}_$AI(e,A=this,t,i){const r=this.strings;let s=!1;if(r===void 0)e=nn(this,e,A,0),s=!jn(e)||e!==this._$AH&&e!==Wn,s&&(this._$AH=e);else{const o=e;let a,c;for(e=r[0],a=0;a<r.length-1;a++)c=nn(this,o[t+a],A,a),c===Wn&&(c=this._$AH[a]),s||(s=!jn(c)||c!==this._$AH[a]),c===fe?e=fe:e!==fe&&(e+=(c??"")+r[a+1]),this._$AH[a]=c}s&&!i&&this.j(e)}j(e){e===fe?this.element.removeAttribute(this.name):this.element.setAttribute(this.name,e??"")}}class Uy extends Pr{constructor(){super(...arguments),this.type=3}j(e){this.element[this.name]=e===fe?void 0:e}}class Qy extends Pr{constructor(){super(...arguments),this.type=4}j(e){this.element.toggleAttribute(this.name,!!e&&e!==fe)}}class Ey extends Pr{constructor(e,A,t,i,r){super(e,A,t,i,r),this.type=5}_$AI(e,A=this){if((e=nn(this,e,A,0)??fe)===Wn)return;const t=this._$AH,i=e===fe&&t!==fe||e.capture!==t.capture||e.once!==t.once||e.passive!==t.passive,r=e!==fe&&(t===fe||i);i&&this.element.removeEventListener(this.name,this,t),r&&this.element.addEventListener(this.name,this,e),this._$AH=e}handleEvent(e){var A;typeof this._$AH=="function"?this._$AH.call(((A=this.options)==null?void 0:A.host)??this.element,e):this._$AH.handleEvent(e)}}class Sy{constructor(e,A,t){this.element=e,this.type=6,this._$AN=void 0,this._$AM=A,this.options=t}get _$AU(){return this._$AM._$AU}_$AI(e){nn(this,e)}}const ca=Gn.litHtmlPolyfillSupport;ca==null||ca(Xn,xr),(Gn.litHtmlVersions??(Gn.litHtmlVersions=[])).push("3.3.0");/**
417
438
  * @license
418
439
  * Copyright 2020 Google LLC
419
440
  * SPDX-License-Identifier: BSD-3-Clause
420
- */const Xp=n=>n.strings===void 0;/**
441
+ */const Ty=n=>n.strings===void 0;/**
421
442
  * @license
422
443
  * Copyright 2017 Google LLC
423
444
  * SPDX-License-Identifier: BSD-3-Clause
424
- */const em={ATTRIBUTE:1,CHILD:2,PROPERTY:3,BOOLEAN_ATTRIBUTE:4,EVENT:5,ELEMENT:6},tm=n=>(...e)=>({_$litDirective$:n,values:e});class im{constructor(e){}get _$AU(){return this._$AM._$AU}_$AT(e,t,i){this._$Ct=e,this._$AM=t,this._$Ci=i}_$AS(e,t){return this.update(e,t)}update(e,t){return this.render(...t)}}/**
445
+ */const Fy={ATTRIBUTE:1,CHILD:2,PROPERTY:3,BOOLEAN_ATTRIBUTE:4,EVENT:5,ELEMENT:6},ky=n=>(...e)=>({_$litDirective$:n,values:e});class Iy{constructor(e){}get _$AU(){return this._$AM._$AU}_$AT(e,A,t){this._$Ct=e,this._$AM=A,this._$Ci=t}_$AS(e,A){return this.update(e,A)}update(e,A){return this.render(...A)}}/**
425
446
  * @license
426
447
  * Copyright 2017 Google LLC
427
448
  * SPDX-License-Identifier: BSD-3-Clause
428
- */const dn=(n,e)=>{var i;const t=n._$AN;if(t===void 0)return!1;for(const s of t)(i=s._$AO)==null||i.call(s,e,!1),dn(s,e);return!0},cs=n=>{let e,t;do{if((e=n._$AM)===void 0)break;t=e._$AN,t.delete(n),n=e}while((t==null?void 0:t.size)===0)},yd=n=>{for(let e;e=n._$AM;n=e){let t=e._$AN;if(t===void 0)e._$AN=t=new Set;else if(t.has(n))break;t.add(n),rm(e)}};function nm(n){this._$AN!==void 0?(cs(this),this._$AM=n,yd(this)):this._$AM=n}function sm(n,e=!1,t=0){const i=this._$AH,s=this._$AN;if(s!==void 0&&s.size!==0)if(e)if(Array.isArray(i))for(let r=t;r<i.length;r++)dn(i[r],!1),cs(i[r]);else i!=null&&(dn(i,!1),cs(i));else dn(this,n)}const rm=n=>{n.type==em.CHILD&&(n._$AP??(n._$AP=sm),n._$AQ??(n._$AQ=nm))};class am extends im{constructor(){super(...arguments),this._$AN=void 0}_$AT(e,t,i){super._$AT(e,t,i),yd(this),this.isConnected=e._$AU}_$AO(e,t=!0){var i,s;e!==this.isConnected&&(this.isConnected=e,e?(i=this.reconnected)==null||i.call(this):(s=this.disconnected)==null||s.call(this)),t&&(dn(this,e),cs(this))}setValue(e){if(Xp(this._$Ct))this._$Ct._$AI(e,this);else{const t=[...this._$Ct._$AH];t[this._$Ci]=e,this._$Ct._$AI(t,this,0)}}disconnected(){}reconnected(){}}/**
449
+ */const $n=(n,e)=>{var t;const A=n._$AN;if(A===void 0)return!1;for(const i of A)(t=i._$AO)==null||t.call(i,e,!1),$n(i,e);return!0},Lr=n=>{let e,A;do{if((e=n._$AM)===void 0)break;A=e._$AN,A.delete(n),n=e}while((A==null?void 0:A.size)===0)},wh=n=>{for(let e;e=n._$AM;n=e){let A=e._$AN;if(A===void 0)e._$AN=A=new Set;else if(A.has(n))break;A.add(n),Py(e)}};function Ry(n){this._$AN!==void 0?(Lr(this),this._$AM=n,wh(this)):this._$AM=n}function xy(n,e=!1,A=0){const t=this._$AH,i=this._$AN;if(i!==void 0&&i.size!==0)if(e)if(Array.isArray(t))for(let r=A;r<t.length;r++)$n(t[r],!1),Lr(t[r]);else t!=null&&($n(t,!1),Lr(t));else $n(this,n)}const Py=n=>{n.type==Fy.CHILD&&(n._$AP??(n._$AP=xy),n._$AQ??(n._$AQ=Ry))};class Ly extends Iy{constructor(){super(...arguments),this._$AN=void 0}_$AT(e,A,t){super._$AT(e,A,t),wh(this),this.isConnected=e._$AU}_$AO(e,A=!0){var t,i;e!==this.isConnected&&(this.isConnected=e,e?(t=this.reconnected)==null||t.call(this):(i=this.disconnected)==null||i.call(this)),A&&($n(this,e),Lr(this))}setValue(e){if(Ty(this._$Ct))this._$Ct._$AI(e,this);else{const A=[...this._$Ct._$AH];A[this._$Ci]=e,this._$Ct._$AI(A,this,0)}}disconnected(){}reconnected(){}}/**
429
450
  * @license
430
451
  * Copyright 2020 Google LLC
431
452
  * SPDX-License-Identifier: BSD-3-Clause
432
- */const om=()=>new cm;class cm{}const Wr=new WeakMap,dm=tm(class extends am{render(n){return he}update(n,[e]){var i;const t=e!==this.G;return t&&this.G!==void 0&&this.rt(void 0),(t||this.lt!==this.ct)&&(this.G=e,this.ht=(i=n.options)==null?void 0:i.host,this.rt(this.ct=n.element)),he}rt(n){if(this.isConnected||(n=void 0),typeof this.G=="function"){const e=this.ht??globalThis;let t=Wr.get(e);t===void 0&&(t=new WeakMap,Wr.set(e,t)),t.get(this.G)!==void 0&&this.G.call(this.ht,void 0),t.set(this.G,n),n!==void 0&&this.G.call(this.ht,n)}else this.G.value=n}get lt(){var n,e;return typeof this.G=="function"?(n=Wr.get(this.ht??globalThis))==null?void 0:n.get(this.G):(e=this.G)==null?void 0:e.value}disconnected(){this.lt===this.ct&&this.rt(void 0)}reconnected(){this.rt(this.ct)}});var lm=Object.defineProperty,um=Object.getOwnPropertyDescriptor,bd=(n,e,t,i)=>{for(var s=i>1?void 0:i?um(e,t):e,r=n.length-1,a;r>=0;r--)(a=n[r])&&(s=(i?a(e,t,s):a(s))||s);return i&&s&&lm(e,t,s),s};class ds extends L.LitElement{constructor(){super(...arguments),this.volume={speaker:"ASSISTANT",volume:0,spectrum:[]},this.canvasRef=om(),this.barCount=8,this.animationFrame=null}connectedCallback(){super.connectedCallback(),this.startAnimation()}disconnectedCallback(){super.disconnectedCallback(),this.stopAnimation()}startAnimation(){const e=()=>{this.drawEqualizer(),this.animationFrame=requestAnimationFrame(e)};this.animationFrame=requestAnimationFrame(e)}stopAnimation(){this.animationFrame&&(cancelAnimationFrame(this.animationFrame),this.animationFrame=null)}drawEqualizer(){const e=this.canvasRef.value;if(!e)return;const t=e.getContext("2d");if(!t)return;const i=window.devicePixelRatio||1,s=e.clientWidth,r=e.clientHeight;e.width=s*i,e.height=r*i,t.scale(i,i),t.clearRect(0,0,s,r);const a=3,o=Math.max(1,(s-(this.barCount-1)*a)/this.barCount),c=r/2,d=this.volume.speaker==="USER"?this.volume.volume:this.volume.volume,l=this.volume.speaker==="USER"?this.volume.spectrum:this.volume.spectrum;if(d===0)return;let u=[];if(l&&l.length>0){const h=l.length,f=Math.ceil(h/10);let g=[];for(let y=0;y<10;y++){const b=y*f,E=Math.min((y+1)*f,h);let M=0;for(let U=b;U<E;U++)M+=l[U]||0;g.push({region:y,startIdx:b,endIdx:E,energy:M})}g.sort((y,b)=>b.energy-y.energy);const m=g.slice(0,3),v=Math.min(...m.map(y=>y.startIdx)),T=Math.max(...m.map(y=>y.endIdx));if(T>v)for(let y=0;y<this.barCount;y++){const b=v+y/(this.barCount-1)*(T-v),E=Math.min(h-1,Math.floor(b));u[y]=l[E]||0}else for(let y=0;y<this.barCount;y++){const b=y/(this.barCount-1)*(h/2),E=Math.min(h-1,Math.floor(b));u[y]=l[E]||0}const x=Math.max(...u,1),P=this.volume.speaker==="USER"?.7:.6;u=u.map((y,b)=>{const E=y/x,M=P+b/(this.barCount-1)*.3;return Math.min(1,E*M)})}else if(this.volume.speaker!=="USER")for(let h=0;h<this.barCount;h++){const f=Date.now()*.002,g=.3+.2*Math.sin(f+h*.7);u[h]=g}for(let h=0;h<this.barCount;h++){const f=u.length>0&&u[h]!==void 0?u[h]:d;this.volume.speaker==="USER"?t.fillStyle=`rgba(109, 40, 217, ${f*.5+.5})`:t.fillStyle=`rgba(255, 255, 255, ${f*.5+.5})`;const g=Math.max(2,f*.8*c),m=s-(this.barCount-h)*(o+a),v=o/2;t.beginPath(),t.moveTo(m+v,r/2-g),t.lineTo(m+o-v,r/2-g),t.quadraticCurveTo(m+o,r/2-g,m+o,r/2-g+v),t.lineTo(m+o,r/2),t.lineTo(m,r/2),t.lineTo(m,r/2-g+v),t.quadraticCurveTo(m,r/2-g,m+v,r/2-g),t.fill(),t.beginPath(),t.moveTo(m,r/2),t.lineTo(m+o,r/2),t.lineTo(m+o,r/2+g-v),t.quadraticCurveTo(m+o,r/2+g,m+o-v,r/2+g),t.lineTo(m+v,r/2+g),t.quadraticCurveTo(m,r/2+g,m,r/2+g-v),t.lineTo(m,r/2),t.fill()}}render(){return L.html` <canvas ${dm(this.canvasRef)} width="52" height="52"></canvas> `}}ds.styles=L.css`
453
+ */const Dy=()=>new _y;class _y{}const la=new WeakMap,Hy=ky(class extends Ly{render(n){return fe}update(n,[e]){var t;const A=e!==this.G;return A&&this.G!==void 0&&this.rt(void 0),(A||this.lt!==this.ct)&&(this.G=e,this.ht=(t=n.options)==null?void 0:t.host,this.rt(this.ct=n.element)),fe}rt(n){if(this.isConnected||(n=void 0),typeof this.G=="function"){const e=this.ht??globalThis;let A=la.get(e);A===void 0&&(A=new WeakMap,la.set(e,A)),A.get(this.G)!==void 0&&this.G.call(this.ht,void 0),A.set(this.G,n),n!==void 0&&this.G.call(this.ht,n)}else this.G.value=n}get lt(){var n,e;return typeof this.G=="function"?(n=la.get(this.ht??globalThis))==null?void 0:n.get(this.G):(e=this.G)==null?void 0:e.value}disconnected(){this.lt===this.ct&&this.rt(void 0)}reconnected(){this.rt(this.ct)}});var Oy=Object.defineProperty,My=Object.getOwnPropertyDescriptor,yh=(n,e,A,t)=>{for(var i=t>1?void 0:t?My(e,A):e,r=n.length-1,s;r>=0;r--)(s=n[r])&&(i=(t?s(e,A,i):s(i))||i);return t&&i&&Oy(e,A,i),i};class Dr extends _.LitElement{constructor(){super(...arguments),this.volume={speaker:"ASSISTANT",volume:0,spectrum:[]},this.canvasRef=Dy(),this.barCount=8,this.animationFrame=null}connectedCallback(){super.connectedCallback(),this.startAnimation()}disconnectedCallback(){super.disconnectedCallback(),this.stopAnimation()}startAnimation(){const e=()=>{this.drawEqualizer(),this.animationFrame=requestAnimationFrame(e)};this.animationFrame=requestAnimationFrame(e)}stopAnimation(){this.animationFrame&&(cancelAnimationFrame(this.animationFrame),this.animationFrame=null)}drawEqualizer(){const e=this.canvasRef.value;if(!e)return;const A=e.getContext("2d");if(!A)return;const t=window.devicePixelRatio||1,i=e.clientWidth,r=e.clientHeight;e.width=i*t,e.height=r*t,A.scale(t,t),A.clearRect(0,0,i,r);const s=3,o=Math.max(1,(i-(this.barCount-1)*s)/this.barCount),a=r/2,c=this.volume.speaker==="USER"?this.volume.volume:this.volume.volume,l=this.volume.speaker==="USER"?this.volume.spectrum:this.volume.spectrum;if(c===0)return;let u=[];if(l&&l.length>0){const d=l.length,h=Math.ceil(d/10);let f=[];for(let v=0;v<10;v++){const B=v*h,w=Math.min((v+1)*h,d);let S=0;for(let F=B;F<w;F++)S+=l[F]||0;f.push({region:v,startIdx:B,endIdx:w,energy:S})}f.sort((v,B)=>B.energy-v.energy);const g=f.slice(0,3),m=Math.min(...g.map(v=>v.startIdx)),C=Math.max(...g.map(v=>v.endIdx));if(C>m)for(let v=0;v<this.barCount;v++){const B=m+v/(this.barCount-1)*(C-m),w=Math.min(d-1,Math.floor(B));u[v]=l[w]||0}else for(let v=0;v<this.barCount;v++){const B=v/(this.barCount-1)*(d/2),w=Math.min(d-1,Math.floor(B));u[v]=l[w]||0}const y=Math.max(...u,1),U=this.volume.speaker==="USER"?.7:.6;u=u.map((v,B)=>{const w=v/y,S=U+B/(this.barCount-1)*.3;return Math.min(1,w*S)})}else if(this.volume.speaker!=="USER")for(let d=0;d<this.barCount;d++){const h=Date.now()*.002,f=.3+.2*Math.sin(h+d*.7);u[d]=f}for(let d=0;d<this.barCount;d++){const h=u.length>0&&u[d]!==void 0?u[d]:c;this.volume.speaker==="USER"?A.fillStyle=`rgba(109, 40, 217, ${h*.5+.5})`:A.fillStyle=`rgba(255, 255, 255, ${h*.5+.5})`;const f=Math.max(2,h*.8*a),g=i-(this.barCount-d)*(o+s),m=o/2;A.beginPath(),A.moveTo(g+m,r/2-f),A.lineTo(g+o-m,r/2-f),A.quadraticCurveTo(g+o,r/2-f,g+o,r/2-f+m),A.lineTo(g+o,r/2),A.lineTo(g,r/2),A.lineTo(g,r/2-f+m),A.quadraticCurveTo(g,r/2-f,g+m,r/2-f),A.fill(),A.beginPath(),A.moveTo(g,r/2),A.lineTo(g+o,r/2),A.lineTo(g+o,r/2+f-m),A.quadraticCurveTo(g+o,r/2+f,g+o-m,r/2+f),A.lineTo(g+m,r/2+f),A.quadraticCurveTo(g,r/2+f,g,r/2+f-m),A.lineTo(g,r/2),A.fill()}}render(){return _.html` <canvas ${Hy(this.canvasRef)} width="52" height="52"></canvas> `}}Dr.styles=_.css`
433
454
  :host {
434
455
  display: block;
435
456
  width: 40px;
@@ -441,16 +462,16 @@ a=extmap-allow-mixed`)!==-1){const r=s.sdp.split(`
441
462
  width: 100%;
442
463
  height: 100%;
443
464
  }
444
- `,bd([ee({type:Object})],ds.prototype,"volume",2),bd([Te()],ds.prototype,"canvasRef",2),customElements.get("obi-audio-equalizer")||customElements.define("obi-audio-equalizer",ds);var hm=Object.defineProperty,fm=Object.getOwnPropertyDescriptor,pm=(n,e,t,i)=>{for(var s=i>1?void 0:i?fm(e,t):e,r=n.length-1,a;r>=0;r--)(a=n[r])&&(s=(i?a(e,t,s):a(s))||s);return i&&s&&hm(e,t,s),s};class Kr extends L.LitElement{constructor(){super(...arguments),this.activeDots=Array(5).fill(!1),this.numDots=5,this.containerWidth=32,this.dotSize=2,this.bounceHeight=12,this.animationDuration=200,this.pauseDuration=300,this.overlapFactor=.7,this.color="#FFF",this.timeoutIds=[]}connectedCallback(){super.connectedCallback(),this.startAnimation(),this.style.setProperty("--dot-loader-width",`${this.containerWidth}px`),this.style.setProperty("--dot-size",`${this.dotSize}px`),this.style.setProperty("--dot-color",this.color)}disconnectedCallback(){super.disconnectedCallback(),this.stopAnimation()}startAnimation(){this.animateSequence()}stopAnimation(){this.timeoutIds.forEach(e=>window.clearTimeout(e)),this.timeoutIds=[]}animateSequence(){this.activeDots=Array(this.numDots).fill(!1);for(let t=0;t<this.numDots;t++){const i=t*(this.animationDuration*this.overlapFactor),s=window.setTimeout(()=>{this.activeDots=[...this.activeDots],this.activeDots[t]=!0;const r=window.setTimeout(()=>{this.activeDots=[...this.activeDots],this.activeDots[t]=!1},this.animationDuration);this.timeoutIds.push(r)},i);this.timeoutIds.push(s)}const e=window.setTimeout(()=>{this.animateSequence()},this.numDots*this.animationDuration*this.overlapFactor+this.pauseDuration);this.timeoutIds.push(e)}render(){return L.html`
465
+ `,yh([z({type:Object})],Dr.prototype,"volume",2),yh([Le()],Dr.prototype,"canvasRef",2),customElements.get("obi-audio-equalizer")||customElements.define("obi-audio-equalizer",Dr);var Ny=Object.defineProperty,Ky=Object.getOwnPropertyDescriptor,Vy=(n,e,A,t)=>{for(var i=t>1?void 0:t?Ky(e,A):e,r=n.length-1,s;r>=0;r--)(s=n[r])&&(i=(t?s(e,A,i):s(i))||i);return t&&i&&Ny(e,A,i),i};class ua extends _.LitElement{constructor(){super(...arguments),this.activeDots=Array(5).fill(!1),this.numDots=5,this.containerWidth=32,this.dotSize=2,this.bounceHeight=12,this.animationDuration=200,this.pauseDuration=300,this.overlapFactor=.7,this.color="#FFF",this.timeoutIds=[]}connectedCallback(){super.connectedCallback(),this.startAnimation(),this.style.setProperty("--dot-loader-width",`${this.containerWidth}px`),this.style.setProperty("--dot-size",`${this.dotSize}px`),this.style.setProperty("--dot-color",this.color)}disconnectedCallback(){super.disconnectedCallback(),this.stopAnimation()}startAnimation(){this.animateSequence()}stopAnimation(){this.timeoutIds.forEach(e=>window.clearTimeout(e)),this.timeoutIds=[]}animateSequence(){this.activeDots=Array(this.numDots).fill(!1);for(let A=0;A<this.numDots;A++){const t=A*(this.animationDuration*this.overlapFactor),i=window.setTimeout(()=>{this.activeDots=[...this.activeDots],this.activeDots[A]=!0;const r=window.setTimeout(()=>{this.activeDots=[...this.activeDots],this.activeDots[A]=!1},this.animationDuration);this.timeoutIds.push(r)},t);this.timeoutIds.push(i)}const e=window.setTimeout(()=>{this.animateSequence()},this.numDots*this.animationDuration*this.overlapFactor+this.pauseDuration);this.timeoutIds.push(e)}render(){return _.html`
445
466
  <div class="dot-loader">
446
- ${this.activeDots.map(e=>L.html`
467
+ ${this.activeDots.map(e=>_.html`
447
468
  <div
448
469
  class="dot"
449
470
  style="transform: ${e?`translateY(-${this.bounceHeight}px)`:"translateY(0)"}"
450
471
  ></div>
451
472
  `)}
452
473
  </div>
453
- `}}Kr.styles=L.css`
474
+ `}}ua.styles=_.css`
454
475
  :host {
455
476
  display: block;
456
477
  }
@@ -477,10 +498,10 @@ a=extmap-allow-mixed`)!==-1){const r=s.sdp.split(`
477
498
  transition: transform 0.2s ease-in-out;
478
499
  opacity: 1;
479
500
  }
480
- `,pm([Te()],Kr.prototype,"activeDots",2),customElements.get("obi-dot-loader")||customElements.define("obi-dot-loader",Kr);class kd extends L.LitElement{render(){return L.html`
501
+ `,Vy([Le()],ua.prototype,"activeDots",2),customElements.get("obi-dot-loader")||customElements.define("obi-dot-loader",ua);class bh extends _.LitElement{render(){return _.html`
481
502
  <obi-dot-loader loading style="margin-left: 2px"></obi-dot-loader>
482
503
  <span class="text">Searching the knowledge base</span>
483
- `}}kd.styles=L.css`
504
+ `}}bh.styles=_.css`
484
505
  :host {
485
506
  display: flex;
486
507
  align-items: center;
@@ -495,39 +516,43 @@ a=extmap-allow-mixed`)!==-1){const r=s.sdp.split(`
495
516
  font-weight: 500;
496
517
  font-size: 14px;
497
518
  }
498
- `,customElements.get("obi-searching-loader")||customElements.define("obi-searching-loader",kd);var mm=Object.defineProperty,gm=Object.getOwnPropertyDescriptor,qe=(n,e,t,i)=>{for(var s=i>1?void 0:i?gm(e,t):e,r=n.length-1,a;r>=0;r--)(a=n[r])&&(s=(i?a(e,t,s):a(s))||s);return i&&s&&mm(e,t,s),s};class ke extends L.LitElement{constructor(){super(),this.apiKey="",this.isActive=!0,this.position="bottom-right",this.user=null,this.state=$.READY,this.storedActiveState=void 0,this.showCourseModal=!1,this.isHovering=!1,this.navVisible=!1,this.activeSession=null,this.volume={speaker:"ASSISTANT",volume:0,spectrum:[]},this.sessionToken=null,this.roomToken=null,this.roomUrl=null,this.boundSaveSessionData=null,this.closeNavTimeoutRef=null,this.updateFromConfig();const e=()=>{this.activeSession&&this.sessionToken&&this.roomToken&&this.roomUrl&&this.saveSessionData()};window.addEventListener("beforeunload",e),window.addEventListener("pagehide",e)}updateFromConfig(){window.obiWidgetConfig&&(this.apiKey=window.obiWidgetConfig.apiKey||this.apiKey,this.position=window.obiWidgetConfig.position||this.position,this.user=window.obiWidgetConfig.user||this.user,window.obiWidgetConfig.isActive!==void 0&&(this.isActive=window.obiWidgetConfig.isActive))}async connectObi(e){if(this.activeSession){console.log("Connection already exists");return}try{const t=new ad({sessionId:e});if(!t){console.error("Failed to create session"),this.state=$.ERROR,this.activeSession=null;return}t.on("stateChanged",s=>{this.state=s.newState,s.newState!==$.READY&&(this.storedActiveState=s.newState)}),t.on("volume",s=>{this.volume=s}),t.on("error",s=>{console.error("Session error:",s.error),this.state=$.ERROR,this.activeSession=null});const i=await t.connect();i&&(this.sessionToken=e,this.roomToken=i.token,this.roomUrl=i.url),this.activeSession=t}catch(t){console.error("Failed to start session:",t),this.state=$.ERROR,this.activeSession=null}}async handleSessionStart(e){if(this.activeSession){console.log("Connection already in progress or active session exists");return}this.showCourseModal=!1,this.state=$.LOADING,await this.connectObi(e)}async checkExistingSession(){try{const e=JSON.parse(Vr.getItem(Br.SESSION_DATA)||"{}"),{sessionToken:t,roomToken:i,roomUrl:s,sessionExpiry:r,obiState:a}=e;if(!t||!i||!s)return;if(r&&new Date(r)<new Date){this.clearSessionStorage();return}this.state=$.LOADING;const o=new ad({sessionId:t});if(!o){console.error("Failed to create session"),this.state=$.ERROR,this.clearSessionStorage();return}o.on("stateChanged",d=>{this.state=d.newState,d.newState!==$.READY&&(this.storedActiveState=d.newState)}),o.on("volume",d=>{this.volume=d}),o.on("error",d=>{console.error("Session error:",d.error),this.state=$.ERROR,this.activeSession=null,this.clearSessionStorage()}),await o.reconnect(s,i,a)?(this.activeSession=o,this.sessionToken=t,this.roomToken=i,this.roomUrl=s,this.state=a,this.storedActiveState=a):this.clearSessionStorage()}catch(e){console.error("Error reconnecting to session:",e),this.state=$.ERROR,this.clearSessionStorage()}}clearSessionStorage(){Vr.removeItem(Br.SESSION_DATA)}connectedCallback(){super.connectedCallback(),this.updateFromConfig(),this.setAttribute("position",this.position),this.boundSaveSessionData=this.saveSessionData.bind(this),window.addEventListener("beforeunload",this.boundSaveSessionData),window.addEventListener("pagehide",this.boundSaveSessionData),this.checkExistingSession()}saveSessionData(){if(this.activeSession&&this.sessionToken&&this.roomToken&&this.roomUrl){const e=new Date;e.setMinutes(e.getMinutes()+5);const t={sessionToken:this.sessionToken,roomToken:this.roomToken,roomUrl:this.roomUrl,obiState:this.storedActiveState??this.state,sessionExpiry:e.toISOString()};Vr.setItem(Br.SESSION_DATA,JSON.stringify(t))}}disconnectedCallback(){this.closeNavTimeoutRef!==null&&window.clearTimeout(this.closeNavTimeoutRef),this.boundSaveSessionData&&(window.removeEventListener("beforeunload",this.boundSaveSessionData),window.removeEventListener("pagehide",this.boundSaveSessionData)),super.disconnectedCallback()}handleMouseEnter(){this.isHovering=!0,this.navVisible=!0}handleMouseLeave(){this.isHovering=!1,this.closeNavTimeoutRef!==null&&window.clearTimeout(this.closeNavTimeoutRef),this.closeNavTimeoutRef=window.setTimeout(()=>{this.isHovering||(this.navVisible=!1),this.closeNavTimeoutRef=null},300)}terminateSession(){this.clearSessionStorage(),this.sessionToken=null,this.roomToken=null,this.roomUrl=null,this.activeSession&&(this.activeSession.disconnect(),this.activeSession=null),this.state=$.READY}handleItemSelect(e,t){if(e==="experiences"){this.showCourseModal=!0;return}pn([e,t]).with(["pause",!0],()=>{var i;(i=this.activeSession)==null||i.pauseRecording()}).with(["pause",!1],()=>{var i;(i=this.activeSession)==null||i.resumeRecording()}).with(["activate",!1],()=>{this.terminateSession()}).otherwise(()=>{})}render(){if(this.updateFromConfig(),!this.isActive)return L.nothing;const e=pn(this.state).with($.LOADING,()=>L.html`<obi-dot-loader></obi-dot-loader>`).with($.RESEARCHING,()=>L.html`<obi-searching-loader></obi-searching-loader>`).with(zd.union($.USER_SPEAKING,$.AGENT_SPEAKING),()=>L.html`<obi-audio-equalizer .volume=${this.volume}></obi-audio-equalizer>`).with($.PAUSED,()=>od).otherwise(()=>od);return L.html`
519
+ `,customElements.get("obi-searching-loader")||customElements.define("obi-searching-loader",bh);var Gy=Object.defineProperty,jy=Object.getOwnPropertyDescriptor,nA=(n,e,A,t)=>{for(var i=t>1?void 0:t?jy(e,A):e,r=n.length-1,s;r>=0;r--)(s=n[r])&&(i=(t?s(e,A,i):s(i))||i);return t&&i&&Gy(e,A,i),i};class Se extends _.LitElement{constructor(){super(),this.apiKey="",this.isActive=!0,this.position="bottom-right",this.user=null,this.state=O.READY,this.storedActiveState=void 0,this.showCourseModal=!1,this.isHovering=!1,this.navVisible=!1,this.activeSession=null,this.volume={speaker:"ASSISTANT",volume:0,spectrum:[]},this.sessionToken=null,this.roomToken=null,this.roomUrl=null,this.boundSaveSessionData=null,this.closeNavTimeoutRef=null,this.updateFromConfig();const e=()=>{this.activeSession&&this.sessionToken&&this.roomToken&&this.roomUrl&&this.saveSessionData()};window.addEventListener("beforeunload",e),window.addEventListener("pagehide",e)}updateFromConfig(){window.obiWidgetConfig&&(this.apiKey=window.obiWidgetConfig.apiKey||this.apiKey,this.position=window.obiWidgetConfig.position||this.position,this.user=window.obiWidgetConfig.user||this.user,window.obiWidgetConfig.isActive!==void 0&&(this.isActive=window.obiWidgetConfig.isActive))}async connectObi(e){if(this.activeSession){console.log("Connection already exists");return}try{const A=new tu({sessionId:e,apiBaseUrl:_r});if(!A){console.error("Failed to create session"),this.state=O.ERROR,this.activeSession=null;return}A.on("stateChanged",i=>{this.state=i,i!==O.READY&&(this.storedActiveState=i)}),A.on("volume",({speaker:i,spectrum:r,volume:s})=>{this.volume={speaker:i,spectrum:r,volume:s}}),A.on("screenCaptureRequested",async()=>{try{const r=(await jw(document.documentElement,{useCORS:!0,allowTaint:!0,foreignObjectRendering:!0})).toDataURL("image/png");this.activeSession.emit("screenCaptureComplete",r)}catch(i){console.error("[obi] error capturing screen:",i),this.activeSession.emit("screenCaptureComplete","error")}}),A.on("error",i=>{console.error("Session error:",i),this.state=O.ERROR,this.activeSession=null});const t=await A.connect();t&&(this.sessionToken=e,this.roomToken=t.token,this.roomUrl=t.url),this.activeSession=A}catch(A){console.error("Failed to start session:",A),this.state=O.ERROR,this.activeSession=null}}async handleSessionStart(e){if(this.activeSession){console.log("Connection already in progress or active session exists");return}this.showCourseModal=!1,this.state=O.LOADING,await this.connectObi(e)}async checkExistingSession(){try{const e=JSON.parse(sa.getItem(ra.SESSION_DATA)||"{}"),{sessionToken:A,roomToken:t,roomUrl:i,sessionExpiry:r,obiState:s}=e;if(!A||!t||!i)return;if(r&&new Date(r)<new Date){this.clearSessionStorage();return}this.state=O.LOADING;const o=new tu({sessionId:A,apiBaseUrl:_r});if(!o){console.error("Failed to create session"),this.state=O.ERROR,this.clearSessionStorage();return}o.on("stateChanged",c=>{this.state=c,c!==O.READY&&(this.storedActiveState=c)}),o.on("volume",({speaker:c,spectrum:l,volume:u})=>{this.volume={speaker:c,spectrum:l,volume:u}}),o.on("error",c=>{console.error("Session error:",c),this.state=O.ERROR,this.activeSession=null,this.clearSessionStorage()}),await o.reconnect(i,t,s)?(this.activeSession=o,this.sessionToken=A,this.roomToken=t,this.roomUrl=i,this.state=s,this.storedActiveState=s):this.clearSessionStorage()}catch(e){console.error("Error reconnecting to session:",e),this.state=O.ERROR,this.clearSessionStorage()}}clearSessionStorage(){sa.removeItem(ra.SESSION_DATA)}connectedCallback(){super.connectedCallback(),this.updateFromConfig(),this.setAttribute("position",this.position),this.boundSaveSessionData=this.saveSessionData.bind(this),window.addEventListener("beforeunload",this.boundSaveSessionData),window.addEventListener("pagehide",this.boundSaveSessionData),this.checkExistingSession()}saveSessionData(){if(this.activeSession&&this.sessionToken&&this.roomToken&&this.roomUrl){const e=new Date;e.setMinutes(e.getMinutes()+5);const A={sessionToken:this.sessionToken,roomToken:this.roomToken,roomUrl:this.roomUrl,obiState:this.storedActiveState??this.state,sessionExpiry:e.toISOString()};sa.setItem(ra.SESSION_DATA,JSON.stringify(A))}}disconnectedCallback(){this.closeNavTimeoutRef!==null&&window.clearTimeout(this.closeNavTimeoutRef),this.boundSaveSessionData&&(window.removeEventListener("beforeunload",this.boundSaveSessionData),window.removeEventListener("pagehide",this.boundSaveSessionData)),super.disconnectedCallback()}handleMouseEnter(){this.isHovering=!0,this.navVisible=!0}handleMouseLeave(){this.isHovering=!1,this.closeNavTimeoutRef!==null&&window.clearTimeout(this.closeNavTimeoutRef),this.closeNavTimeoutRef=window.setTimeout(()=>{this.isHovering||(this.navVisible=!1),this.closeNavTimeoutRef=null},300)}terminateSession(){this.clearSessionStorage(),this.sessionToken=null,this.roomToken=null,this.roomUrl=null,this.activeSession&&(this.activeSession.disconnect(),this.activeSession=null),this.state=O.READY}handleItemSelect(e,A){if(e==="experiences"){this.showCourseModal=!0;return}Pi([e,A]).with(["pause",!0],()=>{var t;(t=this.activeSession)==null||t.pauseRecording()}).with(["pause",!1],()=>{var t;(t=this.activeSession)==null||t.resumeRecording()}).with(["activate",!1],()=>{this.terminateSession()}).otherwise(()=>{})}render(){if(this.updateFromConfig(),!this.isActive)return _.nothing;const e=Pi(this.state).with(O.LOADING,()=>_.html`<obi-dot-loader></obi-dot-loader>`).with(O.RESEARCHING,()=>_.html`<obi-searching-loader></obi-searching-loader>`).with(Bm.union(O.USER_SPEAKING,O.AGENT_SPEAKING),()=>_.html`<obi-audio-equalizer .volume=${this.volume}></obi-audio-equalizer>`).with(O.PAUSED,()=>lh).otherwise(()=>lh);return _.html`
499
520
  <div
500
- class="widget-container ${this.state===$.USER_SPEAKING||this.state===$.AGENT_SPEAKING?"pulse":""} ${this.state!==$.READY||this.navVisible?"rounded":""} ${this.state===$.RESEARCHING?"researching":""} ${this.state===$.USER_SPEAKING?"user-speaking":""}"
521
+ class="widget-container ${this.state===O.USER_SPEAKING||this.state===O.AGENT_SPEAKING?"pulse":""} ${this.state!==O.READY||this.navVisible?"rounded":""} ${this.state===O.RESEARCHING?"researching":""} ${this.state===O.USER_SPEAKING?"user-speaking":""}"
501
522
  @mouseenter=${this.handleMouseEnter}
502
523
  @mouseleave=${this.handleMouseLeave}
503
524
  >
504
525
  ${e}
505
- ${this.navVisible&&this.state!==$.RESEARCHING?L.html`
526
+ ${this.navVisible&&this.state!==O.RESEARCHING?_.html`
506
527
  <obi-navigation-bar
507
- ?isActive=${this.state!==$.READY}
528
+ ?isActive=${this.state!==O.READY}
508
529
  .position=${this.position}
509
530
  data-direction="up"
510
531
  .currentState=${this.state}
511
532
  .onItemSelect=${this.handleItemSelect.bind(this)}
512
533
  ></obi-navigation-bar>
513
- `:L.nothing}
534
+ `:_.nothing}
514
535
  </div>
515
- ${this.showCourseModal?L.html`<obi-course-modal
536
+ ${this.showCourseModal?_.html`<obi-course-modal
516
537
  .onClose=${()=>this.showCourseModal=!1}
517
538
  .onCourseSelect=${this.handleSessionStart.bind(this)}
518
539
  .apiKey=${this.apiKey}
519
- ></obi-course-modal>`:L.nothing}
520
- `}}ke.styles=L.css`
540
+ ></obi-course-modal>`:_.nothing}
541
+ `}}Se.styles=_.css`
521
542
  :host {
522
543
  display: block;
523
544
  position: fixed;
524
545
  z-index: 9999;
525
- font-family: Arial, sans-serif;
546
+ font-family: "Inter", sans-serif;
526
547
  --obi-primary: #7c3aed;
527
548
  --obi-danger: #ef4444;
528
549
  --obi-gray: #6b7280;
529
550
  }
530
551
 
552
+ h1 {
553
+ font-family: "Syne", sans-serif;
554
+ }
555
+
531
556
  /* Position-specific styles */
532
557
  :host([position="bottom-right"]) {
533
558
  bottom: 80px;
@@ -644,4 +669,4 @@ a=extmap-allow-mixed`)!==-1){const r=s.sdp.split(`
644
669
  .pulse {
645
670
  animation: pulse-shadow 2s ease-in-out infinite;
646
671
  }
647
- `,qe([Te()],ke.prototype,"apiKey",2),qe([Te()],ke.prototype,"isActive",2),qe([Te()],ke.prototype,"position",2),qe([Te()],ke.prototype,"user",2),qe([Te()],ke.prototype,"state",2),qe([Te()],ke.prototype,"storedActiveState",2),qe([Te()],ke.prototype,"showCourseModal",2),qe([Te()],ke.prototype,"isHovering",2),qe([Te()],ke.prototype,"navVisible",2),qe([Te()],ke.prototype,"activeSession",2),qe([Te()],ke.prototype,"volume",2),customElements.get("obi-widget")||customElements.define("obi-widget",ke),customElements.get("obi-widget")||customElements.define("obi-widget",ke);function vm(){if(!document.querySelector("obi-widget")){const n=document.createElement("obi-widget");document.body.appendChild(n),console.log("Obi Widget mounted")}}function ym(){const n=window;n.ObiSDK&&Array.isArray(n.ObiSDK.q)&&(n.ObiSDK.q=[])}function bm(){vm(),ym()}bm(),et.EventType=rd,et.ObiWidget=ke,et.SDKState=$,Object.defineProperty(et,Symbol.toStringTag,{value:"Module"})});
672
+ `,nA([Le()],Se.prototype,"apiKey",2),nA([Le()],Se.prototype,"isActive",2),nA([Le()],Se.prototype,"position",2),nA([Le()],Se.prototype,"user",2),nA([Le()],Se.prototype,"state",2),nA([Le()],Se.prototype,"storedActiveState",2),nA([Le()],Se.prototype,"showCourseModal",2),nA([Le()],Se.prototype,"isHovering",2),nA([Le()],Se.prototype,"navVisible",2),nA([Le()],Se.prototype,"activeSession",2),nA([Le()],Se.prototype,"volume",2),customElements.get("obi-widget")||customElements.define("obi-widget",Se),customElements.get("obi-widget")||customElements.define("obi-widget",Se);function Jy(){const n=window;typeof n.ObiSDK=="function"||typeof n.ObiSDK=="object"||(n.ObiSDK=function(e,A){e==="update"&&A&&(n.obiWidgetConfig={...n.obiWidgetConfig,...A})},n.ObiSDK.q=[])}function Wy(){if(!document.querySelector("obi-widget")){const n=document.createElement("obi-widget");document.body.appendChild(n),console.log("Obi Widget mounted")}}function Xy(){const n=window;n.ObiSDK&&Array.isArray(n.ObiSDK.q)&&(n.ObiSDK.q.forEach(e=>{const[A,t]=e;A==="update"&&t&&(n.obiWidgetConfig={...n.obiWidgetConfig,...t})}),n.ObiSDK.q=[])}function $y(){const n=document.createElement("link");n.href="https://fonts.googleapis.com/css2?family=Inter:ital,opsz,wght@0,14..32,100..900;1,14..32,100..900&family=Syne:wght@400..800&display=swap",n.rel="stylesheet",document.head.appendChild(n)}function Yy(){$y(),Jy(),Wy(),Xy()}Yy(),nt.ObiWidget=Se,Object.defineProperty(nt,Symbol.toStringTag,{value:"Module"})});