voice-mode 4.4.0__py3-none-any.whl → 4.5.0__py3-none-any.whl

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 (75) hide show
  1. voice_mode/__version__.py +1 -1
  2. voice_mode/cli.py +79 -3
  3. voice_mode/cli_commands/transcribe.py +7 -6
  4. voice_mode/config.py +1 -1
  5. voice_mode/conversation_logger.py +6 -0
  6. voice_mode/core.py +9 -2
  7. voice_mode/frontend/.next/BUILD_ID +1 -1
  8. voice_mode/frontend/.next/app-build-manifest.json +5 -5
  9. voice_mode/frontend/.next/build-manifest.json +3 -3
  10. voice_mode/frontend/.next/next-minimal-server.js.nft.json +1 -1
  11. voice_mode/frontend/.next/next-server.js.nft.json +1 -1
  12. voice_mode/frontend/.next/prerender-manifest.json +1 -1
  13. voice_mode/frontend/.next/required-server-files.json +1 -1
  14. voice_mode/frontend/.next/server/app/_not-found/page.js +1 -1
  15. voice_mode/frontend/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
  16. voice_mode/frontend/.next/server/app/_not-found.html +1 -1
  17. voice_mode/frontend/.next/server/app/_not-found.rsc +1 -1
  18. voice_mode/frontend/.next/server/app/api/connection-details/route.js +2 -2
  19. voice_mode/frontend/.next/server/app/favicon.ico/route.js +2 -2
  20. voice_mode/frontend/.next/server/app/index.html +1 -1
  21. voice_mode/frontend/.next/server/app/index.rsc +2 -2
  22. voice_mode/frontend/.next/server/app/page.js +3 -3
  23. voice_mode/frontend/.next/server/app/page_client-reference-manifest.js +1 -1
  24. voice_mode/frontend/.next/server/chunks/994.js +1 -1
  25. voice_mode/frontend/.next/server/middleware-build-manifest.js +1 -1
  26. voice_mode/frontend/.next/server/next-font-manifest.js +1 -1
  27. voice_mode/frontend/.next/server/next-font-manifest.json +1 -1
  28. voice_mode/frontend/.next/server/pages/404.html +1 -1
  29. voice_mode/frontend/.next/server/pages/500.html +1 -1
  30. voice_mode/frontend/.next/server/server-reference-manifest.json +1 -1
  31. voice_mode/frontend/.next/standalone/.next/BUILD_ID +1 -1
  32. voice_mode/frontend/.next/standalone/.next/app-build-manifest.json +5 -5
  33. voice_mode/frontend/.next/standalone/.next/build-manifest.json +3 -3
  34. voice_mode/frontend/.next/standalone/.next/prerender-manifest.json +1 -1
  35. voice_mode/frontend/.next/standalone/.next/required-server-files.json +1 -1
  36. voice_mode/frontend/.next/standalone/.next/server/app/_not-found/page.js +1 -1
  37. voice_mode/frontend/.next/standalone/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
  38. voice_mode/frontend/.next/standalone/.next/server/app/_not-found.html +1 -1
  39. voice_mode/frontend/.next/standalone/.next/server/app/_not-found.rsc +1 -1
  40. voice_mode/frontend/.next/standalone/.next/server/app/api/connection-details/route.js +2 -2
  41. voice_mode/frontend/.next/standalone/.next/server/app/favicon.ico/route.js +2 -2
  42. voice_mode/frontend/.next/standalone/.next/server/app/index.html +1 -1
  43. voice_mode/frontend/.next/standalone/.next/server/app/index.rsc +2 -2
  44. voice_mode/frontend/.next/standalone/.next/server/app/page.js +3 -3
  45. voice_mode/frontend/.next/standalone/.next/server/app/page_client-reference-manifest.js +1 -1
  46. voice_mode/frontend/.next/standalone/.next/server/chunks/994.js +1 -1
  47. voice_mode/frontend/.next/standalone/.next/server/middleware-build-manifest.js +1 -1
  48. voice_mode/frontend/.next/standalone/.next/server/next-font-manifest.js +1 -1
  49. voice_mode/frontend/.next/standalone/.next/server/next-font-manifest.json +1 -1
  50. voice_mode/frontend/.next/standalone/.next/server/pages/404.html +1 -1
  51. voice_mode/frontend/.next/standalone/.next/server/pages/500.html +1 -1
  52. voice_mode/frontend/.next/standalone/.next/server/server-reference-manifest.json +1 -1
  53. voice_mode/frontend/.next/standalone/server.js +1 -1
  54. voice_mode/frontend/.next/static/chunks/app/layout-d3ec7f6f14ea7396.js +1 -0
  55. voice_mode/frontend/.next/static/chunks/app/{page-ae0d14863ed895ea.js → page-471796963fb1a4bd.js} +1 -1
  56. voice_mode/frontend/.next/static/chunks/{main-app-836e76fc70b52220.js → main-app-78da5e437b6a2a9f.js} +1 -1
  57. voice_mode/frontend/.next/trace +43 -43
  58. voice_mode/frontend/.next/types/app/api/connection-details/route.ts +1 -1
  59. voice_mode/frontend/.next/types/app/layout.ts +1 -1
  60. voice_mode/frontend/.next/types/app/page.ts +1 -1
  61. voice_mode/frontend/package-lock.json +26 -15
  62. voice_mode/provider_discovery.py +55 -79
  63. voice_mode/providers.py +61 -45
  64. voice_mode/simple_failover.py +41 -12
  65. voice_mode/tools/__init__.py +138 -30
  66. voice_mode/tools/converse.py +148 -337
  67. voice_mode/tools/diagnostics.py +2 -1
  68. voice_mode/tools/voice_registry.py +24 -28
  69. {voice_mode-4.4.0.dist-info → voice_mode-4.5.0.dist-info}/METADATA +5 -2
  70. {voice_mode-4.4.0.dist-info → voice_mode-4.5.0.dist-info}/RECORD +74 -74
  71. voice_mode/frontend/.next/static/chunks/app/layout-917e8410913fe899.js +0 -1
  72. /voice_mode/frontend/.next/static/{WhZriRkBKVNPSmCnOFRav → Ni4GIqyDdn0QehvmlLBZg}/_buildManifest.js +0 -0
  73. /voice_mode/frontend/.next/static/{WhZriRkBKVNPSmCnOFRav → Ni4GIqyDdn0QehvmlLBZg}/_ssgManifest.js +0 -0
  74. {voice_mode-4.4.0.dist-info → voice_mode-4.5.0.dist-info}/WHEEL +0 -0
  75. {voice_mode-4.4.0.dist-info → voice_mode-4.5.0.dist-info}/entry_points.txt +0 -0
@@ -1,6 +1,6 @@
1
- (()=>{var e={};e.id=931,e.ids=[931],e.modules={2934:e=>{"use strict";e.exports=require("next/dist/client/components/action-async-storage.external.js")},4580:e=>{"use strict";e.exports=require("next/dist/client/components/request-async-storage.external.js")},5869:e=>{"use strict";e.exports=require("next/dist/client/components/static-generation-async-storage.external.js")},399:e=>{"use strict";e.exports=require("next/dist/compiled/next-server/app-page.runtime.prod.js")},5315:e=>{"use strict";e.exports=require("path")},7360:e=>{"use strict";e.exports=require("url")},2806:(e,t,i)=>{"use strict";i.r(t),i.d(t,{GlobalError:()=>o.a,__next_app__:()=>h,originalPathname:()=>u,pages:()=>d,routeModule:()=>p,tree:()=>c}),i(908),i(1506),i(5866);var n=i(3191),r=i(8716),s=i(7922),o=i.n(s),a=i(5231),l={};for(let e in a)0>["default","tree","pages","GlobalError","originalPathname","__next_app__","routeModule"].indexOf(e)&&(l[e]=()=>a[e]);i.d(t,l);let c=["",{children:["__PAGE__",{},{page:[()=>Promise.resolve().then(i.bind(i,908)),"/tmp/build-via-sdist-z_iazuah/voice_mode-4.4.0/voice_mode/frontend/app/page.tsx"],metadata:{icon:[async e=>(await Promise.resolve().then(i.bind(i,7481))).default(e)],apple:[],openGraph:[],twitter:[],manifest:void 0}}]},{layout:[()=>Promise.resolve().then(i.bind(i,1506)),"/tmp/build-via-sdist-z_iazuah/voice_mode-4.4.0/voice_mode/frontend/app/layout.tsx"],"not-found":[()=>Promise.resolve().then(i.t.bind(i,5866,23)),"next/dist/client/components/not-found-error"],metadata:{icon:[async e=>(await Promise.resolve().then(i.bind(i,7481))).default(e)],apple:[],openGraph:[],twitter:[],manifest:void 0}}],d=["/tmp/build-via-sdist-z_iazuah/voice_mode-4.4.0/voice_mode/frontend/app/page.tsx"],u="/page",h={require:i,loadChunk:()=>Promise.resolve()},p=new n.AppPageRouteModule({definition:{kind:r.x.APP_PAGE,page:"/page",pathname:"/",bundlePath:"",filename:"",appPaths:[]},userland:{loaderTree:c}})},8677:(e,t,i)=>{Promise.resolve().then(i.bind(i,5337))},1865:(e,t,i)=>{Promise.resolve().then(i.t.bind(i,2994,23)),Promise.resolve().then(i.t.bind(i,6114,23)),Promise.resolve().then(i.t.bind(i,9727,23)),Promise.resolve().then(i.t.bind(i,9671,23)),Promise.resolve().then(i.t.bind(i,1868,23)),Promise.resolve().then(i.t.bind(i,4759,23))},1207:()=>{},5337:(e,t,i)=>{"use strict";let n,r,s,o;i.r(t),i.d(t,{default:()=>fb});var a,l,c,d,u=i(326);function h(){return u.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:u.jsx("path",{d:"M3.33398 3.33334L12.6673 12.6667M12.6673 3.33334L3.33398 12.6667",stroke:"currentColor","stroke-width":"2","stroke-linecap":"square"})})}var p=i(7577);function m(e){(0,p.useRef)(null);let[t,i]=(0,p.useState)(!1),n=(0,p.useRef)(!1);return["listening","thinking","speaking"].includes(e.state)&&!1==n.current&&(n.current=!0),u.jsx(u.Fragment,{children:t?(0,u.jsxs)("div",{className:"fixed text-sm left-1/2 max-w-[90vw] -translate-x-1/2 flex top-6 items-center gap-4 bg-[#1F1F1F] px-4 py-3 rounded-lg",children:[u.jsx("div",{children:u.jsx("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:u.jsx("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M9.85068 3.63564C10.8197 2.00589 13.1793 2.00589 14.1484 3.63564L21.6323 16.2223C22.6232 17.8888 21.4223 20 19.4835 20H4.51555C2.57676 20 1.37584 17.8888 2.36671 16.2223L9.85068 3.63564ZM12 8.5C12.2761 8.5 12.5 8.72386 12.5 9V13.5C12.5 13.7761 12.2761 14 12 14C11.7239 14 11.5 13.7761 11.5 13.5V9C11.5 8.72386 11.7239 8.5 12 8.5ZM12.75 16C12.75 16.4142 12.4142 16.75 12 16.75C11.5858 16.75 11.25 16.4142 11.25 16C11.25 15.5858 11.5858 15.25 12 15.25C12.4142 15.25 12.75 15.5858 12.75 16Z",fill:"#666666"})})}),u.jsx("p",{className:"text-pretty w-max",children:"It's quiet... too quiet. Is your agent lost? Ensure your agent is properly configured and running on your machine."}),u.jsx("a",{href:"https://docs.livekit.io/agents/quickstarts/s2s/",target:"_blank",className:"underline whitespace-nowrap",children:"View guide"}),u.jsx("button",{onClick:()=>i(!1),children:u.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:u.jsx("path",{d:"M3.16602 3.16666L12.8327 12.8333M12.8327 3.16666L3.16602 12.8333",stroke:"#999999",strokeWidth:"1.5",strokeLinecap:"square"})})})]}):null})}var f=Object.defineProperty,g=(e,t,i)=>t in e?f(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i,v=(e,t,i)=>g(e,"symbol"!=typeof t?t+"":t,i);class y{constructor(){v(this,"_locking"),v(this,"_locks"),this._locking=Promise.resolve(),this._locks=0}isLocked(){return this._locks>0}lock(){let e;this._locks+=1;let t=new Promise(t=>e=()=>{this._locks-=1,t()}),i=this._locking.then(()=>e);return this._locking=this._locking.then(()=>t),i}}function b(e,t){if(!e)throw Error(t)}function k(e){if("number"!=typeof e)throw Error("invalid int 32: "+typeof e);if(!Number.isInteger(e)||e>2147483647||e<-2147483648)throw Error("invalid int 32: "+e)}function T(e){if("number"!=typeof e)throw Error("invalid uint 32: "+typeof e);if(!Number.isInteger(e)||e>4294967295||e<0)throw Error("invalid uint 32: "+e)}function S(e){if("number"!=typeof e)throw Error("invalid float 32: "+typeof e);if(Number.isFinite(e)&&(e>34028234663852886e22||e<-34028234663852886e22))throw Error("invalid float 32: "+e)}let C=Symbol("@bufbuild/protobuf/enum-type");function w(e,t,i,n){e[C]=E(t,i.map(t=>({no:t.no,name:t.name,localName:e[t.no]})))}function E(e,t,i){let n=Object.create(null),r=Object.create(null),s=[];for(let e of t){let t=P(e);s.push(t),n[e.name]=t,r[e.no]=t}return{typeName:e,values:s,findName:e=>n[e],findNumber:e=>r[e]}}function P(e){return"localName"in e?e:Object.assign(Object.assign({},e),{localName:e.name})}class x{equals(e){return this.getType().runtime.util.equals(this.getType(),this,e)}clone(){return this.getType().runtime.util.clone(this)}fromBinary(e,t){let i=this.getType().runtime.bin,n=i.makeReadOptions(t);return i.readMessage(this,n.readerFactory(e),e.byteLength,n),this}fromJson(e,t){let i=this.getType(),n=i.runtime.json,r=n.makeReadOptions(t);return n.readMessage(i,e,r,this),this}fromJsonString(e,t){let i;try{i=JSON.parse(e)}catch(e){throw Error("cannot decode ".concat(this.getType().typeName," from JSON: ").concat(e instanceof Error?e.message:String(e)))}return this.fromJson(i,t)}toBinary(e){let t=this.getType().runtime.bin,i=t.makeWriteOptions(e),n=i.writerFactory();return t.writeMessage(this,n,i),n.finish()}toJson(e){let t=this.getType().runtime.json,i=t.makeWriteOptions(e);return t.writeMessage(this,i)}toJsonString(e){var t;return JSON.stringify(this.toJson(e),null,null!==(t=null==e?void 0:e.prettySpaces)&&void 0!==t?t:0)}toJSON(){return this.toJson({emitDefaultValues:!0})}getType(){return Object.getPrototypeOf(this).constructor}}function R(){let e=0,t=0;for(let i=0;i<28;i+=7){let n=this.buf[this.pos++];if(e|=(127&n)<<i,(128&n)==0)return this.assertBounds(),[e,t]}let i=this.buf[this.pos++];if(e|=(15&i)<<28,t=(112&i)>>4,(128&i)==0)return this.assertBounds(),[e,t];for(let i=3;i<=31;i+=7){let n=this.buf[this.pos++];if(t|=(127&n)<<i,(128&n)==0)return this.assertBounds(),[e,t]}throw Error("invalid varint")}function O(e,t,i){for(let n=0;n<28;n+=7){let r=e>>>n,s=!(r>>>7==0&&0==t),o=(s?128|r:r)&255;if(i.push(o),!s)return}let n=e>>>28&15|(7&t)<<4,r=t>>3!=0;if(i.push((r?128|n:n)&255),r){for(let e=3;e<31;e+=7){let n=t>>>e,r=n>>>7!=0,s=(r?128|n:n)&255;if(i.push(s),!r)return}i.push(t>>>31&1)}}function A(e){let t="-"===e[0];t&&(e=e.slice(1));let i=0,n=0;function r(t,r){let s=Number(e.slice(t,r));n*=1e6,(i=1e6*i+s)>=4294967296&&(n+=i/4294967296|0,i%=4294967296)}return r(-24,-18),r(-18,-12),r(-12,-6),r(-6),t?D(i,n):M(i,n)}function I(e,t){if({lo:e,hi:t}={lo:e>>>0,hi:t>>>0},t<=2097151)return String(4294967296*t+e);let i=16777215&e,n=(e>>>24|t<<8)&16777215,r=t>>16&65535,s=i+6777216*n+6710656*r,o=n+8147497*r,a=2*r;return s>=1e7&&(o+=Math.floor(s/1e7),s%=1e7),o>=1e7&&(a+=Math.floor(o/1e7),o%=1e7),a.toString()+_(o)+_(s)}function M(e,t){return{lo:0|e,hi:0|t}}function D(e,t){return t=~t,e?e=~e+1:t+=1,M(e,t)}let _=e=>{let t=String(e);return"0000000".slice(t.length)+t};function N(e,t){if(e>=0){for(;e>127;)t.push(127&e|128),e>>>=7;t.push(e)}else{for(let i=0;i<9;i++)t.push(127&e|128),e>>=7;t.push(1)}}function L(){let e=this.buf[this.pos++],t=127&e;if((128&e)==0||(t|=(127&(e=this.buf[this.pos++]))<<7,(128&e)==0)||(t|=(127&(e=this.buf[this.pos++]))<<14,(128&e)==0)||(t|=(127&(e=this.buf[this.pos++]))<<21,(128&e)==0))return this.assertBounds(),t;t|=(15&(e=this.buf[this.pos++]))<<28;for(let t=5;(128&e)!=0&&t<10;t++)e=this.buf[this.pos++];if((128&e)!=0)throw Error("invalid varint");return this.assertBounds(),t>>>0}let j=function(){let e=new DataView(new ArrayBuffer(8));if("function"==typeof BigInt&&"function"==typeof e.getBigInt64&&"function"==typeof e.getBigUint64&&"function"==typeof e.setBigInt64&&"function"==typeof e.setBigUint64&&("object"!=typeof process||"object"!=typeof process.env||"1"!==process.env.BUF_BIGINT_DISABLE)){let t=BigInt("-9223372036854775808"),i=BigInt("9223372036854775807"),n=BigInt("0"),r=BigInt("18446744073709551615");return{zero:BigInt(0),supported:!0,parse(e){let n="bigint"==typeof e?e:BigInt(e);if(n>i||n<t)throw Error("int64 invalid: ".concat(e));return n},uParse(e){let t="bigint"==typeof e?e:BigInt(e);if(t>r||t<n)throw Error("uint64 invalid: ".concat(e));return t},enc(t){return e.setBigInt64(0,this.parse(t),!0),{lo:e.getInt32(0,!0),hi:e.getInt32(4,!0)}},uEnc(t){return e.setBigInt64(0,this.uParse(t),!0),{lo:e.getInt32(0,!0),hi:e.getInt32(4,!0)}},dec:(t,i)=>(e.setInt32(0,t,!0),e.setInt32(4,i,!0),e.getBigInt64(0,!0)),uDec:(t,i)=>(e.setInt32(0,t,!0),e.setInt32(4,i,!0),e.getBigUint64(0,!0))}}let t=e=>b(/^-?[0-9]+$/.test(e),"int64 invalid: ".concat(e)),i=e=>b(/^[0-9]+$/.test(e),"uint64 invalid: ".concat(e));return{zero:"0",supported:!1,parse:e=>("string"!=typeof e&&(e=e.toString()),t(e),e),uParse:e=>("string"!=typeof e&&(e=e.toString()),i(e),e),enc:e=>("string"!=typeof e&&(e=e.toString()),t(e),A(e)),uEnc:e=>("string"!=typeof e&&(e=e.toString()),i(e),A(e)),dec:(e,t)=>(function(e,t){let i=M(e,t),n=2147483648&i.hi;n&&(i=D(i.lo,i.hi));let r=I(i.lo,i.hi);return n?"-"+r:r})(e,t),uDec:(e,t)=>I(e,t)}}();function U(e,t,i){if(t===i)return!0;if(e==oM.BYTES){if(!(t instanceof Uint8Array)||!(i instanceof Uint8Array)||t.length!==i.length)return!1;for(let e=0;e<t.length;e++)if(t[e]!==i[e])return!1;return!0}switch(e){case oM.UINT64:case oM.FIXED64:case oM.INT64:case oM.SFIXED64:case oM.SINT64:return t==i}return!1}function F(e,t){switch(e){case oM.BOOL:return!1;case oM.UINT64:case oM.FIXED64:case oM.INT64:case oM.SFIXED64:case oM.SINT64:return 0==t?j.zero:"0";case oM.DOUBLE:case oM.FLOAT:return 0;case oM.BYTES:return new Uint8Array(0);case oM.STRING:return"";default:return 0}}function V(e,t){switch(e){case oM.BOOL:return!1===t;case oM.STRING:return""===t;case oM.BYTES:return t instanceof Uint8Array&&!t.byteLength;default:return 0==t}}(function(e){e[e.DOUBLE=1]="DOUBLE",e[e.FLOAT=2]="FLOAT",e[e.INT64=3]="INT64",e[e.UINT64=4]="UINT64",e[e.INT32=5]="INT32",e[e.FIXED64=6]="FIXED64",e[e.FIXED32=7]="FIXED32",e[e.BOOL=8]="BOOL",e[e.STRING=9]="STRING",e[e.BYTES=12]="BYTES",e[e.UINT32=13]="UINT32",e[e.SFIXED32=15]="SFIXED32",e[e.SFIXED64=16]="SFIXED64",e[e.SINT32=17]="SINT32",e[e.SINT64=18]="SINT64"})(oM||(oM={})),function(e){e[e.BIGINT=0]="BIGINT",e[e.STRING=1]="STRING"}(oD||(oD={})),function(e){e[e.Varint=0]="Varint",e[e.Bit64=1]="Bit64",e[e.LengthDelimited=2]="LengthDelimited",e[e.StartGroup=3]="StartGroup",e[e.EndGroup=4]="EndGroup",e[e.Bit32=5]="Bit32"}(o_||(o_={}));class B{constructor(e){this.stack=[],this.textEncoder=null!=e?e:new TextEncoder,this.chunks=[],this.buf=[]}finish(){this.chunks.push(new Uint8Array(this.buf));let e=0;for(let t=0;t<this.chunks.length;t++)e+=this.chunks[t].length;let t=new Uint8Array(e),i=0;for(let e=0;e<this.chunks.length;e++)t.set(this.chunks[e],i),i+=this.chunks[e].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 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(T(e);e>127;)this.buf.push(127&e|128),e>>>=7;return this.buf.push(e),this}int32(e){return k(e),N(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){S(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){T(e);let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!0),this.raw(t)}sfixed32(e){k(e);let t=new Uint8Array(4);return new DataView(t.buffer).setInt32(0,e,!0),this.raw(t)}sint32(e){return k(e),N(e=(e<<1^e>>31)>>>0,this.buf),this}sfixed64(e){let t=new Uint8Array(8),i=new DataView(t.buffer),n=j.enc(e);return i.setInt32(0,n.lo,!0),i.setInt32(4,n.hi,!0),this.raw(t)}fixed64(e){let t=new Uint8Array(8),i=new DataView(t.buffer),n=j.uEnc(e);return i.setInt32(0,n.lo,!0),i.setInt32(4,n.hi,!0),this.raw(t)}int64(e){let t=j.enc(e);return O(t.lo,t.hi,this.buf),this}sint64(e){let t=j.enc(e),i=t.hi>>31;return O(t.lo<<1^i,(t.hi<<1|t.lo>>>31)^i,this.buf),this}uint64(e){let t=j.uEnc(e);return O(t.lo,t.hi,this.buf),this}}class q{constructor(e,t){this.varint64=R,this.uint32=L,this.buf=e,this.len=e.length,this.pos=0,this.view=new DataView(e.buffer,e.byteOffset,e.byteLength),this.textDecoder=null!=t?t:new TextDecoder}tag(){let e=this.uint32(),t=e>>>3,i=7&e;if(t<=0||i<0||i>5)throw Error("illegal tag: field no "+t+" wire type "+i);return[t,i]}skip(e,t){let i=this.pos;switch(e){case o_.Varint:for(;128&this.buf[this.pos++];);break;case o_.Bit64:this.pos+=4;case o_.Bit32:this.pos+=4;break;case o_.LengthDelimited:let n=this.uint32();this.pos+=n;break;case o_.StartGroup:for(;;){let[e,i]=this.tag();if(i===o_.EndGroup){if(void 0!==t&&e!==t)throw Error("invalid end group tag");break}this.skip(i,e)}break;default:throw Error("cant skip wire type "+e)}return this.assertBounds(),this.buf.subarray(i,this.pos)}assertBounds(){if(this.pos>this.len)throw RangeError("premature EOF")}int32(){return 0|this.uint32()}sint32(){let e=this.uint32();return e>>>1^-(1&e)}int64(){return j.dec(...this.varint64())}uint64(){return j.uDec(...this.varint64())}sint64(){let[e,t]=this.varint64(),i=-(1&e);return e=(e>>>1|(1&t)<<31)^i,t=t>>>1^i,j.dec(e,t)}bool(){let[e,t]=this.varint64();return 0!==e||0!==t}fixed32(){return this.view.getUint32((this.pos+=4)-4,!0)}sfixed32(){return this.view.getInt32((this.pos+=4)-4,!0)}fixed64(){return j.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return j.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 z(e){let t=e.field.localName,i=Object.create(null);return i[t]=function(e){let t=e.field;if(t.repeated)return[];if(void 0!==t.default)return t.default;switch(t.kind){case"enum":return t.T.values[0].no;case"scalar":return F(t.T,t.L);case"message":let i=t.T,n=new i;return i.fieldWrapper?i.fieldWrapper.unwrapField(n):n;case"map":throw"map fields are not allowed to be extensions"}}(e),[i,()=>i[t]]}let W="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),H=[];for(let e=0;e<W.length;e++)H[W[e].charCodeAt(0)]=e;H["-".charCodeAt(0)]=W.indexOf("+"),H["_".charCodeAt(0)]=W.indexOf("/");let G={dec(e){let t=3*e.length/4;"="==e[e.length-2]?t-=2:"="==e[e.length-1]&&(t-=1);let i=new Uint8Array(t),n=0,r=0,s,o=0;for(let t=0;t<e.length;t++){if(void 0===(s=H[e.charCodeAt(t)]))switch(e[t]){case"=":r=0;case"\n":case"\r":case" ":case" ":continue;default:throw Error("invalid base64 string.")}switch(r){case 0:o=s,r=1;break;case 1:i[n++]=o<<2|(48&s)>>4,o=s,r=2;break;case 2:i[n++]=(15&o)<<4|(60&s)>>2,o=s,r=3;break;case 3:i[n++]=(3&o)<<6|s,r=0}}if(1==r)throw Error("invalid base64 string.");return i.subarray(0,n)},enc(e){let t="",i=0,n,r=0;for(let s=0;s<e.length;s++)switch(n=e[s],i){case 0:t+=W[n>>2],r=(3&n)<<4,i=1;break;case 1:t+=W[r|n>>4],r=(15&n)<<2,i=2;break;case 2:t+=W[r|n>>6]+W[63&n],i=0}return i&&(t+=W[r]+"=",1==i&&(t+="=")),t}};function $(e,t){let i=e.getType();return t.extendee.typeName===i.typeName&&!!i.runtime.bin.listUnknownFields(e).find(e=>e.no==t.field.no)}function K(e,t){b(e.extendee.typeName==t.getType().typeName,"extension ".concat(e.typeName," can only be applied to message ").concat(e.extendee.typeName))}function J(e,t){let i=e.localName;if(e.repeated)return t[i].length>0;if(e.oneof)return t[e.oneof.localName].case===i;switch(e.kind){case"enum":case"scalar":if(e.opt||e.req)return void 0!==t[i];if("enum"==e.kind)return t[i]!==e.T.values[0].no;return!V(e.T,t[i]);case"message":return void 0!==t[i];case"map":return Object.keys(t[i]).length>0}}function X(e,t){let i=e.localName,n=!e.opt&&!e.req;if(e.repeated)t[i]=[];else if(e.oneof)t[e.oneof.localName]={case:void 0};else switch(e.kind){case"map":t[i]={};break;case"enum":t[i]=n?e.T.values[0].no:void 0;break;case"scalar":t[i]=n?F(e.T,e.L):void 0;break;case"message":t[i]=void 0}}function Y(e,t){if(null===e||"object"!=typeof e||!Object.getOwnPropertyNames(x.prototype).every(t=>t in e&&"function"==typeof e[t]))return!1;let i=e.getType();return null!==i&&"function"==typeof i&&"typeName"in i&&"string"==typeof i.typeName&&(void 0===t||i.typeName==t.typeName)}function Q(e,t){return Y(t)||!e.fieldWrapper?t:e.fieldWrapper.wrapField(t)}oM.DOUBLE,oM.FLOAT,oM.INT64,oM.UINT64,oM.INT32,oM.UINT32,oM.BOOL,oM.STRING,oM.BYTES;let Z={ignoreUnknownFields:!1},ee={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0},et=Symbol(),ei=Symbol();function en(e){if(null===e)return"null";switch(typeof e){case"object":return Array.isArray(e)?"array":"object";case"string":return e.length>100?"string":'"'.concat(e.split('"').join('\\"'),'"');default:return String(e)}}function er(e,t,i,n,r){let s=i.localName;if(i.repeated){if(b("map"!=i.kind),null===t)return;if(!Array.isArray(t))throw Error("cannot decode field ".concat(r.typeName,".").concat(i.name," from JSON: ").concat(en(t)));let o=e[s];for(let e of t){if(null===e)throw Error("cannot decode field ".concat(r.typeName,".").concat(i.name," from JSON: ").concat(en(e)));switch(i.kind){case"message":o.push(i.T.fromJson(e,n));break;case"enum":let t=eo(i.T,e,n.ignoreUnknownFields,!0);t!==ei&&o.push(t);break;case"scalar":try{o.push(es(i.T,e,i.L,!0))}catch(n){let t="cannot decode field ".concat(r.typeName,".").concat(i.name," from JSON: ").concat(en(e));throw n instanceof Error&&n.message.length>0&&(t+=": ".concat(n.message)),Error(t)}}}}else if("map"==i.kind){if(null===t)return;if("object"!=typeof t||Array.isArray(t))throw Error("cannot decode field ".concat(r.typeName,".").concat(i.name," from JSON: ").concat(en(t)));let o=e[s];for(let[e,s]of Object.entries(t)){let a;if(null===s)throw Error("cannot decode field ".concat(r.typeName,".").concat(i.name," from JSON: map value null"));try{a=function(e,t){if(e===oM.BOOL)switch(t){case"true":t=!0;break;case"false":t=!1}return es(e,t,oD.BIGINT,!0).toString()}(i.K,e)}catch(n){let e="cannot decode map key for field ".concat(r.typeName,".").concat(i.name," from JSON: ").concat(en(t));throw n instanceof Error&&n.message.length>0&&(e+=": ".concat(n.message)),Error(e)}switch(i.V.kind){case"message":o[a]=i.V.T.fromJson(s,n);break;case"enum":let l=eo(i.V.T,s,n.ignoreUnknownFields,!0);l!==ei&&(o[a]=l);break;case"scalar":try{o[a]=es(i.V.T,s,oD.BIGINT,!0)}catch(n){let e="cannot decode map value for field ".concat(r.typeName,".").concat(i.name," from JSON: ").concat(en(t));throw n instanceof Error&&n.message.length>0&&(e+=": ".concat(n.message)),Error(e)}}}}else switch(i.oneof&&(e=e[i.oneof.localName]={case:s},s="value"),i.kind){case"message":let o=i.T;if(null===t&&"google.protobuf.Value"!=o.typeName)return;let a=e[s];Y(a)?a.fromJson(t,n):(e[s]=a=o.fromJson(t,n),o.fieldWrapper&&!i.oneof&&(e[s]=o.fieldWrapper.unwrapField(a)));break;case"enum":let l=eo(i.T,t,n.ignoreUnknownFields,!1);switch(l){case et:X(i,e);break;case ei:break;default:e[s]=l}break;case"scalar":try{let n=es(i.T,t,i.L,!1);n===et?X(i,e):e[s]=n}catch(n){let e="cannot decode field ".concat(r.typeName,".").concat(i.name," from JSON: ").concat(en(t));throw n instanceof Error&&n.message.length>0&&(e+=": ".concat(n.message)),Error(e)}}}function es(e,t,i,n){if(null===t)return n?F(e,i):et;switch(e){case oM.DOUBLE:case oM.FLOAT:if("NaN"===t)return Number.NaN;if("Infinity"===t)return Number.POSITIVE_INFINITY;if("-Infinity"===t)return Number.NEGATIVE_INFINITY;if(""===t||"string"==typeof t&&t.trim().length!==t.length||"string"!=typeof t&&"number"!=typeof t)break;let r=Number(t);if(Number.isNaN(r)||!Number.isFinite(r))break;return e==oM.FLOAT&&S(r),r;case oM.INT32:case oM.FIXED32:case oM.SFIXED32:case oM.SINT32:case oM.UINT32:let s;if("number"==typeof t?s=t:"string"==typeof t&&t.length>0&&t.trim().length===t.length&&(s=Number(t)),void 0===s)break;return e==oM.UINT32||e==oM.FIXED32?T(s):k(s),s;case oM.INT64:case oM.SFIXED64:case oM.SINT64:if("number"!=typeof t&&"string"!=typeof t)break;let o=j.parse(t);return i?o.toString():o;case oM.FIXED64:case oM.UINT64:if("number"!=typeof t&&"string"!=typeof t)break;let a=j.uParse(t);return i?a.toString():a;case oM.BOOL:if("boolean"!=typeof t)break;return t;case oM.STRING:if("string"!=typeof t)break;try{encodeURIComponent(t)}catch(e){throw Error("invalid UTF8")}return t;case oM.BYTES:if(""===t)return new Uint8Array(0);if("string"!=typeof t)break;return G.dec(t)}throw Error()}function eo(e,t,i,n){if(null===t)return"google.protobuf.NullValue"==e.typeName?0:n?e.values[0].no:et;switch(typeof t){case"number":if(Number.isInteger(t))return t;break;case"string":let r=e.findName(t);if(void 0!==r)return r.no;if(i)return ei}throw Error("cannot decode enum ".concat(e.typeName," from JSON: ").concat(en(t)))}function ea(e,t,i){if("map"==e.kind){b("object"==typeof t&&null!=t);let n={},r=Object.entries(t);switch(e.V.kind){case"scalar":for(let[t,i]of r)n[t.toString()]=ec(e.V.T,i);break;case"message":for(let[e,t]of r)n[e.toString()]=t.toJson(i);break;case"enum":let s=e.V.T;for(let[e,t]of r)n[e.toString()]=el(s,t,i.enumAsInteger)}return i.emitDefaultValues||r.length>0?n:void 0}if(e.repeated){b(Array.isArray(t));let n=[];switch(e.kind){case"scalar":for(let i=0;i<t.length;i++)n.push(ec(e.T,t[i]));break;case"enum":for(let r=0;r<t.length;r++)n.push(el(e.T,t[r],i.enumAsInteger));break;case"message":for(let e=0;e<t.length;e++)n.push(t[e].toJson(i))}return i.emitDefaultValues||n.length>0?n:void 0}switch(e.kind){case"scalar":return ec(e.T,t);case"enum":return el(e.T,t,i.enumAsInteger);case"message":return Q(e.T,t).toJson(i)}}function el(e,t,i){var n;if(b("number"==typeof t),"google.protobuf.NullValue"==e.typeName)return null;if(i)return t;let r=e.findNumber(t);return null!==(n=null==r?void 0:r.name)&&void 0!==n?n:t}function ec(e,t){switch(e){case oM.INT32:case oM.SFIXED32:case oM.SINT32:case oM.FIXED32:case oM.UINT32:return b("number"==typeof t),t;case oM.FLOAT:case oM.DOUBLE:if(b("number"==typeof t),Number.isNaN(t))return"NaN";if(t===Number.POSITIVE_INFINITY)return"Infinity";if(t===Number.NEGATIVE_INFINITY)return"-Infinity";return t;case oM.STRING:return b("string"==typeof t),t;case oM.BOOL:return b("boolean"==typeof t),t;case oM.UINT64:case oM.FIXED64:case oM.INT64:case oM.SFIXED64:case oM.SINT64:return b("bigint"==typeof t||"string"==typeof t||"number"==typeof t),t.toString();case oM.BYTES:return b(t instanceof Uint8Array),G.enc(t)}}let ed=Symbol("@bufbuild/protobuf/unknown-fields"),eu={readUnknownFields:!0,readerFactory:e=>new q(e)},eh={writeUnknownFields:!0,writerFactory:()=>new B};function ep(e,t,i,n,r){let{repeated:s,localName:o}=i;switch(i.oneof&&((e=e[i.oneof.localName]).case!=o&&delete e.value,e.case=o,o="value"),i.kind){case"scalar":case"enum":let a="enum"==i.kind?oM.INT32:i.T,l=eg;if("scalar"==i.kind&&i.L>0&&(l=ef),s){let i=e[o];if(n==o_.LengthDelimited&&a!=oM.STRING&&a!=oM.BYTES){let e=t.uint32()+t.pos;for(;t.pos<e;)i.push(l(t,a))}else i.push(l(t,a))}else e[o]=l(t,a);break;case"message":let c=i.T;s?e[o].push(em(t,new c,r,i)):Y(e[o])?em(t,e[o],r,i):(e[o]=em(t,new c,r,i),!c.fieldWrapper||i.oneof||i.repeated||(e[o]=c.fieldWrapper.unwrapField(e[o])));break;case"map":let[d,u]=function(e,t,i){let n,r;let s=t.uint32(),o=t.pos+s;for(;t.pos<o;){let[s]=t.tag();switch(s){case 1:n=eg(t,e.K);break;case 2:switch(e.V.kind){case"scalar":r=eg(t,e.V.T);break;case"enum":r=t.int32();break;case"message":r=em(t,new e.V.T,i,void 0)}}}if(void 0===n&&(n=F(e.K,oD.BIGINT)),"string"!=typeof n&&"number"!=typeof n&&(n=n.toString()),void 0===r)switch(e.V.kind){case"scalar":r=F(e.V.T,oD.BIGINT);break;case"enum":r=e.V.T.values[0].no;break;case"message":r=new e.V.T}return[n,r]}(i,t,r);e[o][d]=u}}function em(e,t,i,n){let r=t.getType().runtime.bin,s=null==n?void 0:n.delimited;return r.readMessage(t,e,s?n.no:e.uint32(),i,s),t}function ef(e,t){let i=eg(e,t);return"bigint"==typeof i?i.toString():i}function eg(e,t){switch(t){case oM.STRING:return e.string();case oM.BOOL:return e.bool();case oM.DOUBLE:return e.double();case oM.FLOAT:return e.float();case oM.INT32:return e.int32();case oM.INT64:return e.int64();case oM.UINT64:return e.uint64();case oM.FIXED64:return e.fixed64();case oM.BYTES:return e.bytes();case oM.FIXED32:return e.fixed32();case oM.SFIXED32:return e.sfixed32();case oM.SFIXED64:return e.sfixed64();case oM.SINT64:return e.sint64();case oM.UINT32:return e.uint32();case oM.SINT32:return e.sint32()}}function ev(e,t,i,n){b(void 0!==t);let r=e.repeated;switch(e.kind){case"scalar":case"enum":let s="enum"==e.kind?oM.INT32:e.T;if(r){if(b(Array.isArray(t)),e.packed)(function(e,t,i,n){if(!n.length)return;e.tag(i,o_.LengthDelimited).fork();let[,r]=ek(t);for(let t=0;t<n.length;t++)e[r](n[t]);e.join()})(i,s,e.no,t);else for(let n of t)eb(i,s,e.no,n)}else eb(i,s,e.no,t);break;case"message":if(r)for(let r of(b(Array.isArray(t)),t))ey(i,n,e,r);else ey(i,n,e,t);break;case"map":for(let[r,s]of(b("object"==typeof t&&null!=t),Object.entries(t)))(function(e,t,i,n,r){e.tag(i.no,o_.LengthDelimited),e.fork();let s=n;switch(i.K){case oM.INT32:case oM.FIXED32:case oM.UINT32:case oM.SFIXED32:case oM.SINT32:s=Number.parseInt(n);break;case oM.BOOL:b("true"==n||"false"==n),s="true"==n}switch(eb(e,i.K,1,s),i.V.kind){case"scalar":eb(e,i.V.T,2,r);break;case"enum":eb(e,oM.INT32,2,r);break;case"message":b(void 0!==r),e.tag(2,o_.LengthDelimited).bytes(r.toBinary(t))}e.join()})(i,n,e,r,s)}}function ey(e,t,i,n){let r=Q(i.T,n);i.delimited?e.tag(i.no,o_.StartGroup).raw(r.toBinary(t)).tag(i.no,o_.EndGroup):e.tag(i.no,o_.LengthDelimited).bytes(r.toBinary(t))}function eb(e,t,i,n){b(void 0!==n);let[r,s]=ek(t);e.tag(i,r)[s](n)}function ek(e){let t=o_.Varint;switch(e){case oM.BYTES:case oM.STRING:t=o_.LengthDelimited;break;case oM.DOUBLE:case oM.FIXED64:case oM.SFIXED64:t=o_.Bit64;break;case oM.FIXED32:case oM.SFIXED32:case oM.FLOAT:t=o_.Bit32}return[t,oM[e].toLowerCase()]}function eT(e){if(void 0===e)return e;if(Y(e))return e.clone();if(e instanceof Uint8Array){let t=new Uint8Array(e.byteLength);return t.set(e),t}return e}function eS(e){return e instanceof Uint8Array?e:new Uint8Array(e)}class eC{constructor(e,t){this._fields=e,this._normalizer=t}findJsonName(e){if(!this.jsonNames){let e={};for(let t of this.list())e[t.jsonName]=e[t.name]=t;this.jsonNames=e}return this.jsonNames[e]}find(e){if(!this.numbers){let e={};for(let t of this.list())e[t.no]=t;this.numbers=e}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){let e;this.members=[];let t=this.members;for(let i of this.list())i.oneof?i.oneof!==e&&(e=i.oneof,t.push(e)):t.push(i)}return this.members}}function ew(e,t){let i=eP(e);return t?i:eI(eA(i))}let eE=eP;function eP(e){let t=!1,i=[];for(let n=0;n<e.length;n++){let r=e.charAt(n);switch(r){case"_":t=!0;break;case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":i.push(r),t=!1;break;default:t&&(t=!1,r=r.toUpperCase()),i.push(r)}}return i.join("")}let ex=new Set(["constructor","toString","toJSON","valueOf"]),eR=new Set(["getType","clone","equals","fromBinary","fromJson","fromJsonString","toBinary","toJson","toJsonString","toObject"]),eO=e=>"".concat(e,"$"),eA=e=>eR.has(e)?eO(e):e,eI=e=>ex.has(e)?eO(e):e;class eM{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=ew(e,!1)}addField(e){b(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 e=0;e<this.fields.length;e++)this._lookup[this.fields[e].localName]=this.fields[e]}return this._lookup[e]}}let eD=(oA=e=>new eC(e,e=>(function(e,t){var i,n,r,s,o,a;let l;let c=[];for(let t of"function"==typeof e?e():e){if(t.localName=ew(t.name,void 0!==t.oneof),t.jsonName=null!==(i=t.jsonName)&&void 0!==i?i:eE(t.name),t.repeated=null!==(n=t.repeated)&&void 0!==n&&n,"scalar"==t.kind&&(t.L=null!==(r=t.L)&&void 0!==r?r:oD.BIGINT),t.delimited=null!==(s=t.delimited)&&void 0!==s&&s,t.req=null!==(o=t.req)&&void 0!==o&&o,t.opt=null!==(a=t.opt)&&void 0!==a&&a,void 0===t.packed&&(t.packed="enum"==t.kind||"scalar"==t.kind&&t.T!=oM.BYTES&&t.T!=oM.STRING),void 0!==t.oneof){let e="string"==typeof t.oneof?t.oneof:t.oneof.name;l&&l.name==e||(l=new eM(e)),t.oneof=l,l.addField(t)}c.push(t)}return c})(e)),oI=e=>{for(let t of e.getType().fields.byMember()){if(t.opt)continue;let i=t.localName;if(t.repeated){e[i]=[];continue}switch(t.kind){case"oneof":e[i]={case:void 0};break;case"enum":e[i]=0;break;case"map":e[i]={};break;case"scalar":e[i]=F(t.T,t.L)}}},{syntax:"proto3",json:{makeReadOptions:function(e){return e?Object.assign(Object.assign({},Z),e):Z},makeWriteOptions:function(e){return e?Object.assign(Object.assign({},ee),e):ee},readMessage(e,t,i,n){if(null==t||Array.isArray(t)||"object"!=typeof t)throw Error("cannot decode message ".concat(e.typeName," from JSON: ").concat(en(t)));n=null!=n?n:new e;let r=new Map,s=i.typeRegistry;for(let[o,a]of Object.entries(t)){let t=e.fields.findJsonName(o);if(t){if(t.oneof){if(null===a&&"scalar"==t.kind)continue;let i=r.get(t.oneof);if(void 0!==i)throw Error("cannot decode message ".concat(e.typeName,' from JSON: multiple keys for oneof "').concat(t.oneof.name,'" present: "').concat(i,'", "').concat(o,'"'));r.set(t.oneof,o)}er(n,a,t,i,e)}else{let t=!1;if((null==s?void 0:s.findExtension)&&o.startsWith("[")&&o.endsWith("]")){let r=s.findExtension(o.substring(1,o.length-1));if(r&&r.extendee.typeName==e.typeName){t=!0;let[e,s]=z(r);er(e,a,r.field,i,r),function(e,t,i,n){K(t,e);let r=t.runtime.bin.makeReadOptions(n),s=t.runtime.bin.makeWriteOptions(n);if($(e,t)){let i=e.getType().runtime.bin.listUnknownFields(e).filter(e=>e.no!=t.field.no);for(let t of(e.getType().runtime.bin.discardUnknownFields(e),i))e.getType().runtime.bin.onUnknownField(e,t.no,t.wireType,t.data)}let o=s.writerFactory(),a=t.field;a.opt||a.repeated||"enum"!=a.kind&&"scalar"!=a.kind||(a=Object.assign(Object.assign({},t.field),{opt:!0})),t.runtime.bin.writeField(a,i,o,s);let l=r.readerFactory(o.finish());for(;l.pos<l.len;){let[t,i]=l.tag(),n=l.skip(i,t);e.getType().runtime.bin.onUnknownField(e,t,i,n)}}(n,r,s(),i)}}if(!t&&!i.ignoreUnknownFields)throw Error("cannot decode message ".concat(e.typeName,' from JSON: key "').concat(o,'" is unknown'))}}return n},writeMessage(e,t){let i;let n=e.getType(),r={};try{for(i of n.fields.byNumber()){if(!J(i,e)){var s;if(i.req)throw"required field not set";if(!t.emitDefaultValues||!((s=i).repeated||"map"==s.kind||!s.oneof&&"message"!=s.kind&&!s.opt&&!s.req))continue}let n=i.oneof?e[i.oneof.localName].value:e[i.localName],o=ea(i,n,t);void 0!==o&&(r[t.useProtoFieldName?i.name:i.jsonName]=o)}let o=t.typeRegistry;if(null==o?void 0:o.findExtensionFor)for(let i of n.runtime.bin.listUnknownFields(e)){let s=o.findExtensionFor(n.typeName,i.no);if(s&&$(e,s)){let i=function(e,t,i){K(t,e);let n=t.runtime.bin.makeReadOptions(i),r=function(e,t){if(!t.repeated&&("enum"==t.kind||"scalar"==t.kind)){for(let i=e.length-1;i>=0;--i)if(e[i].no==t.no)return[e[i]];return[]}return e.filter(e=>e.no===t.no)}(e.getType().runtime.bin.listUnknownFields(e),t.field),[s,o]=z(t);for(let e of r)t.runtime.bin.readField(s,n.readerFactory(e.data),t.field,e.wireType,n);return o()}(e,s,t),n=ea(s.field,i,t);void 0!==n&&(r[s.field.jsonName]=n)}}}catch(r){let e=i?"cannot encode field ".concat(n.typeName,".").concat(i.name," to JSON"):"cannot encode message ".concat(n.typeName," to JSON"),t=r instanceof Error?r.message:String(r);throw Error(e+(t.length>0?": ".concat(t):""))}return r},readScalar:(e,t,i)=>es(e,t,null!=i?i:oD.BIGINT,!0),writeScalar(e,t,i){if(void 0!==t&&(i||V(e,t)))return ec(e,t)},debug:en},bin:{makeReadOptions:function(e){return e?Object.assign(Object.assign({},eu),e):eu},makeWriteOptions:function(e){return e?Object.assign(Object.assign({},eh),e):eh},listUnknownFields(e){var t;return null!==(t=e[ed])&&void 0!==t?t:[]},discardUnknownFields(e){delete e[ed]},writeUnknownFields(e,t){let i=e[ed];if(i)for(let e of i)t.tag(e.no,e.wireType).raw(e.data)},onUnknownField(e,t,i,n){Array.isArray(e[ed])||(e[ed]=[]),e[ed].push({no:t,wireType:i,data:n})},readMessage(e,t,i,n,r){let s,o;let a=e.getType(),l=r?t.len:t.pos+i;for(;t.pos<l&&([s,o]=t.tag(),!0!==r||o!=o_.EndGroup);){let i=a.fields.find(s);if(!i){let i=t.skip(o,s);n.readUnknownFields&&this.onUnknownField(e,s,o,i);continue}ep(e,t,i,o,n)}if(r&&(o!=o_.EndGroup||s!==i))throw Error("invalid end group tag")},readField:ep,writeMessage(e,t,i){let n=e.getType();for(let r of n.fields.byNumber()){if(!J(r,e)){if(r.req)throw Error("cannot encode field ".concat(n.typeName,".").concat(r.name," to binary: required field not set"));continue}let s=r.oneof?e[r.oneof.localName].value:e[r.localName];ev(r,s,t,i)}return i.writeUnknownFields&&this.writeUnknownFields(e,t),t},writeField(e,t,i,n){void 0!==t&&ev(e,t,i,n)}},util:Object.assign(Object.assign({},{setEnumType:w,initPartial(e,t){if(void 0!==e)for(let i of t.getType().fields.byMember()){let n=i.localName;if(null!=e[n])switch(i.kind){case"oneof":let r=e[n].case;if(void 0===r)continue;let s=i.findField(r),o=e[n].value;s&&"message"==s.kind&&!Y(o,s.T)?o=new s.T(o):s&&"scalar"===s.kind&&s.T===oM.BYTES&&(o=eS(o)),t[n]={case:r,value:o};break;case"scalar":case"enum":let a=e[n];i.T===oM.BYTES&&(a=i.repeated?a.map(eS):eS(a)),t[n]=a;break;case"map":switch(i.V.kind){case"scalar":case"enum":if(i.V.T===oM.BYTES)for(let[i,r]of Object.entries(e[n]))t[n][i]=eS(r);else Object.assign(t[n],e[n]);break;case"message":let l=i.V.T;for(let i of Object.keys(e[n])){let r=e[n][i];l.fieldWrapper||(r=new l(r)),t[n][i]=r}}break;case"message":let c=i.T;if(i.repeated)t[n]=e[n].map(e=>Y(e,c)?e:new c(e));else{let i=e[n];c.fieldWrapper?"google.protobuf.BytesValue"===c.typeName?t[n]=eS(i):t[n]=i:t[n]=Y(i,c)?i:new c(i)}}}},equals:(e,t,i)=>t===i||!!t&&!!i&&e.fields.byMember().every(e=>{let n=t[e.localName],r=i[e.localName];if(e.repeated){if(n.length!==r.length)return!1;switch(e.kind){case"message":return n.every((t,i)=>e.T.equals(t,r[i]));case"scalar":return n.every((t,i)=>U(e.T,t,r[i]));case"enum":return n.every((e,t)=>U(oM.INT32,e,r[t]))}throw Error("repeated cannot contain ".concat(e.kind))}switch(e.kind){case"message":let s=n,o=r;return e.T.fieldWrapper&&(void 0===s||Y(s)||(s=e.T.fieldWrapper.wrapField(s)),void 0===o||Y(o)||(o=e.T.fieldWrapper.wrapField(o))),e.T.equals(s,o);case"enum":return U(oM.INT32,n,r);case"scalar":return U(e.T,n,r);case"oneof":if(n.case!==r.case)return!1;let a=e.findField(n.case);if(void 0===a)return!0;switch(a.kind){case"message":return a.T.equals(n.value,r.value);case"enum":return U(oM.INT32,n.value,r.value);case"scalar":return U(a.T,n.value,r.value)}throw Error("oneof cannot contain ".concat(a.kind));case"map":let l=Object.keys(n).concat(Object.keys(r));switch(e.V.kind){case"message":let c=e.V.T;return l.every(e=>c.equals(n[e],r[e]));case"enum":return l.every(e=>U(oM.INT32,n[e],r[e]));case"scalar":let d=e.V.T;return l.every(e=>U(d,n[e],r[e]))}}}),clone(e){let t=e.getType(),i=new t;for(let n of t.fields.byMember()){let t;let r=e[n.localName];if(n.repeated)t=r.map(eT);else if("map"==n.kind)for(let[e,s]of(t=i[n.localName],Object.entries(r)))t[e]=eT(s);else t="oneof"==n.kind?n.findField(r.case)?{case:r.case,value:eT(r.value)}:{case:void 0}:eT(r);i[n.localName]=t}for(let n of t.runtime.bin.listUnknownFields(e))t.runtime.bin.onUnknownField(i,n.no,n.wireType,n.data);return i}}),{newFieldList:oA,initFields:oI}),makeMessageType(e,t,i){return function(e,t,i,n){var r;let s=null!==(r=null==n?void 0:n.localName)&&void 0!==r?r:t.substring(t.lastIndexOf(".")+1),o={[s]:function(t){e.util.initFields(this),e.util.initPartial(t,this)}}[s];return Object.setPrototypeOf(o.prototype,new x),Object.assign(o,{runtime:e,typeName:t,fields:e.util.newFieldList(i),fromBinary:(e,t)=>new o().fromBinary(e,t),fromJson:(e,t)=>new o().fromJson(e,t),fromJsonString:(e,t)=>new o().fromJsonString(e,t),equals:(t,i)=>e.util.equals(o,t,i)}),o}(this,e,t,i)},makeEnum:function(e,t,i){let n={};for(let e of t){let t=P(e);n[t.localName]=t.no,n[t.no]=t.localName}return w(n,e,t),n},makeEnumType:E,getEnumType:function(e){let t=e[C];return b(t,"missing enum type on enum object"),t},makeExtension(e,t,i){var n;let r;return n=this,{typeName:e,extendee:t,get field(){if(!r){let t="function"==typeof i?i():i;t.name=e.split(".").pop(),t.jsonName="[".concat(e,"]"),r=n.util.newFieldList([t]).list()[0]}return r},runtime:n}}});class e_ extends x{constructor(e){super(),this.seconds=j.zero,this.nanos=0,eD.util.initPartial(e,this)}fromJson(e,t){if("string"!=typeof e)throw Error("cannot decode google.protobuf.Timestamp from JSON: ".concat(eD.json.debug(e)));let 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 Error("cannot decode google.protobuf.Timestamp from JSON: invalid RFC 3339 string");let n=Date.parse(i[1]+"-"+i[2]+"-"+i[3]+"T"+i[4]+":"+i[5]+":"+i[6]+(i[8]?i[8]:"Z"));if(Number.isNaN(n))throw Error("cannot decode google.protobuf.Timestamp from JSON: invalid RFC 3339 string");if(n<Date.parse("0001-01-01T00:00:00Z")||n>Date.parse("9999-12-31T23:59:59Z"))throw 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=j.parse(n/1e3),this.nanos=0,i[7]&&(this.nanos=parseInt("1"+i[7]+"0".repeat(9-i[7].length))-1e9),this}toJson(e){let t=1e3*Number(this.seconds);if(t<Date.parse("0001-01-01T00:00:00Z")||t>Date.parse("9999-12-31T23:59:59Z"))throw 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 Error("cannot encode google.protobuf.Timestamp to JSON: nanos must not be negative");let i="Z";if(this.nanos>0){let e=(this.nanos+1e9).toString().substring(1);i="000000"===e.substring(3)?"."+e.substring(0,3)+"Z":"000"===e.substring(6)?"."+e.substring(0,6)+"Z":"."+e+"Z"}return new Date(t).toISOString().replace(".000Z",i)}toDate(){return new Date(1e3*Number(this.seconds)+Math.ceil(this.nanos/1e6))}static now(){return e_.fromDate(new Date)}static fromDate(e){let t=e.getTime();return new e_({seconds:j.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 eD.util.equals(e_,e,t)}}e_.runtime=eD,e_.typeName="google.protobuf.Timestamp",e_.fields=eD.util.newFieldList(()=>[{no:1,name:"seconds",kind:"scalar",T:3},{no:2,name:"nanos",kind:"scalar",T:5}]);let eN=eD.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:eL,repeated:!0},{no:5,name:"events",kind:"message",T:eU,repeated:!0}]),eL=eD.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:ej,repeated:!0},{no:5,name:"rid",kind:"scalar",T:13}]),ej=eD.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}]),eU=eD.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}]),eF=eD.makeEnum("livekit.BackupCodecPolicy",[{no:0,name:"PREFER_REGRESSION"},{no:1,name:"SIMULCAST"},{no:2,name:"REGRESSION"}]),eV=eD.makeEnum("livekit.TrackType",[{no:0,name:"AUDIO"},{no:1,name:"VIDEO"},{no:2,name:"DATA"}]),eB=eD.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"}]),eq=eD.makeEnum("livekit.VideoQuality",[{no:0,name:"LOW"},{no:1,name:"MEDIUM"},{no:2,name:"HIGH"},{no:3,name:"OFF"}]),ez=eD.makeEnum("livekit.ConnectionQuality",[{no:0,name:"POOR"},{no:1,name:"GOOD"},{no:2,name:"EXCELLENT"},{no:3,name:"LOST"}]),eW=eD.makeEnum("livekit.ClientConfigSetting",[{no:0,name:"UNSET"},{no:1,name:"DISABLED"},{no:2,name:"ENABLED"}]),eH=eD.makeEnum("livekit.DisconnectReason",[{no:0,name:"UNKNOWN_REASON"},{no:1,name:"CLIENT_INITIATED"},{no:2,name:"DUPLICATE_IDENTITY"},{no:3,name:"SERVER_SHUTDOWN"},{no:4,name:"PARTICIPANT_REMOVED"},{no:5,name:"ROOM_DELETED"},{no:6,name:"STATE_MISMATCH"},{no:7,name:"JOIN_FAILURE"},{no:8,name:"MIGRATION"},{no:9,name:"SIGNAL_CLOSE"},{no:10,name:"ROOM_CLOSED"},{no:11,name:"USER_UNAVAILABLE"},{no:12,name:"USER_REJECTED"},{no:13,name:"SIP_TRUNK_FAILURE"},{no:14,name:"CONNECTION_TIMEOUT"},{no:15,name:"MEDIA_FAILURE"}]),eG=eD.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"}]),e$=eD.makeEnum("livekit.SubscriptionError",[{no:0,name:"SE_UNKNOWN"},{no:1,name:"SE_CODEC_UNSUPPORTED"},{no:2,name:"SE_TRACK_NOTFOUND"}]),eK=eD.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"}]),eJ=eD.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:eX,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:tv}]),eX=eD.makeMessageType("livekit.Codec",()=>[{no:1,name:"mime",kind:"scalar",T:9},{no:2,name:"fmtp_line",kind:"scalar",T:9}]),eY=eD.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:eD.getEnumType(eB),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}]),eQ=eD.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:eD.getEnumType(eZ)},{no:4,name:"tracks",kind:"message",T:e5,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:eY},{no:12,name:"region",kind:"scalar",T:9},{no:13,name:"is_publisher",kind:"scalar",T:8},{no:14,name:"kind",kind:"enum",T:eD.getEnumType(e0)},{no:15,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:16,name:"disconnect_reason",kind:"enum",T:eD.getEnumType(eH)},{no:18,name:"kind_details",kind:"enum",T:eD.getEnumType(e1),repeated:!0}]),eZ=eD.makeEnum("livekit.ParticipantInfo.State",[{no:0,name:"JOINING"},{no:1,name:"JOINED"},{no:2,name:"ACTIVE"},{no:3,name:"DISCONNECTED"}]),e0=eD.makeEnum("livekit.ParticipantInfo.Kind",[{no:0,name:"STANDARD"},{no:1,name:"INGRESS"},{no:2,name:"EGRESS"},{no:3,name:"SIP"},{no:4,name:"AGENT"}]),e1=eD.makeEnum("livekit.ParticipantInfo.KindDetail",[{no:0,name:"CLOUD_AGENT"},{no:1,name:"FORWARDED"}]),e2=eD.makeEnum("livekit.Encryption.Type",[{no:0,name:"NONE"},{no:1,name:"GCM"},{no:2,name:"CUSTOM"}]),e3=eD.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:e4,repeated:!0}]),e5=eD.makeMessageType("livekit.TrackInfo",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"type",kind:"enum",T:eD.getEnumType(eV)},{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:eD.getEnumType(eB)},{no:10,name:"layers",kind:"message",T:e4,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:e3,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:eD.getEnumType(e2)},{no:17,name:"stream",kind:"scalar",T:9},{no:18,name:"version",kind:"message",T:tv},{no:19,name:"audio_features",kind:"enum",T:eD.getEnumType(eK),repeated:!0},{no:20,name:"backup_codec_policy",kind:"enum",T:eD.getEnumType(eF)}]),e4=eD.makeMessageType("livekit.VideoLayer",()=>[{no:1,name:"quality",kind:"enum",T:eD.getEnumType(eq)},{no:2,name:"width",kind:"scalar",T:13},{no:3,name:"height",kind:"scalar",T:13},{no:4,name:"bitrate",kind:"scalar",T:13},{no:5,name:"ssrc",kind:"scalar",T:13},{no:6,name:"spatial_layer",kind:"scalar",T:5},{no:7,name:"rid",kind:"scalar",T:9}]),e6=eD.makeMessageType("livekit.DataPacket",()=>[{no:1,name:"kind",kind:"enum",T:eD.getEnumType(e9)},{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:te,oneof:"value"},{no:3,name:"speaker",kind:"message",T:e8,oneof:"value"},{no:6,name:"sip_dtmf",kind:"message",T:tt,oneof:"value"},{no:7,name:"transcription",kind:"message",T:ti,oneof:"value"},{no:8,name:"metrics",kind:"message",T:eN,oneof:"value"},{no:9,name:"chat_message",kind:"message",T:tr,oneof:"value"},{no:10,name:"rpc_request",kind:"message",T:ts,oneof:"value"},{no:11,name:"rpc_ack",kind:"message",T:to,oneof:"value"},{no:12,name:"rpc_response",kind:"message",T:ta,oneof:"value"},{no:13,name:"stream_header",kind:"message",T:tT,oneof:"value"},{no:14,name:"stream_chunk",kind:"message",T:tS,oneof:"value"},{no:15,name:"stream_trailer",kind:"message",T:tC,oneof:"value"},{no:16,name:"sequence",kind:"scalar",T:13},{no:17,name:"participant_sid",kind:"scalar",T:9}]),e9=eD.makeEnum("livekit.DataPacket.Kind",[{no:0,name:"RELIABLE"},{no:1,name:"LOSSY"}]),e8=eD.makeMessageType("livekit.ActiveSpeakerUpdate",()=>[{no:1,name:"speakers",kind:"message",T:e7,repeated:!0}]),e7=eD.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}]),te=eD.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}]),tt=eD.makeMessageType("livekit.SipDTMF",()=>[{no:3,name:"code",kind:"scalar",T:13},{no:4,name:"digit",kind:"scalar",T:9}]),ti=eD.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:tn,repeated:!0}]),tn=eD.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}]),tr=eD.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}]),ts=eD.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}]),to=eD.makeMessageType("livekit.RpcAck",()=>[{no:1,name:"request_id",kind:"scalar",T:9}]),ta=eD.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:tl,oneof:"value"}]),tl=eD.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}]),tc=eD.makeMessageType("livekit.ParticipantTracks",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"track_sids",kind:"scalar",T:9,repeated:!0}]),td=eD.makeMessageType("livekit.ServerInfo",()=>[{no:1,name:"edition",kind:"enum",T:eD.getEnumType(tu)},{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}]),tu=eD.makeEnum("livekit.ServerInfo.Edition",[{no:0,name:"Standard"},{no:1,name:"Cloud"}]),th=eD.makeMessageType("livekit.ClientInfo",()=>[{no:1,name:"sdk",kind:"enum",T:eD.getEnumType(tp)},{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}]),tp=eD.makeEnum("livekit.ClientInfo.SDK",[{no:0,name:"UNKNOWN"},{no:1,name:"JS"},{no:2,name:"SWIFT"},{no:3,name:"ANDROID"},{no:4,name:"FLUTTER"},{no:5,name:"GO"},{no:6,name:"UNITY"},{no:7,name:"REACT_NATIVE"},{no:8,name:"RUST"},{no:9,name:"PYTHON"},{no:10,name:"CPP"},{no:11,name:"UNITY_WEB"},{no:12,name:"NODE"},{no:13,name:"UNREAL"},{no:14,name:"ESP32"}]),tm=eD.makeMessageType("livekit.ClientConfiguration",()=>[{no:1,name:"video",kind:"message",T:tf},{no:2,name:"screen",kind:"message",T:tf},{no:3,name:"resume_connection",kind:"enum",T:eD.getEnumType(eW)},{no:4,name:"disabled_codecs",kind:"message",T:tg},{no:5,name:"force_relay",kind:"enum",T:eD.getEnumType(eW)}]),tf=eD.makeMessageType("livekit.VideoConfiguration",()=>[{no:1,name:"hardware_encoder",kind:"enum",T:eD.getEnumType(eW)}]),tg=eD.makeMessageType("livekit.DisabledCodecs",()=>[{no:1,name:"codecs",kind:"message",T:eX,repeated:!0},{no:2,name:"publish",kind:"message",T:eX,repeated:!0}]),tv=eD.makeMessageType("livekit.TimedVersion",()=>[{no:1,name:"unix_micro",kind:"scalar",T:3},{no:2,name:"ticks",kind:"scalar",T:5}]),ty=eD.makeEnum("livekit.DataStream.OperationType",[{no:0,name:"CREATE"},{no:1,name:"UPDATE"},{no:2,name:"DELETE"},{no:3,name:"REACTION"}]),tb=eD.makeMessageType("livekit.DataStream.TextHeader",()=>[{no:1,name:"operation_type",kind:"enum",T:eD.getEnumType(ty)},{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"}),tk=eD.makeMessageType("livekit.DataStream.ByteHeader",()=>[{no:1,name:"name",kind:"scalar",T:9}],{localName:"DataStream_ByteHeader"}),tT=eD.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:eD.getEnumType(e2)},{no:8,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:9,name:"text_header",kind:"message",T:tb,oneof:"content_header"},{no:10,name:"byte_header",kind:"message",T:tk,oneof:"content_header"}],{localName:"DataStream_Header"}),tS=eD.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"}),tC=eD.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"}),tw=eD.makeEnum("livekit.SignalTarget",[{no:0,name:"PUBLISHER"},{no:1,name:"SUBSCRIBER"}]),tE=eD.makeEnum("livekit.StreamState",[{no:0,name:"ACTIVE"},{no:1,name:"PAUSED"}]),tP=eD.makeEnum("livekit.CandidateProtocol",[{no:0,name:"UDP"},{no:1,name:"TCP"},{no:2,name:"TLS"}]),tx=eD.makeMessageType("livekit.SignalRequest",()=>[{no:1,name:"offer",kind:"message",T:tj,oneof:"message"},{no:2,name:"answer",kind:"message",T:tj,oneof:"message"},{no:3,name:"trickle",kind:"message",T:tI,oneof:"message"},{no:4,name:"add_track",kind:"message",T:tA,oneof:"message"},{no:5,name:"mute",kind:"message",T:tM,oneof:"message"},{no:6,name:"subscription",kind:"message",T:tF,oneof:"message"},{no:7,name:"track_setting",kind:"message",T:tV,oneof:"message"},{no:8,name:"leave",kind:"message",T:tz,oneof:"message"},{no:10,name:"update_layers",kind:"message",T:tH,oneof:"message"},{no:11,name:"subscription_permission",kind:"message",T:t5,oneof:"message"},{no:12,name:"sync_state",kind:"message",T:t9,oneof:"message"},{no:13,name:"simulate",kind:"message",T:ie,oneof:"message"},{no:14,name:"ping",kind:"scalar",T:3,oneof:"message"},{no:15,name:"update_metadata",kind:"message",T:tG,oneof:"message"},{no:16,name:"ping_req",kind:"message",T:it,oneof:"message"},{no:17,name:"update_audio_track",kind:"message",T:tB,oneof:"message"},{no:18,name:"update_video_track",kind:"message",T:tq,oneof:"message"}]),tR=eD.makeMessageType("livekit.SignalResponse",()=>[{no:1,name:"join",kind:"message",T:tD,oneof:"message"},{no:2,name:"answer",kind:"message",T:tj,oneof:"message"},{no:3,name:"offer",kind:"message",T:tj,oneof:"message"},{no:4,name:"trickle",kind:"message",T:tI,oneof:"message"},{no:5,name:"update",kind:"message",T:tU,oneof:"message"},{no:6,name:"track_published",kind:"message",T:tN,oneof:"message"},{no:8,name:"leave",kind:"message",T:tz,oneof:"message"},{no:9,name:"mute",kind:"message",T:tM,oneof:"message"},{no:10,name:"speakers_changed",kind:"message",T:tK,oneof:"message"},{no:11,name:"room_update",kind:"message",T:tJ,oneof:"message"},{no:12,name:"connection_quality",kind:"message",T:tY,oneof:"message"},{no:13,name:"stream_state_update",kind:"message",T:tZ,oneof:"message"},{no:14,name:"subscribed_quality_update",kind:"message",T:t2,oneof:"message"},{no:15,name:"subscription_permission_update",kind:"message",T:t4,oneof:"message"},{no:16,name:"refresh_token",kind:"scalar",T:9,oneof:"message"},{no:17,name:"track_unpublished",kind:"message",T:tL,oneof:"message"},{no:18,name:"pong",kind:"scalar",T:3,oneof:"message"},{no:19,name:"reconnect",kind:"message",T:t_,oneof:"message"},{no:20,name:"pong_resp",kind:"message",T:ii,oneof:"message"},{no:21,name:"subscription_response",kind:"message",T:io,oneof:"message"},{no:22,name:"request_response",kind:"message",T:ia,oneof:"message"},{no:23,name:"track_subscribed",kind:"message",T:ic,oneof:"message"},{no:24,name:"room_moved",kind:"message",T:t6,oneof:"message"}]),tO=eD.makeMessageType("livekit.SimulcastCodec",()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"cid",kind:"scalar",T:9}]),tA=eD.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:eD.getEnumType(eV)},{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:eD.getEnumType(eB)},{no:9,name:"layers",kind:"message",T:e4,repeated:!0},{no:10,name:"simulcast_codecs",kind:"message",T:tO,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:eD.getEnumType(e2)},{no:15,name:"stream",kind:"scalar",T:9},{no:16,name:"backup_codec_policy",kind:"enum",T:eD.getEnumType(eF)},{no:17,name:"audio_features",kind:"enum",T:eD.getEnumType(eK),repeated:!0}]),tI=eD.makeMessageType("livekit.TrickleRequest",()=>[{no:1,name:"candidateInit",kind:"scalar",T:9},{no:2,name:"target",kind:"enum",T:eD.getEnumType(tw)},{no:3,name:"final",kind:"scalar",T:8}]),tM=eD.makeMessageType("livekit.MuteTrackRequest",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"muted",kind:"scalar",T:8}]),tD=eD.makeMessageType("livekit.JoinResponse",()=>[{no:1,name:"room",kind:"message",T:eJ},{no:2,name:"participant",kind:"message",T:eQ},{no:3,name:"other_participants",kind:"message",T:eQ,repeated:!0},{no:4,name:"server_version",kind:"scalar",T:9},{no:5,name:"ice_servers",kind:"message",T:t$,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:tm},{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:td},{no:13,name:"sif_trailer",kind:"scalar",T:12},{no:14,name:"enabled_publish_codecs",kind:"message",T:eX,repeated:!0},{no:15,name:"fast_publish",kind:"scalar",T:8}]),t_=eD.makeMessageType("livekit.ReconnectResponse",()=>[{no:1,name:"ice_servers",kind:"message",T:t$,repeated:!0},{no:2,name:"client_configuration",kind:"message",T:tm},{no:3,name:"server_info",kind:"message",T:td},{no:4,name:"last_message_seq",kind:"scalar",T:13}]),tN=eD.makeMessageType("livekit.TrackPublishedResponse",()=>[{no:1,name:"cid",kind:"scalar",T:9},{no:2,name:"track",kind:"message",T:e5}]),tL=eD.makeMessageType("livekit.TrackUnpublishedResponse",()=>[{no:1,name:"track_sid",kind:"scalar",T:9}]),tj=eD.makeMessageType("livekit.SessionDescription",()=>[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"sdp",kind:"scalar",T:9},{no:3,name:"id",kind:"scalar",T:13}]),tU=eD.makeMessageType("livekit.ParticipantUpdate",()=>[{no:1,name:"participants",kind:"message",T:eQ,repeated:!0}]),tF=eD.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:tc,repeated:!0}]),tV=eD.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:eD.getEnumType(eq)},{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}]),tB=eD.makeMessageType("livekit.UpdateLocalAudioTrack",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"features",kind:"enum",T:eD.getEnumType(eK),repeated:!0}]),tq=eD.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}]),tz=eD.makeMessageType("livekit.LeaveRequest",()=>[{no:1,name:"can_reconnect",kind:"scalar",T:8},{no:2,name:"reason",kind:"enum",T:eD.getEnumType(eH)},{no:3,name:"action",kind:"enum",T:eD.getEnumType(tW)},{no:4,name:"regions",kind:"message",T:ir}]),tW=eD.makeEnum("livekit.LeaveRequest.Action",[{no:0,name:"DISCONNECT"},{no:1,name:"RESUME"},{no:2,name:"RECONNECT"}]),tH=eD.makeMessageType("livekit.UpdateVideoLayers",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"layers",kind:"message",T:e4,repeated:!0}]),tG=eD.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}]),t$=eD.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}]),tK=eD.makeMessageType("livekit.SpeakersChanged",()=>[{no:1,name:"speakers",kind:"message",T:e7,repeated:!0}]),tJ=eD.makeMessageType("livekit.RoomUpdate",()=>[{no:1,name:"room",kind:"message",T:eJ}]),tX=eD.makeMessageType("livekit.ConnectionQualityInfo",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"quality",kind:"enum",T:eD.getEnumType(ez)},{no:3,name:"score",kind:"scalar",T:2}]),tY=eD.makeMessageType("livekit.ConnectionQualityUpdate",()=>[{no:1,name:"updates",kind:"message",T:tX,repeated:!0}]),tQ=eD.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:eD.getEnumType(tE)}]),tZ=eD.makeMessageType("livekit.StreamStateUpdate",()=>[{no:1,name:"stream_states",kind:"message",T:tQ,repeated:!0}]),t0=eD.makeMessageType("livekit.SubscribedQuality",()=>[{no:1,name:"quality",kind:"enum",T:eD.getEnumType(eq)},{no:2,name:"enabled",kind:"scalar",T:8}]),t1=eD.makeMessageType("livekit.SubscribedCodec",()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"qualities",kind:"message",T:t0,repeated:!0}]),t2=eD.makeMessageType("livekit.SubscribedQualityUpdate",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribed_qualities",kind:"message",T:t0,repeated:!0},{no:3,name:"subscribed_codecs",kind:"message",T:t1,repeated:!0}]),t3=eD.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}]),t5=eD.makeMessageType("livekit.SubscriptionPermission",()=>[{no:1,name:"all_participants",kind:"scalar",T:8},{no:2,name:"track_permissions",kind:"message",T:t3,repeated:!0}]),t4=eD.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}]),t6=eD.makeMessageType("livekit.RoomMovedResponse",()=>[{no:1,name:"room",kind:"message",T:eJ},{no:2,name:"token",kind:"scalar",T:9},{no:3,name:"participant",kind:"message",T:eQ},{no:4,name:"other_participants",kind:"message",T:eQ,repeated:!0}]),t9=eD.makeMessageType("livekit.SyncState",()=>[{no:1,name:"answer",kind:"message",T:tj},{no:2,name:"subscription",kind:"message",T:tF},{no:3,name:"publish_tracks",kind:"message",T:tN,repeated:!0},{no:4,name:"data_channels",kind:"message",T:t7,repeated:!0},{no:5,name:"offer",kind:"message",T:tj},{no:6,name:"track_sids_disabled",kind:"scalar",T:9,repeated:!0},{no:7,name:"datachannel_receive_states",kind:"message",T:t8,repeated:!0}]),t8=eD.makeMessageType("livekit.DataChannelReceiveState",()=>[{no:1,name:"publisher_sid",kind:"scalar",T:9},{no:2,name:"last_seq",kind:"scalar",T:13}]),t7=eD.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:eD.getEnumType(tw)}]),ie=eD.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:eD.getEnumType(tP),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"}]),it=eD.makeMessageType("livekit.Ping",()=>[{no:1,name:"timestamp",kind:"scalar",T:3},{no:2,name:"rtt",kind:"scalar",T:3}]),ii=eD.makeMessageType("livekit.Pong",()=>[{no:1,name:"last_ping_timestamp",kind:"scalar",T:3},{no:2,name:"timestamp",kind:"scalar",T:3}]),ir=eD.makeMessageType("livekit.RegionSettings",()=>[{no:1,name:"regions",kind:"message",T:is,repeated:!0}]),is=eD.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}]),io=eD.makeMessageType("livekit.SubscriptionResponse",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"err",kind:"enum",T:eD.getEnumType(e$)}]),ia=eD.makeMessageType("livekit.RequestResponse",()=>[{no:1,name:"request_id",kind:"scalar",T:13},{no:2,name:"reason",kind:"enum",T:eD.getEnumType(il)},{no:3,name:"message",kind:"scalar",T:9}]),il=eD.makeEnum("livekit.RequestResponse.Reason",[{no:0,name:"OK"},{no:1,name:"NOT_FOUND"},{no:2,name:"NOT_ALLOWED"},{no:3,name:"LIMIT_EXCEEDED"}]),ic=eD.makeMessageType("livekit.TrackSubscribed",()=>[{no:1,name:"track_sid",kind:"scalar",T:9}]);var id={exports:{}},iu=id.exports,ih=function(){var e;return oN||(oN=1,e=function(){var e=function(){},t="undefined",i=typeof window!==t&&typeof window.navigator!==t&&/Trident\/|MSIE /.test(window.navigator.userAgent),n=["trace","debug","info","warn","error"],r={},s=null;function o(e,t){var i=e[t];if("function"==typeof i.bind)return i.bind(e);try{return Function.prototype.bind.call(i,e)}catch(t){return function(){return Function.prototype.apply.apply(i,[e,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 l(){for(var i=this.getLevel(),r=0;r<n.length;r++){var s=n[r];this[s]=r<i?e:this.methodFactory(s,i,this.name)}if(this.log=this.debug,typeof console===t&&i<this.levels.SILENT)return"No console available for logging"}function c(e){return function(){typeof console!==t&&(l.call(this),this[e].apply(this,arguments))}}function d(n,r,s){var l;return"debug"===(l=n)&&(l="log"),typeof console!==t&&("trace"===l&&i?a:void 0!==console[l]?o(console,l):void 0!==console.log?o(console,"log"):e)||c.apply(this,arguments)}function u(e,i){var o,a,c,u=this,h="loglevel";function p(){var e;if(typeof window!==t&&h){try{e=window.localStorage[h]}catch(e){}if(typeof e===t)try{var i=window.document.cookie,n=encodeURIComponent(h),r=i.indexOf(n+"=");-1!==r&&(e=/^([^;]+)/.exec(i.slice(r+n.length+1))[1])}catch(e){}return void 0===u.levels[e]&&(e=void 0),e}}function m(e){var t=e;if("string"==typeof t&&void 0!==u.levels[t.toUpperCase()]&&(t=u.levels[t.toUpperCase()]),"number"==typeof t&&t>=0&&t<=u.levels.SILENT)return t;throw TypeError("log.setLevel() called with invalid level: "+e)}"string"==typeof e?h+=":"+e:"symbol"==typeof e&&(h=void 0),u.name=e,u.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},u.methodFactory=i||d,u.getLevel=function(){return null!=c?c:null!=a?a:o},u.setLevel=function(e,i){return c=m(e),!1!==i&&function(e){var i=(n[e]||"silent").toUpperCase();if(typeof window!==t&&h){try{window.localStorage[h]=i;return}catch(e){}try{window.document.cookie=encodeURIComponent(h)+"="+i+";"}catch(e){}}}(c),l.call(u)},u.setDefaultLevel=function(e){a=m(e),p()||u.setLevel(e,!1)},u.resetLevel=function(){c=null,function(){if(typeof window!==t&&h){try{window.localStorage.removeItem(h)}catch(e){}try{window.document.cookie=encodeURIComponent(h)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch(e){}}}(),l.call(u)},u.enableAll=function(e){u.setLevel(u.levels.TRACE,e)},u.disableAll=function(e){u.setLevel(u.levels.SILENT,e)},u.rebuild=function(){if(s!==u&&(o=m(s.getLevel())),l.call(u),s===u)for(var e in r)r[e].rebuild()},o=m(s?s.getLevel():"WARN");var f=p();null!=f&&(c=m(f)),l.call(u)}(s=new u).getLogger=function(e){if("symbol"!=typeof e&&"string"!=typeof e||""===e)throw TypeError("You must supply a name when creating a logger.");var t=r[e];return t||(t=r[e]=new u(e,s.methodFactory)),t};var h=typeof window!==t?window.log:void 0;return s.noConflict=function(){return typeof window!==t&&window.log===s&&(window.log=h),s},s.getLoggers=function(){return r},s.default=s,s},id.exports?id.exports=e():iu.log=e()),id.exports}();(function(e){e[e.trace=0]="trace",e[e.debug=1]="debug",e[e.info=2]="info",e[e.warn=3]="warn",e[e.error=4]="error",e[e.silent=5]="silent"})(oL||(oL={})),function(e){e.Default="livekit",e.Room="livekit-room",e.Participant="livekit-participant",e.Track="livekit-track",e.Publication="livekit-track-publication",e.Engine="livekit-engine",e.Signal="livekit-signal",e.PCManager="livekit-pc-manager",e.PCTransport="livekit-pc-transport",e.E2EE="lk-e2ee"}(oj||(oj={}));let ip=ih.getLogger("livekit");function im(e){let t=ih.getLogger(e);return t.setDefaultLevel(ip.getLevel()),t}Object.values(oj).map(e=>ih.getLogger(e)),ip.setDefaultLevel(oL.info);let ig=ih.getLogger("lk-e2ee"),iv=[0,300,1200,2700,4800,7e3,7e3,7e3,7e3,7e3];class iy{constructor(e){this._retryDelays=void 0!==e?[...e]:iv}nextRetryDelayInMs(e){if(e.retryCount>=this._retryDelays.length)return null;let t=this._retryDelays[e.retryCount];return e.retryCount<=1?t:t+1e3*Math.random()}}function ib(e,t,i,n){return new(i||(i=Promise))(function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):((t=e.value)instanceof i?t:new i(function(e){e(t)})).then(o,a)}l((n=n.apply(e,t||[])).next())})}function ik(e){if(!Symbol.asyncIterator)throw TypeError("Symbol.asyncIterator is not defined.");var t,i=e[Symbol.asyncIterator];return i?i.call(e):(e=function(e){var t="function"==typeof Symbol&&Symbol.iterator,i=t&&e[t],n=0;if(i)return i.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}(e),t={},n("next"),n("throw"),n("return"),t[Symbol.asyncIterator]=function(){return this},t);function n(i){t[i]=e[i]&&function(t){return new Promise(function(n,r){(function(e,t,i,n){Promise.resolve(n).then(function(t){e({value:t,done:i})},t)})(n,r,(t=e[i](t)).done,t.value)})}}}"function"==typeof SuppressedError&&SuppressedError;var iT={exports:{}},iS=function(){if(oU)return iT.exports;oU=1;var e,t="object"==typeof Reflect?Reflect:null,i=t&&"function"==typeof t.apply?t.apply:function(e,t,i){return Function.prototype.apply.call(e,t,i)};e=t&&"function"==typeof t.ownKeys?t.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var n=Number.isNaN||function(e){return e!=e};function r(){r.init.call(this)}iT.exports=r,iT.exports.once=function(e,t){return new Promise(function(i,n){var r;function s(i){e.removeListener(t,o),n(i)}function o(){"function"==typeof e.removeListener&&e.removeListener("error",s),i([].slice.call(arguments))}m(e,t,o,{once:!0}),"error"!==t&&(r={once:!0},"function"==typeof e.on&&m(e,"error",s,r))})},r.EventEmitter=r,r.prototype._events=void 0,r.prototype._eventsCount=0,r.prototype._maxListeners=void 0;var s=10;function o(e){if("function"!=typeof e)throw TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function a(e){return void 0===e._maxListeners?r.defaultMaxListeners:e._maxListeners}function l(e,t,i,n){if(o(i),void 0===(s=e._events)?(s=e._events=Object.create(null),e._eventsCount=0):(void 0!==s.newListener&&(e.emit("newListener",t,i.listener?i.listener:i),s=e._events),l=s[t]),void 0===l)l=s[t]=i,++e._eventsCount;else if("function"==typeof l?l=s[t]=n?[i,l]:[l,i]:n?l.unshift(i):l.push(i),(r=a(e))>0&&l.length>r&&!l.warned){l.warned=!0;var r,s,l,c=Error("Possible EventEmitter memory leak detected. "+l.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");c.name="MaxListenersExceededWarning",c.emitter=e,c.type=t,c.count=l.length,console&&console.warn&&console.warn(c)}return e}function c(){if(!this.fired)return(this.target.removeListener(this.type,this.wrapFn),this.fired=!0,0==arguments.length)?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function d(e,t,i){var n={fired:!1,wrapFn:void 0,target:e,type:t,listener:i},r=c.bind(n);return r.listener=i,n.wrapFn=r,r}function u(e,t,i){var n=e._events;if(void 0===n)return[];var r=n[t];return void 0===r?[]:"function"==typeof r?i?[r.listener||r]:[r]:i?function(e){for(var t=Array(e.length),i=0;i<t.length;++i)t[i]=e[i].listener||e[i];return t}(r):p(r,r.length)}function h(e){var t=this._events;if(void 0!==t){var i=t[e];if("function"==typeof i)return 1;if(void 0!==i)return i.length}return 0}function p(e,t){for(var i=Array(t),n=0;n<t;++n)i[n]=e[n];return i}function m(e,t,i,n){if("function"==typeof e.on)n.once?e.once(t,i):e.on(t,i);else if("function"==typeof e.addEventListener)e.addEventListener(t,function r(s){n.once&&e.removeEventListener(t,r),i(s)});else throw TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof e)}return Object.defineProperty(r,"defaultMaxListeners",{enumerable:!0,get:function(){return s},set:function(e){if("number"!=typeof e||e<0||n(e))throw RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+e+".");s=e}}),r.init=function(){(void 0===this._events||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},r.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||n(e))throw RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+e+".");return this._maxListeners=e,this},r.prototype.getMaxListeners=function(){return a(this)},r.prototype.emit=function(e){for(var t=[],n=1;n<arguments.length;n++)t.push(arguments[n]);var r="error"===e,s=this._events;if(void 0!==s)r=r&&void 0===s.error;else if(!r)return!1;if(r){if(t.length>0&&(o=t[0]),o instanceof Error)throw o;var o,a=Error("Unhandled error."+(o?" ("+o.message+")":""));throw a.context=o,a}var l=s[e];if(void 0===l)return!1;if("function"==typeof l)i(l,this,t);else for(var c=l.length,d=p(l,c),n=0;n<c;++n)i(d[n],this,t);return!0},r.prototype.addListener=function(e,t){return l(this,e,t,!1)},r.prototype.on=r.prototype.addListener,r.prototype.prependListener=function(e,t){return l(this,e,t,!0)},r.prototype.once=function(e,t){return o(t),this.on(e,d(this,e,t)),this},r.prototype.prependOnceListener=function(e,t){return o(t),this.prependListener(e,d(this,e,t)),this},r.prototype.removeListener=function(e,t){var i,n,r,s,a;if(o(t),void 0===(n=this._events)||void 0===(i=n[e]))return this;if(i===t||i.listener===t)0==--this._eventsCount?this._events=Object.create(null):(delete n[e],n.removeListener&&this.emit("removeListener",e,i.listener||t));else if("function"!=typeof i){for(r=-1,s=i.length-1;s>=0;s--)if(i[s]===t||i[s].listener===t){a=i[s].listener,r=s;break}if(r<0)return this;0===r?i.shift():function(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}(i,r),1===i.length&&(n[e]=i[0]),void 0!==n.removeListener&&this.emit("removeListener",e,a||t)}return this},r.prototype.off=r.prototype.removeListener,r.prototype.removeAllListeners=function(e){var t,i,n;if(void 0===(i=this._events))return this;if(void 0===i.removeListener)return 0==arguments.length?(this._events=Object.create(null),this._eventsCount=0):void 0!==i[e]&&(0==--this._eventsCount?this._events=Object.create(null):delete i[e]),this;if(0==arguments.length){var r,s=Object.keys(i);for(n=0;n<s.length;++n)"removeListener"!==(r=s[n])&&this.removeAllListeners(r);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if("function"==typeof(t=i[e]))this.removeListener(e,t);else if(void 0!==t)for(n=t.length-1;n>=0;n--)this.removeListener(e,t[n]);return this},r.prototype.listeners=function(e){return u(this,e,!0)},r.prototype.rawListeners=function(e){return u(this,e,!1)},r.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):h.call(e,t)},r.prototype.listenerCount=h,r.prototype.eventNames=function(){return this._eventsCount>0?e(this._events):[]},iT.exports}();let iC=!0,iw=!0;function iE(e,t,i){let n=e.match(t);return n&&n.length>=i&&parseFloat(n[i],10)}function iP(e,t,i){if(!e.RTCPeerConnection)return;let n=e.RTCPeerConnection.prototype,r=n.addEventListener;n.addEventListener=function(e,n){if(e!==t)return r.apply(this,arguments);let s=e=>{let t=i(e);t&&(n.handleEvent?n.handleEvent(t):n(t))};return this._eventMap=this._eventMap||{},this._eventMap[t]||(this._eventMap[t]=new Map),this._eventMap[t].set(n,s),r.apply(this,[e,s])};let s=n.removeEventListener;n.removeEventListener=function(e,i){if(e!==t||!this._eventMap||!this._eventMap[t]||!this._eventMap[t].has(i))return s.apply(this,arguments);let n=this._eventMap[t].get(i);return this._eventMap[t].delete(i),0===this._eventMap[t].size&&delete this._eventMap[t],0===Object.keys(this._eventMap).length&&delete this._eventMap,s.apply(this,[e,n])},Object.defineProperty(n,"on"+t,{get(){return this["_on"+t]},set(e){this["_on"+t]&&(this.removeEventListener(t,this["_on"+t]),delete this["_on"+t]),e&&this.addEventListener(t,this["_on"+t]=e)},enumerable:!0,configurable:!0})}function ix(e){return"boolean"!=typeof e?Error("Argument type: "+typeof e+". Please use a boolean."):(iC=e,e?"adapter.js logging disabled":"adapter.js logging enabled")}function iR(e){return"boolean"!=typeof e?Error("Argument type: "+typeof e+". Please use a boolean."):(iw=!e,"adapter.js deprecation warnings "+(e?"disabled":"enabled"))}function iO(){"object"!=typeof window||iC||"undefined"==typeof console||"function"!=typeof console.log||console.log.apply(console,arguments)}function iA(e,t){iw&&console.warn(e+" is deprecated, please use "+t+" instead.")}function iI(e){return"[object Object]"===Object.prototype.toString.call(e)}function iM(e,t,i){let n=i?"outbound-rtp":"inbound-rtp",r=new Map;if(null===t)return r;let s=[];return e.forEach(e=>{"track"===e.type&&e.trackIdentifier===t.id&&s.push(e)}),s.forEach(t=>{e.forEach(i=>{i.type===n&&i.trackId===t.id&&function e(t,i,n){!i||n.has(i.id)||(n.set(i.id,i),Object.keys(i).forEach(r=>{r.endsWith("Id")?e(t,t.get(i[r]),n):r.endsWith("Ids")&&i[r].forEach(i=>{e(t,t.get(i),n)})}))}(e,i,r)})}),r}function iD(e,t){let i=e&&e.navigator;if(!i.mediaDevices)return;let n=function(e){if("object"!=typeof e||e.mandatory||e.optional)return e;let t={};return Object.keys(e).forEach(i=>{if("require"===i||"advanced"===i||"mediaSource"===i)return;let n="object"==typeof e[i]?e[i]:{ideal:e[i]};void 0!==n.exact&&"number"==typeof n.exact&&(n.min=n.max=n.exact);let r=function(e,t){return e?e+t.charAt(0).toUpperCase()+t.slice(1):"deviceId"===t?"sourceId":t};if(void 0!==n.ideal){t.optional=t.optional||[];let e={};"number"==typeof n.ideal?(e[r("min",i)]=n.ideal,t.optional.push(e),(e={})[r("max",i)]=n.ideal):e[r("",i)]=n.ideal,t.optional.push(e)}void 0!==n.exact&&"number"!=typeof n.exact?(t.mandatory=t.mandatory||{},t.mandatory[r("",i)]=n.exact):["min","max"].forEach(e=>{void 0!==n[e]&&(t.mandatory=t.mandatory||{},t.mandatory[r(e,i)]=n[e])})}),e.advanced&&(t.optional=(t.optional||[]).concat(e.advanced)),t},r=function(e,r){if(t.version>=61)return r(e);if((e=JSON.parse(JSON.stringify(e)))&&"object"==typeof e.audio){let t=function(e,t,i){t in e&&!(i in e)&&(e[i]=e[t],delete e[t])};t((e=JSON.parse(JSON.stringify(e))).audio,"autoGainControl","googAutoGainControl"),t(e.audio,"noiseSuppression","googNoiseSuppression"),e.audio=n(e.audio)}if(e&&"object"==typeof e.video){let s=e.video.facingMode;s=s&&("object"==typeof s?s:{ideal:s});let o=t.version<66;if(s&&("user"===s.exact||"environment"===s.exact||"user"===s.ideal||"environment"===s.ideal)&&!(i.mediaDevices.getSupportedConstraints&&i.mediaDevices.getSupportedConstraints().facingMode&&!o)){let t;if(delete e.video.facingMode,"environment"===s.exact||"environment"===s.ideal?t=["back","rear"]:("user"===s.exact||"user"===s.ideal)&&(t=["front"]),t)return i.mediaDevices.enumerateDevices().then(i=>{let o=(i=i.filter(e=>"videoinput"===e.kind)).find(e=>t.some(t=>e.label.toLowerCase().includes(t)));return!o&&i.length&&t.includes("back")&&(o=i[i.length-1]),o&&(e.video.deviceId=s.exact?{exact:o.deviceId}:{ideal:o.deviceId}),e.video=n(e.video),iO("chrome: "+JSON.stringify(e)),r(e)})}e.video=n(e.video)}return iO("chrome: "+JSON.stringify(e)),r(e)},s=function(e){return t.version>=64?e:{name:({PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"})[e.name]||e.name,message:e.message,constraint:e.constraint||e.constraintName,toString(){return this.name+(this.message&&": ")+this.message}}};if(i.getUserMedia=(function(e,t,n){r(e,e=>{i.webkitGetUserMedia(e,t,e=>{n&&n(s(e))})})}).bind(i),i.mediaDevices.getUserMedia){let e=i.mediaDevices.getUserMedia.bind(i.mediaDevices);i.mediaDevices.getUserMedia=function(t){return r(t,t=>e(t).then(e=>{if(t.audio&&!e.getAudioTracks().length||t.video&&!e.getVideoTracks().length)throw e.getTracks().forEach(e=>{e.stop()}),new DOMException("","NotFoundError");return e},e=>Promise.reject(s(e))))}}}function i_(e){e.MediaStream=e.MediaStream||e.webkitMediaStream}function iN(e){if("object"!=typeof e||!e.RTCPeerConnection||"ontrack"in e.RTCPeerConnection.prototype)iP(e,"track",e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e));else{Object.defineProperty(e.RTCPeerConnection.prototype,"ontrack",{get(){return this._ontrack},set(e){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=e)},enumerable:!0,configurable:!0});let t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=t=>{t.stream.addEventListener("addtrack",i=>{let n;n=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find(e=>e.track&&e.track.id===i.track.id):{track:i.track};let r=new Event("track");r.track=i.track,r.receiver=n,r.transceiver={receiver:n},r.streams=[t.stream],this.dispatchEvent(r)}),t.stream.getTracks().forEach(i=>{let n;n=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find(e=>e.track&&e.track.id===i.id):{track:i};let r=new Event("track");r.track=i,r.receiver=n,r.transceiver={receiver:n},r.streams=[t.stream],this.dispatchEvent(r)})},this.addEventListener("addstream",this._ontrackpoly)),t.apply(this,arguments)}}}function iL(e){if("object"==typeof e&&e.RTCPeerConnection&&!("getSenders"in e.RTCPeerConnection.prototype)&&"createDTMFSender"in e.RTCPeerConnection.prototype){let t=function(e,t){return{track:t,get dtmf(){return void 0===this._dtmf&&("audio"===t.kind?this._dtmf=e.createDTMFSender(t):this._dtmf=null),this._dtmf},_pc:e}};if(!e.RTCPeerConnection.prototype.getSenders){e.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};let i=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,n){let r=i.apply(this,arguments);return r||(r=t(this,e),this._senders.push(r)),r};let n=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){n.apply(this,arguments);let t=this._senders.indexOf(e);-1!==t&&this._senders.splice(t,1)}}let i=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._senders=this._senders||[],i.apply(this,[e]),e.getTracks().forEach(e=>{this._senders.push(t(this,e))})};let n=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){this._senders=this._senders||[],n.apply(this,[e]),e.getTracks().forEach(e=>{let t=this._senders.find(t=>t.track===e);t&&this._senders.splice(this._senders.indexOf(t),1)})}}else if("object"==typeof e&&e.RTCPeerConnection&&"getSenders"in e.RTCPeerConnection.prototype&&"createDTMFSender"in e.RTCPeerConnection.prototype&&e.RTCRtpSender&&!("dtmf"in e.RTCRtpSender.prototype)){let t=e.RTCPeerConnection.prototype.getSenders;e.RTCPeerConnection.prototype.getSenders=function(){let e=t.apply(this,[]);return e.forEach(e=>e._pc=this),e},Object.defineProperty(e.RTCRtpSender.prototype,"dtmf",{get(){return void 0===this._dtmf&&("audio"===this.track.kind?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}})}}function ij(e){if(!("object"==typeof e&&e.RTCPeerConnection&&e.RTCRtpSender&&e.RTCRtpReceiver))return;if(!("getStats"in e.RTCRtpSender.prototype)){let t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){let e=t.apply(this,[]);return e.forEach(e=>e._pc=this),e});let i=e.RTCPeerConnection.prototype.addTrack;i&&(e.RTCPeerConnection.prototype.addTrack=function(){let e=i.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){let e=this;return this._pc.getStats().then(t=>iM(t,e.track,!0))}}if(!("getStats"in e.RTCRtpReceiver.prototype)){let t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){let e=t.apply(this,[]);return e.forEach(e=>e._pc=this),e}),iP(e,"track",e=>(e.receiver._pc=e.srcElement,e)),e.RTCRtpReceiver.prototype.getStats=function(){let e=this;return this._pc.getStats().then(t=>iM(t,e.track,!1))}}if(!("getStats"in e.RTCRtpSender.prototype&&"getStats"in e.RTCRtpReceiver.prototype))return;let t=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof e.MediaStreamTrack){let e,t,i;let n=arguments[0];return(this.getSenders().forEach(t=>{t.track===n&&(e?i=!0:e=t)}),this.getReceivers().forEach(e=>(e.track===n&&(t?i=!0:t=e),e.track===n)),i||e&&t)?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):e?e.getStats():t?t.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return t.apply(this,arguments)}}function iU(e){e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map(e=>this._shimmedLocalStreams[e][0])};let t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,i){if(!i)return t.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};let n=t.apply(this,arguments);return this._shimmedLocalStreams[i.id]?-1===this._shimmedLocalStreams[i.id].indexOf(n)&&this._shimmedLocalStreams[i.id].push(n):this._shimmedLocalStreams[i.id]=[i,n],n};let i=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._shimmedLocalStreams=this._shimmedLocalStreams||{},e.getTracks().forEach(e=>{if(this.getSenders().find(t=>t.track===e))throw new DOMException("Track already exists.","InvalidAccessError")});let t=this.getSenders();i.apply(this,arguments);let n=this.getSenders().filter(e=>-1===t.indexOf(e));this._shimmedLocalStreams[e.id]=[e].concat(n)};let n=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[e.id],n.apply(this,arguments)};let r=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},e&&Object.keys(this._shimmedLocalStreams).forEach(t=>{let i=this._shimmedLocalStreams[t].indexOf(e);-1!==i&&this._shimmedLocalStreams[t].splice(i,1),1===this._shimmedLocalStreams[t].length&&delete this._shimmedLocalStreams[t]}),r.apply(this,arguments)}}function iF(e,t){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&t.version>=65)return iU(e);let i=e.RTCPeerConnection.prototype.getLocalStreams;e.RTCPeerConnection.prototype.getLocalStreams=function(){let e=i.apply(this);return this._reverseStreams=this._reverseStreams||{},e.map(e=>this._reverseStreams[e.id])};let n=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(t){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},t.getTracks().forEach(e=>{if(this.getSenders().find(t=>t.track===e))throw new DOMException("Track already exists.","InvalidAccessError")}),!this._reverseStreams[t.id]){let i=new e.MediaStream(t.getTracks());this._streams[t.id]=i,this._reverseStreams[i.id]=t,t=i}n.apply(this,[t])};let r=e.RTCPeerConnection.prototype.removeStream;function s(e,t){let i=t.sdp;return Object.keys(e._reverseStreams||[]).forEach(t=>{let n=e._reverseStreams[t],r=e._streams[n.id];i=i.replace(RegExp(r.id,"g"),n.id)}),new RTCSessionDescription({type:t.type,sdp:i})}e.RTCPeerConnection.prototype.removeStream=function(e){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},r.apply(this,[this._streams[e.id]||e]),delete this._reverseStreams[this._streams[e.id]?this._streams[e.id].id:e.id],delete this._streams[e.id]},e.RTCPeerConnection.prototype.addTrack=function(t,i){if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");let n=[].slice.call(arguments,1);if(1!==n.length||!n[0].getTracks().find(e=>e===t))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(e=>e.track===t))throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};let r=this._streams[i.id];if(r)r.addTrack(t),Promise.resolve().then(()=>{this.dispatchEvent(new Event("negotiationneeded"))});else{let n=new e.MediaStream([t]);this._streams[i.id]=n,this._reverseStreams[n.id]=i,this.addStream(n)}return this.getSenders().find(e=>e.track===t)},["createOffer","createAnswer"].forEach(function(t){let i=e.RTCPeerConnection.prototype[t];e.RTCPeerConnection.prototype[t]=({[t](){let e=arguments,t=arguments.length&&"function"==typeof arguments[0];return t?i.apply(this,[t=>{let i=s(this,t);e[0].apply(null,[i])},t=>{e[1]&&e[1].apply(null,t)},arguments[2]]):i.apply(this,arguments).then(e=>s(this,e))}})[t]});let o=e.RTCPeerConnection.prototype.setLocalDescription;e.RTCPeerConnection.prototype.setLocalDescription=function(){var e,t;let i;return arguments.length&&arguments[0].type&&(arguments[0]=(e=this,t=arguments[0],i=t.sdp,Object.keys(e._reverseStreams||[]).forEach(t=>{let n=e._reverseStreams[t],r=e._streams[n.id];i=i.replace(RegExp(n.id,"g"),r.id)}),new RTCSessionDescription({type:t.type,sdp:i}))),o.apply(this,arguments)};let a=Object.getOwnPropertyDescriptor(e.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(e.RTCPeerConnection.prototype,"localDescription",{get(){let e=a.get.apply(this);return""===e.type?e:s(this,e)}}),e.RTCPeerConnection.prototype.removeTrack=function(e){let t;if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!e._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(e._pc!==this)throw new DOMException("Sender was not created by this connection.","InvalidAccessError");this._streams=this._streams||{},Object.keys(this._streams).forEach(i=>{this._streams[i].getTracks().find(t=>e.track===t)&&(t=this._streams[i])}),t&&(1===t.getTracks().length?this.removeStream(this._reverseStreams[t.id]):t.removeTrack(e.track),this.dispatchEvent(new Event("negotiationneeded")))}}function iV(e,t){!e.RTCPeerConnection&&e.webkitRTCPeerConnection&&(e.RTCPeerConnection=e.webkitRTCPeerConnection),e.RTCPeerConnection&&t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(t){let i=e.RTCPeerConnection.prototype[t];e.RTCPeerConnection.prototype[t]=({[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),i.apply(this,arguments)}})[t]})}function iB(e,t){iP(e,"negotiationneeded",e=>{let i=e.target;if(!(t.version<72)&&(!i.getConfiguration||"plan-b"!==i.getConfiguration().sdpSemantics)||"stable"===i.signalingState)return e})}var iq=Object.freeze({__proto__:null,fixNegotiationNeeded:iB,shimAddTrackRemoveTrack:iF,shimAddTrackRemoveTrackWithNative:iU,shimGetSendersWithDtmf:iL,shimGetUserMedia:iD,shimMediaStream:i_,shimOnTrack:iN,shimPeerConnection:iV,shimSenderReceiverGetStats:ij});function iz(e,t){let i=e&&e.navigator,n=e&&e.MediaStreamTrack;if(i.getUserMedia=function(e,t,n){iA("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),i.mediaDevices.getUserMedia(e).then(t,n)},!(t.version>55&&"autoGainControl"in i.mediaDevices.getSupportedConstraints())){let e=function(e,t,i){t in e&&!(i in e)&&(e[i]=e[t],delete e[t])},t=i.mediaDevices.getUserMedia.bind(i.mediaDevices);if(i.mediaDevices.getUserMedia=function(i){return"object"==typeof i&&"object"==typeof i.audio&&(e((i=JSON.parse(JSON.stringify(i))).audio,"autoGainControl","mozAutoGainControl"),e(i.audio,"noiseSuppression","mozNoiseSuppression")),t(i)},n&&n.prototype.getSettings){let t=n.prototype.getSettings;n.prototype.getSettings=function(){let i=t.apply(this,arguments);return e(i,"mozAutoGainControl","autoGainControl"),e(i,"mozNoiseSuppression","noiseSuppression"),i}}if(n&&n.prototype.applyConstraints){let t=n.prototype.applyConstraints;n.prototype.applyConstraints=function(i){return"audio"===this.kind&&"object"==typeof i&&(e(i=JSON.parse(JSON.stringify(i)),"autoGainControl","mozAutoGainControl"),e(i,"noiseSuppression","mozNoiseSuppression")),t.apply(this,[i])}}}}function iW(e){"object"==typeof e&&e.RTCTrackEvent&&"receiver"in e.RTCTrackEvent.prototype&&!("transceiver"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function iH(e,t){if("object"!=typeof e||!(e.RTCPeerConnection||e.mozRTCPeerConnection))return;!e.RTCPeerConnection&&e.mozRTCPeerConnection&&(e.RTCPeerConnection=e.mozRTCPeerConnection),t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(t){let i=e.RTCPeerConnection.prototype[t];e.RTCPeerConnection.prototype[t]=({[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),i.apply(this,arguments)}})[t]});let i={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},n=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){let[e,r,s]=arguments;return n.apply(this,[e||null]).then(e=>{if(t.version<53&&!r)try{e.forEach(e=>{e.type=i[e.type]||e.type})}catch(t){if("TypeError"!==t.name)throw t;e.forEach((t,n)=>{e.set(n,Object.assign({},t,{type:i[t.type]||t.type}))})}return e}).then(r,s)}}function iG(e){if(!("object"==typeof e&&e.RTCPeerConnection&&e.RTCRtpSender)||e.RTCRtpSender&&"getStats"in e.RTCRtpSender.prototype)return;let t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){let e=t.apply(this,[]);return e.forEach(e=>e._pc=this),e});let i=e.RTCPeerConnection.prototype.addTrack;i&&(e.RTCPeerConnection.prototype.addTrack=function(){let e=i.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}function i$(e){if(!("object"==typeof e&&e.RTCPeerConnection&&e.RTCRtpSender)||e.RTCRtpSender&&"getStats"in e.RTCRtpReceiver.prototype)return;let t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){let e=t.apply(this,[]);return e.forEach(e=>e._pc=this),e}),iP(e,"track",e=>(e.receiver._pc=e.srcElement,e)),e.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function iK(e){!e.RTCPeerConnection||"removeStream"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.removeStream=function(e){iA("removeStream","removeTrack"),this.getSenders().forEach(t=>{t.track&&e.getTracks().includes(t.track)&&this.removeTrack(t)})})}function iJ(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel)}function iX(e){if(!("object"==typeof e&&e.RTCPeerConnection))return;let t=e.RTCPeerConnection.prototype.addTransceiver;t&&(e.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let e=arguments[1]&&arguments[1].sendEncodings;void 0===e&&(e=[]);let i=(e=[...e]).length>0;i&&e.forEach(e=>{if("rid"in e&&!/^[a-z0-9]{0,16}$/i.test(e.rid))throw TypeError("Invalid RID value provided.");if("scaleResolutionDownBy"in e&&!(parseFloat(e.scaleResolutionDownBy)>=1))throw RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in e&&!(parseFloat(e.maxFramerate)>=0))throw RangeError("max_framerate must be >= 0.0")});let n=t.apply(this,arguments);if(i){let{sender:t}=n,i=t.getParameters();"encodings"in i&&(1!==i.encodings.length||0!==Object.keys(i.encodings[0]).length)||(i.encodings=e,t.sendEncodings=e,this.setParametersPromises.push(t.setParameters(i).then(()=>{delete t.sendEncodings}).catch(()=>{delete t.sendEncodings})))}return n})}function iY(e){if(!("object"==typeof e&&e.RTCRtpSender))return;let t=e.RTCRtpSender.prototype.getParameters;t&&(e.RTCRtpSender.prototype.getParameters=function(){let e=t.apply(this,arguments);return"encodings"in e||(e.encodings=[].concat(this.sendEncodings||[{}])),e})}function iQ(e){if(!("object"==typeof e&&e.RTCPeerConnection))return;let t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>t.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):t.apply(this,arguments)}}function iZ(e){if(!("object"==typeof e&&e.RTCPeerConnection))return;let t=e.RTCPeerConnection.prototype.createAnswer;e.RTCPeerConnection.prototype.createAnswer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>t.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):t.apply(this,arguments)}}var i0=Object.freeze({__proto__:null,shimAddTransceiver:iX,shimCreateAnswer:iZ,shimCreateOffer:iQ,shimGetDisplayMedia:function(e,t){e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||!e.navigator.mediaDevices||(e.navigator.mediaDevices.getDisplayMedia=function(i){if(!(i&&i.video)){let e=new DOMException("getDisplayMedia without video constraints is undefined");return e.name="NotFoundError",e.code=8,Promise.reject(e)}return!0===i.video?i.video={mediaSource:t}:i.video.mediaSource=t,e.navigator.mediaDevices.getUserMedia(i)})},shimGetParameters:iY,shimGetUserMedia:iz,shimOnTrack:iW,shimPeerConnection:iH,shimRTCDataChannel:iJ,shimReceiverGetStats:i$,shimRemoveStream:iK,shimSenderGetStats:iG});function i1(e){if("object"==typeof e&&e.RTCPeerConnection){if("getLocalStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in e.RTCPeerConnection.prototype)){let t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addStream=function(e){this._localStreams||(this._localStreams=[]),this._localStreams.includes(e)||this._localStreams.push(e),e.getAudioTracks().forEach(i=>t.call(this,i,e)),e.getVideoTracks().forEach(i=>t.call(this,i,e))},e.RTCPeerConnection.prototype.addTrack=function(e){for(var i=arguments.length,n=Array(i>1?i-1:0),r=1;r<i;r++)n[r-1]=arguments[r];return n&&n.forEach(e=>{this._localStreams?this._localStreams.includes(e)||this._localStreams.push(e):this._localStreams=[e]}),t.apply(this,arguments)}}"removeStream"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.removeStream=function(e){this._localStreams||(this._localStreams=[]);let t=this._localStreams.indexOf(e);if(-1===t)return;this._localStreams.splice(t,1);let i=e.getTracks();this.getSenders().forEach(e=>{i.includes(e.track)&&this.removeTrack(e)})})}}function i2(e){if("object"==typeof e&&e.RTCPeerConnection&&("getRemoteStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]}),!("onaddstream"in e.RTCPeerConnection.prototype))){Object.defineProperty(e.RTCPeerConnection.prototype,"onaddstream",{get(){return this._onaddstream},set(e){this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=e),this.addEventListener("track",this._onaddstreampoly=e=>{e.streams.forEach(e=>{if(this._remoteStreams||(this._remoteStreams=[]),this._remoteStreams.includes(e))return;this._remoteStreams.push(e);let t=new Event("addstream");t.stream=e,this.dispatchEvent(t)})})}});let t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){let e=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(t){t.streams.forEach(t=>{if(e._remoteStreams||(e._remoteStreams=[]),e._remoteStreams.indexOf(t)>=0)return;e._remoteStreams.push(t);let i=new Event("addstream");i.stream=t,e.dispatchEvent(i)})}),t.apply(e,arguments)}}}function i3(e){if("object"!=typeof e||!e.RTCPeerConnection)return;let t=e.RTCPeerConnection.prototype,i=t.createOffer,n=t.createAnswer,r=t.setLocalDescription,s=t.setRemoteDescription,o=t.addIceCandidate;t.createOffer=function(e,t){let n=arguments.length>=2?arguments[2]:arguments[0],r=i.apply(this,[n]);return t?(r.then(e,t),Promise.resolve()):r},t.createAnswer=function(e,t){let i=arguments.length>=2?arguments[2]:arguments[0],r=n.apply(this,[i]);return t?(r.then(e,t),Promise.resolve()):r};let a=function(e,t,i){let n=r.apply(this,[e]);return i?(n.then(t,i),Promise.resolve()):n};t.setLocalDescription=a,a=function(e,t,i){let n=s.apply(this,[e]);return i?(n.then(t,i),Promise.resolve()):n},t.setRemoteDescription=a,a=function(e,t,i){let n=o.apply(this,[e]);return i?(n.then(t,i),Promise.resolve()):n},t.addIceCandidate=a}function i5(e){let t=e&&e.navigator;if(t.mediaDevices&&t.mediaDevices.getUserMedia){let e=t.mediaDevices,i=e.getUserMedia.bind(e);t.mediaDevices.getUserMedia=e=>i(i4(e))}!t.getUserMedia&&t.mediaDevices&&t.mediaDevices.getUserMedia&&(t.getUserMedia=(function(e,i,n){t.mediaDevices.getUserMedia(e).then(i,n)}).bind(t))}function i4(e){return e&&void 0!==e.video?Object.assign({},e,{video:function e(t){return iI(t)?Object.keys(t).reduce(function(i,n){let r=iI(t[n]),s=r?e(t[n]):t[n],o=r&&!Object.keys(s).length;return void 0===s||o?i:Object.assign(i,{[n]:s})},{}):t}(e.video)}):e}function i6(e){if(!e.RTCPeerConnection)return;let t=e.RTCPeerConnection;e.RTCPeerConnection=function(e,i){if(e&&e.iceServers){let t=[];for(let i=0;i<e.iceServers.length;i++){let n=e.iceServers[i];void 0===n.urls&&n.url?(iA("RTCIceServer.url","RTCIceServer.urls"),(n=JSON.parse(JSON.stringify(n))).urls=n.url,delete n.url,t.push(n)):t.push(e.iceServers[i])}e.iceServers=t}return new t(e,i)},e.RTCPeerConnection.prototype=t.prototype,"generateCertificate"in t&&Object.defineProperty(e.RTCPeerConnection,"generateCertificate",{get:()=>t.generateCertificate})}function i9(e){"object"==typeof e&&e.RTCTrackEvent&&"receiver"in e.RTCTrackEvent.prototype&&!("transceiver"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function i8(e){let t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(e){if(e){void 0!==e.offerToReceiveAudio&&(e.offerToReceiveAudio=!!e.offerToReceiveAudio);let t=this.getTransceivers().find(e=>"audio"===e.receiver.track.kind);!1===e.offerToReceiveAudio&&t?"sendrecv"===t.direction?t.setDirection?t.setDirection("sendonly"):t.direction="sendonly":"recvonly"===t.direction&&(t.setDirection?t.setDirection("inactive"):t.direction="inactive"):!0!==e.offerToReceiveAudio||t||this.addTransceiver("audio",{direction:"recvonly"}),void 0!==e.offerToReceiveVideo&&(e.offerToReceiveVideo=!!e.offerToReceiveVideo);let i=this.getTransceivers().find(e=>"video"===e.receiver.track.kind);!1===e.offerToReceiveVideo&&i?"sendrecv"===i.direction?i.setDirection?i.setDirection("sendonly"):i.direction="sendonly":"recvonly"===i.direction&&(i.setDirection?i.setDirection("inactive"):i.direction="inactive"):!0!==e.offerToReceiveVideo||i||this.addTransceiver("video",{direction:"recvonly"})}return t.apply(this,arguments)}}function i7(e){"object"!=typeof e||e.AudioContext||(e.AudioContext=e.webkitAudioContext)}var ne=Object.freeze({__proto__:null,shimAudioContext:i7,shimCallbacksAPI:i3,shimConstraints:i4,shimCreateOfferLegacy:i8,shimGetUserMedia:i5,shimLocalStreamsAPI:i1,shimRTCIceServerUrls:i6,shimRemoteStreamsAPI:i2,shimTrackEventTransceiver:i9}),nt={exports:{}},ni=(oF||(oF=1,function(e){let t={};t.generateIdentifier=function(){return Math.random().toString(36).substring(2,12)},t.localCName=t.generateIdentifier(),t.splitLines=function(e){return e.trim().split("\n").map(e=>e.trim())},t.splitSections=function(e){return e.split("\nm=").map((e,t)=>(t>0?"m="+e:e).trim()+"\r\n")},t.getDescription=function(e){let i=t.splitSections(e);return i&&i[0]},t.getMediaSections=function(e){let i=t.splitSections(e);return i.shift(),i},t.matchPrefix=function(e,i){return t.splitLines(e).filter(e=>0===e.indexOf(i))},t.parseCandidate=function(e){let t;let i={foundation:(t=0===e.indexOf("a=candidate:")?e.substring(12).split(" "):e.substring(10).split(" "))[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 e=8;e<t.length;e+=2)switch(t[e]){case"raddr":i.relatedAddress=t[e+1];break;case"rport":i.relatedPort=parseInt(t[e+1],10);break;case"tcptype":i.tcpType=t[e+1];break;case"ufrag":i.ufrag=t[e+1],i.usernameFragment=t[e+1];break;default:void 0===i[t[e]]&&(i[t[e]]=t[e+1])}return i},t.writeCandidate=function(e){let t=[];t.push(e.foundation);let i=e.component;"rtp"===i?t.push(1):"rtcp"===i?t.push(2):t.push(i),t.push(e.protocol.toUpperCase()),t.push(e.priority),t.push(e.address||e.ip),t.push(e.port);let n=e.type;return t.push("typ"),t.push(n),"host"!==n&&e.relatedAddress&&e.relatedPort&&(t.push("raddr"),t.push(e.relatedAddress),t.push("rport"),t.push(e.relatedPort)),e.tcpType&&"tcp"===e.protocol.toLowerCase()&&(t.push("tcptype"),t.push(e.tcpType)),(e.usernameFragment||e.ufrag)&&(t.push("ufrag"),t.push(e.usernameFragment||e.ufrag)),"candidate:"+t.join(" ")},t.parseIceOptions=function(e){return e.substring(14).split(" ")},t.parseRtpMap=function(e){let t=e.substring(9).split(" "),i={payloadType:parseInt(t.shift(),10)};return t=t[0].split("/"),i.name=t[0],i.clockRate=parseInt(t[1],10),i.channels=3===t.length?parseInt(t[2],10):1,i.numChannels=i.channels,i},t.writeRtpMap=function(e){let t=e.payloadType;void 0!==e.preferredPayloadType&&(t=e.preferredPayloadType);let i=e.channels||e.numChannels||1;return"a=rtpmap:"+t+" "+e.name+"/"+e.clockRate+(1!==i?"/"+i:"")+"\r\n"},t.parseExtmap=function(e){let t=e.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(" ")}},t.writeExtmap=function(e){return"a=extmap:"+(e.id||e.preferredId)+(e.direction&&"sendrecv"!==e.direction?"/"+e.direction:"")+" "+e.uri+(e.attributes?" "+e.attributes:"")+"\r\n"},t.parseFmtp=function(e){let t;let i={},n=e.substring(e.indexOf(" ")+1).split(";");for(let e=0;e<n.length;e++)i[(t=n[e].trim().split("="))[0].trim()]=t[1];return i},t.writeFmtp=function(e){let t="",i=e.payloadType;if(void 0!==e.preferredPayloadType&&(i=e.preferredPayloadType),e.parameters&&Object.keys(e.parameters).length){let n=[];Object.keys(e.parameters).forEach(t=>{void 0!==e.parameters[t]?n.push(t+"="+e.parameters[t]):n.push(t)}),t+="a=fmtp:"+i+" "+n.join(";")+"\r\n"}return t},t.parseRtcpFb=function(e){let t=e.substring(e.indexOf(" ")+1).split(" ");return{type:t.shift(),parameter:t.join(" ")}},t.writeRtcpFb=function(e){let t="",i=e.payloadType;return void 0!==e.preferredPayloadType&&(i=e.preferredPayloadType),e.rtcpFeedback&&e.rtcpFeedback.length&&e.rtcpFeedback.forEach(e=>{t+="a=rtcp-fb:"+i+" "+e.type+(e.parameter&&e.parameter.length?" "+e.parameter:"")+"\r\n"}),t},t.parseSsrcMedia=function(e){let t=e.indexOf(" "),i={ssrc:parseInt(e.substring(7,t),10)},n=e.indexOf(":",t);return n>-1?(i.attribute=e.substring(t+1,n),i.value=e.substring(n+1)):i.attribute=e.substring(t+1),i},t.parseSsrcGroup=function(e){let t=e.substring(13).split(" ");return{semantics:t.shift(),ssrcs:t.map(e=>parseInt(e,10))}},t.getMid=function(e){let i=t.matchPrefix(e,"a=mid:")[0];if(i)return i.substring(6)},t.parseFingerprint=function(e){let t=e.substring(14).split(" ");return{algorithm:t[0].toLowerCase(),value:t[1].toUpperCase()}},t.getDtlsParameters=function(e,i){return{role:"auto",fingerprints:t.matchPrefix(e+i,"a=fingerprint:").map(t.parseFingerprint)}},t.writeDtlsParameters=function(e,t){let i="a=setup:"+t+"\r\n";return e.fingerprints.forEach(e=>{i+="a=fingerprint:"+e.algorithm+" "+e.value+"\r\n"}),i},t.parseCryptoLine=function(e){let t=e.substring(9).split(" ");return{tag:parseInt(t[0],10),cryptoSuite:t[1],keyParams:t[2],sessionParams:t.slice(3)}},t.writeCryptoLine=function(e){return"a=crypto:"+e.tag+" "+e.cryptoSuite+" "+("object"==typeof e.keyParams?t.writeCryptoKeyParams(e.keyParams):e.keyParams)+(e.sessionParams?" "+e.sessionParams.join(" "):"")+"\r\n"},t.parseCryptoKeyParams=function(e){if(0!==e.indexOf("inline:"))return null;let t=e.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}},t.writeCryptoKeyParams=function(e){return e.keyMethod+":"+e.keySalt+(e.lifeTime?"|"+e.lifeTime:"")+(e.mkiValue&&e.mkiLength?"|"+e.mkiValue+":"+e.mkiLength:"")},t.getCryptoParameters=function(e,i){return t.matchPrefix(e+i,"a=crypto:").map(t.parseCryptoLine)},t.getIceParameters=function(e,i){let n=t.matchPrefix(e+i,"a=ice-ufrag:")[0],r=t.matchPrefix(e+i,"a=ice-pwd:")[0];return n&&r?{usernameFragment:n.substring(12),password:r.substring(10)}:null},t.writeIceParameters=function(e){let t="a=ice-ufrag:"+e.usernameFragment+"\r\na=ice-pwd:"+e.password+"\r\n";return e.iceLite&&(t+="a=ice-lite\r\n"),t},t.parseRtpParameters=function(e){let i={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},n=t.splitLines(e)[0].split(" ");i.profile=n[2];for(let r=3;r<n.length;r++){let s=n[r],o=t.matchPrefix(e,"a=rtpmap:"+s+" ")[0];if(o){let n=t.parseRtpMap(o),r=t.matchPrefix(e,"a=fmtp:"+s+" ");switch(n.parameters=r.length?t.parseFmtp(r[0]):{},n.rtcpFeedback=t.matchPrefix(e,"a=rtcp-fb:"+s+" ").map(t.parseRtcpFb),i.codecs.push(n),n.name.toUpperCase()){case"RED":case"ULPFEC":i.fecMechanisms.push(n.name.toUpperCase())}}}t.matchPrefix(e,"a=extmap:").forEach(e=>{i.headerExtensions.push(t.parseExtmap(e))});let r=t.matchPrefix(e,"a=rtcp-fb:* ").map(t.parseRtcpFb);return i.codecs.forEach(e=>{r.forEach(t=>{e.rtcpFeedback.find(e=>e.type===t.type&&e.parameter===t.parameter)||e.rtcpFeedback.push(t)})}),i},t.writeRtpDescription=function(e,i){let n="";n+="m="+e+" "+(i.codecs.length>0?"9":"0")+" "+(i.profile||"UDP/TLS/RTP/SAVPF")+" "+i.codecs.map(e=>void 0!==e.preferredPayloadType?e.preferredPayloadType:e.payloadType).join(" ")+"\r\nc=IN IP4 0.0.0.0\r\na=rtcp:9 IN IP4 0.0.0.0\r\n",i.codecs.forEach(e=>{n+=t.writeRtpMap(e)+t.writeFmtp(e)+t.writeRtcpFb(e)});let r=0;return i.codecs.forEach(e=>{e.maxptime>r&&(r=e.maxptime)}),r>0&&(n+="a=maxptime:"+r+"\r\n"),i.headerExtensions&&i.headerExtensions.forEach(e=>{n+=t.writeExtmap(e)}),n},t.parseRtpEncodingParameters=function(e){let i;let n=[],r=t.parseRtpParameters(e),s=-1!==r.fecMechanisms.indexOf("RED"),o=-1!==r.fecMechanisms.indexOf("ULPFEC"),a=t.matchPrefix(e,"a=ssrc:").map(e=>t.parseSsrcMedia(e)).filter(e=>"cname"===e.attribute),l=a.length>0&&a[0].ssrc,c=t.matchPrefix(e,"a=ssrc-group:FID").map(e=>e.substring(17).split(" ").map(e=>parseInt(e,10)));c.length>0&&c[0].length>1&&c[0][0]===l&&(i=c[0][1]),r.codecs.forEach(e=>{if("RTX"===e.name.toUpperCase()&&e.parameters.apt){let t={ssrc:l,codecPayloadType:parseInt(e.parameters.apt,10)};l&&i&&(t.rtx={ssrc:i}),n.push(t),s&&((t=JSON.parse(JSON.stringify(t))).fec={ssrc:l,mechanism:o?"red+ulpfec":"red"},n.push(t))}}),0===n.length&&l&&n.push({ssrc:l});let d=t.matchPrefix(e,"b=");return d.length&&(d=0===d[0].indexOf("b=TIAS:")?parseInt(d[0].substring(7),10):0===d[0].indexOf("b=AS:")?950*parseInt(d[0].substring(5),10)-16e3:void 0,n.forEach(e=>{e.maxBitrate=d})),n},t.parseRtcpParameters=function(e){let i={},n=t.matchPrefix(e,"a=ssrc:").map(e=>t.parseSsrcMedia(e)).filter(e=>"cname"===e.attribute)[0];n&&(i.cname=n.value,i.ssrc=n.ssrc);let r=t.matchPrefix(e,"a=rtcp-rsize");i.reducedSize=r.length>0,i.compound=0===r.length;let s=t.matchPrefix(e,"a=rtcp-mux");return i.mux=s.length>0,i},t.writeRtcpParameters=function(e){let t="";return e.reducedSize&&(t+="a=rtcp-rsize\r\n"),e.mux&&(t+="a=rtcp-mux\r\n"),void 0!==e.ssrc&&e.cname&&(t+="a=ssrc:"+e.ssrc+" cname:"+e.cname+"\r\n"),t},t.parseMsid=function(e){let i;let n=t.matchPrefix(e,"a=msid:");if(1===n.length)return{stream:(i=n[0].substring(7).split(" "))[0],track:i[1]};let r=t.matchPrefix(e,"a=ssrc:").map(e=>t.parseSsrcMedia(e)).filter(e=>"msid"===e.attribute);if(r.length>0)return{stream:(i=r[0].value.split(" "))[0],track:i[1]}},t.parseSctpDescription=function(e){let i;let n=t.parseMLine(e),r=t.matchPrefix(e,"a=max-message-size:");r.length>0&&(i=parseInt(r[0].substring(19),10)),isNaN(i)&&(i=65536);let s=t.matchPrefix(e,"a=sctp-port:");if(s.length>0)return{port:parseInt(s[0].substring(12),10),protocol:n.fmt,maxMessageSize:i};let o=t.matchPrefix(e,"a=sctpmap:");if(o.length>0){let e=o[0].substring(10).split(" ");return{port:parseInt(e[0],10),protocol:e[1],maxMessageSize:i}}},t.writeSctpDescription=function(e,t){let i=[];return i="DTLS/SCTP"!==e.protocol?["m="+e.kind+" 9 "+e.protocol+" "+t.protocol+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctp-port:"+t.port+"\r\n"]:["m="+e.kind+" 9 "+e.protocol+" "+t.port+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctpmap:"+t.port+" "+t.protocol+" 65535\r\n"],void 0!==t.maxMessageSize&&i.push("a=max-message-size:"+t.maxMessageSize+"\r\n"),i.join("")},t.generateSessionId=function(){return Math.random().toString().substr(2,22)},t.writeSessionBoilerplate=function(e,i,n){return"v=0\r\no="+(n||"thisisadapterortc")+" "+(e||t.generateSessionId())+" "+(void 0!==i?i:2)+" IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\n"},t.getDirection=function(e,i){let n=t.splitLines(e);for(let e=0;e<n.length;e++)switch(n[e]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return n[e].substring(2)}return i?t.getDirection(i):"sendrecv"},t.getKind=function(e){return t.splitLines(e)[0].split(" ")[0].substring(2)},t.isRejected=function(e){return"0"===e.split(" ",2)[1]},t.parseMLine=function(e){let i=t.splitLines(e)[0].substring(2).split(" ");return{kind:i[0],port:parseInt(i[1],10),protocol:i[2],fmt:i.slice(3).join(" ")}},t.parseOLine=function(e){let i=t.matchPrefix(e,"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]}},t.isValidSDP=function(e){if("string"!=typeof e||0===e.length)return!1;let i=t.splitLines(e);for(let e=0;e<i.length;e++)if(i[e].length<2||"="!==i[e].charAt(1))return!1;return!0},e.exports=t}(nt)),nt.exports),nn=function(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}(ni),nr=function(e,t){return t.forEach(function(t){t&&"string"!=typeof t&&!Array.isArray(t)&&Object.keys(t).forEach(function(i){if("default"!==i&&!(i in e)){var n=Object.getOwnPropertyDescriptor(t,i);Object.defineProperty(e,i,n.get?n:{enumerable:!0,get:function(){return t[i]}})}})}),Object.freeze(e)}({__proto__:null,default:nn},[ni]);function ns(e){if(!e.RTCIceCandidate||e.RTCIceCandidate&&"foundation"in e.RTCIceCandidate.prototype)return;let t=e.RTCIceCandidate;e.RTCIceCandidate=function(e){if("object"==typeof e&&e.candidate&&0===e.candidate.indexOf("a=")&&((e=JSON.parse(JSON.stringify(e))).candidate=e.candidate.substring(2)),e.candidate&&e.candidate.length){let i=new t(e),n=nn.parseCandidate(e.candidate);for(let e in n)e in i||Object.defineProperty(i,e,{value:n[e]});return i.toJSON=function(){return{candidate:i.candidate,sdpMid:i.sdpMid,sdpMLineIndex:i.sdpMLineIndex,usernameFragment:i.usernameFragment}},i}return new t(e)},e.RTCIceCandidate.prototype=t.prototype,iP(e,"icecandidate",t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new e.RTCIceCandidate(t.candidate),writable:"false"}),t))}function no(e){!e.RTCIceCandidate||e.RTCIceCandidate&&"relayProtocol"in e.RTCIceCandidate.prototype||iP(e,"icecandidate",e=>{if(e.candidate){let t=nn.parseCandidate(e.candidate.candidate);"relay"===t.type&&(e.candidate.relayProtocol=({0:"tls",1:"tcp",2:"udp"})[t.priority>>24])}return e})}function na(e,t){if(!e.RTCPeerConnection)return;"sctp"in e.RTCPeerConnection.prototype||Object.defineProperty(e.RTCPeerConnection.prototype,"sctp",{get(){return void 0===this._sctp?null:this._sctp}});let i=function(e){if(!e||!e.sdp)return!1;let t=nn.splitSections(e.sdp);return t.shift(),t.some(e=>{let t=nn.parseMLine(e);return t&&"application"===t.kind&&-1!==t.protocol.indexOf("SCTP")})},n=function(e){let t=e.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(null===t||t.length<2)return -1;let i=parseInt(t[1],10);return i!=i?-1:i},r=function(e){let i=65536;return"firefox"===t.browser&&(i=t.version<57?-1===e?16384:2147483637:t.version<60?57===t.version?65535:65536:2147483637),i},s=function(e,i){let n=65536;"firefox"===t.browser&&57===t.version&&(n=65535);let r=nn.matchPrefix(e.sdp,"a=max-message-size:");return r.length>0?n=parseInt(r[0].substring(19),10):"firefox"===t.browser&&-1!==i&&(n=2147483637),n},o=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,"chrome"===t.browser&&t.version>=76){let{sdpSemantics:e}=this.getConfiguration();"plan-b"===e&&Object.defineProperty(this,"sctp",{get(){return void 0===this._sctp?null:this._sctp},enumerable:!0,configurable:!0})}if(i(arguments[0])){let e;let t=n(arguments[0]),i=r(t),o=s(arguments[0],t);e=0===i&&0===o?Number.POSITIVE_INFINITY:0===i||0===o?Math.max(i,o):Math.min(i,o);let a={};Object.defineProperty(a,"maxMessageSize",{get:()=>e}),this._sctp=a}return o.apply(this,arguments)}}function nl(e){if(!(e.RTCPeerConnection&&"createDataChannel"in e.RTCPeerConnection.prototype))return;function t(e,t){let i=e.send;e.send=function(){let n=arguments[0],r=n.length||n.size||n.byteLength;if("open"===e.readyState&&t.sctp&&r>t.sctp.maxMessageSize)throw TypeError("Message too large (can send a maximum of "+t.sctp.maxMessageSize+" bytes)");return i.apply(e,arguments)}}let i=e.RTCPeerConnection.prototype.createDataChannel;e.RTCPeerConnection.prototype.createDataChannel=function(){let e=i.apply(this,arguments);return t(e,this),e},iP(e,"datachannel",e=>(t(e.channel,e.target),e))}function nc(e){if(!e.RTCPeerConnection||"connectionState"in e.RTCPeerConnection.prototype)return;let t=e.RTCPeerConnection.prototype;Object.defineProperty(t,"connectionState",{get(){return({completed:"connected",checking:"connecting"})[this.iceConnectionState]||this.iceConnectionState},enumerable:!0,configurable:!0}),Object.defineProperty(t,"onconnectionstatechange",{get(){return this._onconnectionstatechange||null},set(e){this._onconnectionstatechange&&(this.removeEventListener("connectionstatechange",this._onconnectionstatechange),delete this._onconnectionstatechange),e&&this.addEventListener("connectionstatechange",this._onconnectionstatechange=e)},enumerable:!0,configurable:!0}),["setLocalDescription","setRemoteDescription"].forEach(e=>{let i=t[e];t[e]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=e=>{let t=e.target;if(t._lastConnectionState!==t.connectionState){t._lastConnectionState=t.connectionState;let i=new Event("connectionstatechange",e);t.dispatchEvent(i)}return e},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),i.apply(this,arguments)}})}function nd(e,t){if(!e.RTCPeerConnection||"chrome"===t.browser&&t.version>=71||"safari"===t.browser&&t._safariVersion>=13.1)return;let i=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(t){if(t&&t.sdp&&-1!==t.sdp.indexOf("\na=extmap-allow-mixed")){let i=t.sdp.split("\n").filter(e=>"a=extmap-allow-mixed"!==e.trim()).join("\n");e.RTCSessionDescription&&t instanceof e.RTCSessionDescription?arguments[0]=new e.RTCSessionDescription({type:t.type,sdp:i}):t.sdp=i}return i.apply(this,arguments)}}function nu(e,t){if(!(e.RTCPeerConnection&&e.RTCPeerConnection.prototype))return;let i=e.RTCPeerConnection.prototype.addIceCandidate;i&&0!==i.length&&(e.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?("chrome"===t.browser&&t.version<78||"firefox"===t.browser&&t.version<68||"safari"===t.browser)&&arguments[0]&&""===arguments[0].candidate?Promise.resolve():i.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}function nh(e,t){if(!(e.RTCPeerConnection&&e.RTCPeerConnection.prototype))return;let i=e.RTCPeerConnection.prototype.setLocalDescription;i&&0!==i.length&&(e.RTCPeerConnection.prototype.setLocalDescription=function(){let e=arguments[0]||{};if("object"!=typeof e||e.type&&e.sdp)return i.apply(this,arguments);if(!(e={type:e.type,sdp:e.sdp}).type)switch(this.signalingState){case"stable":case"have-local-offer":case"have-remote-pranswer":e.type="offer";break;default:e.type="answer"}return e.sdp||"offer"!==e.type&&"answer"!==e.type?i.apply(this,[e]):("offer"===e.type?this.createOffer:this.createAnswer).apply(this).then(e=>i.apply(this,[e]))})}var np=Object.freeze({__proto__:null,removeExtmapAllowMixed:nd,shimAddIceCandidateNullOrEmpty:nu,shimConnectionState:nc,shimMaxMessageSize:na,shimParameterlessSetLocalDescription:nh,shimRTCIceCandidate:ns,shimRTCIceCandidateRelayProtocol:no,shimSendThrowTypeError:nl});!function(){let{window:e}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{shimChrome:!0,shimFirefox:!0,shimSafari:!0},i=function(e){let t={browser:null,version:null};if(void 0===e||!e.navigator||!e.navigator.userAgent)return t.browser="Not a browser.",t;let{navigator:i}=e;if(i.userAgentData&&i.userAgentData.brands){let e=i.userAgentData.brands.find(e=>"Chromium"===e.brand);if(e)return{browser:"chrome",version:parseInt(e.version,10)}}return i.mozGetUserMedia?(t.browser="firefox",t.version=parseInt(iE(i.userAgent,/Firefox\/(\d+)\./,1))):i.webkitGetUserMedia||!1===e.isSecureContext&&e.webkitRTCPeerConnection?(t.browser="chrome",t.version=parseInt(iE(i.userAgent,/Chrom(e|ium)\/(\d+)\./,2))):e.RTCPeerConnection&&i.userAgent.match(/AppleWebKit\/(\d+)\./)?(t.browser="safari",t.version=parseInt(iE(i.userAgent,/AppleWebKit\/(\d+)\./,1)),t.supportsUnifiedPlan=e.RTCRtpTransceiver&&"currentDirection"in e.RTCRtpTransceiver.prototype,t._safariVersion=iE(i.userAgent,/Version\/(\d+(\.?\d+))/,1)):t.browser="Not a supported browser.",t}(e),n={browserDetails:i,commonShim:np,extractVersion:iE,disableLog:ix,disableWarnings:iR,sdp:nr};switch(i.browser){case"chrome":if(!iq||!iV||!t.shimChrome){iO("Chrome shim is not included in this adapter release.");break}if(null===i.version){iO("Chrome shim can not determine version, not shimming.");break}iO("adapter.js shimming chrome."),n.browserShim=iq,nu(e,i),nh(e),iD(e,i),i_(e),iV(e,i),iN(e),iF(e,i),iL(e),ij(e),iB(e,i),ns(e),no(e),nc(e),na(e,i),nl(e),nd(e,i);break;case"firefox":if(!i0||!iH||!t.shimFirefox){iO("Firefox shim is not included in this adapter release.");break}iO("adapter.js shimming firefox."),n.browserShim=i0,nu(e,i),nh(e),iz(e,i),iH(e,i),iW(e),iK(e),iG(e),i$(e),iJ(e),iX(e),iY(e),iQ(e),iZ(e),ns(e),nc(e),na(e,i),nl(e);break;case"safari":if(!ne||!t.shimSafari){iO("Safari shim is not included in this adapter release.");break}iO("adapter.js shimming safari."),n.browserShim=ne,nu(e,i),nh(e),i6(e),i8(e),i3(e),i1(e),i2(e),i9(e),i5(e),i7(e),ns(e),no(e),na(e,i),nl(e),nd(e,i);break;default:iO("Unsupported browser!")}}({window:"undefined"==typeof window?void 0:window});let nm="lk_e2ee";function nf(){return void 0!==window.RTCRtpScriptTransform}(function(e){e.SetKey="setKey",e.RatchetRequest="ratchetRequest",e.KeyRatcheted="keyRatcheted"})(oV||(oV={})),(oB||(oB={})).KeyRatcheted="keyRatcheted",function(e){e.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",e.EncryptionError="encryptionError"}(oq||(oq={})),(oz||(oz={})).Error="cryptorError";class ng extends Error{constructor(e,t){super(t||"an error has occured"),this.name="LiveKitError",this.code=e}}!function(e){e[e.NotAllowed=0]="NotAllowed",e[e.ServerUnreachable=1]="ServerUnreachable",e[e.InternalError=2]="InternalError",e[e.Cancelled=3]="Cancelled",e[e.LeaveRequest=4]="LeaveRequest",e[e.Timeout=5]="Timeout"}(oW||(oW={}));class nv extends ng{constructor(e,t,i,n){super(1,e),this.name="ConnectionError",this.status=i,this.reason=t,this.context=n,this.reasonName=oW[t]}}class ny extends ng{constructor(e){super(21,null!=e?e:"device is unsupported"),this.name="DeviceUnsupportedError"}}class nb extends ng{constructor(e){super(20,null!=e?e:"track is invalid"),this.name="TrackInvalidError"}}class nk extends ng{constructor(e){super(10,null!=e?e:"unsupported server"),this.name="UnsupportedServer"}}class nT extends ng{constructor(e){super(12,null!=e?e:"unexpected connection state"),this.name="UnexpectedConnectionState"}}class nS extends ng{constructor(e){super(13,null!=e?e:"unable to negotiate"),this.name="NegotiationError"}}class nC extends ng{constructor(e,t){super(15,e),this.name="PublishTrackError",this.status=t}}class nw extends ng{constructor(e,t){super(15,e),this.reason=t,this.reasonName="string"==typeof t?t:il[t]}}(function(e){e.PermissionDenied="PermissionDenied",e.NotFound="NotFound",e.DeviceInUse="DeviceInUse",e.Other="Other"})(oH||(oH={})),function(e){e.getFailure=function(t){if(t&&"name"in t)return"NotFoundError"===t.name||"DevicesNotFoundError"===t.name?e.NotFound:"NotAllowedError"===t.name||"PermissionDeniedError"===t.name?e.PermissionDenied:"NotReadableError"===t.name||"TrackStartError"===t.name?e.DeviceInUse:e.Other}}(oH||(oH={})),function(e){e[e.InvalidKey=0]="InvalidKey",e[e.MissingKey=1]="MissingKey",e[e.InternalError=2]="InternalError"}(oG||(oG={})),function(e){e.Connected="connected",e.Reconnecting="reconnecting",e.SignalReconnecting="signalReconnecting",e.Reconnected="reconnected",e.Disconnected="disconnected",e.ConnectionStateChanged="connectionStateChanged",e.Moved="moved",e.MediaDevicesChanged="mediaDevicesChanged",e.ParticipantConnected="participantConnected",e.ParticipantDisconnected="participantDisconnected",e.TrackPublished="trackPublished",e.TrackSubscribed="trackSubscribed",e.TrackSubscriptionFailed="trackSubscriptionFailed",e.TrackUnpublished="trackUnpublished",e.TrackUnsubscribed="trackUnsubscribed",e.TrackMuted="trackMuted",e.TrackUnmuted="trackUnmuted",e.LocalTrackPublished="localTrackPublished",e.LocalTrackUnpublished="localTrackUnpublished",e.LocalAudioSilenceDetected="localAudioSilenceDetected",e.ActiveSpeakersChanged="activeSpeakersChanged",e.ParticipantMetadataChanged="participantMetadataChanged",e.ParticipantNameChanged="participantNameChanged",e.ParticipantAttributesChanged="participantAttributesChanged",e.ParticipantActive="participantActive",e.RoomMetadataChanged="roomMetadataChanged",e.DataReceived="dataReceived",e.SipDTMFReceived="sipDTMFReceived",e.TranscriptionReceived="transcriptionReceived",e.ConnectionQualityChanged="connectionQualityChanged",e.TrackStreamStateChanged="trackStreamStateChanged",e.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",e.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",e.AudioPlaybackStatusChanged="audioPlaybackChanged",e.VideoPlaybackStatusChanged="videoPlaybackChanged",e.MediaDevicesError="mediaDevicesError",e.ParticipantPermissionsChanged="participantPermissionsChanged",e.SignalConnected="signalConnected",e.RecordingStatusChanged="recordingStatusChanged",e.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",e.EncryptionError="encryptionError",e.DCBufferStatusChanged="dcBufferStatusChanged",e.ActiveDeviceChanged="activeDeviceChanged",e.ChatMessage="chatMessage",e.LocalTrackSubscribed="localTrackSubscribed",e.MetricsReceived="metricsReceived"}(o$||(o$={})),function(e){e.TrackPublished="trackPublished",e.TrackSubscribed="trackSubscribed",e.TrackSubscriptionFailed="trackSubscriptionFailed",e.TrackUnpublished="trackUnpublished",e.TrackUnsubscribed="trackUnsubscribed",e.TrackMuted="trackMuted",e.TrackUnmuted="trackUnmuted",e.LocalTrackPublished="localTrackPublished",e.LocalTrackUnpublished="localTrackUnpublished",e.LocalTrackCpuConstrained="localTrackCpuConstrained",e.LocalSenderCreated="localSenderCreated",e.ParticipantMetadataChanged="participantMetadataChanged",e.ParticipantNameChanged="participantNameChanged",e.DataReceived="dataReceived",e.SipDTMFReceived="sipDTMFReceived",e.TranscriptionReceived="transcriptionReceived",e.IsSpeakingChanged="isSpeakingChanged",e.ConnectionQualityChanged="connectionQualityChanged",e.TrackStreamStateChanged="trackStreamStateChanged",e.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",e.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",e.TrackCpuConstrained="trackCpuConstrained",e.MediaDevicesError="mediaDevicesError",e.AudioStreamAcquired="audioStreamAcquired",e.ParticipantPermissionsChanged="participantPermissionsChanged",e.PCTrackAdded="pcTrackAdded",e.AttributesChanged="attributesChanged",e.LocalTrackSubscribed="localTrackSubscribed",e.ChatMessage="chatMessage",e.Active="active"}(oK||(oK={})),function(e){e.TransportsCreated="transportsCreated",e.Connected="connected",e.Disconnected="disconnected",e.Resuming="resuming",e.Resumed="resumed",e.Restarting="restarting",e.Restarted="restarted",e.SignalResumed="signalResumed",e.SignalRestarted="signalRestarted",e.Closing="closing",e.MediaTrackAdded="mediaTrackAdded",e.ActiveSpeakersUpdate="activeSpeakersUpdate",e.DataPacketReceived="dataPacketReceived",e.RTPVideoMapUpdate="rtpVideoMapUpdate",e.DCBufferStatusChanged="dcBufferStatusChanged",e.ParticipantUpdate="participantUpdate",e.RoomUpdate="roomUpdate",e.SpeakersChanged="speakersChanged",e.StreamStateChanged="streamStateChanged",e.ConnectionQualityUpdate="connectionQualityUpdate",e.SubscriptionError="subscriptionError",e.SubscriptionPermissionUpdate="subscriptionPermissionUpdate",e.RemoteMute="remoteMute",e.SubscribedQualityUpdate="subscribedQualityUpdate",e.LocalTrackUnpublished="localTrackUnpublished",e.LocalTrackSubscribed="localTrackSubscribed",e.Offline="offline",e.SignalRequestResponse="signalRequestResponse",e.SignalConnected="signalConnected",e.RoomMoved="roomMoved"}(oJ||(oJ={})),function(e){e.Message="message",e.Muted="muted",e.Unmuted="unmuted",e.Restarted="restarted",e.Ended="ended",e.Subscribed="subscribed",e.Unsubscribed="unsubscribed",e.CpuConstrained="cpuConstrained",e.UpdateSettings="updateSettings",e.UpdateSubscription="updateSubscription",e.AudioPlaybackStarted="audioPlaybackStarted",e.AudioPlaybackFailed="audioPlaybackFailed",e.AudioSilenceDetected="audioSilenceDetected",e.VisibilityChanged="visibilityChanged",e.VideoDimensionsChanged="videoDimensionsChanged",e.VideoPlaybackStarted="videoPlaybackStarted",e.VideoPlaybackFailed="videoPlaybackFailed",e.ElementAttached="elementAttached",e.ElementDetached="elementDetached",e.UpstreamPaused="upstreamPaused",e.UpstreamResumed="upstreamResumed",e.SubscriptionPermissionChanged="subscriptionPermissionChanged",e.SubscriptionStatusChanged="subscriptionStatusChanged",e.SubscriptionFailed="subscriptionFailed",e.TrackProcessorUpdate="trackProcessorUpdate",e.AudioTrackFeatureUpdate="audioTrackFeatureUpdate",e.TranscriptionReceived="transcriptionReceived",e.TimeSyncUpdate="timeSyncUpdate",e.PreConnectBufferFlushed="preConnectBufferFlushed"}(oX||(oX={}));let nE=/version\/(\d+(\.?_?\d+)+)/i;function nP(e){let t=!(arguments.length>1)||void 0===arguments[1]||arguments[1];if(void 0===e&&"undefined"==typeof navigator)return;let i=(null!=e?e:navigator.userAgent).toLowerCase();if(void 0===n||t){let e=nx.find(e=>{let{test:t}=e;return t.test(i)});n=null==e?void 0:e.describe(i)}return n}let nx=[{test:/firefox|iceweasel|fxios/i,describe:e=>({name:"Firefox",version:nR(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,e),os:e.toLowerCase().includes("fxios")?"iOS":void 0,osVersion:nO(e)})},{test:/chrom|crios|crmo/i,describe:e=>({name:"Chrome",version:nR(/(?:chrome|chromium|crios|crmo)\/(\d+(\.?_?\d+)+)/i,e),os:e.toLowerCase().includes("crios")?"iOS":void 0,osVersion:nO(e)})},{test:/safari|applewebkit/i,describe:e=>({name:"Safari",version:nR(nE,e),os:e.includes("mobile/")?"iOS":"macOS",osVersion:nO(e)})}];function nR(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1,n=t.match(e);return n&&n.length>=i&&n[i]||""}function nO(e){return e.includes("mac os")?nR(/\(.+?(\d+_\d+(:?_\d+)?)/,e,1).replace(/_/g,"."):void 0}class nA{}nA.setTimeout=function(){return setTimeout(...arguments)},nA.setInterval=function(){return setInterval(...arguments)},nA.clearTimeout=function(){return clearTimeout(...arguments)},nA.clearInterval=function(){return clearInterval(...arguments)};let nI=[];!function(e){e[e.LOW=0]="LOW",e[e.MEDIUM=1]="MEDIUM",e[e.HIGH=2]="HIGH"}(oY||(oY={}));class nM extends iS.EventEmitter{constructor(e,t){var i;let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};super(),this.attachedElements=[],this.isMuted=!1,this.streamState=nM.StreamState.Active,this.isInBackground=!1,this._currentBitrate=0,this.log=ip,this.appVisibilityChangedListener=()=>{this.backgroundTimeout&&clearTimeout(this.backgroundTimeout),"hidden"===document.visibilityState?this.backgroundTimeout=setTimeout(()=>this.handleAppVisibilityChanged(),5e3):this.handleAppVisibilityChanged()},this.log=im(null!==(i=n.loggerName)&&void 0!==i?i:oj.Track),this.loggerContextCb=n.loggerContextCb,this.setMaxListeners(100),this.kind=t,this._mediaStreamTrack=e,this._mediaStreamID=e.id,this.source=nM.Source.Unknown}get logContext(){var e;return Object.assign(Object.assign({},null===(e=this.loggerContextCb)||void 0===e?void 0:e.call(this)),rT(this))}get currentBitrate(){return this._currentBitrate}get mediaStreamTrack(){return this._mediaStreamTrack}get mediaStreamID(){return this._mediaStreamID}attach(e){let t="audio";this.kind===nM.Kind.Video&&(t="video"),0===this.attachedElements.length&&this.kind===nM.Kind.Video&&this.addAppVisibilityListener(),e||("audio"===t&&(nI.forEach(t=>{null!==t.parentElement||e||(e=t)}),e&&nI.splice(nI.indexOf(e),1)),e||(e=document.createElement(t))),this.attachedElements.includes(e)||this.attachedElements.push(e),nD(this.mediaStreamTrack,e);let i=e.srcObject.getTracks(),n=i.some(e=>"audio"===e.kind);return e.play().then(()=>{this.emit(n?oX.AudioPlaybackStarted:oX.VideoPlaybackStarted)}).catch(t=>{"NotAllowedError"===t.name?this.emit(n?oX.AudioPlaybackFailed:oX.VideoPlaybackFailed,t):"AbortError"===t.name?ip.debug("".concat(n?"audio":"video"," playback aborted, likely due to new play request")):ip.warn("could not playback ".concat(n?"audio":"video"),t),n&&e&&i.some(e=>"video"===e.kind)&&"NotAllowedError"===t.name&&(e.muted=!0,e.play().catch(()=>{}))}),this.emit(oX.ElementAttached,e),e}detach(e){try{if(e){n_(this.mediaStreamTrack,e);let t=this.attachedElements.indexOf(e);return t>=0&&(this.attachedElements.splice(t,1),this.recycleElement(e),this.emit(oX.ElementDetached,e)),e}let t=[];return this.attachedElements.forEach(e=>{n_(this.mediaStreamTrack,e),t.push(e),this.recycleElement(e),this.emit(oX.ElementDetached,e)}),this.attachedElements=[],t}finally{0===this.attachedElements.length&&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=im(e.loggerName)),e.loggerContextCb&&(this.loggerContextCb=e.loggerContextCb)}recycleElement(e){if(e instanceof HTMLAudioElement){let t=!0;e.pause(),nI.forEach(e=>{e.parentElement||(t=!1)}),t&&nI.push(e)}}handleAppVisibilityChanged(){return ib(this,void 0,void 0,function*(){this.isInBackground="hidden"===document.visibilityState,this.isInBackground||this.kind!==nM.Kind.Video||setTimeout(()=>this.attachedElements.forEach(e=>e.play().catch(()=>{})),0)})}addAppVisibilityListener(){nY()?(this.isInBackground="hidden"===document.visibilityState,document.addEventListener("visibilitychange",this.appVisibilityChangedListener)):this.isInBackground=!1}removeAppVisibilityListener(){nY()&&document.removeEventListener("visibilitychange",this.appVisibilityChangedListener)}}function nD(e,t){let i,n;t.srcObject instanceof MediaStream?i=t.srcObject:i=new MediaStream,(n="audio"===e.kind?i.getAudioTracks():i.getVideoTracks()).includes(e)||(n.forEach(e=>{i.removeTrack(e)}),i.addTrack(e)),nK()&&t instanceof HTMLVideoElement||(t.autoplay=!0),t.muted=0===i.getAudioTracks().length,t instanceof HTMLVideoElement&&(t.playsInline=!0),t.srcObject!==i&&(t.srcObject=i,(nK()||n$())&&t instanceof HTMLVideoElement&&setTimeout(()=>{t.srcObject=i,t.play().catch(()=>{})},0))}function n_(e,t){if(t.srcObject instanceof MediaStream){let i=t.srcObject;i.removeTrack(e),i.getTracks().length>0?t.srcObject=i:t.srcObject=null}}!function(e){var t,i,n;let r,s,o;(t=r=e.Kind||(e.Kind={})).Audio="audio",t.Video="video",t.Unknown="unknown",(i=s=e.Source||(e.Source={})).Camera="camera",i.Microphone="microphone",i.ScreenShare="screen_share",i.ScreenShareAudio="screen_share_audio",i.Unknown="unknown",(n=o=e.StreamState||(e.StreamState={})).Active="active",n.Paused="paused",n.Unknown="unknown",e.kindToProto=function(e){switch(e){case r.Audio:return eV.AUDIO;case r.Video:return eV.VIDEO;default:return eV.DATA}},e.kindFromProto=function(e){switch(e){case eV.AUDIO:return r.Audio;case eV.VIDEO:return r.Video;default:return r.Unknown}},e.sourceToProto=function(e){switch(e){case s.Camera:return eB.CAMERA;case s.Microphone:return eB.MICROPHONE;case s.ScreenShare:return eB.SCREEN_SHARE;case s.ScreenShareAudio:return eB.SCREEN_SHARE_AUDIO;default:return eB.UNKNOWN}},e.sourceFromProto=function(e){switch(e){case eB.CAMERA:return s.Camera;case eB.MICROPHONE:return s.Microphone;case eB.SCREEN_SHARE:return s.ScreenShare;case eB.SCREEN_SHARE_AUDIO:return s.ScreenShareAudio;default:return s.Unknown}},e.streamStateFromProto=function(e){switch(e){case tE.ACTIVE:return o.Active;case tE.PAUSED:return o.Paused;default:return o.Unknown}}}(nM||(nM={}));class nN{constructor(e,t,i,n,r){if("object"==typeof e)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(void 0!==t&&void 0!==i)this.width=e,this.height=t,this.aspectRatio=e/t,this.encoding={maxBitrate:i,maxFramerate:n,priority:r};else throw 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}}}let nL=["vp8","h264"],nj=["vp8","h264","vp9","av1","h265"];(function(e){e[e.PREFER_REGRESSION=0]="PREFER_REGRESSION",e[e.SIMULCAST=1]="SIMULCAST",e[e.REGRESSION=2]="REGRESSION"})(oQ||(oQ={})),function(e){e.telephone={maxBitrate:12e3},e.speech={maxBitrate:24e3},e.music={maxBitrate:48e3},e.musicStereo={maxBitrate:64e3},e.musicHighQuality={maxBitrate:96e3},e.musicHighQualityStereo={maxBitrate:128e3}}(oZ||(oZ={}));let nU={h90:new nN(160,90,9e4,20),h180:new nN(320,180,16e4,20),h216:new nN(384,216,18e4,20),h360:new nN(640,360,45e4,20),h540:new nN(960,540,8e5,25),h720:new nN(1280,720,17e5,30),h1080:new nN(1920,1080,3e6,30),h1440:new nN(2560,1440,5e6,30),h2160:new nN(3840,2160,8e6,30)},nF={h120:new nN(160,120,7e4,20),h180:new nN(240,180,125e3,20),h240:new nN(320,240,14e4,20),h360:new nN(480,360,33e4,20),h480:new nN(640,480,5e5,20),h540:new nN(720,540,6e5,25),h720:new nN(960,720,13e5,30),h1080:new nN(1440,1080,23e5,30),h1440:new nN(1920,1440,38e5,30)},nV={h360fps3:new nN(640,360,2e5,3,"medium"),h360fps15:new nN(640,360,4e5,15,"medium"),h720fps5:new nN(1280,720,8e5,5,"medium"),h720fps15:new nN(1280,720,15e5,15,"medium"),h720fps30:new nN(1280,720,2e6,30,"medium"),h1080fps15:new nN(1920,1080,25e5,15,"medium"),h1080fps30:new nN(1920,1080,5e6,30,"medium"),original:new nN(0,0,7e6,30,"medium")},nB="https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension";function nq(e){return ib(this,void 0,void 0,function*(){return new Promise(t=>nA.setTimeout(t,e))})}function nz(){return"addTransceiver"in RTCPeerConnection.prototype}function nW(){return"addTrack"in RTCPeerConnection.prototype}function nH(e){return"av1"===e||"vp9"===e}function nG(e){return!(!document||nJ())&&(e||(e=document.createElement("audio")),"setSinkId"in e)}function n$(){var e;return(null===(e=nP())||void 0===e?void 0:e.name)==="Firefox"}function nK(){var e;return(null===(e=nP())||void 0===e?void 0:e.name)==="Safari"}function nJ(){let e=nP();return(null==e?void 0:e.name)==="Safari"||(null==e?void 0:e.os)==="iOS"}function nX(){var e,t;return!!nY()&&(null!==(t=null===(e=navigator.userAgentData)||void 0===e?void 0:e.mobile)&&void 0!==t?t:/Tablet|iPad|Mobile|Android|BlackBerry/.test(navigator.userAgent))}function nY(){return"undefined"!=typeof document}function nQ(){return"ReactNative"==navigator.product}function nZ(e){return e.hostname.endsWith(".livekit.cloud")||e.hostname.endsWith(".livekit.run")}function n0(){if(global&&global.LiveKitReactNativeGlobal)return global.LiveKitReactNativeGlobal}function n1(){if(!nQ())return;let e=n0();if(e)return e.platform}function n2(){if(nY())return window.devicePixelRatio;if(nQ()){let e=n0();if(e)return e.devicePixelRatio}return 1}function n3(e,t){let i=e.split("."),n=t.split("."),r=Math.min(i.length,n.length);for(let e=0;e<r;++e){let t=parseInt(i[e],10),s=parseInt(n[e],10);if(t>s)return 1;if(t<s)return -1;if(e===r-1&&t===s)return 0}return""===e&&""!==t?-1:""===t?1:i.length==n.length?0:i.length<n.length?-1:1}function n5(e){for(let t of e)t.target.handleResize(t)}function n4(e){for(let t of e)t.target.handleVisibilityChanged(t)}let n6=null,n9=()=>(n6||(n6=new ResizeObserver(n5)),n6),n8=null,n7=()=>(n8||(n8=new IntersectionObserver(n4,{root:null,rootMargin:"0px"})),n8);function re(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:16,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:16,i=arguments.length>2&&void 0!==arguments[2]&&arguments[2],n=arguments.length>3&&void 0!==arguments[3]&&arguments[3],r=document.createElement("canvas");r.width=e,r.height=t;let s=r.getContext("2d");null==s||s.fillRect(0,0,r.width,r.height),n&&s&&(s.beginPath(),s.arc(e/2,t/2,50,0,2*Math.PI,!0),s.closePath(),s.fillStyle="grey",s.fill());let[o]=r.captureStream().getTracks();if(!o)throw Error("Could not get empty media stream video track");return o.enabled=i,o}function rt(){if(!r){let e=new AudioContext,t=e.createOscillator(),i=e.createGain();i.gain.setValueAtTime(0,0);let n=e.createMediaStreamDestination();if(t.connect(i),i.connect(n),t.start(),[r]=n.stream.getAudioTracks(),!r)throw Error("Could not get empty media stream audio track");r.enabled=!1}return r.clone()}class ri{get isResolved(){return this._isResolved}constructor(e,t){this._isResolved=!1,this.onFinally=t,this.promise=new Promise((t,i)=>ib(this,void 0,void 0,function*(){this.resolve=t,this.reject=i,e&&(yield e(t,i))})).finally(()=>{var e;this._isResolved=!0,null===(e=this.onFinally)||void 0===e||e.call(this)})}}function rn(e){if("string"==typeof e||"number"==typeof e)return e;if(Array.isArray(e))return e[0];if(e.exact)return Array.isArray(e.exact)?e.exact[0]:e.exact;if(e.ideal)return Array.isArray(e.ideal)?e.ideal[0]:e.ideal;throw Error("could not unwrap constraint")}function rr(e){return e.startsWith("ws")?e.replace(/^(ws)/,"http"):e}function rs(e){switch(e.reason){case oW.LeaveRequest:return e.context;case oW.Cancelled:return eH.CLIENT_INITIATED;case oW.NotAllowed:return eH.USER_REJECTED;case oW.ServerUnreachable:return eH.JOIN_FAILURE;default:return eH.UNKNOWN_REASON}}function ro(e){return void 0!==e?Number(e):void 0}function ra(e){return void 0!==e?BigInt(e):void 0}function rl(e){return!!e&&!(e instanceof MediaStreamTrack)&&e.isLocal}function rc(e){return!!e&&e.kind==nM.Kind.Audio}function rd(e){return!!e&&e.kind==nM.Kind.Video}function ru(e){return rl(e)&&rd(e)}function rh(e){return rl(e)&&rc(e)}function rp(e){return!!e&&!e.isLocal}function rm(e){return rp(e)&&rd(e)}function rf(e,t,i){var n,r,s,o;let{optionsWithoutProcessor:a,audioProcessor:l,videoProcessor:c}=rS(null!=e?e:{}),d=null==t?void 0:t.processor,u=null==i?void 0:i.processor,h=null!=a?a:{};return!0===h.audio&&(h.audio={}),!0===h.video&&(h.video={}),h.audio&&(rg(h.audio,t),null!==(n=(s=h.audio).deviceId)&&void 0!==n||(s.deviceId={ideal:"default"}),(l||d)&&(h.audio.processor=null!=l?l:d)),h.video&&(rg(h.video,i),null!==(r=(o=h.video).deviceId)&&void 0!==r||(o.deviceId={ideal:"default"}),(c||u)&&(h.video.processor=null!=c?c:u)),h}function rg(e,t){return Object.keys(t).forEach(i=>{void 0===e[i]&&(e[i]=t[i])}),e}function rv(e){var t,i,n,r;let s={};if(e.video){if("object"==typeof e.video){let i={},r=e.video;Object.keys(r).forEach(e=>{"resolution"===e?rg(i,r.resolution):i[e]=r[e]}),s.video=i,null!==(t=(n=s.video).deviceId)&&void 0!==t||(n.deviceId={ideal:"default"})}else s.video=!!e.video&&{deviceId:{ideal:"default"}}}else s.video=!1;return e.audio?"object"==typeof e.audio?(s.audio=e.audio,null!==(i=(r=s.audio).deviceId)&&void 0!==i||(r.deviceId={ideal:"default"})):s.audio={deviceId:{ideal:"default"}}:s.audio=!1,s}function ry(){var e;let t="undefined"!=typeof window&&(window.AudioContext||window.webkitAudioContext);if(t){let i=new t({latencyHint:"interactive"});if("suspended"===i.state&&"undefined"!=typeof window&&(null===(e=window.document)||void 0===e?void 0:e.body)){let e=()=>ib(this,void 0,void 0,function*(){var t;try{"suspended"===i.state&&(yield i.resume())}catch(e){console.warn("Error trying to auto-resume audio context",e)}null===(t=window.document.body)||void 0===t||t.removeEventListener("click",e)});window.document.body.addEventListener("click",e)}return i}}function rb(e){return e===nM.Source.Microphone?"audioinput":e===nM.Source.Camera?"videoinput":void 0}function rk(e){return e.split("/")[1].toLowerCase()}function rT(e){return"mediaStreamTrack"in e?{trackID:e.sid,source:e.source,muted:e.isMuted,enabled:e.mediaStreamTrack.enabled,kind:e.kind,streamID:e.mediaStreamID,streamTrackID:e.mediaStreamTrack.id}:{trackID:e.trackSid,enabled:e.isEnabled,muted:e.isMuted,trackInfo:Object.assign({mimeType:e.mimeType,name:e.trackName,encrypted:e.isEncrypted,kind:e.kind,source:e.source},e.track?rT(e.track):{})}}function rS(e){let t,i;let n=Object.assign({},e);return"object"==typeof n.audio&&n.audio.processor&&(t=n.audio.processor,n.audio=Object.assign(Object.assign({},n.audio),{processor:void 0})),"object"==typeof n.video&&n.video.processor&&(i=n.video.processor,n.video=Object.assign(Object.assign({},n.video),{processor:void 0})),{audioProcessor:t,videoProcessor:i,optionsWithoutProcessor:void 0===n?n:"function"!=typeof structuredClone?JSON.parse(JSON.stringify(n)):"object"==typeof n&&null!==n?structuredClone(Object.assign({},n)):structuredClone(n)}}function rC(e,t){return e.width*e.height<t.width*t.height}class rw extends iS.EventEmitter{constructor(e){super(),this.onWorkerMessage=e=>{var t,i;let{kind:n,data:r}=e.data;switch(n){case"error":ip.error(r.error.message),this.emit(oq.EncryptionError,r.error);break;case"initAck":r.enabled&&this.keyProvider.getKeys().forEach(e=>{this.postKey(e)});break;case"enable":if(r.enabled&&this.keyProvider.getKeys().forEach(e=>{this.postKey(e)}),this.encryptionEnabled!==r.enabled&&r.participantIdentity===(null===(t=this.room)||void 0===t?void 0:t.localParticipant.identity))this.emit(oq.ParticipantEncryptionStatusChanged,r.enabled,this.room.localParticipant),this.encryptionEnabled=r.enabled;else if(r.participantIdentity){let e=null===(i=this.room)||void 0===i?void 0:i.getParticipantByIdentity(r.participantIdentity);if(!e)throw TypeError("couldn't set encryption status, participant not found".concat(r.participantIdentity));this.emit(oq.ParticipantEncryptionStatusChanged,r.enabled,e)}break;case"ratchetKey":this.keyProvider.emit(oV.KeyRatcheted,r.ratchetResult,r.participantIdentity,r.keyIndex)}},this.onWorkerError=e=>{ip.error("e2ee worker encountered an error:",{error:e.error}),this.emit(oq.EncryptionError,e.error)},this.keyProvider=e.keyProvider,this.worker=e.worker,this.encryptionEnabled=!1}setup(e){if(!(void 0!==window.RTCRtpSender&&void 0!==window.RTCRtpSender.prototype.createEncodedStreams||nf()))throw new ny("tried to setup end-to-end encryption on an unsupported browser");if(ip.info("setting up e2ee"),e!==this.room){this.room=e,this.setupEventListeners(e,this.keyProvider);let t={kind:"init",data:{keyProviderOptions:this.keyProvider.getOptions(),loglevel:ig.getLevel()}};this.worker&&(ip.info("initializing worker",{worker:this.worker}),this.worker.onmessage=this.onWorkerMessage,this.worker.onerror=this.onWorkerError,this.worker.postMessage(t))}}setParticipantCryptorEnabled(e,t){ip.debug("set e2ee to ".concat(e," for participant ").concat(t)),this.postEnable(e,t)}setSifTrailer(e){e&&0!==e.length?this.postSifTrailer(e):ip.warn("ignoring server sent trailer as it's empty")}setupEngine(e){e.on(oJ.RTPVideoMapUpdate,e=>{this.postRTPMap(e)})}setupEventListeners(e,t){e.on(o$.TrackPublished,(e,t)=>this.setParticipantCryptorEnabled(e.trackInfo.encryption!==e2.NONE,t.identity)),e.on(o$.ConnectionStateChanged,t=>{t===ae.Connected&&e.remoteParticipants.forEach(e=>{e.trackPublications.forEach(t=>{this.setParticipantCryptorEnabled(t.trackInfo.encryption!==e2.NONE,e.identity)})})}).on(o$.TrackUnsubscribed,(e,t,i)=>{var n;let r={kind:"removeTransform",data:{participantIdentity:i.identity,trackId:e.mediaStreamID}};null===(n=this.worker)||void 0===n||n.postMessage(r)}).on(o$.TrackSubscribed,(e,t,i)=>{this.setupE2EEReceiver(e,i.identity,t.trackInfo)}).on(o$.SignalConnected,()=>{if(!this.room)throw TypeError("expected room to be present on signal connect");t.getKeys().forEach(e=>{this.postKey(e)}),this.setParticipantCryptorEnabled(this.room.localParticipant.isE2EEEnabled,this.room.localParticipant.identity)}),e.localParticipant.on(oK.LocalSenderCreated,(e,t)=>ib(this,void 0,void 0,function*(){this.setupE2EESender(t,e)})),t.on(oV.SetKey,e=>this.postKey(e)).on(oV.RatchetRequest,(e,t)=>this.postRatchetRequest(e,t))}postRatchetRequest(e,t){if(!this.worker)throw Error("could not ratchet key, worker is missing");this.worker.postMessage({kind:"ratchetRequest",data:{participantIdentity:e,keyIndex:t}})}postKey(e){var t;let{key:i,participantIdentity:n,keyIndex:r}=e;if(!this.worker)throw Error("could not set key, worker is missing");let s={kind:"setKey",data:{participantIdentity:n,isPublisher:n===(null===(t=this.room)||void 0===t?void 0:t.localParticipant.identity),key:i,keyIndex:r}};this.worker.postMessage(s)}postEnable(e,t){if(this.worker)this.worker.postMessage({kind:"enable",data:{enabled:e,participantIdentity:t}});else throw 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(!(null===(t=this.room)||void 0===t?void 0:t.localParticipant.identity))throw TypeError("could not post rtp map, local participant identity is missing");let 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");this.worker.postMessage({kind:"setSifTrailer",data:{trailer:e}})}setupE2EEReceiver(e,t,i){if(e.receiver){if(!(null==i?void 0:i.mimeType)||""===i.mimeType)throw TypeError("MimeType missing from trackInfo, cannot set up E2EE cryptor");this.handleReceiver(e.receiver,e.mediaStreamID,t,"video"===e.kind?rk(i.mimeType):void 0)}}setupE2EESender(e,t){if(!rl(e)||!t){t||ip.warn("early return because sender is not ready");return}this.handleSender(t,e.mediaStreamID,void 0)}handleReceiver(e,t,i,n){return ib(this,void 0,void 0,function*(){if(this.worker){if(nf())e.transform=new RTCRtpScriptTransform(this.worker,{kind:"decode",participantIdentity:i,trackId:t,codec:n});else{if(nm in e&&n){this.worker.postMessage({kind:"updateCodec",data:{trackId:t,codec:n,participantIdentity:i}});return}let r=e.writableStream,s=e.readableStream;if(!r||!s){let t=e.createEncodedStreams();e.writableStream=t.writable,r=t.writable,e.readableStream=t.readable,s=t.readable}let o={kind:"decode",data:{readableStream:s,writableStream:r,trackId:t,codec:n,participantIdentity:i,isReuse:nm in e}};this.worker.postMessage(o,[s,r])}e[nm]=!0}})}handleSender(e,t,i){var n;if(!(nm in e)&&this.worker){if(!(null===(n=this.room)||void 0===n?void 0:n.localParticipant.identity)||""===this.room.localParticipant.identity)throw TypeError("local identity needs to be known in order to set up encrypted sender");if(nf()){ip.info("initialize script transform");let n={kind:"encode",participantIdentity:this.room.localParticipant.identity,trackId:t,codec:i};e.transform=new RTCRtpScriptTransform(this.worker,n)}else{ip.info("initialize encoded streams");let n=e.createEncodedStreams(),r={kind:"encode",data:{readableStream:n.readable,writableStream:n.writable,codec:i,trackId:t,participantIdentity:this.room.localParticipant.identity,isReuse:!1}};this.worker.postMessage(r,[n.readable,n.writable])}e[nm]=!0}}}let rE="default";class rP{constructor(){this._previousDevices=[]}static getInstance(){return void 0===this.instance&&(this.instance=new rP),this.instance}get previousDevices(){return this._previousDevices}getDevices(e){return ib(this,arguments,void 0,function(e){var t=this;let i=!(arguments.length>1)||void 0===arguments[1]||arguments[1];return function*(){var n;if((null===(n=rP.userMediaPromiseMap)||void 0===n?void 0:n.size)>0){ip.debug("awaiting getUserMedia promise");try{e?yield rP.userMediaPromiseMap.get(e):yield Promise.all(rP.userMediaPromiseMap.values())}catch(e){ip.warn("error waiting for media permissons")}}let r=yield navigator.mediaDevices.enumerateDevices();if(i&&!(nK()&&t.hasDeviceInUse(e))&&(0===r.filter(t=>t.kind===e).length||r.some(t=>{let i=""===t.label,n=!e||t.kind===e;return i&&n}))){let t=yield navigator.mediaDevices.getUserMedia({video:"audioinput"!==e&&"audiooutput"!==e,audio:"videoinput"!==e&&{deviceId:{ideal:"default"}}});r=yield navigator.mediaDevices.enumerateDevices(),t.getTracks().forEach(e=>{e.stop()})}return t._previousDevices=r,e&&(r=r.filter(t=>t.kind===e)),r}()})}normalizeDeviceId(e,t,i){return ib(this,void 0,void 0,function*(){if(t!==rE)return t;let n=yield this.getDevices(e),r=n.find(e=>e.deviceId===rE);if(!r){ip.warn("could not reliably determine default device");return}let s=n.find(e=>e.deviceId!==rE&&e.groupId===(null!=i?i:r.groupId));if(!s){ip.warn("could not reliably determine default device");return}return null==s?void 0:s.deviceId})}hasDeviceInUse(e){return e?rP.userMediaPromiseMap.has(e):rP.userMediaPromiseMap.size>0}}rP.mediaDeviceKinds=["audioinput","audiooutput","videoinput"],rP.userMediaPromiseMap=new Map,function(e){e[e.WAITING=0]="WAITING",e[e.RUNNING=1]="RUNNING",e[e.COMPLETED=2]="COMPLETED"}(o0||(o0={}));class rx{constructor(){this.pendingTasks=new Map,this.taskMutex=new y,this.nextTaskIndex=0}run(e){return ib(this,void 0,void 0,function*(){let t={id:this.nextTaskIndex++,enqueuedAt:Date.now(),status:o0.WAITING};this.pendingTasks.set(t.id,t);let i=yield this.taskMutex.lock();try{return t.executedAt=Date.now(),t.status=o0.RUNNING,yield e()}finally{t.status=o0.COMPLETED,this.pendingTasks.delete(t.id),i()}})}flush(){return ib(this,void 0,void 0,function*(){return this.run(()=>ib(this,void 0,void 0,function*(){}))})}snapshot(){return Array.from(this.pendingTasks.values())}}function rR(e,t){var i;return e.pathname="".concat((i=e.pathname).endsWith("/")?i:"".concat(i,"/")).concat(t),e.toString()}let rO=["syncState","trickle","offer","answer","simulate","leave"];!function(e){e[e.CONNECTING=0]="CONNECTING",e[e.CONNECTED=1]="CONNECTED",e[e.RECONNECTING=2]="RECONNECTING",e[e.DISCONNECTING=3]="DISCONNECTING",e[e.DISCONNECTED=4]="DISCONNECTED"}(o1||(o1={}));class rA{get currentState(){return this.state}get isDisconnected(){return this.state===o1.DISCONNECTING||this.state===o1.DISCONNECTED}get isEstablishingConnection(){return this.state===o1.CONNECTING||this.state===o1.RECONNECTING}getNextRequestId(){return this._requestId+=1,this._requestId}constructor(){var e;let t=arguments.length>0&&void 0!==arguments[0]&&arguments[0],i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};this.rtt=0,this.state=o1.DISCONNECTED,this.log=ip,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=im(null!==(e=i.loggerName)&&void 0!==e?e:oj.Signal),this.loggerContextCb=i.loggerContextCb,this.useJSON=t,this.requestQueue=new rx,this.queuedRequests=[],this.closingLock=new y,this.connectionLock=new y,this.state=o1.DISCONNECTED}get logContext(){var e,t;return null!==(t=null===(e=this.loggerContextCb)||void 0===e?void 0:e.call(this))&&void 0!==t?t:{}}join(e,t,i,n){return ib(this,void 0,void 0,function*(){return this.state=o1.CONNECTING,this.options=i,yield this.connect(e,t,i,n)})}reconnect(e,t,i,n){return ib(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=o1.RECONNECTING,this.clearPingInterval(),yield this.connect(e,t,Object.assign(Object.assign({},this.options),{reconnect:!0,sid:i,reconnectReason:n}))})}connect(e,t,i,n){this.connectOptions=i;let r=function(e,t){let i=new URL(e.startsWith("http")?e.replace(/^(http)/,"ws"):e);return t.forEach((e,t)=>{i.searchParams.set(t,e)}),rR(i,"rtc")}(e,function(e,t,i){var n;let r=new URLSearchParams;return r.set("access_token",e),i.reconnect&&(r.set("reconnect","1"),i.sid&&r.set("sid",i.sid)),r.set("auto_subscribe",i.autoSubscribe?"1":"0"),r.set("sdk",nQ()?"reactnative":"js"),r.set("version",t.version),r.set("protocol",t.protocol.toString()),t.deviceModel&&r.set("device_model",t.deviceModel),t.os&&r.set("os",t.os),t.osVersion&&r.set("os_version",t.osVersion),t.browser&&r.set("browser",t.browser),t.browserVersion&&r.set("browser_version",t.browserVersion),i.adaptiveStream&&r.set("adaptive_stream","1"),i.reconnectReason&&r.set("reconnect_reason",i.reconnectReason.toString()),(null===(n=navigator.connection)||void 0===n?void 0:n.type)&&r.set("network",navigator.connection.type),r}(t,function(){var e;let t=new th({sdk:tp.JS,protocol:16,version:"2.15.4"});return nQ()&&(t.os=null!==(e=n1())&&void 0!==e?e:""),t}(),i)),s=rR(new URL(rr(r)),"validate");return new Promise((e,t)=>ib(this,void 0,void 0,function*(){let o=yield this.connectionLock.lock();try{let o=()=>ib(this,void 0,void 0,function*(){this.close(),clearTimeout(a),t(new nv("room connection has been cancelled (signal)",oW.Cancelled))}),a=setTimeout(()=>{this.close(),t(new nv("room connection has timed out (signal)",oW.ServerUnreachable))},i.websocketTimeout);(null==n?void 0:n.aborted)&&o(),null==n||n.addEventListener("abort",o);let l=new URL(r);l.searchParams.has("access_token")&&l.searchParams.set("access_token","<redacted>"),this.log.debug("connecting to ".concat(l),Object.assign({reconnect:i.reconnect,reconnectReason:i.reconnectReason},this.logContext)),this.ws&&(yield this.close(!1)),this.ws=new WebSocket(r),this.ws.binaryType="arraybuffer",this.ws.onopen=()=>{clearTimeout(a)},this.ws.onerror=e=>ib(this,void 0,void 0,function*(){if(this.state!==o1.CONNECTED){this.state=o1.DISCONNECTED,clearTimeout(a);try{let i=yield fetch(s);if(i.status.toFixed(0).startsWith("4")){let e=yield i.text();t(new nv(e,oW.NotAllowed,i.status))}else t(new nv("Encountered unknown websocket error during connection: ".concat(e.toString()),oW.InternalError,i.status))}catch(e){t(new nv(e instanceof Error?e.message:"server was not reachable",oW.ServerUnreachable))}return}this.handleWSError(e)}),this.ws.onmessage=r=>ib(this,void 0,void 0,function*(){var s,a,l;let c;if("string"==typeof r.data){let e=JSON.parse(r.data);c=tR.fromJson(e,{ignoreUnknownFields:!0})}else if(r.data instanceof ArrayBuffer)c=tR.fromBinary(new Uint8Array(r.data));else{this.log.error("could not decode websocket message: ".concat(typeof r.data),this.logContext);return}if(this.state!==o1.CONNECTED){let r=!1;if((null===(s=c.message)||void 0===s?void 0:s.case)==="join"?(this.state=o1.CONNECTED,null==n||n.removeEventListener("abort",o),this.pingTimeoutDuration=c.message.value.pingTimeout,this.pingIntervalDuration=c.message.value.pingInterval,this.pingTimeoutDuration&&this.pingTimeoutDuration>0&&(this.log.debug("ping config",Object.assign(Object.assign({},this.logContext),{timeout:this.pingTimeoutDuration,interval:this.pingIntervalDuration})),this.startPingInterval()),e(c.message.value)):this.state===o1.RECONNECTING&&"leave"!==c.message.case?(this.state=o1.CONNECTED,null==n||n.removeEventListener("abort",o),this.startPingInterval(),(null===(a=c.message)||void 0===a?void 0:a.case)==="reconnect"?e(c.message.value):(this.log.debug("declaring signal reconnected without reconnect response received",this.logContext),e(void 0),r=!0)):this.isEstablishingConnection&&"leave"===c.message.case?t(new nv("Received leave request while trying to (re)connect",oW.LeaveRequest,void 0,c.message.value.reason)):i.reconnect||t(new nv("did not receive join response, got ".concat(null===(l=c.message)||void 0===l?void 0:l.case," instead"),oW.InternalError)),!r)return}this.signalLatency&&(yield nq(this.signalLatency)),this.handleSignalResponse(c)}),this.ws.onclose=e=>{this.isEstablishingConnection&&t(new nv("Websocket got closed during a (re)connection attempt",oW.InternalError)),this.log.warn("websocket closed",Object.assign(Object.assign({},this.logContext),{reason:e.reason,code:e.code,wasClean:e.wasClean,state:this.state})),this.handleOnClose(e.reason)}}finally{o()}}))}close(){return ib(this,arguments,void 0,function(){var e=this;let t=!(arguments.length>0)||void 0===arguments[0]||arguments[0];return function*(){let i=yield e.closingLock.lock();try{if(e.clearPingInterval(),t&&(e.state=o1.DISCONNECTING),e.ws){e.ws.onmessage=null,e.ws.onopen=null,e.ws.onclose=null;let t=new Promise(t=>{e.ws?e.ws.onclose=()=>{t()}:t()});e.ws.readyState<e.ws.CLOSING&&(e.ws.close(),yield Promise.race([t,nq(250)])),e.ws=void 0}}finally{t&&(e.state=o1.DISCONNECTED),i()}}()})}sendOffer(e,t){this.log.debug("sending offer",Object.assign(Object.assign({},this.logContext),{offerSdp:e.sdp})),this.sendRequest({case:"offer",value:rM(e,t)})}sendAnswer(e,t){return this.log.debug("sending answer",Object.assign(Object.assign({},this.logContext),{answerSdp:e.sdp})),this.sendRequest({case:"answer",value:rM(e,t)})}sendIceCandidate(e,t){return this.log.debug("sending ice candidate",Object.assign(Object.assign({},this.logContext),{candidate:e})),this.sendRequest({case:"trickle",value:new tI({candidateInit:JSON.stringify(e),target:t})})}sendMuteTrack(e,t){return this.sendRequest({case:"mute",value:new tM({sid:e,muted:t})})}sendAddTrack(e){return this.sendRequest({case:"addTrack",value:e})}sendUpdateLocalMetadata(e,t){return ib(this,arguments,void 0,function(e,t){var i=this;let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return function*(){let r=i.getNextRequestId();return yield i.sendRequest({case:"updateMetadata",value:new tG({requestId:r,metadata:e,name:t,attributes:n})}),r}()})}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 tH({trackSid:e,layers:t})})}sendUpdateSubscriptionPermissions(e,t){return this.sendRequest({case:"subscriptionPermission",value:new t5({allParticipants:e,trackPermissions:t})})}sendSimulateScenario(e){return this.sendRequest({case:"simulate",value:e})}sendPing(){return Promise.all([this.sendRequest({case:"ping",value:j.parse(Date.now())}),this.sendRequest({case:"pingReq",value:new it({timestamp:j.parse(Date.now()),rtt:j.parse(this.rtt)})})])}sendUpdateLocalAudioTrack(e,t){return this.sendRequest({case:"updateAudioTrack",value:new tB({trackSid:e,features:t})})}sendLeave(){return this.sendRequest({case:"leave",value:new tz({reason:eH.CLIENT_INITIATED,action:tW.DISCONNECT})})}sendRequest(e){return ib(this,arguments,void 0,function(e){var t=this;let i=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return function*(){if(!i&&!function(e){let t=rO.indexOf(e.case)>=0;return ip.trace("request allowed to bypass queue:",{canPass:t,req:e}),t}(e)&&t.state===o1.RECONNECTING){t.queuedRequests.push(()=>ib(t,void 0,void 0,function*(){yield this.sendRequest(e,!0)}));return}if(i||(yield t.requestQueue.flush()),t.signalLatency&&(yield nq(t.signalLatency)),t.isDisconnected){t.log.debug("skipping signal request (type: ".concat(e.case,") - SignalClient disconnected"));return}if(!t.ws||t.ws.readyState!==t.ws.OPEN){t.log.error("cannot send signal request before connected, type: ".concat(null==e?void 0:e.case),t.logContext);return}let n=new tx({message:e});try{t.useJSON?t.ws.send(n.toJsonString()):t.ws.send(n.toBinary())}catch(e){t.log.error("error sending signal message",Object.assign(Object.assign({},t.logContext),{error:e}))}}()})}handleSignalResponse(e){var t,i;let n=e.message;if(void 0==n){this.log.debug("received unsupported message",this.logContext);return}let r=!1;if("answer"===n.case){let e=rI(n.value);this.onAnswer&&this.onAnswer(e,n.value.id)}else if("offer"===n.case){let e=rI(n.value);this.onOffer&&this.onOffer(e,n.value.id)}else if("trickle"===n.case){let e=JSON.parse(n.value.candidateInit);this.onTrickle&&this.onTrickle(e,n.value.target)}else"update"===n.case?this.onParticipantUpdate&&this.onParticipantUpdate(null!==(t=n.value.participants)&&void 0!==t?t:[]):"trackPublished"===n.case?this.onLocalTrackPublished&&this.onLocalTrackPublished(n.value):"speakersChanged"===n.case?this.onSpeakersChanged&&this.onSpeakersChanged(null!==(i=n.value.speakers)&&void 0!==i?i:[]):"leave"===n.case?this.onLeave&&this.onLeave(n.value):"mute"===n.case?this.onRemoteMuteChanged&&this.onRemoteMuteChanged(n.value.sid,n.value.muted):"roomUpdate"===n.case?this.onRoomUpdate&&n.value.room&&this.onRoomUpdate(n.value.room):"connectionQuality"===n.case?this.onConnectionQuality&&this.onConnectionQuality(n.value):"streamStateUpdate"===n.case?this.onStreamStateUpdate&&this.onStreamStateUpdate(n.value):"subscribedQualityUpdate"===n.case?this.onSubscribedQualityUpdate&&this.onSubscribedQualityUpdate(n.value):"subscriptionPermissionUpdate"===n.case?this.onSubscriptionPermissionUpdate&&this.onSubscriptionPermissionUpdate(n.value):"refreshToken"===n.case?this.onTokenRefresh&&this.onTokenRefresh(n.value):"trackUnpublished"===n.case?this.onLocalTrackUnpublished&&this.onLocalTrackUnpublished(n.value):"subscriptionResponse"===n.case?this.onSubscriptionError&&this.onSubscriptionError(n.value):"pong"===n.case||("pongResp"===n.case?(this.rtt=Date.now()-Number.parseInt(n.value.lastPingTimestamp.toString()),this.resetPingTimeout(),r=!0):"requestResponse"===n.case?this.onRequestResponse&&this.onRequestResponse(n.value):"trackSubscribed"===n.case?this.onLocalTrackSubscribed&&this.onLocalTrackSubscribed(n.value.trackSid):"roomMoved"===n.case?(this.onTokenRefresh&&this.onTokenRefresh(n.value.token),this.onRoomMoved&&this.onRoomMoved(n.value)):this.log.debug("unsupported message",Object.assign(Object.assign({},this.logContext),{msgCase:n.case})));r||this.resetPingTimeout()}setReconnected(){for(;this.queuedRequests.length>0;){let e=this.queuedRequests.shift();e&&this.requestQueue.run(e)}}handleOnClose(e){return ib(this,void 0,void 0,function*(){if(this.state===o1.DISCONNECTED)return;let 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=nA.setTimeout(()=>{this.log.warn("ping timeout triggered. last pong received at: ".concat(new Date(Date.now()-1e3*this.pingTimeoutDuration).toUTCString()),this.logContext),this.handleOnClose("ping timeout")},1e3*this.pingTimeoutDuration)}clearPingTimeout(){this.pingTimeout&&nA.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=nA.setInterval(()=>{this.sendPing()},1e3*this.pingIntervalDuration)}clearPingInterval(){this.log.debug("clearing ping interval",this.logContext),this.clearPingTimeout(),this.pingInterval&&nA.clearInterval(this.pingInterval)}}function rI(e){let t={type:"offer",sdp:e.sdp};switch(e.type){case"answer":case"offer":case"pranswer":case"rollback":t.type=e.type}return t}function rM(e,t){return new tj({sdp:e.sdp,type:e.type,id:t})}class rD{constructor(){this.buffer=[],this._totalSize=0}push(e){this.buffer.push(e),this._totalSize+=e.data.byteLength}pop(){let e=this.buffer.shift();return e&&(this._totalSize-=e.data.byteLength),e}getAll(){return this.buffer.slice()}popToSequence(e){for(;this.buffer.length>0;)if(this.buffer[0].sequence<=e)this.pop();else break}alignBufferedAmount(e){for(;this.buffer.length>0;){let t=this.buffer[0];if(this._totalSize-t.data.byteLength<=e)break;this.pop()}}get length(){return this.buffer.length}}class r_{constructor(e){this._map=new Map,this._lastCleanup=0,this.ttl=e}set(e,t){let i=Date.now();i-this._lastCleanup>this.ttl/2&&this.cleanup();let n=i+this.ttl;return this._map.set(e,{value:t,expiresAt:n}),this}get(e){let t=this._map.get(e);if(t){if(t.expiresAt<Date.now()){this._map.delete(e);return}return t.value}}has(e){let t=this._map.get(e);return!!t&&(!(t.expiresAt<Date.now())||(this._map.delete(e),!1))}delete(e){return this._map.delete(e)}clear(){this._map.clear()}cleanup(){let e=Date.now();for(let[t,i]of this._map.entries())i.expiresAt<e&&this._map.delete(t);this._lastCleanup=e}get size(){return this.cleanup(),this._map.size}forEach(e){for(let[t,i]of(this.cleanup(),this._map.entries()))i.expiresAt>=Date.now()&&e(i.value,t,this.asValueMap())}map(e){this.cleanup();let t=[],i=this.asValueMap();for(let[n,r]of i.entries())t.push(e(r,n,i));return t}asValueMap(){let e=new Map;for(let[t,i]of this._map.entries())i.expiresAt>=Date.now()&&e.set(t,i.value);return e}}var rN={},rL={},rj={exports:{}};function rU(){if(o2)return rj.exports;o2=1;var e=rj.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 null!=e.address?"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 null!=e.subtype?"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 null!=e.sessionConfig?"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+=(null!=e.raddr?" raddr %s rport %d":"%v%v")+(null!=e.tcptype?" tcptype %s":"%v"),null!=e.generation&&(t+=" generation %d"),t+=(null!=e["network-id"]?" network-id %d":"%v")+(null!=e["network-cost"]?" network-cost %d":"%v")}},{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 null!=e.attribute&&(t+=" %s",null!=e.value&&(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 null!=e.maxMessageSize?"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: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: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"+(null!=e.clksrcExt?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(e){return"mediaclk:"+((null!=e.id?"id=%s %s":"%v%s")+(null!=e.mediaClockValue?"=%s":"")+(null!=e.rateNumerator?" rate=%s":""))+(null!=e.rateDenominator?"/%s":"")}},{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(e).forEach(function(t){e[t].forEach(function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")})}),rj.exports}var rF=function(){if(o6)return rN;o6=1;var e,t,i,n,r,s,o=(o3||(o3=1,e=function(e){return String(Number(e))===e?Number(e):e},t=function(t,i,n,r){if(r&&!n)i[r]=e(t[1]);else for(var s=0;s<n.length;s+=1)null!=t[s+1]&&(i[n[s]]=e(t[s+1]))},i=function(e,i,n){var r=e.name&&e.names;e.push&&!i[e.push]?i[e.push]=[]:r&&!i[e.name]&&(i[e.name]={});var s=e.push?{}:r?i[e.name]:i;t(n.match(e.reg),s,e.names,e.name),e.push&&i[e.push].push(s)},n=rU(),r=RegExp.prototype.test.bind(/^([a-z])=(.*)/),rL.parse=function(e){var t={},s=[],o=t;return e.split(/(\r\n|\r|\n)/).filter(r).forEach(function(e){var t=e[0],r=e.slice(2);"m"===t&&(s.push({rtp:[],fmtp:[]}),o=s[s.length-1]);for(var a=0;a<(n[t]||[]).length;a+=1){var l=n[t][a];if(l.reg.test(r))return i(l,o,r)}}),t.media=s,t},s=function(t,i){var n=i.split(/=(.+)/,2);return 2===n.length?t[n[0]]=e(n[1]):1===n.length&&i.length>1&&(t[n[0]]=void 0),t},rL.parseParams=function(e){return e.split(/;\s?/).reduce(s,{})},rL.parseFmtpConfig=rL.parseParams,rL.parsePayloads=function(e){return e.toString().split(" ").map(Number)},rL.parseRemoteCandidates=function(t){for(var i=[],n=t.split(" ").map(e),r=0;r<n.length;r+=3)i.push({component:n[r],ip:n[r+1],port:n[r+2]});return i},rL.parseImageAttributes=function(e){return e.split(" ").map(function(e){return e.substring(1,e.length-1).split(",").reduce(s,{})})},rL.parseSimulcastStreamList=function(t){return t.split(";").map(function(t){return t.split(",").map(function(t){var i,n=!1;return"~"!==t[0]?i=e(t):(i=e(t.substring(1,t.length)),n=!0),{scid:i,paused:n}})})}),rL),a=function(){if(o4)return o5;o4=1;var e=rU(),t=/%[sdv%]/g,i=function(e){var i=1,n=arguments,r=n.length;return e.replace(t,function(e){if(i>=r)return e;var t=n[i];switch(i+=1,e){case"%%":return"%";case"%s":return String(t);case"%d":return Number(t);case"%v":return""}})},n=function(e,t,n){var r=[e+"="+(t.format instanceof Function?t.format(t.push?n:n[t.name]):t.format)];if(t.names)for(var s=0;s<t.names.length;s+=1){var o=t.names[s];t.name?r.push(n[t.name][o]):r.push(n[t.names[s]])}else r.push(n[t.name]);return i.apply(null,r)},r=["v","o","s","i","u","e","p","c","b","t","r","z","a"],s=["i","c","b","a"];return o5=function(t,i){i=i||{},null==t.version&&(t.version=0),null==t.name&&(t.name=" "),t.media.forEach(function(e){null==e.payloads&&(e.payloads="")});var o=i.outerOrder||r,a=i.innerOrder||s,l=[];return o.forEach(function(i){e[i].forEach(function(e){e.name in t&&null!=t[e.name]?l.push(n(i,e,t)):e.push in t&&null!=t[e.push]&&t[e.push].forEach(function(t){l.push(n(i,e,t))})})}),t.media.forEach(function(t){l.push(n("m",e.m[0],t)),a.forEach(function(i){e[i].forEach(function(e){e.name in t&&null!=t[e.name]?l.push(n(i,e,t)):e.push in t&&null!=t[e.push]&&t[e.push].forEach(function(t){l.push(n(i,e,t))})})})}),l.join("\r\n")+"\r\n"}}(),l=rU();return rN.grammar=l,rN.write=a,rN.parse=o.parse,rN.parseParams=o.parseParams,rN.parseFmtpConfig=o.parseFmtpConfig,rN.parsePayloads=o.parsePayloads,rN.parseRemoteCandidates=o.parseRemoteCandidates,rN.parseImageAttributes=o.parseImageAttributes,rN.parseSimulcastStreamList=o.parseSimulcastStreamList,rN}();function rV(e,t,i){void 0===t&&(t=50),void 0===i&&(i={});var n,r,s,o=null!=(n=i.isImmediate)&&n,a=null!=(r=i.callback)&&r,l=i.maxWait,c=Date.now(),d=[],u=function(){var i=[].slice.call(arguments),n=this;return new Promise(function(r,u){var h=o&&void 0===s;if(void 0!==s&&clearTimeout(s),s=setTimeout(function(){if(s=void 0,c=Date.now(),!o){var t=e.apply(n,i);a&&a(t),d.forEach(function(e){return(0,e.resolve)(t)}),d=[]}},function(){if(void 0!==l){var e=Date.now()-c;if(e+t>=l)return l-e}return t}()),h){var p=e.apply(n,i);return a&&a(p),r(p)}d.push({resolve:r,reject:u})})};return u.cancel=function(e){void 0!==s&&clearTimeout(s),d.forEach(function(t){return(0,t.reject)(e)}),d=[]},u}let rB={NegotiationStarted:"negotiationStarted",NegotiationComplete:"negotiationComplete",RTPVideoPayloadTypes:"rtpVideoPayloadTypes"};class rq extends iS.EventEmitter{get pc(){return this._pc||(this._pc=this.createPC()),this._pc}constructor(e){var t;let i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};super(),this.log=ip,this.ddExtID=0,this.latestOfferId=0,this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate=!1,this.trackBitrates=[],this.remoteStereoMids=[],this.remoteNackMids=[],this.negotiate=rV(e=>ib(this,void 0,void 0,function*(){this.emit(rB.NegotiationStarted);try{yield this.createAndSendOffer()}catch(t){if(e)e(t);else throw t}}),20),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=im(null!==(t=i.loggerName)&&void 0!==t?t:oj.PCTransport),this.loggerOptions=i,this.config=e,this._pc=this.createPC(),this.offerLock=new y}createPC(){let e=new RTCPeerConnection(this.config);return e.onicecandidate=e=>{var t;e.candidate&&(null===(t=this.onIceCandidate)||void 0===t||t.call(this,e.candidate))},e.onicecandidateerror=e=>{var t;null===(t=this.onIceCandidateError)||void 0===t||t.call(this,e)},e.oniceconnectionstatechange=()=>{var t;null===(t=this.onIceConnectionStateChange)||void 0===t||t.call(this,e.iceConnectionState)},e.onsignalingstatechange=()=>{var t;null===(t=this.onSignalingStatechange)||void 0===t||t.call(this,e.signalingState)},e.onconnectionstatechange=()=>{var t;null===(t=this.onConnectionStateChange)||void 0===t||t.call(this,e.connectionState)},e.ondatachannel=e=>{var t;null===(t=this.onDataChannel)||void 0===t||t.call(this,e)},e.ontrack=e=>{var t;null===(t=this.onTrack)||void 0===t||t.call(this,e)},e}get logContext(){var e,t;return Object.assign({},null===(t=(e=this.loggerOptions).loggerContextCb)||void 0===t?void 0:t.call(e))}get isICEConnected(){return null!==this._pc&&("connected"===this.pc.iceConnectionState||"completed"===this.pc.iceConnectionState)}addIceCandidate(e){return ib(this,void 0,void 0,function*(){if(this.pc.remoteDescription&&!this.restartingIce)return this.pc.addIceCandidate(e);this.pendingCandidates.push(e)})}setRemoteDescription(e,t){return ib(this,void 0,void 0,function*(){var i;let n;if("answer"===e.type&&this.latestOfferId>0&&t>0&&t!==this.latestOfferId)return this.log.warn("ignoring answer for old offer",Object.assign(Object.assign({},this.logContext),{offerId:t,latestOfferId:this.latestOfferId})),!1;if("offer"===e.type){let{stereoMids:t,nackMids:i}=function(e){var t;let i=[],n=[],r=rF.parse(null!==(t=e.sdp)&&void 0!==t?t:""),s=0;return r.media.forEach(e=>{var t;"audio"===e.type&&(e.rtp.some(e=>"opus"===e.codec&&(s=e.payload,!0)),(null===(t=e.rtcpFb)||void 0===t?void 0:t.some(e=>e.payload===s&&"nack"===e.type))&&n.push(e.mid),e.fmtp.some(t=>t.payload===s&&(t.config.includes("sprop-stereo=1")&&i.push(e.mid),!0)))}),{stereoMids:i,nackMids:n}}(e);this.remoteStereoMids=t,this.remoteNackMids=i}else if("answer"===e.type){let t=rF.parse(null!==(i=e.sdp)&&void 0!==i?i:"");t.media.forEach(e=>{"audio"===e.type&&this.trackBitrates.some(t=>{if(!t.transceiver||e.mid!=t.transceiver.mid)return!1;let i=0;if(e.rtp.some(e=>e.codec.toUpperCase()===t.codec.toUpperCase()&&(i=e.payload,!0)),0===i)return!0;let n=!1;for(let r of e.fmtp)if(r.payload===i){r.config=r.config.split(";").filter(e=>!e.includes("maxaveragebitrate")).join(";"),t.maxbr>0&&(r.config+=";maxaveragebitrate=".concat(1e3*t.maxbr)),n=!0;break}return!n&&t.maxbr>0&&e.fmtp.push({payload:i,config:"maxaveragebitrate=".concat(1e3*t.maxbr)}),!0})}),n=rF.write(t)}return yield this.setMungedSDP(e,n,!0),this.pendingCandidates.forEach(e=>{this.pc.addIceCandidate(e)}),this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate?(this.renegotiate=!1,yield this.createAndSendOffer()):"answer"===e.type&&(this.emit(rB.NegotiationComplete),e.sdp&&rF.parse(e.sdp).media.forEach(e=>{"video"===e.type&&this.emit(rB.RTPVideoPayloadTypes,e.rtp)})),!0})}createAndSendOffer(e){return ib(this,void 0,void 0,function*(){var t;let i=yield this.offerLock.lock();try{if(void 0===this.onOffer)return;if((null==e?void 0:e.iceRestart)&&(this.log.debug("restarting ICE",this.logContext),this.restartingIce=!0),this._pc&&"have-local-offer"===this._pc.signalingState){let t=this._pc.remoteDescription;if((null==e?void 0:e.iceRestart)&&t)yield this._pc.setRemoteDescription(t);else{this.renegotiate=!0;return}}else if(!this._pc||"closed"===this._pc.signalingState){this.log.warn("could not createOffer with closed peer connection",this.logContext);return}this.log.debug("starting to negotiate",this.logContext);let i=this.latestOfferId+1;this.latestOfferId=i;let n=yield this.pc.createOffer(e);this.log.debug("original offer",Object.assign({sdp:n.sdp},this.logContext));let r=rF.parse(null!==(t=n.sdp)&&void 0!==t?t:"");if(r.media.forEach(e=>{rW(e),"audio"===e.type?rz(e,[],[]):"video"===e.type&&this.trackBitrates.some(t=>{if(!e.msid||!t.cid||!e.msid.includes(t.cid))return!1;let i=0;if(e.rtp.some(e=>e.codec.toUpperCase()===t.codec.toUpperCase()&&(i=e.payload,!0)),0===i||(nH(t.codec)&&!nK()&&this.ensureVideoDDExtensionForSVC(e,r),"av1"!==t.codec))return!0;let n=Math.round(.7*t.maxbr);for(let t of e.fmtp)if(t.payload===i){t.config.includes("x-google-start-bitrate")||(t.config+=";x-google-start-bitrate=".concat(n));break}return!0})}),this.latestOfferId>i){this.log.warn("latestOfferId mismatch",Object.assign(Object.assign({},this.logContext),{latestOfferId:this.latestOfferId,offerId:i}));return}yield this.setMungedSDP(n,rF.write(r)),this.onOffer(n,this.latestOfferId)}finally{i()}})}createAndSetAnswer(){return ib(this,void 0,void 0,function*(){var e;let t=yield this.pc.createAnswer(),i=rF.parse(null!==(e=t.sdp)&&void 0!==e?e:"");return i.media.forEach(e=>{rW(e),"audio"===e.type&&rz(e,this.remoteStereoMids,this.remoteNackMids)}),yield this.setMungedSDP(t,rF.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 nT("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 nT("PC closed, cannot configure");return null===(t=this._pc)||void 0===t?void 0:t.setConfiguration(e)}canRemoveTrack(){var e;return!!(null===(e=this._pc)||void 0===e?void 0:e.removeTrack)}removeTrack(e){var t;return null===(t=this._pc)||void 0===t?void 0:t.removeTrack(e)}getConnectionState(){var e,t;return null!==(t=null===(e=this._pc)||void 0===e?void 0:e.connectionState)&&void 0!==t?t:"closed"}getICEConnectionState(){var e,t;return null!==(t=null===(e=this._pc)||void 0===e?void 0:e.iceConnectionState)&&void 0!==t?t:"closed"}getSignallingState(){var e,t;return null!==(t=null===(e=this._pc)||void 0===e?void 0:e.signalingState)&&void 0!==t?t:"closed"}getTransceivers(){var e,t;return null!==(t=null===(e=this._pc)||void 0===e?void 0:e.getTransceivers())&&void 0!==t?t:[]}getSenders(){var e,t;return null!==(t=null===(e=this._pc)||void 0===e?void 0:e.getSenders())&&void 0!==t?t:[]}getLocalDescription(){var e;return null===(e=this._pc)||void 0===e?void 0:e.localDescription}getRemoteDescription(){var e;return null===(e=this.pc)||void 0===e?void 0:e.remoteDescription}getStats(){return this.pc.getStats()}getConnectedAddress(){return ib(this,void 0,void 0,function*(){var e;if(!this._pc)return;let t="",i=new Map,n=new Map;if((yield this._pc.getStats()).forEach(e=>{switch(e.type){case"transport":t=e.selectedCandidatePairId;break;case"candidate-pair":""===t&&e.selected&&(t=e.id),i.set(e.id,e);break;case"remote-candidate":n.set(e.id,"".concat(e.address,":").concat(e.port))}}),""===t)return;let r=null===(e=i.get(t))||void 0===e?void 0:e.remoteCandidateId;if(void 0!==r)return n.get(r)})}setMungedSDP(e,t,i){return ib(this,void 0,void 0,function*(){if(t){let n=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(i){this.log.warn("not able to set ".concat(e.type,", falling back to unmodified sdp"),Object.assign(Object.assign({},this.logContext),{error:i,sdp:t})),e.sdp=n}}try{i?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e)}catch(r){let t="unknown error";r instanceof Error?t=r.message:"string"==typeof r&&(t=r);let n={error:t,sdp:e.sdp};throw!i&&this.pc.remoteDescription&&(n.remoteSdp=this.pc.remoteDescription),this.log.error("unable to set ".concat(e.type),Object.assign(Object.assign({},this.logContext),{fields:n})),new nS(t)}})}ensureVideoDDExtensionForSVC(e,t){var i,n;if(!(null===(i=e.ext)||void 0===i?void 0:i.some(e=>e.uri===nB))){if(0===this.ddExtID){let e=0;t.media.forEach(t=>{var i;"video"===t.type&&(null===(i=t.ext)||void 0===i||i.forEach(t=>{t.value>e&&(e=t.value)}))}),this.ddExtID=e+1}null===(n=e.ext)||void 0===n||n.push({value:this.ddExtID,uri:nB})}}}function rz(e,t,i){let n=0;e.rtp.some(e=>"opus"===e.codec&&(n=e.payload,!0)),n>0&&(e.rtcpFb||(e.rtcpFb=[]),i.includes(e.mid)&&!e.rtcpFb.some(e=>e.payload===n&&"nack"===e.type)&&e.rtcpFb.push({payload:n,type:"nack"}),t.includes(e.mid)&&e.fmtp.some(e=>e.payload===n&&(e.config.includes("stereo=1")||(e.config+=";stereo=1"),!0)))}function rW(e){if(e.connection){let t=e.connection.ip.indexOf(":")>=0;(4===e.connection.version&&t||6===e.connection.version&&!t)&&(e.connection.ip="0.0.0.0",e.connection.version=4)}}let rH={audioPreset:oZ.music,dtx:!0,red:!0,forceStereo:!1,simulcast:!0,screenShareEncoding:nV.h1080fps15.encoding,stopMicTrackOnMute:!1,videoCodec:"vp8",backupCodec:!0,preConnectBuffer:!1},rG={deviceId:{ideal:"default"},autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0,voiceIsolation:!0},r$={deviceId:{ideal:"default"},resolution:nU.h720.resolution},rK={adaptiveStream:!1,dynacast:!1,stopLocalTrackOnUnpublish:!0,reconnectPolicy:new iy,disconnectOnPageLeave:!0,webAudioMix:!1},rJ={autoSubscribe:!0,maxRetries:1,peerConnectionTimeout:15e3,websocketTimeout:15e3};!function(e){e[e.NEW=0]="NEW",e[e.CONNECTING=1]="CONNECTING",e[e.CONNECTED=2]="CONNECTED",e[e.FAILED=3]="FAILED",e[e.CLOSING=4]="CLOSING",e[e.CLOSED=5]="CLOSED"}(o9||(o9={}));class rX{get needsPublisher(){return this.isPublisherConnectionRequired}get needsSubscriber(){return this.isSubscriberConnectionRequired}get currentState(){return this.state}constructor(e,t,i){var n;this.peerConnectionTimeout=rJ.peerConnectionTimeout,this.log=ip,this.updateState=()=>{var e;let t=this.state,i=this.requiredTransports.map(e=>e.getConnectionState());i.every(e=>"connected"===e)?this.state=o9.CONNECTED:i.some(e=>"failed"===e)?this.state=o9.FAILED:i.some(e=>"connecting"===e)?this.state=o9.CONNECTING:i.every(e=>"closed"===e)?this.state=o9.CLOSED:i.some(e=>"closed"===e)?this.state=o9.CLOSING:i.every(e=>"new"===e)&&(this.state=o9.NEW),t!==this.state&&(this.log.debug("pc state change: from ".concat(o9[t]," to ").concat(o9[this.state]),this.logContext),null===(e=this.onStateChange)||void 0===e||e.call(this,this.state,this.publisher.getConnectionState(),this.subscriber.getConnectionState()))},this.log=im(null!==(n=i.loggerName)&&void 0!==n?n:oj.PCManager),this.loggerOptions=i,this.isPublisherConnectionRequired=!t,this.isSubscriberConnectionRequired=t,this.publisher=new rq(e,i),this.subscriber=new rq(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=e=>{var t;null===(t=this.onIceCandidate)||void 0===t||t.call(this,e,tw.PUBLISHER)},this.subscriber.onIceCandidate=e=>{var t;null===(t=this.onIceCandidate)||void 0===t||t.call(this,e,tw.SUBSCRIBER)},this.subscriber.onDataChannel=e=>{var t;null===(t=this.onDataChannel)||void 0===t||t.call(this,e)},this.subscriber.onTrack=e=>{var t;null===(t=this.onTrack)||void 0===t||t.call(this,e)},this.publisher.onOffer=(e,t)=>{var i;null===(i=this.onPublisherOffer)||void 0===i||i.call(this,e,t)},this.state=o9.NEW,this.connectionLock=new y,this.remoteOfferLock=new y}get logContext(){var e,t;return Object.assign({},null===(t=(e=this.loggerOptions).loggerContextCb)||void 0===t?void 0:t.call(e))}requirePublisher(){let e=!(arguments.length>0)||void 0===arguments[0]||arguments[0];this.isPublisherConnectionRequired=e,this.updateState()}requireSubscriber(){let e=!(arguments.length>0)||void 0===arguments[0]||arguments[0];this.isSubscriberConnectionRequired=e,this.updateState()}createAndSendPublisherOffer(e){return this.publisher.createAndSendOffer(e)}setPublisherAnswer(e,t){return this.publisher.setRemoteDescription(e,t)}removeTrack(e){return this.publisher.removeTrack(e)}close(){return ib(this,void 0,void 0,function*(){if(this.publisher&&"closed"!==this.publisher.getSignallingState()){let e=this.publisher;for(let t of e.getSenders())try{e.canRemoveTrack()&&e.removeTrack(t)}catch(e){this.log.warn("could not removeTrack",Object.assign(Object.assign({},this.logContext),{error:e}))}}yield Promise.all([this.publisher.close(),this.subscriber.close()]),this.updateState()})}triggerIceRestart(){return ib(this,void 0,void 0,function*(){this.subscriber.restartingIce=!0,this.needsPublisher&&(yield this.createAndSendPublisherOffer({iceRestart:!0}))})}addIceCandidate(e,t){return ib(this,void 0,void 0,function*(){t===tw.PUBLISHER?yield this.publisher.addIceCandidate(e):yield this.subscriber.addIceCandidate(e)})}createSubscriberAnswerFromOffer(e,t){return ib(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()}));let i=yield this.remoteOfferLock.lock();try{if(!(yield this.subscriber.setRemoteDescription(e,t)))return;return yield this.subscriber.createAndSetAnswer()}finally{i()}})}updateConfiguration(e,t){this.publisher.setConfiguration(e),this.subscriber.setConfiguration(e),t&&this.triggerIceRestart()}ensurePCTransportConnection(e,t){return ib(this,void 0,void 0,function*(){var i;let n=yield this.connectionLock.lock();try{this.isPublisherConnectionRequired&&"connected"!==this.publisher.getConnectionState()&&"connecting"!==this.publisher.getConnectionState()&&(this.log.debug("negotiation required, start negotiating",this.logContext),this.publisher.negotiate()),yield Promise.all(null===(i=this.requiredTransports)||void 0===i?void 0:i.map(i=>this.ensureTransportConnected(i,e,t)))}finally{n()}})}negotiate(e){return ib(this,void 0,void 0,function*(){return new Promise((t,i)=>ib(this,void 0,void 0,function*(){let n=setTimeout(()=>{i("negotiation timed out")},this.peerConnectionTimeout);e.signal.addEventListener("abort",()=>{clearTimeout(n),i("negotiation aborted")}),this.publisher.once(rB.NegotiationStarted,()=>{e.signal.aborted||this.publisher.once(rB.NegotiationComplete,()=>{clearTimeout(n),t()})}),yield this.publisher.negotiate(e=>{clearTimeout(n),i(e)})}))})}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===tw.PUBLISHER?this.publisher.getConnectedAddress():e===tw.SUBSCRIBER?this.publisher.getConnectedAddress():this.requiredTransports[0].getConnectedAddress()}get requiredTransports(){let e=[];return this.isPublisherConnectionRequired&&e.push(this.publisher),this.isSubscriberConnectionRequired&&e.push(this.subscriber),e}ensureTransportConnected(e,t){return ib(this,arguments,void 0,function(e,t){var i=this;let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:this.peerConnectionTimeout;return function*(){if("connected"!==e.getConnectionState())return new Promise((e,r)=>ib(i,void 0,void 0,function*(){let i=()=>{this.log.warn("abort transport connection",this.logContext),nA.clearTimeout(s),r(new nv("room connection has been cancelled",oW.Cancelled))};(null==t?void 0:t.signal.aborted)&&i(),null==t||t.signal.addEventListener("abort",i);let s=nA.setTimeout(()=>{null==t||t.signal.removeEventListener("abort",i),r(new nv("could not establish pc connection",oW.InternalError))},n);for(;this.state!==o9.CONNECTED;)if(yield nq(50),null==t?void 0:t.signal.aborted){r(new nv("room connection has been cancelled",oW.Cancelled));return}nA.clearTimeout(s),null==t||t.signal.removeEventListener("abort",i),e()}))}()})}}class rY extends Error{constructor(e,t,i){super(t),this.code=e,this.message=rZ(t,rY.MAX_MESSAGE_BYTES),this.data=i?rZ(i,rY.MAX_DATA_BYTES):void 0}static fromProto(e){return new rY(e.code,e.message,e.data)}toProto(){return new tl({code:this.code,message:this.message,data:this.data})}static builtIn(e,t){return new rY(rY.ErrorCode[e],rY.ErrorMessage[e],t)}}function rQ(e){return new TextEncoder().encode(e).length}function rZ(e,t){if(rQ(e)<=t)return e;let i=0,n=e.length,r=new TextEncoder;for(;i<n;){let s=Math.floor((i+n+1)/2);r.encode(e.slice(0,s)).length<=t?i=s:n=s-1}return e.slice(0,i)}function r0(e,t){let i,n;return t?("bytesReceived"in e?(i=e.bytesReceived,n=t.bytesReceived):"bytesSent"in e&&(i=e.bytesSent,n=t.bytesSent),void 0===i||void 0===n||void 0===e.timestamp||void 0===t.timestamp)?0:(i-n)*8e3/(e.timestamp-t.timestamp):0}rY.MAX_MESSAGE_BYTES=256,rY.MAX_DATA_BYTES=15360,rY.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},rY.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"};let r1="undefined"!=typeof MediaRecorder;class r2{constructor(){throw Error("MediaRecorder is not available in this environment")}}let r3=r1?MediaRecorder:r2;class r5 extends r3{constructor(e,t){let i,n;if(!r1)throw Error("MediaRecorder is not available in this environment");super(new MediaStream([e.mediaStreamTrack]),t);let r=()=>void 0===n,s=()=>{this.removeEventListener("dataavailable",i),this.removeEventListener("stop",s),this.removeEventListener("error",o),null==n||n.close(),n=void 0},o=e=>{null==n||n.error(e),this.removeEventListener("dataavailable",i),this.removeEventListener("stop",s),this.removeEventListener("error",o),n=void 0};this.byteStream=new ReadableStream({start:e=>{n=e,i=t=>ib(this,void 0,void 0,function*(){let i;if(t.data.arrayBuffer)i=new Uint8Array((yield t.data.arrayBuffer()));else if(t.data.byteArray)i=t.data.byteArray;else throw Error("no data available!");r()||e.enqueue(i)}),this.addEventListener("dataavailable",i)},cancel:()=>{s()}}),this.addEventListener("stop",s),this.addEventListener("error",o)}}class r4 extends nM{get sender(){return this._sender}set sender(e){this._sender=e}get constraints(){return this._constraints}get hasPreConnectBuffer(){return!!this.localTrackRecorder}constructor(e,t,i){let n=arguments.length>3&&void 0!==arguments[3]&&arguments[3],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=rV(()=>ib(this,void 0,void 0,function*(){yield this.pauseUpstream()}),5e3),this.handleTrackUnmuteEvent=()=>ib(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(oX.Ended,this)},this.reacquireTrack=!1,this.providedByUser=n,this.muteLock=new y,this.pauseUpstreamLock=new y,this.processorLock=new y,this.restartLock=new y,this.setMediaStreamTrack(e,!0),this._constraints=e.getConstraints(),i&&(this._constraints=i)}get id(){return this._mediaStreamTrack.id}get dimensions(){if(this.kind!==nM.Kind.Video)return;let{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 null!==(t=null===(e=this.processor)||void 0===e?void 0:e.processedTrack)&&void 0!==t?t:this._mediaStreamTrack}get isLocal(){return!0}getSourceTrackSettings(){return this._mediaStreamTrack.getSettings()}setMediaStreamTrack(e,t){return ib(this,void 0,void 0,function*(){var i;let n;if(e!==this._mediaStreamTrack||t){if(this._mediaStreamTrack&&(this.attachedElements.forEach(e=>{n_(this._mediaStreamTrack,e)}),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()),this.processor&&e){let t=yield this.processorLock.lock();try{if(this.log.debug("restarting processor",this.logContext),"unknown"===this.kind)throw TypeError("cannot set processor on track of unknown kind");this.processorElement&&(nD(e,this.processorElement),this.processorElement.muted=!0),yield this.processor.restart({track:e,kind:this.kind,element:this.processorElement}),n=this.processor.processedTrack}finally{t()}}this.sender&&(null===(i=this.sender.transport)||void 0===i?void 0:i.state)!=="closed"&&(yield this.sender.replaceTrack(null!=n?n:e)),this.providedByUser||this._mediaStreamTrack===e||this._mediaStreamTrack.stop(),this._mediaStreamTrack=e,e&&(this._mediaStreamTrack.enabled=!this.isMuted,yield this.resumeUpstream(),this.attachedElements.forEach(t=>{nD(null!=n?n:e,t)}))}})}waitForDimensions(){return ib(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1e3;return function*(){var i;if(e.kind===nM.Kind.Audio)throw Error("cannot get dimensions for audio tracks");(null===(i=nP())||void 0===i?void 0:i.os)==="iOS"&&(yield nq(10));let n=Date.now();for(;Date.now()-n<t;){let t=e.dimensions;if(t)return t;yield nq(50)}throw new nb("unable to get track dimensions after timeout")}()})}setDeviceId(e){return ib(this,void 0,void 0,function*(){return this._constraints.deviceId===e&&this._mediaStreamTrack.getSettings().deviceId===rn(e)||(this._constraints.deviceId=e,!!this.isMuted||(yield this.restartTrack(),rn(e)===this._mediaStreamTrack.getSettings().deviceId))})}getDeviceId(){return ib(this,arguments,void 0,function(){var e=this;let t=!(arguments.length>0)||void 0===arguments[0]||arguments[0];return function*(){if(e.source===nM.Source.ScreenShare)return;let{deviceId:i,groupId:n}=e._mediaStreamTrack.getSettings(),r=e.kind===nM.Kind.Audio?"audioinput":"videoinput";return t?rP.getInstance().normalizeDeviceId(r,i,n):i}()})}mute(){return ib(this,void 0,void 0,function*(){return this.setTrackMuted(!0),this})}unmute(){return ib(this,void 0,void 0,function*(){return this.setTrackMuted(!1),this})}replaceTrack(e,t){return ib(this,void 0,void 0,function*(){let i,n;if(!this.sender)throw new nb("unable to replace an unpublished track");return"boolean"==typeof t?i=t:void 0!==t&&(i=t.userProvidedTrack,n=t.stopProcessor),this.providedByUser=null==i||i,this.log.debug("replace MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(e),n&&this.processor&&(yield this.stopProcessor()),this})}restart(e){return ib(this,void 0,void 0,function*(){this.manuallyStopped=!1;let t=yield this.restartLock.lock();try{e||(e=this._constraints);let{deviceId:t,facingMode:i}=e,n=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&0>t.indexOf(n)&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var r=0,n=Object.getOwnPropertySymbols(e);r<n.length;r++)0>t.indexOf(n[r])&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(i[n[r]]=e[n[r]]);return i}(e,["deviceId","facingMode"]);this.log.debug("restarting track with constraints",Object.assign(Object.assign({},this.logContext),{constraints:e}));let r={audio:!1,video:!1};this.kind===nM.Kind.Video?r.video=!t&&!i||{deviceId:t,facingMode:i}:r.audio=!t||{deviceId:t},this.attachedElements.forEach(e=>{n_(this.mediaStreamTrack,e)}),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.stop();let s=(yield navigator.mediaDevices.getUserMedia(r)).getTracks()[0];return yield s.applyConstraints(n),s.addEventListener("ended",this.handleEnded),this.log.debug("re-acquired MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(s),this._constraints=e,this.emit(oX.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?oX.Muted:oX.Unmuted,this))}get needsReAcquisition(){return"live"!==this._mediaStreamTrack.readyState||this._mediaStreamTrack.muted||!this._mediaStreamTrack.enabled||this.reacquireTrack}handleAppVisibilityChanged(){let e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return ib(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),!nX()||(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),null===(e=this.processor)||void 0===e||e.destroy(),this.processor=void 0}pauseUpstream(){return ib(this,void 0,void 0,function*(){var e;let t=yield this.pauseUpstreamLock.lock();try{if(!0===this._isUpstreamPaused)return;if(!this.sender){this.log.warn("unable to pause upstream for an unpublished track",this.logContext);return}this._isUpstreamPaused=!0,this.emit(oX.UpstreamPaused,this);let t=nP();if((null==t?void 0:t.name)==="Safari"&&0>n3(t.version,"12.0"))throw new ny("pauseUpstream is not supported on Safari < 12.");(null===(e=this.sender.transport)||void 0===e?void 0:e.state)!=="closed"&&(yield this.sender.replaceTrack(null))}finally{t()}})}resumeUpstream(){return ib(this,void 0,void 0,function*(){var e;let t=yield this.pauseUpstreamLock.lock();try{if(!1===this._isUpstreamPaused)return;if(!this.sender){this.log.warn("unable to resume upstream for an unpublished track",this.logContext);return}this._isUpstreamPaused=!1,this.emit(oX.UpstreamResumed,this),(null===(e=this.sender.transport)||void 0===e?void 0:e.state)!=="closed"&&(yield this.sender.replaceTrack(this.mediaStreamTrack))}finally{t()}})}getRTCStatsReport(){return ib(this,void 0,void 0,function*(){var e;if(null===(e=this.sender)||void 0===e?void 0:e.getStats)return yield this.sender.getStats()})}setProcessor(e){return ib(this,arguments,void 0,function(e){var t=this;let i=!(arguments.length>1)||void 0===arguments[1]||arguments[1];return function*(){var n;let r=yield t.processorLock.lock();try{t.log.debug("setting up processor",t.logContext);let r=document.createElement(t.kind),s={kind:t.kind,track:t._mediaStreamTrack,element:r,audioContext:t.audioContext};if(yield e.init(s),t.log.debug("processor initialized",t.logContext),t.processor&&(yield t.stopProcessor()),"unknown"===t.kind)throw TypeError("cannot set processor on track of unknown kind");if(nD(t._mediaStreamTrack,r),r.muted=!0,r.play().catch(e=>{e instanceof DOMException&&"AbortError"===e.name?(t.log.warn("failed to play processor element, retrying",Object.assign(Object.assign({},t.logContext),{error:e})),setTimeout(()=>{r.play().catch(e=>{t.log.error("failed to play processor element",Object.assign(Object.assign({},t.logContext),{err:e}))})},100)):t.log.error("failed to play processor element",Object.assign(Object.assign({},t.logContext),{error:e}))}),t.processor=e,t.processorElement=r,t.processor.processedTrack){for(let e of t.attachedElements)e!==t.processorElement&&i&&(n_(t._mediaStreamTrack,e),nD(t.processor.processedTrack,e));yield null===(n=t.sender)||void 0===n?void 0:n.replaceTrack(t.processor.processedTrack)}t.emit(oX.TrackProcessorUpdate,t.processor)}finally{r()}}()})}getProcessor(){return this.processor}stopProcessor(){return ib(this,arguments,void 0,function(){var e=this;let t=!(arguments.length>0)||void 0===arguments[0]||arguments[0];return function*(){var i,n;e.processor&&(e.log.debug("stopping processor",e.logContext),null===(i=e.processor.processedTrack)||void 0===i||i.stop(),yield e.processor.destroy(),e.processor=void 0,t||(null===(n=e.processorElement)||void 0===n||n.remove(),e.processorElement=void 0),yield e._mediaStreamTrack.applyConstraints(e._constraints),yield e.setMediaStreamTrack(e._mediaStreamTrack,!0),e.emit(oX.TrackProcessorUpdate))}()})}startPreConnectBuffer(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:100;if(!r1){this.log.warn("MediaRecorder is not available, cannot start preconnect buffer",this.logContext);return}if(this.localTrackRecorder){this.log.warn("preconnect buffer already started");return}{let e="audio/webm;codecs=opus";MediaRecorder.isTypeSupported(e)||(e="video/mp4"),this.localTrackRecorder=new r5(this,{mimeType:e})}this.localTrackRecorder.start(e),this.autoStopPreConnectBuffer=setTimeout(()=>{this.log.warn("preconnect buffer timed out, stopping recording automatically",this.logContext),this.stopPreConnectBuffer()},1e4)}stopPreConnectBuffer(){clearTimeout(this.autoStopPreConnectBuffer),this.localTrackRecorder&&(this.localTrackRecorder.stop(),this.localTrackRecorder=void 0)}getPreConnectBuffer(){var e;return null===(e=this.localTrackRecorder)||void 0===e?void 0:e.byteStream}getPreConnectBufferMimeType(){var e;return null===(e=this.localTrackRecorder)||void 0===e?void 0:e.mimeType}}class r6 extends r4{get enhancedNoiseCancellation(){return this.isKrispNoiseFilterEnabled}constructor(e,t){let i=!(arguments.length>2)||void 0===arguments[2]||arguments[2],n=arguments.length>3?arguments[3]:void 0,r=arguments.length>4?arguments[4]:void 0;super(e,nM.Kind.Audio,t,i,r),this.stopOnMute=!1,this.isKrispNoiseFilterEnabled=!1,this.monitorSender=()=>ib(this,void 0,void 0,function*(){let e;if(!this.sender){this._currentBitrate=0;return}try{e=yield this.getSenderStats()}catch(e){this.log.error("could not get audio sender stats",Object.assign(Object.assign({},this.logContext),{error:e}));return}e&&this.prevStats&&(this._currentBitrate=r0(e,this.prevStats)),this.prevStats=e}),this.handleKrispNoiseFilterEnable=()=>{this.isKrispNoiseFilterEnabled=!0,this.log.debug("Krisp noise filter enabled",this.logContext),this.emit(oX.AudioTrackFeatureUpdate,this,eK.TF_ENHANCED_NOISE_CANCELLATION,!0)},this.handleKrispNoiseFilterDisable=()=>{this.isKrispNoiseFilterEnabled=!1,this.log.debug("Krisp noise filter disabled",this.logContext),this.emit(oX.AudioTrackFeatureUpdate,this,eK.TF_ENHANCED_NOISE_CANCELLATION,!1)},this.audioContext=n,this.checkForSilence()}mute(){let e=Object.create(null,{mute:{get:()=>super.mute}});return ib(this,void 0,void 0,function*(){let t=yield this.muteLock.lock();try{if(this.isMuted)return this.log.debug("Track already muted",this.logContext),this;return this.source===nM.Source.Microphone&&this.stopOnMute&&!this.isUserProvided&&(this.log.debug("stopping mic track",this.logContext),this._mediaStreamTrack.stop()),yield e.mute.call(this),this}finally{t()}})}unmute(){let e=Object.create(null,{unmute:{get:()=>super.unmute}});return ib(this,void 0,void 0,function*(){let t=yield this.muteLock.lock();try{if(!this.isMuted)return this.log.debug("Track already unmuted",this.logContext),this;let t=this._constraints.deviceId&&this._mediaStreamTrack.getSettings().deviceId!==rn(this._constraints.deviceId);return this.source===nM.Source.Microphone&&(this.stopOnMute||"ended"===this._mediaStreamTrack.readyState||t)&&!this.isUserProvided&&(this.log.debug("reacquiring mic track",this.logContext),yield this.restartTrack()),yield e.unmute.call(this),this}finally{t()}})}restartTrack(e){return ib(this,void 0,void 0,function*(){let t;if(e){let i=rv({audio:e});"boolean"!=typeof i.audio&&(t=i.audio)}yield this.restart(t)})}restart(e){let t=Object.create(null,{restart:{get:()=>super.restart}});return ib(this,void 0,void 0,function*(){let i=yield t.restart.call(this,e);return this.checkForSilence(),i})}startMonitor(){nY()&&!this.monitorInterval&&(this.monitorInterval=setInterval(()=>{this.monitorSender()},2e3))}setProcessor(e){return ib(this,void 0,void 0,function*(){var t;let i=yield this.processorLock.lock();try{if(!nQ()&&!this.audioContext)throw Error("Audio context needs to be set on LocalAudioTrack in order to enable processors");this.processor&&(yield this.stopProcessor());let 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 null===(t=this.sender)||void 0===t?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(oX.TrackProcessorUpdate,this.processor)}finally{i()}})}setAudioContext(e){this.audioContext=e}getSenderStats(){return ib(this,void 0,void 0,function*(){var e;let t;if(null===(e=this.sender)||void 0===e?void 0:e.getStats)return(yield this.sender.getStats()).forEach(e=>{"outbound-rtp"===e.type&&(t={type:"audio",streamId:e.id,packetsSent:e.packetsSent,packetsLost:e.packetsLost,bytesSent:e.bytesSent,timestamp:e.timestamp,roundTripTime:e.roundTripTime,jitter:e.jitter})}),t})}checkForSilence(){return ib(this,void 0,void 0,function*(){let e=yield function(e){return ib(this,arguments,void 0,function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:200;return function*(){let i=ry();if(i){let n=i.createAnalyser();n.fftSize=2048;let r=new Uint8Array(n.frequencyBinCount);i.createMediaStreamSource(new MediaStream([e.mediaStreamTrack])).connect(n),yield nq(t),n.getByteTimeDomainData(r);let s=r.some(e=>128!==e&&0!==e);return i.close(),!s}return!1}()})}(this);return e&&(this.isMuted||this.log.warn("silence detected on local audio track",this.logContext),this.emit(oX.AudioSilenceDetected)),e})}}let r9=Object.values(nU),r8=Object.values(nF),r7=Object.values(nV),se=[nU.h180,nU.h360],st=[nF.h180,nF.h360],si=e=>[{scaleResolutionDownBy:2,fps:e.encoding.maxFramerate}].map(t=>{var i,n;return new nN(Math.floor(e.width/t.scaleResolutionDownBy),Math.floor(e.height/t.scaleResolutionDownBy),Math.max(15e4,Math.floor(e.encoding.maxBitrate/(Math.pow(t.scaleResolutionDownBy,2)*((null!==(i=e.encoding.maxFramerate)&&void 0!==i?i:30)/(null!==(n=t.fps)&&void 0!==n?n:30))))),t.fps,e.encoding.priority)}),sn=["q","h","f"];function sr(e,t,i,n){var r,s,o;let a;let l=null==n?void 0:n.videoEncoding;e&&(l=null==n?void 0:n.screenShareEncoding);let c=null==n?void 0:n.simulcast,d=null==n?void 0:n.scalabilityMode,u=null==n?void 0:n.videoCodec;if(!l&&!c&&!d||!t||!i)return[{}];l||(l=function(e,t,i,n){let r=function(e,t,i){if(e)return r7;let n=t>i?t/i:i/t;return Math.abs(n-16/9)<Math.abs(n-4/3)?r9:r8}(e,t,i),{encoding:s}=r[0],o=Math.max(t,i);for(let e=0;e<r.length;e+=1){let t=r[e];if(s=t.encoding,t.width>=o)break}if(n)switch(n){case"av1":case"h265":(s=Object.assign({},s)).maxBitrate=.7*s.maxBitrate;break;case"vp9":(s=Object.assign({},s)).maxBitrate=.85*s.maxBitrate}return s}(e,t,i,u),ip.debug("using video encoding",l));let h=l.maxFramerate,p=new nN(t,i,l.maxBitrate,l.maxFramerate,l.priority);if(d&&nH(u)){let e=new sl(d),t=[];if(e.spatial>3)throw Error("unsupported scalabilityMode: ".concat(d));let i=nP();if(nJ()||nQ()||(null==i?void 0:i.name)==="Chrome"&&0>n3(null==i?void 0:i.version,"113")){let n="h"==e.suffix?2:3,r=((o=i)||(o=nP()),(null==o?void 0:o.name)==="Safari"&&n3(o.version,"18.3")>0||(null==o?void 0:o.os)==="iOS"&&!!(null==o?void 0:o.osVersion)&&n3(o.osVersion,"18.3")>0);for(let i=0;i<e.spatial;i+=1)t.push({rid:sn[2-i],maxBitrate:l.maxBitrate/Math.pow(n,i),maxFramerate:p.encoding.maxFramerate,scaleResolutionDownBy:r?Math.pow(2,i):void 0});t[0].scalabilityMode=d}else t.push({maxBitrate:l.maxBitrate,maxFramerate:p.encoding.maxFramerate,scalabilityMode:d});return p.encoding.priority&&(t[0].priority=p.encoding.priority,t[0].networkPriority=p.encoding.priority),ip.debug("using svc encoding",{encodings:t}),t}if(!c)return[l];let m=[];if((m=e?null!==(r=sa(null==n?void 0:n.screenShareSimulcastLayers))&&void 0!==r?r:ss(e,p):null!==(s=sa(null==n?void 0:n.videoSimulcastLayers))&&void 0!==s?s:ss(e,p)).length>0){let e=m[0];m.length>1&&([,a]=m);let n=Math.max(t,i);if(n>=960&&a)return so(t,i,[e,a,p],h);if(n>=480)return so(t,i,[e,p],h)}return so(t,i,[p])}function ss(e,t){if(e)return si(t);let{width:i,height:n}=t,r=i>n?i/n:n/i;return Math.abs(r-16/9)<Math.abs(r-4/3)?se:st}function so(e,t,i,n){let r=[];if(i.forEach((i,s)=>{if(s>=sn.length)return;let o={rid:sn[s],scaleResolutionDownBy:Math.max(1,Math.min(e,t)/Math.min(i.width,i.height)),maxBitrate:i.encoding.maxBitrate},a=n&&i.encoding.maxFramerate?Math.min(n,i.encoding.maxFramerate):i.encoding.maxFramerate;a&&(o.maxFramerate=a);let l=n$()||0===s;i.encoding.priority&&l&&(o.priority=i.encoding.priority,o.networkPriority=i.encoding.priority),r.push(o)}),nQ()&&"ios"===n1()){let e;r.forEach(t=>{e?t.maxFramerate&&t.maxFramerate>e&&(e=t.maxFramerate):e=t.maxFramerate});let t=!0;r.forEach(i=>{var n;i.maxFramerate!=e&&(t&&(t=!1,ip.info("Simulcast on iOS React-Native requires all encodings to share the same framerate.")),ip.info('Setting framerate of encoding "'.concat(null!==(n=i.rid)&&void 0!==n?n:"",'" to ').concat(e)),i.maxFramerate=e)})}return r}function sa(e){if(e)return e.sort((e,t)=>{let{encoding:i}=e,{encoding:n}=t;return i.maxBitrate>n.maxBitrate?1:i.maxBitrate<n.maxBitrate?-1:i.maxBitrate===n.maxBitrate&&i.maxFramerate&&n.maxFramerate?i.maxFramerate>n.maxFramerate?1:-1:0})}class sl{constructor(e){let t=e.match(/^L(\d)T(\d)(h|_KEY|_KEY_SHIFT){0,1}$/);if(!t)throw 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(null!==(e=this.suffix)&&void 0!==e?e:"")}}class sc extends r4{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)||void 0===arguments[2]||arguments[2],n=arguments.length>3?arguments[3]:void 0;super(e,nM.Kind.Video,t,i,n),this.simulcastCodecs=new Map,this.degradationPreference="balanced",this.isCpuConstrained=!1,this.optimizeForPerformance=!1,this.monitorSender=()=>ib(this,void 0,void 0,function*(){let e;if(!this.sender){this._currentBitrate=0;return}try{e=yield this.getSenderStats()}catch(e){this.log.error("could not get video sender stats",Object.assign(Object.assign({},this.logContext),{error:e}));return}let t=new Map(e.map(e=>[e.rid,e])),i=e.some(e=>"cpu"===e.qualityLimitationReason);if(i!==this.isCpuConstrained&&(this.isCpuConstrained=i,this.isCpuConstrained&&this.emit(oX.CpuConstrained)),this.prevStats){let e=0;t.forEach((t,i)=>{var n;let r=null===(n=this.prevStats)||void 0===n?void 0:n.get(i);e+=r0(t,r)}),this._currentBitrate=e}this.prevStats=t}),this.senderLock=new y}get isSimulcast(){return!!this.sender&&this.sender.getParameters().encodings.length>1}startMonitor(e){var t;if(this.signalClient=e,!nY())return;let i=null===(t=this.sender)||void 0===t?void 0:t.getParameters();i&&(this.encodings=i.encodings),this.monitorInterval||(this.monitorInterval=setInterval(()=>{this.monitorSender()},2e3))}stop(){this._mediaStreamTrack.getConstraints(),this.simulcastCodecs.forEach(e=>{e.mediaStreamTrack.stop()}),super.stop()}pauseUpstream(){let e=Object.create(null,{pauseUpstream:{get:()=>super.pauseUpstream}});return ib(this,void 0,void 0,function*(){yield e.pauseUpstream.call(this);try{for(var t,i,n,r,s,o,a=!0,l=ik(this.simulcastCodecs.values());!(t=(o=yield l.next()).done);a=!0)r=o.value,a=!1,yield null===(s=r.sender)||void 0===s?void 0:s.replaceTrack(null)}catch(e){i={error:e}}finally{try{!a&&!t&&(n=l.return)&&(yield n.call(l))}finally{if(i)throw i.error}}})}resumeUpstream(){let e=Object.create(null,{resumeUpstream:{get:()=>super.resumeUpstream}});return ib(this,void 0,void 0,function*(){yield e.resumeUpstream.call(this);try{for(var t,i,n,r,s,o,a=!0,l=ik(this.simulcastCodecs.values());!(t=(o=yield l.next()).done);a=!0)r=o.value,a=!1,yield null===(s=r.sender)||void 0===s?void 0:s.replaceTrack(r.mediaStreamTrack)}catch(e){i={error:e}}finally{try{!a&&!t&&(n=l.return)&&(yield n.call(l))}finally{if(i)throw i.error}}})}mute(){let e=Object.create(null,{mute:{get:()=>super.mute}});return ib(this,void 0,void 0,function*(){let t=yield this.muteLock.lock();try{if(this.isMuted)return this.log.debug("Track already muted",this.logContext),this;return this.source!==nM.Source.Camera||this.isUserProvided||(this.log.debug("stopping camera track",this.logContext),this._mediaStreamTrack.stop()),yield e.mute.call(this),this}finally{t()}})}unmute(){let e=Object.create(null,{unmute:{get:()=>super.unmute}});return ib(this,void 0,void 0,function*(){let t=yield this.muteLock.lock();try{if(!this.isMuted)return this.log.debug("Track already unmuted",this.logContext),this;return this.source!==nM.Source.Camera||this.isUserProvided||(this.log.debug("reacquiring camera track",this.logContext),yield this.restartTrack()),yield e.unmute.call(this),this}finally{t()}})}setTrackMuted(e){for(let t of(super.setTrackMuted(e),this.simulcastCodecs.values()))t.mediaStreamTrack.enabled=!e}getSenderStats(){return ib(this,void 0,void 0,function*(){var e;if(!(null===(e=this.sender)||void 0===e?void 0:e.getStats))return[];let t=[],i=yield this.sender.getStats();return i.forEach(e=>{var n;if("outbound-rtp"===e.type){let r={type:"video",streamId:e.id,frameHeight:e.frameHeight,frameWidth:e.frameWidth,framesPerSecond:e.framesPerSecond,framesSent:e.framesSent,firCount:e.firCount,pliCount:e.pliCount,nackCount:e.nackCount,packetsSent:e.packetsSent,bytesSent:e.bytesSent,qualityLimitationReason:e.qualityLimitationReason,qualityLimitationDurations:e.qualityLimitationDurations,qualityLimitationResolutionChanges:e.qualityLimitationResolutionChanges,rid:null!==(n=e.rid)&&void 0!==n?n:e.id,retransmittedPacketsSent:e.retransmittedPacketsSent,targetBitrate:e.targetBitrate,timestamp:e.timestamp},s=i.get(e.remoteId);s&&(r.jitter=s.jitter,r.packetsLost=s.packetsLost,r.roundTripTime=s.roundTripTime),t.push(r)}}),t.sort((e,t)=>{var i,n;return(null!==(i=t.frameWidth)&&void 0!==i?i:0)-(null!==(n=e.frameWidth)&&void 0!==n?n:0)}),t})}setPublishingQuality(e){let t=[];for(let i=oY.LOW;i<=oY.HIGH;i+=1)t.push(new t0({quality:i,enabled:i<=e}));this.log.debug("setting publishing quality. max quality ".concat(e),this.logContext),this.setPublishingLayers(nH(this.codec),t)}restartTrack(e){return ib(this,void 0,void 0,function*(){let t;if(e){let i=rv({video:e});"boolean"!=typeof i.video&&(t=i.video)}yield this.restart(t),this.isCpuConstrained=!1;try{for(var i,n,r,s,o,a,l=!0,c=ik(this.simulcastCodecs.values());!(i=(a=yield c.next()).done);l=!0)s=a.value,l=!1,s.sender&&(null===(o=s.sender.transport)||void 0===o?void 0:o.state)!=="closed"&&(s.mediaStreamTrack=this.mediaStreamTrack.clone(),yield s.sender.replaceTrack(s.mediaStreamTrack))}catch(e){n={error:e}}finally{try{!l&&!i&&(r=c.return)&&(yield r.call(c))}finally{if(n)throw n.error}}})}setProcessor(e){let t=Object.create(null,{setProcessor:{get:()=>super.setProcessor}});return ib(this,arguments,void 0,function(e){var i=this;let n=!(arguments.length>1)||void 0===arguments[1]||arguments[1];return function*(){if(yield t.setProcessor.call(i,e,n),null===(l=i.processor)||void 0===l?void 0:l.processedTrack)try{for(var r,s,o,a,l,c,d,u=!0,h=ik(i.simulcastCodecs.values());!(r=(d=yield h.next()).done);u=!0)a=d.value,u=!1,yield null===(c=a.sender)||void 0===c?void 0:c.replaceTrack(i.processor.processedTrack)}catch(e){s={error:e}}finally{try{!u&&!r&&(o=h.return)&&(yield o.call(h))}finally{if(s)throw s.error}}}()})}setDegradationPreference(e){return ib(this,void 0,void 0,function*(){if(this.degradationPreference=e,this.sender)try{this.log.debug("setting degradationPreference to ".concat(e),this.logContext);let t=this.sender.getParameters();t.degradationPreference=e,this.sender.setParameters(t)}catch(e){this.log.warn("failed to set degradationPreference",Object.assign({error:e},this.logContext))}})}addSimulcastTrack(e,t){if(this.simulcastCodecs.has(e)){this.log.error("".concat(e," already added, skipping adding simulcast codec"),this.logContext);return}let i={codec:e,mediaStreamTrack:this.mediaStreamTrack.clone(),sender:void 0,encodings:t};return this.simulcastCodecs.set(e,i),i}setSimulcastTrackSender(e,t){let i=this.simulcastCodecs.get(e);i&&(i.sender=t,setTimeout(()=>{this.subscribedCodecs&&this.setPublishingCodecs(this.subscribedCodecs)},5e3))}setPublishingCodecs(e){return ib(this,void 0,void 0,function*(){var t,i,n,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(nH(e[0].codec),e[0].qualities),[];this.subscribedCodecs=e;let l=[];try{for(t=!0,i=ik(e);!(r=(n=yield i.next()).done);t=!0)if(a=n.value,t=!1,this.codec&&this.codec!==a.codec){let e=this.simulcastCodecs.get(a.codec);if(this.log.debug("try setPublishingCodec for ".concat(a.codec),Object.assign(Object.assign({},this.logContext),{simulcastCodecInfo:e})),e&&e.sender)e.encodings&&(this.log.debug("try setPublishingLayersForSender ".concat(a.codec),this.logContext),yield sd(e.sender,e.encodings,a.qualities,this.senderLock,nH(a.codec),this.log,this.logContext));else for(let e of a.qualities)if(e.enabled){l.push(a.codec);break}}else yield this.setPublishingLayers(nH(a.codec),a.qualities)}catch(e){s={error:e}}finally{try{!t&&!r&&(o=i.return)&&(yield o.call(i))}finally{if(s)throw s.error}}return l})}setPublishingLayers(e,t){return ib(this,void 0,void 0,function*(){if(this.optimizeForPerformance){this.log.info("skipping setPublishingLayers due to optimized publishing performance",Object.assign(Object.assign({},this.logContext),{qualities:t}));return}this.log.debug("setting publishing layers",Object.assign(Object.assign({},this.logContext),{qualities:t})),this.sender&&this.encodings&&(yield sd(this.sender,this.encodings,t,this.senderLock,e,this.log,this.logContext))})}prioritizePerformance(){return ib(this,void 0,void 0,function*(){if(!this.sender)throw Error("sender not found");let e=yield this.senderLock.lock();try{this.optimizeForPerformance=!0;let e=this.sender.getParameters();e.encodings=e.encodings.map((e,t)=>{var i;return Object.assign(Object.assign({},e),{active:0===t,scaleResolutionDownBy:Math.max(1,Math.ceil((null!==(i=this.mediaStreamTrack.getSettings().height)&&void 0!==i?i:360)/360)),scalabilityMode:0===t&&nH(this.codec)?"L1T3":void 0,maxFramerate:0===t?15:0,maxBitrate:0===t?e.maxBitrate:0})}),this.log.debug("setting performance optimised encodings",Object.assign(Object.assign({},this.logContext),{encodings:e.encodings})),this.encodings=e.encodings,yield this.sender.setParameters(e)}catch(e){this.log.error("failed to set performance optimised encodings",Object.assign(Object.assign({},this.logContext),{error:e})),this.optimizeForPerformance=!1}finally{e()}})}handleAppVisibilityChanged(){let e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return ib(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),nX()&&this.isInBackground&&this.source===nM.Source.Camera&&(this._mediaStreamTrack.enabled=!1)})}}function sd(e,t,i,n,r,s,o){return ib(this,void 0,void 0,function*(){let a=yield n.lock();s.debug("setPublishingLayersForSender",Object.assign(Object.assign({},o),{sender:e,qualities:i,senderEncodings:t}));try{let n=e.getParameters(),{encodings:a}=n;if(!a)return;if(a.length!==t.length){s.warn("cannot set publishing layers, encodings mismatch",Object.assign(Object.assign({},o),{encodings:a,senderEncodings:t}));return}let l=!1;r&&i.some(e=>e.enabled)&&i.forEach(e=>e.enabled=!0),a.forEach((e,n)=>{var r;let a=null!==(r=e.rid)&&void 0!==r?r:"";""===a&&(a="q");let c=su(a),d=i.find(e=>e.quality===c);d&&e.active!==d.enabled&&(l=!0,e.active=d.enabled,s.debug("setting layer ".concat(d.quality," to ").concat(e.active?"enabled":"disabled"),o),n$()&&(d.enabled?(e.scaleResolutionDownBy=t[n].scaleResolutionDownBy,e.maxBitrate=t[n].maxBitrate,e.maxFrameRate=t[n].maxFrameRate):(e.scaleResolutionDownBy=4,e.maxBitrate=10,e.maxFrameRate=2)))}),l&&(n.encodings=a,s.debug("setting encodings",Object.assign(Object.assign({},o),{encodings:n.encodings})),yield e.setParameters(n))}finally{a()}})}function su(e){switch(e){case"f":default:return oY.HIGH;case"h":return oY.MEDIUM;case"q":return oY.LOW}}function sh(e,t,i,n){if(!i)return[new e4({quality:oY.HIGH,width:e,height:t,bitrate:0,ssrc:0})];if(n){let n=new sl(i[0].scalabilityMode),r=[],s="h"==n.suffix?1.5:2,o="h"==n.suffix?2:3;for(let a=0;a<n.spatial;a+=1)r.push(new e4({quality:Math.min(oY.HIGH,n.spatial-1)-a,width:Math.ceil(e/Math.pow(s,a)),height:Math.ceil(t/Math.pow(s,a)),bitrate:i[0].maxBitrate?Math.ceil(i[0].maxBitrate/Math.pow(o,a)):0,ssrc:0}));return r}return i.map(i=>{var n,r,s;let o=null!==(n=i.scaleResolutionDownBy)&&void 0!==n?n:1;return new e4({quality:su(null!==(r=i.rid)&&void 0!==r?r:""),width:Math.ceil(e/o),height:Math.ceil(t/o),bitrate:null!==(s=i.maxBitrate)&&void 0!==s?s:0,ssrc:0})})}let sp="_lossy",sm="_reliable",sf="leave-reconnect";!function(e){e[e.New=0]="New",e[e.Connected=1]="Connected",e[e.Disconnected=2]="Disconnected",e[e.Reconnecting=3]="Reconnecting",e[e.Closed=4]="Closed"}(o8||(o8={}));class sg extends iS.EventEmitter{get isClosed(){return this._isClosed}get pendingReconnect(){return!!this.reconnectTimeout}constructor(e){var t;super(),this.options=e,this.rtcConfig={},this.peerConnectionTimeout=rJ.peerConnectionTimeout,this.fullReconnectOnNext=!1,this.latestRemoteOfferId=0,this.subscriberPrimary=!1,this.pcState=o8.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=ip,this.reliableDataSequence=1,this.reliableMessageBuffer=new rD,this.reliableReceivedState=new r_(3e4),this.handleDataChannel=e=>ib(this,[e],void 0,function(e){var t=this;let{channel:i}=e;return function*(){if(i){if(i.label===sm)t.reliableDCSub=i;else{if(i.label!==sp)return;t.lossyDCSub=i}t.log.debug("on data channel ".concat(i.id,", ").concat(i.label),t.logContext),i.onmessage=t.handleDataMessage}}()}),this.handleDataMessage=e=>ib(this,void 0,void 0,function*(){var t,i;let n=yield this.dataProcessLock.lock();try{let n;if(e.data instanceof ArrayBuffer)n=e.data;else if(e.data instanceof Blob)n=yield e.data.arrayBuffer();else{this.log.error("unsupported data type",Object.assign(Object.assign({},this.logContext),{data:e.data}));return}let r=e6.fromBinary(new Uint8Array(n));if(r.sequence>0&&""!==r.participantSid){let e=this.reliableReceivedState.get(r.participantSid);if(e&&r.sequence<=e)return;this.reliableReceivedState.set(r.participantSid,r.sequence)}(null===(t=r.value)||void 0===t?void 0:t.case)==="speaker"?this.emit(oJ.ActiveSpeakersUpdate,r.value.value.speakers):((null===(i=r.value)||void 0===i?void 0:i.case)==="user"&&function(e,t){let i=e.participantIdentity?e.participantIdentity:t.participantIdentity;e.participantIdentity=i,t.participantIdentity=i;let n=0!==e.destinationIdentities.length?e.destinationIdentities:t.destinationIdentities;e.destinationIdentities=n,t.destinationIdentities=n}(r,r.value.value),this.emit(oJ.DataPacketReceived,r))}finally{n()}}),this.handleDataError=e=>{let t=0===e.currentTarget.maxRetransmits?"lossy":"reliable";if(e instanceof ErrorEvent&&e.error){let{error:i}=e.error;this.log.error("DataChannel error on ".concat(t,": ").concat(e.message),Object.assign(Object.assign({},this.logContext),{error:i}))}else this.log.error("Unknown DataChannel error on ".concat(t),Object.assign(Object.assign({},this.logContext),{event:e}))},this.handleBufferedAmountLow=e=>{let t=0===e.currentTarget.maxRetransmits?e9.LOSSY:e9.RELIABLE;this.updateAndEmitDCBufferStatus(t)},this.handleDisconnect=(e,t)=>{if(this._isClosed)return;this.log.warn("".concat(e," disconnected"),this.logContext),0===this.reconnectAttempts&&(this.reconnectStart=Date.now());let i=Date.now()-this.reconnectStart,n=this.getNextRetryDelay({elapsedMs:i,retryCount:this.reconnectAttempts});if(null===n){(e=>{this.log.warn("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(e,"ms. giving up"),this.logContext),this.emit(oJ.Disconnected),this.close()})(i);return}e===sf&&(n=0),this.log.debug("reconnecting in ".concat(n,"ms"),this.logContext),this.clearReconnectTimeout(),this.token&&this.regionUrlProvider&&this.regionUrlProvider.updateToken(this.token),this.reconnectTimeout=nA.setTimeout(()=>this.attemptReconnect(t).finally(()=>this.reconnectTimeout=void 0),n)},this.waitForRestarted=()=>new Promise((e,t)=>{this.pcState===o8.Connected&&e();let i=()=>{this.off(oJ.Disconnected,n),e()},n=()=>{this.off(oJ.Restarted,i),t()};this.once(oJ.Restarted,i),this.once(oJ.Disconnected,n)}),this.updateAndEmitDCBufferStatus=e=>{let t=this.isBufferStatusLow(e);void 0!==t&&t!==this.dcBufferStatus.get(e)&&(this.dcBufferStatus.set(e,t),this.emit(oJ.DCBufferStatusChanged,t,e))},this.isBufferStatusLow=e=>{let t=this.dataChannelForKind(e);if(t)return e===e9.RELIABLE&&this.reliableMessageBuffer.alignBufferedAmount(t.bufferedAmount),t.bufferedAmount<=t.bufferedAmountLowThreshold},this.handleBrowserOnLine=()=>{this.client.currentState===o1.RECONNECTING&&(this.clearReconnectTimeout(),this.attemptReconnect(eG.RR_SIGNAL_DISCONNECTED))},this.log=im(null!==(t=e.loggerName)&&void 0!==t?t:oj.Engine),this.loggerOptions={loggerName:e.loggerName,loggerContextCb:()=>this.logContext},this.client=new rA(void 0,this.loggerOptions),this.client.signalLatency=this.options.expSignalLatency,this.reconnectPolicy=this.options.reconnectPolicy,this.registerOnLineListener(),this.closingLock=new y,this.dataProcessLock=new y,this.dcBufferStatus=new Map([[e9.LOSSY,!0],[e9.RELIABLE,!0]]),this.client.onParticipantUpdate=e=>this.emit(oJ.ParticipantUpdate,e),this.client.onConnectionQuality=e=>this.emit(oJ.ConnectionQualityUpdate,e),this.client.onRoomUpdate=e=>this.emit(oJ.RoomUpdate,e),this.client.onSubscriptionError=e=>this.emit(oJ.SubscriptionError,e),this.client.onSubscriptionPermissionUpdate=e=>this.emit(oJ.SubscriptionPermissionUpdate,e),this.client.onSpeakersChanged=e=>this.emit(oJ.SpeakersChanged,e),this.client.onStreamStateUpdate=e=>this.emit(oJ.StreamStateChanged,e),this.client.onRequestResponse=e=>this.emit(oJ.SignalRequestResponse,e)}get logContext(){var e,t,i,n,r,s;return{room:null===(t=null===(e=this.latestJoinResponse)||void 0===e?void 0:e.room)||void 0===t?void 0:t.name,roomID:null===(n=null===(i=this.latestJoinResponse)||void 0===i?void 0:i.room)||void 0===n?void 0:n.sid,participant:null===(s=null===(r=this.latestJoinResponse)||void 0===r?void 0:r.participant)||void 0===s?void 0:s.identity,pID:this.participantSid}}join(e,t,i,n){return ib(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();let r=yield this.client.join(e,t,i,n);return this._isClosed=!1,this.latestJoinResponse=r,this.subscriberPrimary=r.subscriberPrimary,this.pcManager||(yield this.configure(r)),(!this.subscriberPrimary||r.fastPublish)&&this.negotiate(),this.clientConfiguration=r.clientConfiguration,this.emit(oJ.SignalConnected,r),r}catch(r){if(r instanceof nv&&r.reason===oW.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,n);throw r}})}close(){return ib(this,void 0,void 0,function*(){let e=yield this.closingLock.lock();if(this.isClosed){e();return}try{this._isClosed=!0,this.joinAttempts=0,this.emit(oJ.Closing),this.removeAllListeners(),this.deregisterOnLineListener(),this.clearPendingReconnect(),yield this.cleanupPeerConnections(),yield this.cleanupClient()}finally{e()}})}cleanupPeerConnections(){return ib(this,void 0,void 0,function*(){var e;yield null===(e=this.pcManager)||void 0===e?void 0:e.close(),this.pcManager=void 0;let t=e=>{e&&(e.close(),e.onbufferedamountlow=null,e.onclose=null,e.onclosing=null,e.onerror=null,e.onmessage=null,e.onopen=null)};t(this.lossyDC),t(this.lossyDCSub),t(this.reliableDC),t(this.reliableDCSub),this.lossyDC=void 0,this.lossyDCSub=void 0,this.reliableDC=void 0,this.reliableDCSub=void 0,this.reliableMessageBuffer=new rD,this.reliableDataSequence=1,this.reliableReceivedState.clear()})}cleanupClient(){return ib(this,void 0,void 0,function*(){yield this.client.close(),this.client.resetCallbacks()})}addTrack(e){if(this.pendingTrackResolvers[e.cid])throw new nb("a track with the same ID has already been published");return new Promise((t,i)=>{let n=setTimeout(()=>{delete this.pendingTrackResolvers[e.cid],i(new nv("publication of local track timed out, no response from server",oW.Timeout))},1e4);this.pendingTrackResolvers[e.cid]={resolve:e=>{clearTimeout(n),t(e)},reject:()=>{clearTimeout(n),i(Error("Cancelled publication by calling unpublish"))}},this.client.sendAddTrack(e)})}removeTrack(e){if(e.track&&this.pendingTrackResolvers[e.track.id]){let{reject:t}=this.pendingTrackResolvers[e.track.id];t&&t(),delete this.pendingTrackResolvers[e.track.id]}try{return this.pcManager.removeTrack(e),!0}catch(e){this.log.warn("failed to remove track",Object.assign(Object.assign({},this.logContext),{error:e}))}return!1}updateMuteStatus(e,t){this.client.sendMuteTrack(e,t)}get dataSubscriberReadyState(){var e;return null===(e=this.reliableDCSub)||void 0===e?void 0:e.readyState}getConnectedServerAddress(){return ib(this,void 0,void 0,function*(){var e;return null===(e=this.pcManager)||void 0===e?void 0:e.getConnectedAddress()})}setRegionUrlProvider(e){this.regionUrlProvider=e}configure(e){return ib(this,void 0,void 0,function*(){var t,i,n;if(this.pcManager&&this.pcManager.currentState!==o9.NEW)return;this.participantSid=null===(t=e.participant)||void 0===t?void 0:t.sid;let r=this.makeRTCConfiguration(e);this.pcManager=new rX(r,e.subscriberPrimary,this.loggerOptions),this.emit(oJ.TransportsCreated,this.pcManager.publisher,this.pcManager.subscriber),this.pcManager.onIceCandidate=(e,t)=>{this.client.sendIceCandidate(e,t)},this.pcManager.onPublisherOffer=(e,t)=>{this.client.sendOffer(e,t)},this.pcManager.onDataChannel=this.handleDataChannel,this.pcManager.onStateChange=(t,i,n)=>ib(this,void 0,void 0,function*(){if(this.log.debug("primary PC state changed ".concat(t),this.logContext),["closed","disconnected","failed"].includes(i)&&(this.publisherConnectionPromise=void 0),t===o9.CONNECTED){let t=this.pcState===o8.New;this.pcState=o8.Connected,t&&this.emit(oJ.Connected,e)}else t===o9.FAILED&&this.pcState===o8.Connected&&(this.pcState=o8.Disconnected,this.handleDisconnect("peerconnection failed","failed"===n?eG.RR_SUBSCRIBER_FAILED:eG.RR_PUBLISHER_FAILED));let r=this.client.isDisconnected||this.client.currentState===o1.RECONNECTING,s=[o9.FAILED,o9.CLOSING,o9.CLOSED].includes(t);r&&s&&!this._isClosed&&this.emit(oJ.Offline)}),this.pcManager.onTrack=e=>{this.emit(oJ.MediaTrackAdded,e.track,e.streams[0],e.receiver)},void 0!==(n=null===(i=e.serverInfo)||void 0===i?void 0:i.protocol)&&n>13||this.createDataChannels()})}setupSignalClientCallbacks(){this.client.onAnswer=(e,t)=>ib(this,void 0,void 0,function*(){this.pcManager&&(this.log.debug("received server answer",Object.assign(Object.assign({},this.logContext),{RTCSdpType:e.type})),yield this.pcManager.setPublisherAnswer(e,t))}),this.client.onTrickle=(e,t)=>{this.pcManager&&(this.log.debug("got ICE candidate from peer",Object.assign(Object.assign({},this.logContext),{candidate:e,target:t})),this.pcManager.addIceCandidate(e,t))},this.client.onOffer=(e,t)=>ib(this,void 0,void 0,function*(){if(this.latestRemoteOfferId=t,!this.pcManager)return;let i=yield this.pcManager.createSubscriberAnswerFromOffer(e,t);i&&this.client.sendAnswer(i,t)}),this.client.onLocalTrackPublished=e=>{var t;if(this.log.debug("received trackPublishedResponse",Object.assign(Object.assign({},this.logContext),{cid:e.cid,track:null===(t=e.track)||void 0===t?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}let{resolve:i}=this.pendingTrackResolvers[e.cid];delete this.pendingTrackResolvers[e.cid],i(e.track)},this.client.onLocalTrackUnpublished=e=>{this.emit(oJ.LocalTrackUnpublished,e)},this.client.onLocalTrackSubscribed=e=>{this.emit(oJ.LocalTrackSubscribed,e)},this.client.onTokenRefresh=e=>{this.token=e},this.client.onRemoteMuteChanged=(e,t)=>{this.emit(oJ.RemoteMute,e,t)},this.client.onSubscribedQualityUpdate=e=>{this.emit(oJ.SubscribedQualityUpdate,e)},this.client.onRoomMoved=e=>{var t;this.participantSid=null===(t=e.participant)||void 0===t?void 0:t.sid,this.latestJoinResponse&&(this.latestJoinResponse.room=e.room),this.emit(oJ.RoomMoved,e)},this.client.onClose=()=>{this.handleDisconnect("signal",eG.RR_SIGNAL_DISCONNECTED)},this.client.onLeave=e=>{switch(this.log.debug("client leave request",Object.assign(Object.assign({},this.logContext),{reason:null==e?void 0:e.reason})),e.regions&&this.regionUrlProvider&&(this.log.debug("updating regions",this.logContext),this.regionUrlProvider.setServerReportedRegions(e.regions)),e.action){case tW.DISCONNECT:this.emit(oJ.Disconnected,null==e?void 0:e.reason),this.close();break;case tW.RECONNECT:this.fullReconnectOnNext=!0,this.handleDisconnect(sf);break;case tW.RESUME:this.handleDisconnect(sf)}}}makeRTCConfiguration(e){var t;let i=Object.assign({},this.rtcConfig);if((null===(t=this.signalOpts)||void 0===t?void 0:t.e2eeEnabled)&&(this.log.debug("E2EE - setting up transports with insertable streams",this.logContext),i.encodedInsertableStreams=!0),e.iceServers&&!i.iceServers){let t=[];e.iceServers.forEach(e=>{let i={urls:e.urls};e.username&&(i.username=e.username),e.credential&&(i.credential=e.credential),t.push(i)}),i.iceServers=t}return e.clientConfiguration&&e.clientConfiguration.forceRelay===eW.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(sp,{ordered:!1,maxRetransmits:0}),this.reliableDC=this.pcManager.createPublisherDataChannel(sm,{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 ib(this,void 0,void 0,function*(){if(nz())return yield this.createTransceiverRTCRtpSender(e,t,i);if(nW())return this.log.warn("using add-track fallback",this.logContext),yield this.createRTCRtpSender(e.mediaStreamTrack);throw new nT("Required webRTC APIs not supported on this device")})}createSimulcastSender(e,t,i,n){return ib(this,void 0,void 0,function*(){if(nz())return this.createSimulcastTransceiverSender(e,t,i,n);if(nW())return this.log.debug("using add-track fallback",this.logContext),this.createRTCRtpSender(e.mediaStreamTrack);throw new nT("Cannot stream on this device")})}createTransceiverRTCRtpSender(e,t,i){return ib(this,void 0,void 0,function*(){if(!this.pcManager)throw new nT("publisher is closed");let n=[];e.mediaStream&&n.push(e.mediaStream),rd(e)&&(e.codec=t.videoCodec);let r={direction:"sendonly",streams:n};return i&&(r.sendEncodings=i),(yield this.pcManager.addPublisherTransceiver(e.mediaStreamTrack,r)).sender})}createSimulcastTransceiverSender(e,t,i,n){return ib(this,void 0,void 0,function*(){if(!this.pcManager)throw new nT("publisher is closed");let r={direction:"sendonly"};n&&(r.sendEncodings=n);let s=yield this.pcManager.addPublisherTransceiver(t.mediaStreamTrack,r);if(i.videoCodec)return e.setSimulcastTrackSender(i.videoCodec,s.sender),s.sender})}createRTCRtpSender(e){return ib(this,void 0,void 0,function*(){if(!this.pcManager)throw new nT("publisher is closed");return this.pcManager.addPublisherTrack(e)})}attemptReconnect(e){return ib(this,void 0,void 0,function*(){var t,i,n;if(!this._isClosed){if(this.attemptingReconnect){ip.warn("already attempting reconnect, returning early",this.logContext);return}((null===(t=this.clientConfiguration)||void 0===t?void 0:t.resumeConnection)===eW.DISABLED||(null!==(n=null===(i=this.pcManager)||void 0===i?void 0:i.currentState)&&void 0!==n?n:o9.NEW)===o9.NEW)&&(this.fullReconnectOnNext=!0);try{this.attemptingReconnect=!0,this.fullReconnectOnNext?yield this.restartConnection():yield this.resumeConnection(e),this.clearPendingReconnect(),this.fullReconnectOnNext=!1}catch(t){this.reconnectAttempts+=1;let e=!0;t instanceof nT?(this.log.debug("received unrecoverable error",Object.assign(Object.assign({},this.logContext),{error:t})),e=!1):t instanceof sv||(this.fullReconnectOnNext=!0),e?this.handleDisconnect("reconnect",eG.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(oJ.Disconnected),yield this.close())}finally{this.attemptingReconnect=!1}}})}getNextRetryDelay(e){try{return this.reconnectPolicy.nextRetryDelayInMs(e)}catch(e){this.log.warn("encountered error in reconnect policy",Object.assign(Object.assign({},this.logContext),{error:e}))}return null}restartConnection(e){return ib(this,void 0,void 0,function*(){var t,i,n;try{let i;if(!this.url||!this.token)throw new nT("could not reconnect, url or token not saved");this.log.info("reconnecting, attempt: ".concat(this.reconnectAttempts),this.logContext),this.emit(oJ.Restarting),this.client.isDisconnected||(yield this.client.sendLeave()),yield this.cleanupPeerConnections(),yield this.cleanupClient();try{if(!this.signalOpts)throw this.log.warn("attempted connection restart, without signal options present",this.logContext),new sv;i=yield this.join(null!=e?e:this.url,this.token,this.signalOpts)}catch(e){if(e instanceof nv&&e.reason===oW.NotAllowed)throw new nT("could not reconnect, token might be expired");throw new sv}if(this.shouldFailNext)throw this.shouldFailNext=!1,Error("simulated failure");if(this.client.setReconnected(),this.emit(oJ.SignalRestarted,i),yield this.waitForPCReconnected(),this.client.currentState!==o1.CONNECTED)throw new sv("Signal connection got severed during reconnect");null===(t=this.regionUrlProvider)||void 0===t||t.resetAttempts(),this.emit(oJ.Restarted)}catch(t){let e=yield null===(i=this.regionUrlProvider)||void 0===i?void 0:i.getNextBestRegionUrl();if(e){yield this.restartConnection(e);return}throw null===(n=this.regionUrlProvider)||void 0===n||n.resetAttempts(),t}})}resumeConnection(e){return ib(this,void 0,void 0,function*(){var t;let i;if(!this.url||!this.token)throw new nT("could not reconnect, url or token not saved");if(!this.pcManager)throw new nT("publisher and subscriber connections unset");this.log.info("resuming signal connection, attempt ".concat(this.reconnectAttempts),this.logContext),this.emit(oJ.Resuming);try{this.setupSignalClientCallbacks(),i=yield this.client.reconnect(this.url,this.token,this.participantSid,e)}catch(t){let e="";if(t instanceof Error&&(e=t.message,this.log.error(t.message,Object.assign(Object.assign({},this.logContext),{error:t}))),t instanceof nv&&t.reason===oW.NotAllowed)throw new nT("could not reconnect, token might be expired");if(t instanceof nv&&t.reason===oW.LeaveRequest)throw t;throw new sv(e)}if(this.emit(oJ.SignalResumed),i){let e=this.makeRTCConfiguration(i);this.pcManager.updateConfiguration(e),this.latestJoinResponse&&(this.latestJoinResponse.serverInfo=i.serverInfo)}else this.log.warn("Did not receive reconnect response",this.logContext);if(this.shouldFailNext)throw this.shouldFailNext=!1,Error("simulated failure");if(yield this.pcManager.triggerIceRestart(),yield this.waitForPCReconnected(),this.client.currentState!==o1.CONNECTED)throw new sv("Signal connection got severed during reconnect");this.client.setReconnected(),(null===(t=this.reliableDC)||void 0===t?void 0:t.readyState)==="open"&&null===this.reliableDC.id&&this.createDataChannels(),(null==i?void 0:i.lastMessageSeq)&&this.resendReliableMessagesForResume(i.lastMessageSeq),this.emit(oJ.Resumed)})}waitForPCInitialConnection(e,t){return ib(this,void 0,void 0,function*(){if(!this.pcManager)throw new nT("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(t,e)})}waitForPCReconnected(){return ib(this,void 0,void 0,function*(){this.pcState=o8.Reconnecting,this.log.debug("waiting for peer connection to reconnect",this.logContext);try{if(yield nq(2e3),!this.pcManager)throw new nT("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(void 0,this.peerConnectionTimeout),this.pcState=o8.Connected}catch(e){throw this.pcState=o8.Disconnected,new nv("could not establish PC connection, ".concat(e.message),oW.InternalError)}})}publishRpcResponse(e,t,i,n){return ib(this,void 0,void 0,function*(){let r=new e6({destinationIdentities:[e],kind:e9.RELIABLE,value:{case:"rpcResponse",value:new ta({requestId:t,value:n?{case:"error",value:n.toProto()}:{case:"payload",value:null!=i?i:""}})}});yield this.sendDataPacket(r,e9.RELIABLE)})}publishRpcAck(e,t){return ib(this,void 0,void 0,function*(){let i=new e6({destinationIdentities:[e],kind:e9.RELIABLE,value:{case:"rpcAck",value:new to({requestId:t})}});yield this.sendDataPacket(i,e9.RELIABLE)})}sendDataPacket(e,t){return ib(this,void 0,void 0,function*(){yield this.ensurePublisherConnected(t),t===e9.RELIABLE&&(e.sequence=this.reliableDataSequence,this.reliableDataSequence+=1);let i=e.toBinary(),n=this.dataChannelForKind(t);if(n){if(t===e9.RELIABLE&&this.reliableMessageBuffer.push({data:i,sequence:e.sequence}),this.attemptingReconnect)return;n.send(i)}this.updateAndEmitDCBufferStatus(t)})}resendReliableMessagesForResume(e){return ib(this,void 0,void 0,function*(){yield this.ensurePublisherConnected(e9.RELIABLE);let t=this.dataChannelForKind(e9.RELIABLE);t&&(this.reliableMessageBuffer.popToSequence(e),this.reliableMessageBuffer.getAll().forEach(e=>{t.send(e.data)})),this.updateAndEmitDCBufferStatus(e9.RELIABLE)})}waitForBufferStatusLow(e){return new Promise((t,i)=>ib(this,void 0,void 0,function*(){if(this.isBufferStatusLow(e))t();else{let n=()=>i("Engine closed");for(this.once(oJ.Closing,n);!this.dcBufferStatus.get(e);)yield nq(10);this.off(oJ.Closing,n),t()}}))}ensureDataTransportConnected(e){return ib(this,arguments,void 0,function(e){var t=this;let i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.subscriberPrimary;return function*(){var n;if(!t.pcManager)throw new nT("PC manager is closed");let r=i?t.pcManager.subscriber:t.pcManager.publisher,s=i?"Subscriber":"Publisher";if(!r)throw new nv("".concat(s," connection not set"),oW.InternalError);let o=!1;i||t.dataChannelForKind(e,i)||(t.createDataChannels(),o=!0),o||i||t.pcManager.publisher.isICEConnected||"checking"===t.pcManager.publisher.getICEConnectionState()||(o=!0),o&&t.negotiate();let a=t.dataChannelForKind(e,i);if((null==a?void 0:a.readyState)==="open")return;let l=new Date().getTime()+t.peerConnectionTimeout;for(;new Date().getTime()<l;){if(r.isICEConnected&&(null===(n=t.dataChannelForKind(e,i))||void 0===n?void 0:n.readyState)==="open")return;yield nq(50)}throw new nv("could not establish ".concat(s," connection, state: ").concat(r.getICEConnectionState()),oW.InternalError)}()})}ensurePublisherConnected(e){return ib(this,void 0,void 0,function*(){this.publisherConnectionPromise||(this.publisherConnectionPromise=this.ensureDataTransportConnected(e,!1)),yield this.publisherConnectionPromise})}verifyTransport(){return!!this.pcManager&&this.pcManager.currentState===o9.CONNECTED&&!!this.client.ws&&this.client.ws.readyState!==WebSocket.CLOSED}negotiate(){return ib(this,void 0,void 0,function*(){return new Promise((e,t)=>ib(this,void 0,void 0,function*(){if(!this.pcManager){t(new nS("PC manager is closed"));return}this.pcManager.requirePublisher(),0!=this.pcManager.publisher.getTransceivers().length||this.lossyDC||this.reliableDC||this.createDataChannels();let i=new AbortController,n=()=>{i.abort(),this.log.debug("engine disconnected while negotiation was ongoing",this.logContext),e()};this.isClosed&&t("cannot negotiate on closed engine"),this.on(oJ.Closing,n),this.pcManager.publisher.once(rB.RTPVideoPayloadTypes,e=>{let t=new Map;e.forEach(e=>{let i=e.codec.toLowerCase();nj.includes(i)&&t.set(e.payload,i)}),this.emit(oJ.RTPVideoMapUpdate,t)});try{yield this.pcManager.negotiate(i),e()}catch(e){e instanceof nS&&(this.fullReconnectOnNext=!0),this.handleDisconnect("negotiation",eG.RR_UNKNOWN),t(e)}finally{this.off(oJ.Closing,n)}}))})}dataChannelForKind(e,t){if(t){if(e===e9.LOSSY)return this.lossyDCSub;if(e===e9.RELIABLE)return this.reliableDCSub}else{if(e===e9.LOSSY)return this.lossyDC;if(e===e9.RELIABLE)return this.reliableDC}}sendSyncState(e,t){var i,n;if(!this.pcManager){this.log.warn("sync state cannot be sent without peer connection setup",this.logContext);return}let r=this.pcManager.subscriber.getLocalDescription(),s=this.pcManager.subscriber.getRemoteDescription(),o=null===(n=null===(i=this.signalOpts)||void 0===i?void 0:i.autoSubscribe)||void 0===n||n,a=[],l=[];e.forEach(e=>{e.isDesired!==o&&a.push(e.trackSid),e.isEnabled||l.push(e.trackSid)}),this.client.sendSyncState(new t9({answer:r?rM({sdp:r.sdp,type:r.type}):void 0,offer:s?rM({sdp:s.sdp,type:s.type}):void 0,subscription:new tF({trackSids:a,subscribe:!o,participantTracks:[]}),publishTracks:function(e){let t=[];return e.forEach(e=>{void 0!==e.track&&t.push(new tN({cid:e.track.mediaStreamID,track:e.trackInfo}))}),t}(t),dataChannels:this.dataChannelsInfo(),trackSidsDisabled:l,datachannelReceiveStates:this.reliableReceivedState.map((e,t)=>new t8({publisherSid:t,lastSeq:e}))}))}failNext(){this.shouldFailNext=!0}dataChannelsInfo(){let e=[],t=(t,i)=>{(null==t?void 0:t.id)!==void 0&&null!==t.id&&e.push(new t7({label:t.label,id:t.id,target:i}))};return t(this.dataChannelForKind(e9.LOSSY),tw.PUBLISHER),t(this.dataChannelForKind(e9.RELIABLE),tw.PUBLISHER),t(this.dataChannelForKind(e9.LOSSY,!0),tw.SUBSCRIBER),t(this.dataChannelForKind(e9.RELIABLE,!0),tw.SUBSCRIBER),e}clearReconnectTimeout(){this.reconnectTimeout&&nA.clearTimeout(this.reconnectTimeout)}clearPendingReconnect(){this.clearReconnectTimeout(),this.reconnectAttempts=0}registerOnLineListener(){nY()&&window.addEventListener("online",this.handleBrowserOnLine)}deregisterOnLineListener(){nY()&&window.removeEventListener("online",this.handleBrowserOnLine)}}class sv extends Error{}class sy{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 nZ(this.serverUrl)}getServerUrl(){return this.serverUrl}getNextBestRegionUrl(e){return ib(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));let t=this.regionSettings.regions.filter(e=>!this.attemptedRegions.find(t=>t.url===e.url));if(!(t.length>0))return null;{let e=t[0];return this.attemptedRegions.push(e),ip.debug("next region: ".concat(e.region)),e.url}})}resetAttempts(){this.attemptedRegions=[]}fetchRegionSettings(e){return ib(this,void 0,void 0,function*(){var t;let i=yield fetch("".concat((t=this.serverUrl,"".concat(t.protocol.replace("ws","http"),"//").concat(t.host,"/settings")),"/regions"),{headers:{authorization:"Bearer ".concat(this.token)},signal:e});if(i.ok){let e=yield i.json();return this.lastUpdateAt=Date.now(),e}throw new nv("Could not fetch region settings: ".concat(i.statusText),401===i.status?oW.NotAllowed:oW.InternalError,i.status)})}setServerReportedRegions(e){this.regionSettings=e,this.lastUpdateAt=Date.now()}}class sb{get info(){return this._info}constructor(e,t,i){this.reader=t,this.totalByteSize=i,this._info=e,this.bytesReceived=0}}class sk extends sb{handleChunkReceived(e){var t;this.bytesReceived+=e.content.byteLength;let i=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;null===(t=this.onProgress)||void 0===t||t.call(this,i)}[Symbol.asyncIterator](){let e=this.reader.getReader();return{next:()=>ib(this,void 0,void 0,function*(){try{let{done:t,value:i}=yield e.read();if(t)return{done:!0,value:void 0};return this.handleChunkReceived(i),{done:!1,value:i.content}}catch(e){return{done:!0,value:void 0}}}),return(){return ib(this,void 0,void 0,function*(){return e.releaseLock(),{done:!0,value:void 0}})}}}readAll(){return ib(this,void 0,void 0,function*(){var e,t,i,n;let r=new Set;try{for(var s,o=!0,a=ik(this);!(e=(s=yield a.next()).done);o=!0)n=s.value,o=!1,r.add(n)}catch(e){t={error:e}}finally{try{!o&&!e&&(i=a.return)&&(yield i.call(a))}finally{if(t)throw t.error}}return Array.from(r)})}}class sT extends sb{constructor(e,t,i){super(e,t,i),this.receivedChunks=new Map}handleChunkReceived(e){var t;let i=ro(e.chunkIndex),n=this.receivedChunks.get(i);if(n&&n.version>e.version)return;this.receivedChunks.set(i,e),this.bytesReceived+=e.content.byteLength;let r=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;null===(t=this.onProgress)||void 0===t||t.call(this,r)}[Symbol.asyncIterator](){let e=this.reader.getReader(),t=new TextDecoder;return{next:()=>ib(this,void 0,void 0,function*(){try{let{done:i,value:n}=yield e.read();if(i)return{done:!0,value:void 0};return this.handleChunkReceived(n),{done:!1,value:t.decode(n.content)}}catch(e){return{done:!0,value:void 0}}}),return(){return ib(this,void 0,void 0,function*(){return e.releaseLock(),{done:!0,value:void 0}})}}}readAll(){return ib(this,void 0,void 0,function*(){var e,t,i,n;let r="";try{for(var s,o=!0,a=ik(this);!(e=(s=yield a.next()).done);o=!0)n=s.value,o=!1,r+=n}catch(e){t={error:e}}finally{try{!o&&!e&&(i=a.return)&&(yield i.call(a))}finally{if(t)throw t.error}}return r})}}class sS{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 ib(this,void 0,void 0,function*(){var e;yield this.defaultWriter.close(),this.defaultWriter.releaseLock(),null===(e=this.onClose)||void 0===e||e.call(this)})}}class sC extends sS{}class sw extends sS{}class sE extends nM{constructor(e,t,i,n,r){super(e,i,r),this.sid=t,this.receiver=n}get isLocal(){return!1}setMuted(e){this.isMuted!==e&&(this.isMuted=e,this._mediaStreamTrack.enabled=!e,this.emit(e?oX.Muted:oX.Unmuted,this))}setMediaStream(e){this.mediaStream=e;let 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(oX.Ended,this))};e.addEventListener("removetrack",t)}start(){this.startMonitor(),super.enable()}stop(){this.stopMonitor(),super.disable()}getRTCStatsReport(){return ib(this,void 0,void 0,function*(){var e;if(null===(e=this.receiver)||void 0===e?void 0:e.getStats)return yield this.receiver.getStats()})}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(),2e3)),"undefined"!=typeof RTCRtpReceiver&&"getSynchronizationSources"in RTCRtpReceiver&&this.registerTimeSyncUpdate()}registerTimeSyncUpdate(){let e=()=>{var t;this.timeSyncHandle=requestAnimationFrame(()=>e());let i=null===(t=this.receiver)||void 0===t?void 0:t.getSynchronizationSources()[0];if(i){let{timestamp:e,rtpTimestamp:t}=i;t&&this.rtpTimestamp!==t&&(this.emit(oX.TimeSyncUpdate,{timestamp:e,rtpTimestamp:t}),this.rtpTimestamp=t)}};e()}}class sP extends sE{constructor(e,t,i,n,r,s){super(e,t,nM.Kind.Audio,i,s),this.monitorReceiver=()=>ib(this,void 0,void 0,function*(){if(!this.receiver){this._currentBitrate=0;return}let e=yield this.getReceiverStats();e&&this.prevStats&&this.receiver&&(this._currentBitrate=r0(e,this.prevStats)),this.prevStats=e}),this.audioContext=n,this.webAudioPluginNodes=[],r&&(this.sinkId=r.deviceId)}setVolume(e){var t;for(let i of this.attachedElements)this.audioContext?null===(t=this.gainNode)||void 0===t||t.gain.setTargetAtTime(e,0,.1):i.volume=e;nQ()&&this._mediaStreamTrack._setVolume(e),this.elementVolume=e}getVolume(){if(this.elementVolume)return this.elementVolume;if(nQ())return 1;let e=0;return this.attachedElements.forEach(t=>{t.volume>e&&(e=t.volume)}),e}setSinkId(e){return ib(this,void 0,void 0,function*(){this.sinkId=e,yield Promise.all(this.attachedElements.map(t=>{if(nG(t))return t.setSinkId(e)}))})}attach(e){let t=0===this.attachedElements.length;return e?super.attach(e):e=super.attach(),this.sinkId&&nG(e)&&e.setSinkId(this.sinkId).catch(e=>{this.log.error("Failed to set sink id on remote audio track",e,this.logContext)}),this.audioContext&&t&&(this.log.debug("using audio context mapping",this.logContext),this.connectWebAudio(this.audioContext,e),e.volume=0,e.muted=!0),this.elementVolume&&this.setVolume(this.elementVolume),e}detach(e){let t;return e?(t=super.detach(e),this.audioContext&&(this.attachedElements.length>0?this.connectWebAudio(this.audioContext,this.attachedElements[0]):this.disconnectWebAudio())):(t=super.detach(),this.disconnectWebAudio()),t}setAudioContext(e){this.audioContext=e,e&&this.attachedElements.length>0?this.connectWebAudio(e,this.attachedElements[0]):e||this.disconnectWebAudio()}setWebAudioPlugins(e){this.webAudioPluginNodes=e,this.attachedElements.length>0&&this.audioContext&&this.connectWebAudio(this.audioContext,this.attachedElements[0])}connectWebAudio(e,t){this.disconnectWebAudio(),this.sourceNode=e.createMediaStreamSource(t.srcObject);let i=this.sourceNode;this.webAudioPluginNodes.forEach(e=>{i.connect(e),i=e}),this.gainNode=e.createGain(),i.connect(this.gainNode),this.gainNode.connect(e.destination),this.elementVolume&&this.gainNode.gain.setTargetAtTime(this.elementVolume,0,.1),"running"!==e.state&&e.resume().then(()=>{"running"!==e.state&&this.emit(oX.AudioPlaybackFailed,Error("Audio Context couldn't be started automatically"))}).catch(e=>{this.emit(oX.AudioPlaybackFailed,e)})}disconnectWebAudio(){var e,t;null===(e=this.gainNode)||void 0===e||e.disconnect(),null===(t=this.sourceNode)||void 0===t||t.disconnect(),this.gainNode=void 0,this.sourceNode=void 0}getReceiverStats(){return ib(this,void 0,void 0,function*(){let e;if(this.receiver&&this.receiver.getStats)return(yield this.receiver.getStats()).forEach(t=>{"inbound-rtp"===t.type&&(e={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})}),e})}}class sx extends sE{constructor(e,t,i,n,r){super(e,t,nM.Kind.Video,i,r),this.elementInfos=[],this.monitorReceiver=()=>ib(this,void 0,void 0,function*(){if(!this.receiver){this._currentBitrate=0;return}let e=yield this.getReceiverStats();e&&this.prevStats&&this.receiver&&(this._currentBitrate=r0(e,this.prevStats)),this.prevStats=e}),this.debouncedHandleResize=rV(()=>{this.updateDimensions()},100),this.adaptiveStreamSettings=n}get isAdaptiveStream(){return void 0!==this.adaptiveStreamSettings}get mediaStreamTrack(){return this._mediaStreamTrack}setMuted(e){super.setMuted(e),this.attachedElements.forEach(t=>{e?n_(this._mediaStreamTrack,t):nD(this._mediaStreamTrack,t)})}attach(e){if(e?super.attach(e):e=super.attach(),this.adaptiveStreamSettings&&void 0===this.elementInfos.find(t=>t.element===e)){let t=new sR(e);this.observeElementInfo(t)}return e}observeElementInfo(e){this.adaptiveStreamSettings&&void 0===this.elementInfos.find(t=>t===e)?(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}for(let t of this.elementInfos.filter(t=>t===e))t.stopObserving();this.elementInfos=this.elementInfos.filter(t=>t!==e),this.updateVisibility(),this.debouncedHandleResize()}detach(e){let t=[];if(e)return this.stopObservingElement(e),super.detach(e);for(let e of t=super.detach())this.stopObservingElement(e);return t}getDecoderImplementation(){var e;return null===(e=this.prevStats)||void 0===e?void 0:e.decoderImplementation}getReceiverStats(){return ib(this,void 0,void 0,function*(){let e;if(!this.receiver||!this.receiver.getStats)return;let t=yield this.receiver.getStats(),i="",n=new Map;return t.forEach(t=>{"inbound-rtp"===t.type?(i=t.codecId,e={type:"video",streamId:t.id,framesDecoded:t.framesDecoded,framesDropped:t.framesDropped,framesReceived:t.framesReceived,packetsReceived:t.packetsReceived,packetsLost:t.packetsLost,frameWidth:t.frameWidth,frameHeight:t.frameHeight,pliCount:t.pliCount,firCount:t.firCount,nackCount:t.nackCount,jitter:t.jitter,timestamp:t.timestamp,bytesReceived:t.bytesReceived,decoderImplementation:t.decoderImplementation}):"codec"===t.type&&n.set(t.id,t)}),e&&""!==i&&n.get(i)&&(e.mimeType=n.get(i).mimeType),e})}stopObservingElement(e){for(let t of this.elementInfos.filter(t=>t.element===e))this.stopObservingElementInfo(t)}handleAppVisibilityChanged(){let e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return ib(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),this.isAdaptiveStream&&this.updateVisibility()})}updateVisibility(){var e,t;let i=this.elementInfos.reduce((e,t)=>Math.max(e,t.visibilityChangedAt||0),0),n=(null===(t=null===(e=this.adaptiveStreamSettings)||void 0===e?void 0:e.pauseVideoInBackground)||void 0===t||!!t)&&this.isInBackground,r=this.elementInfos.some(e=>e.pictureInPicture),s=this.elementInfos.some(e=>e.visible)&&!n||r;if(this.lastVisible!==s){if(!s&&Date.now()-i<100){nA.setTimeout(()=>{this.updateVisibility()},100);return}this.lastVisible=s,this.emit(oX.VisibilityChanged,s,this)}}updateDimensions(){var e,t;let i=0,n=0,r=this.getPixelDensity();for(let e of this.elementInfos){let t=e.width()*r,s=e.height()*r;t+s>i+n&&(i=t,n=s)}((null===(e=this.lastDimensions)||void 0===e?void 0:e.width)!==i||(null===(t=this.lastDimensions)||void 0===t?void 0:t.height)!==n)&&(this.lastDimensions={width:i,height:n},this.emit(oX.VideoDimensionsChanged,this.lastDimensions,this))}getPixelDensity(){var e;let t=null===(e=this.adaptiveStreamSettings)||void 0===e?void 0:e.pixelDensity;return"screen"===t?n2():t||(n2()>2?2:1)}}class sR{get visible(){return this.isPiP||this.isIntersecting}get pictureInPicture(){return this.isPiP}constructor(e,t){this.onVisibilityChanged=e=>{var t;let{target:i,isIntersecting:n}=e;i===this.element&&(this.isIntersecting=n,this.isPiP=sO(this.element),this.visibilityChangedAt=Date.now(),null===(t=this.handleVisibilityChanged)||void 0===t||t.call(this))},this.onEnterPiP=()=>{var e,t,i;null===(t=null===(e=window.documentPictureInPicture)||void 0===e?void 0:e.window)||void 0===t||t.addEventListener("pagehide",this.onLeavePiP),this.isPiP=sO(this.element),null===(i=this.handleVisibilityChanged)||void 0===i||i.call(this)},this.onLeavePiP=()=>{var e;this.isPiP=sO(this.element),null===(e=this.handleVisibilityChanged)||void 0===e||e.call(this)},this.element=e,this.isIntersecting=null!=t?t:sA(e),this.isPiP=nY()&&sO(e),this.visibilityChangedAt=0}width(){return this.element.clientWidth}height(){return this.element.clientHeight}observe(){var e,t,i;this.isIntersecting=sA(this.element),this.isPiP=sO(this.element),this.element.handleResize=()=>{var e;null===(e=this.handleResize)||void 0===e||e.call(this)},this.element.handleVisibilityChanged=this.onVisibilityChanged,n7().observe(this.element),n9().observe(this.element),this.element.addEventListener("enterpictureinpicture",this.onEnterPiP),this.element.addEventListener("leavepictureinpicture",this.onLeavePiP),null===(e=window.documentPictureInPicture)||void 0===e||e.addEventListener("enter",this.onEnterPiP),null===(i=null===(t=window.documentPictureInPicture)||void 0===t?void 0:t.window)||void 0===i||i.addEventListener("pagehide",this.onLeavePiP)}stopObserving(){var e,t,i,n,r;null===(e=n7())||void 0===e||e.unobserve(this.element),null===(t=n9())||void 0===t||t.unobserve(this.element),this.element.removeEventListener("enterpictureinpicture",this.onEnterPiP),this.element.removeEventListener("leavepictureinpicture",this.onLeavePiP),null===(i=window.documentPictureInPicture)||void 0===i||i.removeEventListener("enter",this.onEnterPiP),null===(r=null===(n=window.documentPictureInPicture)||void 0===n?void 0:n.window)||void 0===r||r.removeEventListener("pagehide",this.onLeavePiP)}}function sO(e){var t,i;return document.pictureInPictureElement===e||null!==(t=window.documentPictureInPicture)&&void 0!==t&&!!t.window&&sA(e,null===(i=window.documentPictureInPicture)||void 0===i?void 0:i.window)}function sA(e,t){let i=t||window,n=e.offsetTop,r=e.offsetLeft,s=e.offsetWidth,o=e.offsetHeight,{hidden:a}=e,{display:l}=getComputedStyle(e);for(;e.offsetParent;)n+=(e=e.offsetParent).offsetTop,r+=e.offsetLeft;return n<i.pageYOffset+i.innerHeight&&r<i.pageXOffset+i.innerWidth&&n+o>i.pageYOffset&&r+s>i.pageXOffset&&!a&&"none"!==l}class sI extends iS.EventEmitter{constructor(e,t,i,n){var r;super(),this.metadataMuted=!1,this.encryption=e2.NONE,this.log=ip,this.handleMuted=()=>{this.emit(oX.Muted)},this.handleUnmuted=()=>{this.emit(oX.Unmuted)},this.log=im(null!==(r=null==n?void 0:n.loggerName)&&void 0!==r?r:oj.Publication),this.loggerContextCb=this.loggerContextCb,this.setMaxListeners(100),this.kind=e,this.trackSid=t,this.trackName=i,this.source=nM.Source.Unknown}setTrack(e){this.track&&(this.track.off(oX.Muted,this.handleMuted),this.track.off(oX.Unmuted,this.handleUnmuted)),this.track=e,e&&(e.on(oX.Muted,this.handleMuted),e.on(oX.Unmuted,this.handleUnmuted))}get logContext(){var e;return Object.assign(Object.assign({},null===(e=this.loggerContextCb)||void 0===e?void 0:e.call(this)),rT(this))}get isMuted(){return this.metadataMuted}get isEnabled(){return!0}get isSubscribed(){return void 0!==this.track}get isEncrypted(){return this.encryption!==e2.NONE}get audioTrack(){if(rc(this.track))return this.track}get videoTrack(){if(rd(this.track))return this.track}updateInfo(e){this.trackSid=e.sid,this.trackName=e.name,this.source=nM.sourceFromProto(e.source),this.mimeType=e.mimeType,this.kind===nM.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(e){var t,i;(t=e.SubscriptionStatus||(e.SubscriptionStatus={})).Desired="desired",t.Subscribed="subscribed",t.Unsubscribed="unsubscribed",(i=e.PermissionStatus||(e.PermissionStatus={})).Allowed="allowed",i.NotAllowed="not_allowed"}(sI||(sI={}));class sM extends sI{get isUpstreamPaused(){var e;return null===(e=this.track)||void 0===e?void 0:e.isUpstreamPaused}constructor(e,t,i,n){super(e,t.sid,t.name,n),this.track=void 0,this.handleTrackEnded=()=>{this.emit(oX.Ended)},this.handleCpuConstrained=()=>{this.track&&rd(this.track)&&this.emit(oX.CpuConstrained,this.track)},this.updateInfo(t),this.setTrack(i)}setTrack(e){this.track&&(this.track.off(oX.Ended,this.handleTrackEnded),this.track.off(oX.CpuConstrained,this.handleCpuConstrained)),super.setTrack(e),e&&(e.on(oX.Ended,this.handleTrackEnded),e.on(oX.CpuConstrained,this.handleCpuConstrained))}get isMuted(){return this.track?this.track.isMuted:super.isMuted}get audioTrack(){return super.audioTrack}get videoTrack(){return super.videoTrack}get isLocal(){return!0}mute(){return ib(this,void 0,void 0,function*(){var e;return null===(e=this.track)||void 0===e?void 0:e.mute()})}unmute(){return ib(this,void 0,void 0,function*(){var e;return null===(e=this.track)||void 0===e?void 0:e.unmute()})}pauseUpstream(){return ib(this,void 0,void 0,function*(){var e;yield null===(e=this.track)||void 0===e?void 0:e.pauseUpstream()})}resumeUpstream(){return ib(this,void 0,void 0,function*(){var e;yield null===(e=this.track)||void 0===e?void 0:e.resumeUpstream()})}getTrackFeatures(){var e;if(!rc(this.track))return[];{let t=this.track.getSourceTrackSettings(),i=new Set;return t.autoGainControl&&i.add(eK.TF_AUTO_GAIN_CONTROL),t.echoCancellation&&i.add(eK.TF_ECHO_CANCELLATION),t.noiseSuppression&&i.add(eK.TF_NOISE_SUPPRESSION),t.channelCount&&t.channelCount>1&&i.add(eK.TF_STEREO),(null===(e=this.options)||void 0===e?void 0:e.dtx)||i.add(eK.TF_NO_DTX),this.track.enhancedNoiseCancellation&&i.add(eK.TF_ENHANCED_NOISE_CANCELLATION),Array.from(i.values())}}}!function(e){e.Excellent="excellent",e.Good="good",e.Poor="poor",e.Lost="lost",e.Unknown="unknown"}(o7||(o7={}));class sD extends iS.EventEmitter{get logContext(){var e,t;return Object.assign({},null===(t=null===(e=this.loggerOptions)||void 0===e?void 0:e.loggerContextCb)||void 0===t?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(null===(e=this.permissions)||void 0===e?void 0:e.agent)||this.kind===e0.AGENT}get isActive(){var e;return(null===(e=this.participantInfo)||void 0===e?void 0:e.state)===eZ.ACTIVE}get kind(){return this._kind}get attributes(){return Object.freeze(Object.assign({},this._attributes))}constructor(e,t,i,n,r,s){var o;let a=arguments.length>6&&void 0!==arguments[6]?arguments[6]:e0.STANDARD;super(),this.audioLevel=0,this.isSpeaking=!1,this._connectionQuality=o7.Unknown,this.log=ip,this.log=im(null!==(o=null==s?void 0:s.loggerName)&&void 0!==o?o:oj.Participant),this.loggerOptions=s,this.setMaxListeners(100),this.sid=e,this.identity=t,this.name=i,this.metadata=n,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this._kind=a,this._attributes=null!=r?r:{}}getTrackPublications(){return Array.from(this.trackPublications.values())}getTrackPublication(e){for(let[,t]of this.trackPublications)if(t.source===e)return t}getTrackPublicationByName(e){for(let[,t]of this.trackPublications)if(t.trackName===e)return t}waitUntilActive(){return this.isActive?Promise.resolve():(this.activeFuture||(this.activeFuture=new ri,this.once(oK.Active,()=>{var e,t;null===(t=null===(e=this.activeFuture)||void 0===e?void 0:e.resolve)||void 0===t||t.call(e),this.activeFuture=void 0})),this.activeFuture.promise)}get connectionQuality(){return this._connectionQuality}get isCameraEnabled(){var e;let t=this.getTrackPublication(nM.Source.Camera);return!(null===(e=null==t?void 0:t.isMuted)||void 0===e||e)}get isMicrophoneEnabled(){var e;let t=this.getTrackPublication(nM.Source.Microphone);return!(null===(e=null==t?void 0:t.isMuted)||void 0===e||e)}get isScreenShareEnabled(){return!!this.getTrackPublication(nM.Source.ScreenShare)}get isLocal(){return!1}get joinedAt(){return this.participantInfo?new Date(1e3*Number.parseInt(this.participantInfo.joinedAt.toString())):new Date}updateInfo(e){var t;return(!this.participantInfo||this.participantInfo.sid!==e.sid||!(this.participantInfo.version>e.version))&&(this.identity=e.identity,this.sid=e.sid,this._setName(e.name),this._setMetadata(e.metadata),this._setAttributes(e.attributes),e.state===eZ.ACTIVE&&(null===(t=this.participantInfo)||void 0===t?void 0:t.state)!==eZ.ACTIVE&&this.emit(oK.Active),e.permission&&this.setPermissions(e.permission),this.participantInfo=e,!0)}_setMetadata(e){let t=this.metadata!==e,i=this.metadata;this.metadata=e,t&&this.emit(oK.ParticipantMetadataChanged,i)}_setName(e){let t=this.name!==e;this.name=e,t&&this.emit(oK.ParticipantNameChanged,e)}_setAttributes(e){let t=function(e,t){var i;void 0===e&&(e={}),void 0===t&&(t={});let n=[...Object.keys(t),...Object.keys(e)],r={};for(let s of n)e[s]!==t[s]&&(r[s]=null!==(i=t[s])&&void 0!==i?i:"");return r}(this.attributes,e);this._attributes=e,Object.keys(t).length>0&&this.emit(oK.AttributesChanged,t)}setPermissions(e){var t,i,n,r,s,o;let a=this.permissions,l=e.canPublish!==(null===(t=this.permissions)||void 0===t?void 0:t.canPublish)||e.canSubscribe!==(null===(i=this.permissions)||void 0===i?void 0:i.canSubscribe)||e.canPublishData!==(null===(n=this.permissions)||void 0===n?void 0:n.canPublishData)||e.hidden!==(null===(r=this.permissions)||void 0===r?void 0:r.hidden)||e.recorder!==(null===(s=this.permissions)||void 0===s?void 0:s.recorder)||e.canPublishSources.length!==this.permissions.canPublishSources.length||e.canPublishSources.some((e,t)=>{var i;return e!==(null===(i=this.permissions)||void 0===i?void 0:i.canPublishSources[t])})||e.canSubscribeMetrics!==(null===(o=this.permissions)||void 0===o?void 0:o.canSubscribeMetrics);return this.permissions=e,l&&this.emit(oK.ParticipantPermissionsChanged,a),l}setIsSpeaking(e){e!==this.isSpeaking&&(this.isSpeaking=e,e&&(this.lastSpokeAt=new Date),this.emit(oK.IsSpeakingChanged,e))}setConnectionQuality(e){let t=this._connectionQuality;this._connectionQuality=function(e){switch(e){case ez.EXCELLENT:return o7.Excellent;case ez.GOOD:return o7.Good;case ez.POOR:return o7.Poor;case ez.LOST:return o7.Lost;default:return o7.Unknown}}(e),t!==this._connectionQuality&&this.emit(oK.ConnectionQualityChanged,this._connectionQuality)}setDisconnected(){var e,t;this.activeFuture&&(null===(t=(e=this.activeFuture).reject)||void 0===t||t.call(e,Error("Participant disconnected")),this.activeFuture=void 0)}setAudioContext(e){this.audioContext=e,this.audioTrackPublications.forEach(t=>rc(t.track)&&t.track.setAudioContext(e))}addTrackPublication(e){switch(e.on(oX.Muted,()=>{this.emit(oK.TrackMuted,e)}),e.on(oX.Unmuted,()=>{this.emit(oK.TrackUnmuted,e)}),e.track&&(e.track.sid=e.trackSid),this.trackPublications.set(e.trackSid,e),e.kind){case nM.Kind.Audio:this.audioTrackPublications.set(e.trackSid,e);break;case nM.Kind.Video:this.videoTrackPublications.set(e.trackSid,e)}}}class s_ extends sD{constructor(e,t,i,n,r){super(e,t,void 0,void 0,void 0,{loggerName:n.loggerName,loggerContextCb:()=>this.engine.logContext}),this.pendingPublishing=new Set,this.pendingPublishPromises=new Map,this.participantTrackPermissions=[],this.allParticipantsAllowedToSubscribe=!0,this.encryptionType=e2.NONE,this.enabledPublishVideoCodecs=[],this.pendingAcks=new Map,this.pendingResponses=new Map,this.handleReconnecting=()=>{this.reconnectFuture||(this.reconnectFuture=new ri)},this.handleReconnected=()=>{var e,t;null===(t=null===(e=this.reconnectFuture)||void 0===e?void 0:e.resolve)||void 0===t||t.call(e),this.reconnectFuture=void 0,this.updateTrackSubscriptionPermissions()},this.handleClosing=()=>{var e,t,i,n,r,s;this.reconnectFuture&&(this.reconnectFuture.promise.catch(e=>this.log.warn(e.message,this.logContext)),null===(t=null===(e=this.reconnectFuture)||void 0===e?void 0:e.reject)||void 0===t||t.call(e,"Got disconnected during reconnection attempt"),this.reconnectFuture=void 0),this.signalConnectedFuture&&(null===(n=(i=this.signalConnectedFuture).reject)||void 0===n||n.call(i,"Got disconnected without signal connected"),this.signalConnectedFuture=void 0),null===(s=null===(r=this.activeAgentFuture)||void 0===r?void 0:r.reject)||void 0===s||s.call(r,"Got disconnected without active agent present"),this.activeAgentFuture=void 0,this.firstActiveAgent=void 0},this.handleSignalConnected=e=>{var t,i;e.participant&&this.updateInfo(e.participant),this.signalConnectedFuture||(this.signalConnectedFuture=new ri),null===(i=(t=this.signalConnectedFuture).resolve)||void 0===i||i.call(t)},this.handleSignalRequestResponse=e=>{let{requestId:t,reason:i,message:n}=e,r=this.pendingSignalRequests.get(t);r&&(i!==il.OK&&r.reject(new nw(n,i)),this.pendingSignalRequests.delete(t))},this.handleDataPacket=e=>{switch(e.value.case){case"rpcResponse":let t=e.value.value,i=null,n=null;"payload"===t.value.case?i=t.value.value:"error"===t.value.case&&(n=rY.fromProto(t.value.value)),this.handleIncomingRpcResponse(t.requestId,i,n);break;case"rpcAck":let r=e.value.value;this.handleIncomingRpcAck(r.requestId)}},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(e=>(function(e){var t,i,n;if(!e.participantSid&&!e.participantIdentity)throw Error("Invalid track permission, must provide at least one of participantIdentity and participantSid");return new t3({participantIdentity:null!==(t=e.participantIdentity)&&void 0!==t?t:"",participantSid:null!==(i=e.participantSid)&&void 0!==i?i:"",allTracks:null!==(n=e.allowAll)&&void 0!==n&&n,trackSids:e.allowedTrackSids||[]})})(e)))},this.onTrackUnmuted=e=>{this.onTrackMuted(e,e.isUpstreamPaused)},this.onTrackMuted=(e,t)=>{if(void 0===t&&(t=!0),!e.sid){this.log.error("could not update mute status for unpublished track",Object.assign(Object.assign({},this.logContext),rT(e)));return}this.engine.updateMuteStatus(e.sid,t)},this.onTrackUpstreamPaused=e=>{this.log.debug("upstream paused",Object.assign(Object.assign({},this.logContext),rT(e))),this.onTrackMuted(e,!0)},this.onTrackUpstreamResumed=e=>{this.log.debug("upstream resumed",Object.assign(Object.assign({},this.logContext),rT(e))),this.onTrackMuted(e,e.isMuted)},this.onTrackFeatureUpdate=e=>{let t=this.audioTrackPublications.get(e.sid);if(!t){this.log.warn("Could not update local audio track settings, missing publication for track ".concat(e.sid),this.logContext);return}this.engine.client.sendUpdateLocalAudioTrack(t.trackSid,t.getTrackFeatures())},this.onTrackCpuConstrained=(e,t)=>{this.log.debug("track cpu constrained",Object.assign(Object.assign({},this.logContext),rT(t))),this.emit(oK.LocalTrackCpuConstrained,e,t)},this.handleSubscribedQualityUpdate=e=>ib(this,void 0,void 0,function*(){if(!(null===(a=this.roomOptions)||void 0===a?void 0:a.dynacast))return;let t=this.videoTrackPublications.get(e.trackSid);if(!t){this.log.warn("received subscribed quality update for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:e.trackSid}));return}if(!t.videoTrack)return;let i=yield t.videoTrack.setPublishingCodecs(e.subscribedCodecs);try{for(var n,r,s,o,a,l,c=!0,d=ik(i);!(n=(l=yield d.next()).done);c=!0)o=l.value,c=!1,function(e){return!!nL.find(t=>t===e)}(o)&&(this.log.debug("publish ".concat(o," for ").concat(t.videoTrack.sid),Object.assign(Object.assign({},this.logContext),rT(t))),yield this.publishAdditionalCodecForTrack(t.videoTrack,o,t.options))}catch(e){r={error:e}}finally{try{!c&&!n&&(s=d.return)&&(yield s.call(d))}finally{if(r)throw r.error}}}),this.handleLocalTrackUnpublished=e=>{let t=this.trackPublications.get(e.trackSid);if(!t){this.log.warn("received unpublished event for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:e.trackSid}));return}this.unpublishTrack(t.track)},this.handleTrackEnded=e=>ib(this,void 0,void 0,function*(){if(e.source===nM.Source.ScreenShare||e.source===nM.Source.ScreenShareAudio)this.log.debug("unpublishing local track due to TrackEnded",Object.assign(Object.assign({},this.logContext),rT(e))),this.unpublishTrack(e);else if(e.isUserProvided)yield e.mute();else if(rh(e)||ru(e))try{if(nY())try{let t=yield null==navigator?void 0:navigator.permissions.query({name:e.source===nM.Source.Camera?"camera":"microphone"});if(t&&"denied"===t.state)throw this.log.warn("user has revoked access to ".concat(e.source),Object.assign(Object.assign({},this.logContext),rT(e))),t.onchange=()=>{"denied"!==t.state&&(e.isMuted||e.restartTrack(),t.onchange=null)},Error("GetUserMedia Permission denied")}catch(e){}e.isMuted||(this.log.debug("track ended, attempting to use a different device",Object.assign(Object.assign({},this.logContext),rT(e))),rh(e)?yield e.restartTrack({deviceId:"default"}):yield e.restartTrack())}catch(t){this.log.warn("could not restart track, muting instead",Object.assign(Object.assign({},this.logContext),rT(e))),yield e.mute()}}),this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this.engine=i,this.roomOptions=n,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!==e2.NONE}getTrackPublication(e){let t=super.getTrackPublication(e);if(t)return t}getTrackPublicationByName(e){let t=super.getTrackPublicationByName(e);if(t)return t}setupEngine(e){var t;this.engine=e,this.engine.on(oJ.RemoteMute,(e,t)=>{let i=this.trackPublications.get(e);i&&i.track&&(t?i.mute():i.unmute())}),(null===(t=this.signalConnectedFuture)||void 0===t?void 0:t.isResolved)&&(this.signalConnectedFuture=void 0),this.engine.on(oJ.Connected,this.handleReconnected).on(oJ.SignalConnected,this.handleSignalConnected).on(oJ.SignalRestarted,this.handleReconnected).on(oJ.SignalResumed,this.handleReconnected).on(oJ.Restarting,this.handleReconnecting).on(oJ.Resuming,this.handleReconnecting).on(oJ.LocalTrackUnpublished,this.handleLocalTrackUnpublished).on(oJ.SubscribedQualityUpdate,this.handleSubscribedQualityUpdate).on(oJ.Closing,this.handleClosing).on(oJ.SignalRequestResponse,this.handleSignalRequestResponse).on(oJ.DataPacketReceived,this.handleDataPacket)}setMetadata(e){return ib(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({metadata:e})})}setName(e){return ib(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({name:e})})}setAttributes(e){return ib(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({attributes:e})})}requestMetadataUpdate(e){return ib(this,arguments,void 0,function(e){var t=this;let{metadata:i,name:n,attributes:r}=e;return function*(){return new Promise((e,s)=>ib(t,void 0,void 0,function*(){var t,o;try{let a=!1,l=yield this.engine.client.sendUpdateLocalMetadata(null!==(t=null!=i?i:this.metadata)&&void 0!==t?t:"",null!==(o=null!=n?n:this.name)&&void 0!==o?o:"",r),c=performance.now();for(this.pendingSignalRequests.set(l,{resolve:e,reject:e=>{s(e),a=!0},values:{name:n,metadata:i,attributes:r}});performance.now()-c<5e3&&!a;){if((!n||this.name===n)&&(!i||this.metadata===i)&&(!r||Object.entries(r).every(e=>{let[t,i]=e;return this.attributes[t]===i||""===i&&!this.attributes[t]}))){this.pendingSignalRequests.delete(l),e();return}yield nq(50)}s(new nw("Request to update local metadata timed out","TimeoutError"))}catch(e){e instanceof Error&&s(e)}}))}()})}setCameraEnabled(e,t,i){return this.setTrackEnabled(nM.Source.Camera,e,t,i)}setMicrophoneEnabled(e,t,i){return this.setTrackEnabled(nM.Source.Microphone,e,t,i)}setScreenShareEnabled(e,t,i){return this.setTrackEnabled(nM.Source.ScreenShare,e,t,i)}setPermissions(e){let t=this.permissions,i=super.setPermissions(e);return i&&t&&this.emit(oK.ParticipantPermissionsChanged,t),i}setE2EEEnabled(e){return ib(this,void 0,void 0,function*(){this.encryptionType=e?e2.GCM:e2.NONE,yield this.republishAllTracks(void 0,!1)})}setTrackEnabled(e,t,i,n){return ib(this,void 0,void 0,function*(){this.log.debug("setTrackEnabled",Object.assign(Object.assign({},this.logContext),{source:e,enabled:t})),this.republishPromise&&(yield this.republishPromise);let r=this.getTrackPublication(e);if(t){if(r)yield r.unmute();else{let t;if(this.pendingPublishing.has(e)){let t=yield this.waitForPendingPublicationOfSource(e);return t||this.log.info("waiting for pending publication promise timed out",Object.assign(Object.assign({},this.logContext),{source:e})),yield null==t?void 0:t.unmute(),t}this.pendingPublishing.add(e);try{switch(e){case nM.Source.Camera:t=yield this.createTracks({video:null==i||i});break;case nM.Source.Microphone:t=yield this.createTracks({audio:null==i||i});break;case nM.Source.ScreenShare:t=yield this.createScreenTracks(Object.assign({},i));break;default:throw new nb(e)}}catch(i){throw null==t||t.forEach(e=>{e.stop()}),i instanceof Error&&this.emit(oK.MediaDevicesError,i,rb(e)),this.pendingPublishing.delete(e),i}for(let n of t){let t=Object.assign(Object.assign({},this.roomOptions.publishDefaults),i);e===nM.Source.Microphone&&rc(n)&&t.preConnectBuffer&&(this.log.info("starting preconnect buffer for microphone",Object.assign({},this.logContext)),n.startPreConnectBuffer())}try{let e=[];for(let i of t)this.log.info("publishing track",Object.assign(Object.assign({},this.logContext),rT(i))),e.push(this.publishTrack(i,n));let i=yield Promise.all(e);[r]=i}catch(e){throw null==t||t.forEach(e=>{e.stop()}),e}finally{this.pendingPublishing.delete(e)}}}else if(!(!(null==r?void 0:r.track)&&this.pendingPublishing.has(e))||(r=yield this.waitForPendingPublicationOfSource(e))||this.log.info("waiting for pending publication promise timed out",Object.assign(Object.assign({},this.logContext),{source:e})),r&&r.track){if(e===nM.Source.ScreenShare){r=yield this.unpublishTrack(r.track);let e=this.getTrackPublication(nM.Source.ScreenShareAudio);e&&e.track&&this.unpublishTrack(e.track)}else yield r.mute()}return r})}enableCameraAndMicrophone(){return ib(this,void 0,void 0,function*(){if(!(this.pendingPublishing.has(nM.Source.Camera)||this.pendingPublishing.has(nM.Source.Microphone))){this.pendingPublishing.add(nM.Source.Camera),this.pendingPublishing.add(nM.Source.Microphone);try{let e=yield this.createTracks({audio:!0,video:!0});yield Promise.all(e.map(e=>this.publishTrack(e)))}finally{this.pendingPublishing.delete(nM.Source.Camera),this.pendingPublishing.delete(nM.Source.Microphone)}}})}createTracks(e){return ib(this,void 0,void 0,function*(){var t,i;null!=e||(e={});let n=rf(e,null===(t=this.roomOptions)||void 0===t?void 0:t.audioCaptureDefaults,null===(i=this.roomOptions)||void 0===i?void 0:i.videoCaptureDefaults);try{return(yield function e(t,i){return ib(this,void 0,void 0,function*(){null!=t||(t={});let n=!1,{audioProcessor:r,videoProcessor:s,optionsWithoutProcessor:o}=rS(t),a=o.audio,l=o.video;if(r&&"object"==typeof o.audio&&(o.audio.processor=r),s&&"object"==typeof o.video&&(o.video.processor=s),t.audio&&"object"==typeof o.audio&&"string"==typeof o.audio.deviceId){let e=o.audio.deviceId;o.audio.deviceId={exact:e},n=!0,a=Object.assign(Object.assign({},o.audio),{deviceId:{ideal:e}})}if(o.video&&"object"==typeof o.video&&"string"==typeof o.video.deviceId){let e=o.video.deviceId;o.video.deviceId={exact:e},n=!0,l=Object.assign(Object.assign({},o.video),{deviceId:{ideal:e}})}!0!==o.audio&&("object"!=typeof o.audio||o.audio.deviceId)||(o.audio={deviceId:"default"}),!0===o.video?o.video={deviceId:"default"}:"object"!=typeof o.video||o.video.deviceId||(o.video.deviceId="default");let c=rf(o,rG,r$),d=rv(c),u=navigator.mediaDevices.getUserMedia(d);o.audio&&(rP.userMediaPromiseMap.set("audioinput",u),u.catch(()=>rP.userMediaPromiseMap.delete("audioinput"))),o.video&&(rP.userMediaPromiseMap.set("videoinput",u),u.catch(()=>rP.userMediaPromiseMap.delete("videoinput")));try{let e=yield u;return yield Promise.all(e.getTracks().map(t=>ib(this,void 0,void 0,function*(){let n;let o="audio"===t.kind,a=o?c.audio:c.video;"boolean"!=typeof a&&a||(a={});let l=o?d.audio:d.video;"boolean"!=typeof l&&(n=l);let u=t.getSettings().deviceId;(null==n?void 0:n.deviceId)&&rn(n.deviceId)!==u?n.deviceId=u:n||(n={deviceId:u});let h=function(e,t,i){switch(e.kind){case"audio":return new r6(e,t,!1,void 0,i);case"video":return new sc(e,t,!1,i);default:throw new nb("unsupported track type: ".concat(e.kind))}}(t,n,i);return h.kind===nM.Kind.Video?h.source=nM.Source.Camera:h.kind===nM.Kind.Audio&&(h.source=nM.Source.Microphone),h.mediaStream=e,rc(h)&&r?yield h.setProcessor(r):rd(h)&&s&&(yield h.setProcessor(s)),h})))}catch(r){if(!n)throw r;return e(Object.assign(Object.assign({},t),{audio:a,video:l}),i)}})}(n,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext})).map(e=>(rc(e)&&(this.microphoneError=void 0,e.setAudioContext(this.audioContext),e.source=nM.Source.Microphone,this.emit(oK.AudioStreamAcquired)),rd(e)&&(this.cameraError=void 0,e.source=nM.Source.Camera),e))}catch(t){throw t instanceof Error&&(e.audio&&(this.microphoneError=t),e.video&&(this.cameraError=t)),t}})}createScreenTracks(e){return ib(this,void 0,void 0,function*(){var t,i,n;let r;if(void 0===e&&(e={}),void 0===navigator.mediaDevices.getDisplayMedia)throw new ny("getDisplayMedia not supported");void 0===e.resolution&&!function(){let e=nP();return(null==e?void 0:e.name)==="Safari"&&e.version.startsWith("17.")||(null==e?void 0:e.os)==="iOS"&&!!(null==e?void 0:e.osVersion)&&n3(e.osVersion,"17")>=0}()&&(e.resolution=nV.h1080fps30.resolution);let s=(r=null===(i=(t=e).video)||void 0===i||i,t.resolution&&t.resolution.width>0&&t.resolution.height>0&&(r="boolean"==typeof r?{}:r,r=nK()?Object.assign(Object.assign({},r),{width:{max:t.resolution.width},height:{max:t.resolution.height},frameRate:t.resolution.frameRate}):Object.assign(Object.assign({},r),{width:{ideal:t.resolution.width},height:{ideal:t.resolution.height},frameRate:t.resolution.frameRate})),{audio:null!==(n=t.audio)&&void 0!==n&&n,video:r,controller:t.controller,selfBrowserSurface:t.selfBrowserSurface,surfaceSwitching:t.surfaceSwitching,systemAudio:t.systemAudio,preferCurrentTab:t.preferCurrentTab}),o=yield navigator.mediaDevices.getDisplayMedia(s),a=o.getVideoTracks();if(0===a.length)throw new nb("no video track found");let l=new sc(a[0],void 0,!1,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});l.source=nM.Source.ScreenShare,e.contentHint&&(l.mediaStreamTrack.contentHint=e.contentHint);let c=[l];if(o.getAudioTracks().length>0){this.emit(oK.AudioStreamAcquired);let e=new r6(o.getAudioTracks()[0],void 0,!1,this.audioContext,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});e.source=nM.Source.ScreenShareAudio,c.push(e)}return c})}publishTrack(e,t){return ib(this,void 0,void 0,function*(){return this.publishOrRepublishTrack(e,t)})}publishOrRepublishTrack(e,t){return ib(this,arguments,void 0,function(e,t){var i=this;let n=arguments.length>2&&void 0!==arguments[2]&&arguments[2];return function*(){var r,s,o,a;let l,c;if(rh(e)&&e.setAudioContext(i.audioContext),yield null===(r=i.reconnectFuture)||void 0===r?void 0:r.promise,i.republishPromise&&!n&&(yield i.republishPromise),rl(e)&&i.pendingPublishPromises.has(e)&&(yield i.pendingPublishPromises.get(e)),e instanceof MediaStreamTrack)l=e.getConstraints();else{let t;switch(l=e.constraints,e.source){case nM.Source.Microphone:t="audioinput";break;case nM.Source.Camera:t="videoinput"}t&&i.activeDeviceMap.has(t)&&(l=Object.assign(Object.assign({},l),{deviceId:i.activeDeviceMap.get(t)}))}if(e instanceof MediaStreamTrack)switch(e.kind){case"audio":e=new r6(e,l,!0,i.audioContext,{loggerName:i.roomOptions.loggerName,loggerContextCb:()=>i.logContext});break;case"video":e=new sc(e,l,!0,{loggerName:i.roomOptions.loggerName,loggerContextCb:()=>i.logContext});break;default:throw new nb("unsupported MediaStreamTrack kind ".concat(e.kind))}else e.updateLoggerOptions({loggerName:i.roomOptions.loggerName,loggerContextCb:()=>i.logContext});if(i.trackPublications.forEach(t=>{t.track&&t.track===e&&(c=t)}),c)return i.log.warn("track has already been published, skipping",Object.assign(Object.assign({},i.logContext),rT(c))),c;let d="channelCount"in e.mediaStreamTrack.getSettings()&&2===e.mediaStreamTrack.getSettings().channelCount||2===e.mediaStreamTrack.getConstraints().channelCount,u=null!==(s=null==t?void 0:t.forceStereo)&&void 0!==s?s:d;u&&(t||(t={}),void 0===t.dtx&&i.log.info("Opus DTX will be disabled for stereo tracks by default. Enable them explicitly to make it work.",Object.assign(Object.assign({},i.logContext),rT(e))),void 0===t.red&&i.log.info("Opus RED will be disabled for stereo tracks by default. Enable them explicitly to make it work."),null!==(o=t.dtx)&&void 0!==o||(t.dtx=!1),null!==(a=t.red)&&void 0!==a||(t.red=!1));let h=Object.assign(Object.assign({},i.roomOptions.publishDefaults),t);!function(){let e=nP(),t="17.2";if(e)return"Safari"!==e.name&&"iOS"!==e.os||!!("iOS"===e.os&&e.osVersion&&n3(t,e.osVersion)>=0)||!!("Safari"===e.name&&n3(t,e.version)>=0)}()&&i.roomOptions.e2ee&&(i.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({},i.logContext)),h.simulcast=!1),h.source&&(e.source=h.source);let p=new Promise((t,n)=>ib(i,void 0,void 0,function*(){try{if(this.engine.client.currentState!==o1.CONNECTED){this.log.debug("deferring track publication until signal is connected",Object.assign(Object.assign({},this.logContext),{track:rT(e)}));let i=setTimeout(()=>{n(new nC("publishing rejected as engine not connected within timeout",408))},15e3);yield this.waitUntilEngineConnected(),clearTimeout(i);let r=yield this.publish(e,h,u);t(r)}else try{let i=yield this.publish(e,h,u);t(i)}catch(e){n(e)}}catch(e){n(e)}}));i.pendingPublishPromises.set(e,p);try{return yield p}catch(e){throw e}finally{i.pendingPublishPromises.delete(e)}}()})}waitUntilEngineConnected(){return this.signalConnectedFuture||(this.signalConnectedFuture=new ri),this.signalConnectedFuture.promise}hasPermissionsToPublish(e){if(!this.permissions)return this.log.warn("no permissions present for publishing track",Object.assign(Object.assign({},this.logContext),rT(e))),!1;let{canPublish:t,canPublishSources:i}=this.permissions;return!!(t&&(0===i.length||i.map(e=>(function(e){switch(e){case eB.CAMERA:return nM.Source.Camera;case eB.MICROPHONE:return nM.Source.Microphone;case eB.SCREEN_SHARE:return nM.Source.ScreenShare;case eB.SCREEN_SHARE_AUDIO:return nM.Source.ScreenShareAudio;default:return nM.Source.Unknown}})(e)).includes(e.source)))||(this.log.warn("insufficient permissions to publish",Object.assign(Object.assign({},this.logContext),rT(e))),!1)}publish(e,t,i){return ib(this,void 0,void 0,function*(){var n,r,s,o,a,l,c,d,u,h;let p,m;if(!this.hasPermissionsToPublish(e))throw new nC("failed to publish track, insufficient permissions",403);Array.from(this.trackPublications.values()).find(t=>rl(e)&&t.source===e.source)&&e.source!==nM.Source.Unknown&&this.log.info("publishing a second track with the same source: ".concat(e.source),Object.assign(Object.assign({},this.logContext),rT(e))),t.stopMicTrackOnMute&&rc(e)&&(e.stopOnMute=!0),e.source===nM.Source.ScreenShare&&n$()&&(t.simulcast=!1),"av1"===t.videoCodec&&!function(){if(!("getCapabilities"in RTCRtpSender)||nK())return!1;let e=RTCRtpSender.getCapabilities("video"),t=!1;if(e){for(let i of e.codecs)if("video/AV1"===i.mimeType){t=!0;break}}return t}()&&(t.videoCodec=void 0),"vp9"===t.videoCodec&&!function(){if(!("getCapabilities"in RTCRtpSender)||n$())return!1;if(nK()){let e=nP();if((null==e?void 0:e.version)&&0>n3(e.version,"16")||(null==e?void 0:e.os)==="iOS"&&(null==e?void 0:e.osVersion)&&0>n3(e.osVersion,"16"))return!1}let e=RTCRtpSender.getCapabilities("video"),t=!1;if(e){for(let i of e.codecs)if("video/VP9"===i.mimeType){t=!0;break}}return t}()&&(t.videoCodec=void 0),void 0===t.videoCodec&&(t.videoCodec="vp8"),this.enabledPublishVideoCodecs.length>0&&!this.enabledPublishVideoCodecs.some(e=>t.videoCodec===rk(e.mime))&&(t.videoCodec=rk(this.enabledPublishVideoCodecs[0].mime));let f=t.videoCodec;e.on(oX.Muted,this.onTrackMuted),e.on(oX.Unmuted,this.onTrackUnmuted),e.on(oX.Ended,this.handleTrackEnded),e.on(oX.UpstreamPaused,this.onTrackUpstreamPaused),e.on(oX.UpstreamResumed,this.onTrackUpstreamResumed),e.on(oX.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate);let g=[],v=!(null===(n=t.dtx)||void 0===n||n),y=e.getSourceTrackSettings();y.autoGainControl&&g.push(eK.TF_AUTO_GAIN_CONTROL),y.echoCancellation&&g.push(eK.TF_ECHO_CANCELLATION),y.noiseSuppression&&g.push(eK.TF_NOISE_SUPPRESSION),y.channelCount&&y.channelCount>1&&g.push(eK.TF_STEREO),v&&g.push(eK.TF_NO_DTX),rh(e)&&e.hasPreConnectBuffer&&g.push(eK.TF_PRECONNECT_BUFFER);let b=new tA({cid:e.mediaStreamTrack.id,name:t.name,type:nM.kindToProto(e.kind),muted:e.isMuted,source:nM.sourceToProto(e.source),disableDtx:v,encryption:this.encryptionType,stereo:i,disableRed:this.isE2EEEnabled||!(null===(r=t.red)||void 0===r||r),stream:null==t?void 0:t.stream,backupCodecPolicy:null==t?void 0:t.backupCodecPolicy,audioFeatures:g});if(e.kind===nM.Kind.Video){let i={width:0,height:0};try{i=yield e.waitForDimensions()}catch(n){let t=null!==(o=null===(s=this.roomOptions.videoCaptureDefaults)||void 0===s?void 0:s.resolution)&&void 0!==o?o:nU.h720.resolution;i={width:t.width,height:t.height},this.log.error("could not determine track dimensions, using defaults",Object.assign(Object.assign(Object.assign({},this.logContext),rT(e)),{dims:i}))}b.width=i.width,b.height=i.height,ru(e)&&(nH(f)&&(e.source===nM.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),rT(e))))),t.scalabilityMode=null!==(a=t.scalabilityMode)&&void 0!==a?a:"L3T3_KEY"),b.simulcastCodecs=[new tO({codec:f,cid:e.mediaStreamTrack.id})],!0===t.backupCodec&&(t.backupCodec={codec:"vp8"}),t.backupCodec&&f!==t.backupCodec.codec&&b.encryption===e2.NONE&&(this.roomOptions.dynacast||(this.roomOptions.dynacast=!0),b.simulcastCodecs.push(new tO({codec:t.backupCodec.codec,cid:""})))),p=sr(e.source===nM.Source.ScreenShare,b.width,b.height,t),b.layers=sh(b.width,b.height,p,nH(t.videoCodec))}else e.kind===nM.Kind.Audio&&(p=[{maxBitrate:null===(l=t.audioPreset)||void 0===l?void 0:l.maxBitrate,priority:null!==(d=null===(c=t.audioPreset)||void 0===c?void 0:c.priority)&&void 0!==d?d:"high",networkPriority:null!==(h=null===(u=t.audioPreset)||void 0===u?void 0:u.priority)&&void 0!==h?h:"high"}]);if(!this.engine||this.engine.isClosed)throw new nT("cannot publish track when not connected");let k=()=>ib(this,void 0,void 0,function*(){var i,n,r;if(!this.engine.pcManager)throw new nT("pcManager is not ready");if(e.sender=yield this.engine.createSender(e,t,p),this.emit(oK.LocalSenderCreated,e.sender,e),ru(e)&&(null!==(i=t.degradationPreference)&&void 0!==i||(t.degradationPreference=e.source===nM.Source.ScreenShare||e.constraints.height&&rn(e.constraints.height)>=1080?"maintain-resolution":"balanced"),e.setDegradationPreference(t.degradationPreference)),p){if(n$()&&e.kind===nM.Kind.Audio){let t;for(let i of this.engine.pcManager.publisher.getTransceivers())if(i.sender===e.sender){t=i;break}t&&this.engine.pcManager.publisher.setTrackCodecBitrate({transceiver:t,codec:"opus",maxbr:(null===(n=p[0])||void 0===n?void 0:n.maxBitrate)?p[0].maxBitrate/1e3:0})}else e.codec&&nH(e.codec)&&(null===(r=p[0])||void 0===r?void 0:r.maxBitrate)&&this.engine.pcManager.publisher.setTrackCodecBitrate({cid:b.cid,codec:e.codec,maxbr:p[0].maxBitrate/1e3})}yield this.engine.negotiate()}),T=new Promise((t,i)=>ib(this,void 0,void 0,function*(){var n;try{m=yield this.engine.addTrack(b),t(m)}catch(t){e.sender&&(null===(n=this.engine.pcManager)||void 0===n?void 0:n.publisher)&&(this.engine.pcManager.publisher.removeTrack(e.sender),yield this.engine.negotiate().catch(t=>{this.log.error("failed to negotiate after removing track due to failed add track request",Object.assign(Object.assign(Object.assign({},this.logContext),rT(e)),{error:t}))})),i(t)}}));if(this.enabledPublishVideoCodecs.length>0)m=(yield Promise.all([T,k()]))[0];else{let i;if((m=yield T).codecs.forEach(e=>{void 0===i&&(i=e.mimeType)}),i&&e.kind===nM.Kind.Video){let n=rk(i);n!==f&&(this.log.debug("falling back to server selected codec",Object.assign(Object.assign(Object.assign({},this.logContext),rT(e)),{codec:n})),t.videoCodec=n,p=sr(e.source===nM.Source.ScreenShare,b.width,b.height,t))}yield k()}let S=new sM(e.kind,m,e,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});if(S.on(oX.CpuConstrained,e=>this.onTrackCpuConstrained(e,S)),S.options=t,e.sid=m.sid,this.log.debug("publishing ".concat(e.kind," with encodings"),Object.assign(Object.assign({},this.logContext),{encodings:p,trackInfo:m})),ru(e)?e.startMonitor(this.engine.client):rh(e)&&e.startMonitor(),this.addTrackPublication(S),this.emit(oK.LocalTrackPublished,S),rh(e)&&m.audioFeatures.includes(eK.TF_PRECONNECT_BUFFER)){let t=e.getPreConnectBuffer(),i=e.getPreConnectBufferMimeType();this.on(oK.LocalTrackSubscribed,t=>{if(t.trackSid===m.sid){if(!e.hasPreConnectBuffer){this.log.warn("subscribe event came to late, buffer already closed",this.logContext);return}this.log.debug("finished recording preconnect buffer",Object.assign(Object.assign({},this.logContext),rT(e))),e.stopPreConnectBuffer()}}),t&&new Promise((n,r)=>ib(this,void 0,void 0,function*(){try{this.log.debug("waiting for agent",Object.assign(Object.assign({},this.logContext),rT(e)));let m=setTimeout(()=>{r(Error("agent not active within 10 seconds"))},1e4),f=yield this.waitUntilActiveAgentPresent();clearTimeout(m),this.log.debug("sending preconnect buffer",Object.assign(Object.assign({},this.logContext),rT(e)));let g=yield this.streamBytes({name:"preconnect-buffer",mimeType:i,topic:"lk.agent.pre-connect-audio-buffer",destinationIdentities:[f.identity],attributes:{trackId:S.trackSid,sampleRate:String(null!==(c=y.sampleRate)&&void 0!==c?c:"48000"),channels:String(null!==(d=y.channelCount)&&void 0!==d?d:"1")}});try{for(var s,o,a,l,c,d,u,h=!0,p=ik(t);!(s=(u=yield p.next()).done);h=!0)l=u.value,h=!1,yield g.write(l)}catch(e){o={error:e}}finally{try{!h&&!s&&(a=p.return)&&(yield a.call(p))}finally{if(o)throw o.error}}yield g.close(),n()}catch(e){r(e)}})).then(()=>{this.log.debug("preconnect buffer sent successfully",Object.assign(Object.assign({},this.logContext),rT(e)))}).catch(t=>{this.log.error("error sending preconnect buffer",Object.assign(Object.assign(Object.assign({},this.logContext),rT(e)),{error:t}))})}return S})}get isLocal(){return!0}publishAdditionalCodecForTrack(e,t,i){return ib(this,void 0,void 0,function*(){var n;let r;if(this.encryptionType!==e2.NONE)return;if(this.trackPublications.forEach(t=>{t.track&&t.track===e&&(r=t)}),!r)throw new nb("track is not published");if(!ru(e))throw new nb("track is not a video track");let s=Object.assign(Object.assign({},null===(n=this.roomOptions)||void 0===n?void 0:n.publishDefaults),i),o=function(e,t,i){var n,r,s,o;if(!i.backupCodec||!0===i.backupCodec||i.backupCodec.codec===i.videoCodec)return;t!==i.backupCodec.codec&&ip.warn("requested a different codec than specified as backup",{serverRequested:t,backup:i.backupCodec.codec}),i.videoCodec=t,i.videoEncoding=i.backupCodec.encoding;let a=e.mediaStreamTrack.getSettings(),l=null!==(n=a.width)&&void 0!==n?n:null===(r=e.dimensions)||void 0===r?void 0:r.width,c=null!==(s=a.height)&&void 0!==s?s:null===(o=e.dimensions)||void 0===o?void 0:o.height;return e.source===nM.Source.ScreenShare&&i.simulcast&&(i.simulcast=!1),sr(e.source===nM.Source.ScreenShare,l,c,i)}(e,t,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),rT(e)));return}let a=e.addSimulcastTrack(t,o);if(!a)return;let l=new tA({cid:a.mediaStreamTrack.id,type:nM.kindToProto(e.kind),muted:e.isMuted,source:nM.sourceToProto(e.source),sid:e.sid,simulcastCodecs:[{codec:s.videoCodec,cid:a.mediaStreamTrack.id}]});if(l.layers=sh(l.width,l.height,o),!this.engine||this.engine.isClosed)throw new nT("cannot publish track when not connected");let c=(yield Promise.all([this.engine.addTrack(l),ib(this,void 0,void 0,function*(){yield this.engine.createSimulcastSender(e,a,s,o),yield this.engine.negotiate()})]))[0];this.log.debug("published ".concat(t," for track ").concat(e.sid),Object.assign(Object.assign({},this.logContext),{encodings:o,trackInfo:c}))})}unpublishTrack(e,t){return ib(this,void 0,void 0,function*(){var i,n;if(rl(e)){let t=this.pendingPublishPromises.get(e);t&&(this.log.info("awaiting publish promise before attempting to unpublish",Object.assign(Object.assign({},this.logContext),rT(e))),yield t)}let r=this.getPublicationForTrack(e),s=r?rT(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).off(oX.Muted,this.onTrackMuted),e.off(oX.Unmuted,this.onTrackUnmuted),e.off(oX.Ended,this.handleTrackEnded),e.off(oX.UpstreamPaused,this.onTrackUpstreamPaused),e.off(oX.UpstreamResumed,this.onTrackUpstreamResumed),e.off(oX.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate),void 0===t&&(t=null===(n=null===(i=this.roomOptions)||void 0===i?void 0:i.stopLocalTrackOnUnpublish)||void 0===n||n),t?e.stop():e.stopMonitor();let o=!1,a=e.sender;if(e.sender=void 0,this.engine.pcManager&&this.engine.pcManager.currentState<o9.FAILED&&a)try{for(let e of this.engine.pcManager.publisher.getTransceivers())e.sender===a&&(e.direction="inactive",o=!0);if(this.engine.removeTrack(a)&&(o=!0),ru(e)){for(let[,t]of e.simulcastCodecs)t.sender&&(this.engine.removeTrack(t.sender)&&(o=!0),t.sender=void 0);e.simulcastCodecs.clear()}}catch(e){this.log.warn("failed to unpublish track",Object.assign(Object.assign(Object.assign({},this.logContext),s),{error:e}))}switch(this.trackPublications.delete(r.trackSid),r.kind){case nM.Kind.Audio:this.audioTrackPublications.delete(r.trackSid);break;case nM.Kind.Video:this.videoTrackPublications.delete(r.trackSid)}return this.emit(oK.LocalTrackUnpublished,r),r.setTrack(void 0),o&&(yield this.engine.negotiate()),r})}unpublishTracks(e){return ib(this,void 0,void 0,function*(){return(yield Promise.all(e.map(e=>this.unpublishTrack(e)))).filter(e=>!!e)})}republishAllTracks(e){return ib(this,arguments,void 0,function(e){var t=this;let i=!(arguments.length>1)||void 0===arguments[1]||arguments[1];return function*(){t.republishPromise&&(yield t.republishPromise),t.republishPromise=new Promise((n,r)=>ib(t,void 0,void 0,function*(){try{let t=[];this.trackPublications.forEach(i=>{i.track&&(e&&(i.options=Object.assign(Object.assign({},i.options),e)),t.push(i))}),yield Promise.all(t.map(e=>ib(this,void 0,void 0,function*(){let t=e.track;yield this.unpublishTrack(t,!1),i&&!t.isMuted&&t.source!==nM.Source.ScreenShare&&t.source!==nM.Source.ScreenShareAudio&&(rh(t)||ru(t))&&!t.isUserProvided&&(this.log.debug("restarting existing track",Object.assign(Object.assign({},this.logContext),{track:e.trackSid})),yield t.restartTrack()),yield this.publishOrRepublishTrack(t,e.options,!0)}))),n()}catch(e){r(e)}finally{this.republishPromise=void 0}})),yield t.republishPromise}()})}publishData(e){return ib(this,arguments,void 0,function(e){var t=this;let i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){let n=i.reliable?e9.RELIABLE:e9.LOSSY,r=i.destinationIdentities,s=i.topic,o=new e6({kind:n,value:{case:"user",value:new te({participantIdentity:t.identity,payload:e,destinationIdentities:r,topic:s})}});yield t.engine.sendDataPacket(o,n)}()})}publishDtmf(e,t){return ib(this,void 0,void 0,function*(){let i=new e6({kind:e9.RELIABLE,value:{case:"sipDtmf",value:new tt({code:e,digit:t})}});yield this.engine.sendDataPacket(i,e9.RELIABLE)})}sendChatMessage(e,t){return ib(this,void 0,void 0,function*(){let i={id:crypto.randomUUID(),message:e,timestamp:Date.now(),attachedFiles:null==t?void 0:t.attachments},n=new e6({value:{case:"chatMessage",value:new tr(Object.assign(Object.assign({},i),{timestamp:j.parse(i.timestamp)}))}});return yield this.engine.sendDataPacket(n,e9.RELIABLE),this.emit(oK.ChatMessage,i),i})}editChatMessage(e,t){return ib(this,void 0,void 0,function*(){let i=Object.assign(Object.assign({},t),{message:e,editTimestamp:Date.now()}),n=new e6({value:{case:"chatMessage",value:new tr(Object.assign(Object.assign({},i),{timestamp:j.parse(i.timestamp),editTimestamp:j.parse(i.editTimestamp)}))}});return yield this.engine.sendDataPacket(n,e9.RELIABLE),this.emit(oK.ChatMessage,i),i})}sendText(e,t){return ib(this,void 0,void 0,function*(){var i;let n=crypto.randomUUID(),r=new TextEncoder().encode(e).byteLength,s=null===(i=null==t?void 0:t.attachments)||void 0===i?void 0:i.map(()=>crypto.randomUUID()),o=Array(s?s.length+1:1).fill(0),a=(e,i)=>{var n;o[i]=e;let r=o.reduce((e,t)=>e+t,0);null===(n=null==t?void 0:t.onProgress)||void 0===n||n.call(t,r)},l=yield this.streamText({streamId:n,totalSize:r,destinationIdentities:null==t?void 0:t.destinationIdentities,topic:null==t?void 0:t.topic,attachedStreamIds:s,attributes:null==t?void 0:t.attributes});return yield l.write(e),a(1,0),yield l.close(),(null==t?void 0:t.attachments)&&s&&(yield Promise.all(t.attachments.map((e,i)=>ib(this,void 0,void 0,function*(){return this._sendFile(s[i],e,{topic:t.topic,mimeType:e.type,onProgress:e=>{a(e,i+1)}})})))),l.info})}streamText(e){return ib(this,void 0,void 0,function*(){var t,i;let n=null!==(t=null==e?void 0:e.streamId)&&void 0!==t?t:crypto.randomUUID(),r={id:n,mimeType:"text/plain",timestamp:Date.now(),topic:null!==(i=null==e?void 0:e.topic)&&void 0!==i?i:"",size:null==e?void 0:e.totalSize,attributes:null==e?void 0:e.attributes},s=new tT({streamId:n,mimeType:r.mimeType,topic:r.topic,timestamp:ra(r.timestamp),totalLength:ra(null==e?void 0:e.totalSize),attributes:r.attributes,contentHeader:{case:"textHeader",value:new tb({version:null==e?void 0:e.version,attachedStreamIds:null==e?void 0:e.attachedStreamIds,replyToStreamId:null==e?void 0:e.replyToStreamId,operationType:(null==e?void 0:e.type)==="update"?ty.UPDATE:ty.CREATE})}}),o=null==e?void 0:e.destinationIdentities,a=new e6({destinationIdentities:o,value:{case:"streamHeader",value:s}});yield this.engine.sendDataPacket(a,e9.RELIABLE);let l=0,c=this,d=new WritableStream({write(e){return ib(this,void 0,void 0,function*(){for(let t of function(e,t){let i=[],n=new TextEncoder().encode(e);for(;n.length>15e3;){let e=15e3;for(;e>0;){let t=n[e];if(void 0!==t&&(192&t)!=128)break;e--}i.push(n.slice(0,e)),n=n.slice(e)}return n.length>0&&i.push(n),i}(e,0)){yield c.engine.waitForBufferStatusLow(e9.RELIABLE);let e=new e6({destinationIdentities:o,value:{case:"streamChunk",value:new tS({content:t,streamId:n,chunkIndex:ra(l)})}});yield c.engine.sendDataPacket(e,e9.RELIABLE),l+=1}})},close(){return ib(this,void 0,void 0,function*(){let e=new e6({destinationIdentities:o,value:{case:"streamTrailer",value:new tC({streamId:n})}});yield c.engine.sendDataPacket(e,e9.RELIABLE)})},abort(e){console.log("Sink error:",e)}}),u=()=>ib(this,void 0,void 0,function*(){yield h.close()});c.engine.once(oJ.Closing,u);let h=new sC(d,r,()=>this.engine.off(oJ.Closing,u));return h})}sendFile(e,t){return ib(this,void 0,void 0,function*(){let i=crypto.randomUUID();return yield this._sendFile(i,e,t),{id:i}})}_sendFile(e,t,i){return ib(this,void 0,void 0,function*(){var n;let r=yield this.streamBytes({streamId:e,totalSize:t.size,name:t.name,mimeType:null!==(n=null==i?void 0:i.mimeType)&&void 0!==n?n:t.type,topic:null==i?void 0:i.topic,destinationIdentities:null==i?void 0:i.destinationIdentities}),s=t.stream().getReader();for(;;){let{done:e,value:t}=yield s.read();if(e)break;yield r.write(t)}return yield r.close(),r.info})}streamBytes(e){return ib(this,void 0,void 0,function*(){var t,i,n,r,s;let o=null!==(t=null==e?void 0:e.streamId)&&void 0!==t?t:crypto.randomUUID(),a=null==e?void 0:e.destinationIdentities,l={id:o,mimeType:null!==(i=null==e?void 0:e.mimeType)&&void 0!==i?i:"application/octet-stream",topic:null!==(n=null==e?void 0:e.topic)&&void 0!==n?n:"",timestamp:Date.now(),attributes:null==e?void 0:e.attributes,size:null==e?void 0:e.totalSize,name:null!==(r=null==e?void 0:e.name)&&void 0!==r?r:"unknown"},c=new e6({destinationIdentities:a,value:{case:"streamHeader",value:new tT({totalLength:ra(null!==(s=l.size)&&void 0!==s?s:0),mimeType:l.mimeType,streamId:o,topic:l.topic,timestamp:ra(Date.now()),attributes:l.attributes,contentHeader:{case:"byteHeader",value:new tk({name:l.name})}})}});yield this.engine.sendDataPacket(c,e9.RELIABLE);let d=0,u=new y,h=this.engine,p=this.log;return new sw(new WritableStream({write(e){return ib(this,void 0,void 0,function*(){let t=yield u.lock(),i=0;try{for(;i<e.byteLength;){let t=e.slice(i,i+15e3);yield h.waitForBufferStatusLow(e9.RELIABLE);let n=new e6({destinationIdentities:a,value:{case:"streamChunk",value:new tS({content:t,streamId:o,chunkIndex:ra(d)})}});yield h.sendDataPacket(n,e9.RELIABLE),d+=1,i+=t.byteLength}}finally{t()}})},close(){return ib(this,void 0,void 0,function*(){let e=new e6({destinationIdentities:a,value:{case:"streamTrailer",value:new tC({streamId:o})}});yield h.sendDataPacket(e,e9.RELIABLE)})},abort(e){p.error("Sink error:",e)}}),l)})}performRpc(e){return ib(this,arguments,void 0,function(e){var t=this;let{destinationIdentity:i,method:n,payload:r,responseTimeout:s=1e4}=e;return function*(){return new Promise((e,o)=>ib(t,void 0,void 0,function*(){var t,a,l,c;if(rQ(r)>15360){o(rY.builtIn("REQUEST_PAYLOAD_TOO_LARGE"));return}if((null===(a=null===(t=this.engine.latestJoinResponse)||void 0===t?void 0:t.serverInfo)||void 0===a?void 0:a.version)&&0>n3(null===(c=null===(l=this.engine.latestJoinResponse)||void 0===l?void 0:l.serverInfo)||void 0===c?void 0:c.version,"1.8.0")){o(rY.builtIn("UNSUPPORTED_SERVER"));return}let d=crypto.randomUUID();yield this.publishRpcRequest(i,d,n,r,s-2e3);let u=setTimeout(()=>{this.pendingAcks.delete(d),o(rY.builtIn("CONNECTION_TIMEOUT")),this.pendingResponses.delete(d),clearTimeout(h)},2e3);this.pendingAcks.set(d,{resolve:()=>{clearTimeout(u)},participantIdentity:i});let h=setTimeout(()=>{this.pendingResponses.delete(d),o(rY.builtIn("RESPONSE_TIMEOUT"))},s);this.pendingResponses.set(d,{resolve:(t,i)=>{clearTimeout(h),this.pendingAcks.has(d)&&(console.warn("RPC response received before ack",d),this.pendingAcks.delete(d),clearTimeout(u)),i?o(i):e(null!=t?t:"")},participantIdentity:i})}))}()})}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&&void 0!==arguments[1]?arguments[1]:[];this.participantTrackPermissions=t,this.allParticipantsAllowedToSubscribe=e,this.engine.client.isDisconnected||this.updateTrackSubscriptionPermissions()}handleIncomingRpcAck(e){let 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){let n=this.pendingResponses.get(e);n?(n.resolve(t,i),this.pendingResponses.delete(e)):console.error("Response received for unexpected RPC request",e)}publishRpcRequest(e,t,i,n,r){return ib(this,void 0,void 0,function*(){let s=new e6({destinationIdentities:[e],kind:e9.RELIABLE,value:{case:"rpcRequest",value:new ts({id:t,method:i,payload:n,responseTimeoutMs:r,version:1})}});yield this.engine.sendDataPacket(s,e9.RELIABLE)})}handleParticipantDisconnected(e){for(let[t,{participantIdentity:i}]of this.pendingAcks)i===e&&this.pendingAcks.delete(t);for(let[t,{participantIdentity:i,resolve:n}]of this.pendingResponses)i===e&&(n(null,rY.builtIn("RECIPIENT_DISCONNECTED")),this.pendingResponses.delete(t))}setEnabledPublishCodecs(e){this.enabledPublishVideoCodecs=e.filter(e=>"video"===e.mime.split("/")[0].toLowerCase())}updateInfo(e){return!!super.updateInfo(e)&&(e.tracks.forEach(e=>{var t,i;let n=this.trackPublications.get(e.sid);if(n){let r=n.isMuted||null!==(i=null===(t=n.track)||void 0===t?void 0:t.isUpstreamPaused)&&void 0!==i&&i;r!==e.muted&&(this.log.debug("updating server mute state after reconcile",Object.assign(Object.assign(Object.assign({},this.logContext),rT(n)),{mutedOnServer:r})),this.engine.client.sendMuteTrack(e.sid,r))}}),!0)}setActiveAgent(e){var t,i,n,r;this.firstActiveAgent=e,e&&!this.firstActiveAgent&&(this.firstActiveAgent=e),e?null===(i=null===(t=this.activeAgentFuture)||void 0===t?void 0:t.resolve)||void 0===i||i.call(t,e):null===(r=null===(n=this.activeAgentFuture)||void 0===n?void 0:n.reject)||void 0===r||r.call(n,"Agent disconnected"),this.activeAgentFuture=void 0}waitUntilActiveAgentPresent(){return this.firstActiveAgent?Promise.resolve(this.firstActiveAgent):(this.activeAgentFuture||(this.activeAgentFuture=new ri),this.activeAgentFuture.promise)}getPublicationForTrack(e){let t;return this.trackPublications.forEach(i=>{let n=i.track;n&&(e instanceof MediaStreamTrack?(rh(n)||ru(n))&&n.mediaStreamTrack===e&&(t=i):e===n&&(t=i))}),t}waitForPendingPublicationOfSource(e){return ib(this,void 0,void 0,function*(){let t=Date.now();for(;Date.now()<t+1e4;){let t=Array.from(this.pendingPublishPromises.entries()).find(t=>{let[i]=t;return i.source===e});if(t)return t[1];yield nq(20)}})}}class sN extends sI{constructor(e,t,i,n){super(e,t.sid,t.name,n),this.track=void 0,this.allowed=!0,this.requestedDisabled=void 0,this.visible=!0,this.handleEnded=e=>{this.setTrack(void 0),this.emit(oX.Ended,e)},this.handleVisibilityChange=e=>{this.log.debug("adaptivestream video visibility ".concat(this.trackSid,", visible=").concat(e),this.logContext),this.visible=e,this.emitTrackUpdate()},this.handleVideoDimensionsChange=e=>{this.log.debug("adaptivestream video dimensions ".concat(e.width,"x").concat(e.height),this.logContext),this.videoDimensionsAdaptiveStream=e,this.emitTrackUpdate()},this.subscribed=i,this.updateInfo(t)}setSubscribed(e){let t=this.subscriptionStatus,i=this.permissionStatus;this.subscribed=e,e&&(this.allowed=!0);let n=new tF({trackSids:[this.trackSid],subscribe:this.subscribed,participantTracks:[new tc({participantSid:"",trackSids:[this.trackSid]})]});this.emit(oX.UpdateSubscription,n),this.emitSubscriptionUpdateIfChanged(t),this.emitPermissionUpdateIfChanged(i)}get subscriptionStatus(){return!1===this.subscribed?sI.SubscriptionStatus.Unsubscribed:super.isSubscribed?sI.SubscriptionStatus.Subscribed:sI.SubscriptionStatus.Desired}get permissionStatus(){return this.allowed?sI.PermissionStatus.Allowed:sI.PermissionStatus.NotAllowed}get isSubscribed(){return!1!==this.subscribed&&super.isSubscribed}get isDesired(){return!1!==this.subscribed}get isEnabled(){return void 0!==this.requestedDisabled?!this.requestedDisabled:!this.isAdaptiveStream||this.visible}get isLocal(){return!1}setEnabled(e){this.isManualOperationAllowed()&&!e!==this.requestedDisabled&&(this.requestedDisabled=!e,this.emitTrackUpdate())}setVideoQuality(e){this.isManualOperationAllowed()&&this.requestedMaxQuality!==e&&(this.requestedMaxQuality=e,this.requestedVideoDimensions=void 0,this.emitTrackUpdate())}setVideoDimensions(e){var t,i;this.isManualOperationAllowed()&&((null===(t=this.requestedVideoDimensions)||void 0===t?void 0:t.width)!==e.width||(null===(i=this.requestedVideoDimensions)||void 0===i?void 0:i.height)!==e.height)&&(rm(this.track)&&(this.requestedVideoDimensions=e),this.requestedMaxQuality=void 0,this.emitTrackUpdate())}setVideoFPS(e){this.isManualOperationAllowed()&&rm(this.track)&&this.fps!==e&&(this.fps=e,this.emitTrackUpdate())}get videoQuality(){var e;return null!==(e=this.requestedMaxQuality)&&void 0!==e?e:oY.HIGH}setTrack(e){let t=this.subscriptionStatus,i=this.permissionStatus,n=this.track;n!==e&&(n&&(n.off(oX.VideoDimensionsChanged,this.handleVideoDimensionsChange),n.off(oX.VisibilityChanged,this.handleVisibilityChange),n.off(oX.Ended,this.handleEnded),n.detach(),n.stopMonitor(),this.emit(oX.Unsubscribed,n)),super.setTrack(e),e&&(e.sid=this.trackSid,e.on(oX.VideoDimensionsChanged,this.handleVideoDimensionsChange),e.on(oX.VisibilityChanged,this.handleVisibilityChange),e.on(oX.Ended,this.handleEnded),this.emit(oX.Subscribed,e)),this.emitPermissionUpdateIfChanged(i),this.emitSubscriptionUpdateIfChanged(t))}setAllowed(e){let t=this.subscriptionStatus,i=this.permissionStatus;this.allowed=e,this.emitPermissionUpdateIfChanged(i),this.emitSubscriptionUpdateIfChanged(t)}setSubscriptionError(e){this.emit(oX.SubscriptionFailed,e)}updateInfo(e){super.updateInfo(e);let t=this.metadataMuted;this.metadataMuted=e.muted,this.track?this.track.setMuted(e.muted):t!==e.muted&&this.emit(e.muted?oX.Muted:oX.Unmuted)}emitSubscriptionUpdateIfChanged(e){let t=this.subscriptionStatus;e!==t&&this.emit(oX.SubscriptionStatusChanged,t,e)}emitPermissionUpdateIfChanged(e){this.permissionStatus!==e&&this.emit(oX.SubscriptionPermissionChanged,this.permissionStatus,e)}isManualOperationAllowed(){return!!this.isDesired||(this.log.warn("cannot update track settings when not subscribed",this.logContext),!1)}get isAdaptiveStream(){return rm(this.track)&&this.track.isAdaptiveStream}emitTrackUpdate(){let e=new tV({trackSids:[this.trackSid],disabled:!this.isEnabled,fps:this.fps});if(this.kind===nM.Kind.Video){let r=this.requestedVideoDimensions;if(void 0!==this.videoDimensionsAdaptiveStream){if(r)rC(this.videoDimensionsAdaptiveStream,r)&&(this.log.debug("using adaptive stream dimensions instead of requested",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),r=this.videoDimensionsAdaptiveStream);else if(void 0!==this.requestedMaxQuality&&this.trackInfo){var t,i,n;let e=(t=this.trackInfo,i=this.requestedMaxQuality,null===(n=t.layers)||void 0===n?void 0:n.find(e=>e.quality===i));e&&rC(this.videoDimensionsAdaptiveStream,e)&&(this.log.debug("using adaptive stream dimensions instead of max quality layer",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),r=this.videoDimensionsAdaptiveStream)}else this.log.debug("using adaptive stream dimensions",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),r=this.videoDimensionsAdaptiveStream}r?(e.width=Math.ceil(r.width),e.height=Math.ceil(r.height)):void 0!==this.requestedMaxQuality?(this.log.debug("using requested max quality",Object.assign(Object.assign({},this.logContext),{quality:this.requestedMaxQuality})),e.quality=this.requestedMaxQuality):(this.log.debug("using default quality",Object.assign(Object.assign({},this.logContext),{quality:oY.HIGH})),e.quality=oY.HIGH)}this.emit(oX.UpdateSettings,e)}}class sL extends sD{static fromParticipantInfo(e,t,i){return new sL(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,n,r,s,o){let a=arguments.length>7&&void 0!==arguments[7]?arguments[7]:e0.STANDARD;super(t,i||"",n,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(oX.UpdateSettings,t=>{this.log.debug("send update settings",Object.assign(Object.assign(Object.assign({},this.logContext),rT(e)),{settings:t})),this.signalClient.sendUpdateTrackSettings(t)}),e.on(oX.UpdateSubscription,e=>{e.participantTracks.forEach(e=>{e.participantSid=this.sid}),this.signalClient.sendUpdateSubscription(e)}),e.on(oX.SubscriptionPermissionChanged,t=>{this.emit(oK.TrackSubscriptionPermissionChanged,e,t)}),e.on(oX.SubscriptionStatusChanged,t=>{this.emit(oK.TrackSubscriptionStatusChanged,e,t)}),e.on(oX.Subscribed,t=>{this.emit(oK.TrackSubscribed,t,e)}),e.on(oX.Unsubscribed,t=>{this.emit(oK.TrackUnsubscribed,t,e)}),e.on(oX.SubscriptionFailed,t=>{this.emit(oK.TrackSubscriptionFailed,e.trackSid,t)})}getTrackPublication(e){let t=super.getTrackPublication(e);if(t)return t}getTrackPublicationByName(e){let t=super.getTrackPublicationByName(e);if(t)return t}setVolume(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:nM.Source.Microphone;this.volumeMap.set(t,e);let i=this.getTrackPublication(t);i&&i.track&&i.track.setVolume(e)}getVolume(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:nM.Source.Microphone,t=this.getTrackPublication(e);return t&&t.track?t.track.getVolume():this.volumeMap.get(e)}addSubscribedMediaTrack(e,t,i,n,r,s){let o,a=this.getTrackPublicationBySid(t);if(a||t.startsWith("TR")||this.trackPublications.forEach(t=>{a||e.kind!==t.kind.toString()||(a=t)}),!a){if(0===s){this.log.error("could not find published track",Object.assign(Object.assign({},this.logContext),{trackSid:t})),this.emit(oK.TrackSubscriptionFailed,t);return}void 0===s&&(s=20),setTimeout(()=>{this.addSubscribedMediaTrack(e,t,i,n,r,s-1)},150);return}if("ended"===e.readyState){this.log.error("unable to subscribe because MediaStreamTrack is ended. Do not call MediaStreamTrack.stop()",Object.assign(Object.assign({},this.logContext),rT(a))),this.emit(oK.TrackSubscriptionFailed,t);return}return(o="video"===e.kind?new sx(e,t,n,r):new sP(e,t,n,this.audioContext,this.audioOutput)).source=a.source,o.isMuted=a.isMuted,o.setMediaStream(i),o.start(),a.setTrack(o),this.volumeMap.has(a.source)&&rp(o)&&rc(o)&&o.setVolume(this.volumeMap.get(a.source)),a}get hasMetadata(){return!!this.participantInfo}getTrackPublicationBySid(e){return this.trackPublications.get(e)}updateInfo(e){if(!super.updateInfo(e))return!1;let t=new Map,i=new Map;return e.tracks.forEach(e=>{var n,r;let s=this.getTrackPublicationBySid(e.sid);if(s)s.updateInfo(e);else{let t=nM.kindFromProto(e.type);if(!t)return;(s=new sN(t,e,null===(n=this.signalClient.connectOptions)||void 0===n?void 0:n.autoSubscribe,{loggerContextCb:()=>this.logContext,loggerName:null===(r=this.loggerOptions)||void 0===r?void 0:r.loggerName})).updateInfo(e),i.set(e.sid,s);let o=Array.from(this.trackPublications.values()).find(e=>e.source===(null==s?void 0:s.source));o&&s.source!==nM.Source.Unknown&&this.log.debug("received a second track publication for ".concat(this.identity," with the same source: ").concat(s.source),Object.assign(Object.assign({},this.logContext),{oldTrack:rT(o),newTrack:rT(s)})),this.addTrackPublication(s)}t.set(e.sid,s)}),this.trackPublications.forEach(e=>{t.has(e.trackSid)||(this.log.trace("detected removed track on remote participant, unpublishing",Object.assign(Object.assign({},this.logContext),rT(e))),this.unpublishTrack(e.trackSid,!0))}),i.forEach(e=>{this.emit(oK.TrackPublished,e)}),!0}unpublishTrack(e,t){let i=this.trackPublications.get(e);if(!i)return;let{track:n}=i;switch(n&&(n.stop(),i.setTrack(void 0)),this.trackPublications.delete(e),i.kind){case nM.Kind.Audio:this.audioTrackPublications.delete(e);break;case nM.Kind.Video:this.videoTrackPublications.delete(e)}t&&this.emit(oK.TrackUnpublished,i)}setAudioOutput(e){return ib(this,void 0,void 0,function*(){this.audioOutput=e;let t=[];this.audioTrackPublications.forEach(i=>{var n;rc(i.track)&&rp(i.track)&&t.push(i.track.setSinkId(null!==(n=e.deviceId)&&void 0!==n?n:"default"))}),yield Promise.all(t)})}emit(e){for(var t=arguments.length,i=Array(t>1?t-1:0),n=1;n<t;n++)i[n-1]=arguments[n];return this.log.trace("participant event",Object.assign(Object.assign({},this.logContext),{event:e,args:i})),super.emit(e,...i)}}!function(e){e.Disconnected="disconnected",e.Connecting="connecting",e.Connected="connected",e.Reconnecting="reconnecting",e.SignalReconnecting="signalReconnecting"}(ae||(ae={}));class sj extends iS.EventEmitter{constructor(e){var t,i,n,r;if(super(),t=this,this.state=ae.Disconnected,this.activeSpeakers=[],this.isE2EEEnabled=!1,this.audioEnabled=!0,this.isVideoPlaybackBlocked=!1,this.log=ip,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=(e,t,i)=>ib(this,void 0,void 0,function*(){var n;if(!("undefined"!=typeof RTCPeerConnection&&(nz()||nW()))){if(nQ())throw Error("WebRTC isn't detected, have you called registerGlobals?");throw Error("LiveKit doesn't seem to be supported on this browser. Try to update your browser and make sure no browser extensions are disabling webRTC.")}let r=yield this.disconnectLock.lock();if(this.state===ae.Connected)return this.log.info("already connected to room ".concat(this.name),this.logContext),r(),Promise.resolve();if(this.connectFuture)return r(),this.connectFuture.promise;this.setAndEmitConnectionState(ae.Connecting),(null===(n=this.regionUrlProvider)||void 0===n?void 0:n.getServerUrl().toString())!==e&&(this.regionUrl=void 0,this.regionUrlProvider=void 0),nZ(new URL(e))&&(void 0===this.regionUrlProvider?this.regionUrlProvider=new sy(e,t):this.regionUrlProvider.updateToken(t),this.regionUrlProvider.fetchRegionSettings().then(e=>{var t;null===(t=this.regionUrlProvider)||void 0===t||t.setServerReportedRegions(e)}).catch(e=>{this.log.warn("could not fetch region settings",Object.assign(Object.assign({},this.logContext),{error:e}))}));let s=(n,o,a)=>ib(this,void 0,void 0,function*(){var l,c;this.abortController&&this.abortController.abort();let d=new AbortController;this.abortController=d,null==r||r();try{yield this.attemptConnection(null!=a?a:e,t,i,d),this.abortController=void 0,n()}catch(e){if(this.regionUrlProvider&&e instanceof nv&&e.reason!==oW.Cancelled&&e.reason!==oW.NotAllowed){let t=null;try{t=yield this.regionUrlProvider.getNextBestRegionUrl(null===(l=this.abortController)||void 0===l?void 0:l.signal)}catch(e){if(e instanceof nv&&(401===e.status||e.reason===oW.Cancelled)){this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),o(e);return}}!t||(null===(c=this.abortController)||void 0===c?void 0:c.signal.aborted)?(this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,rs(e)),o(e)):(this.log.info("Initial connection failed with ConnectionError: ".concat(e.message,". Retrying with another region: ").concat(t),this.logContext),this.recreateEngine(),yield s(n,o,t))}else{let t=eH.UNKNOWN_REASON;e instanceof nv&&(t=rs(e)),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,t),o(e)}}}),o=this.regionUrl;return this.regionUrl=void 0,this.connectFuture=new ri((e,t)=>{s(e,t,o)},()=>{this.clearConnectionFutures()}),this.connectFuture.promise}),this.connectSignal=(e,t,i,n,r,s)=>ib(this,void 0,void 0,function*(){var o,a,l;let c=yield i.join(e,t,{autoSubscribe:n.autoSubscribe,adaptiveStream:"object"==typeof r.adaptiveStream||r.adaptiveStream,maxRetries:n.maxRetries,e2eeEnabled:!!this.e2eeManager,websocketTimeout:n.websocketTimeout},s.signal),d=c.serverInfo;if(d||(d={version:c.serverVersion,region:c.serverRegion}),this.serverInfo=d,this.log.debug("connected to Livekit Server ".concat(Object.entries(d).map(e=>{let[t,i]=e;return"".concat(t,": ").concat(i)}).join(", ")),{room:null===(o=c.room)||void 0===o?void 0:o.name,roomSid:null===(a=c.room)||void 0===a?void 0:a.sid,identity:null===(l=c.participant)||void 0===l?void 0:l.identity}),!d.version)throw new nk("unknown server version");return"0.15.1"===d.version&&this.options.dynacast&&(this.log.debug("disabling dynacast due to server version",this.logContext),r.dynacast=!1),c}),this.applyJoinResponse=e=>{let t=e.participant;if(this.localParticipant.sid=t.sid,this.localParticipant.identity=t.identity,this.localParticipant.setEnabledPublishCodecs(e.enabledPublishCodecs),this.options.e2ee&&this.e2eeManager)try{this.e2eeManager.setSifTrailer(e.sifTrailer)}catch(e){this.log.error(e instanceof Error?e.message:"Could not set SifTrailer",Object.assign(Object.assign({},this.logContext),{error:e}))}this.handleParticipantUpdates([t,...e.otherParticipants]),e.room&&this.handleRoomUpdate(e.room)},this.attemptConnection=(e,t,i,n)=>ib(this,void 0,void 0,function*(){var r,s;this.state===ae.Reconnecting||this.isResuming||(null===(r=this.engine)||void 0===r?void 0:r.pendingReconnect)?(this.log.info("Reconnection attempt replaced by new connection attempt",this.logContext),this.recreateEngine()):this.maybeCreateEngine(),(null===(s=this.regionUrlProvider)||void 0===s?void 0:s.isCloud())&&this.engine.setRegionUrlProvider(this.regionUrlProvider),this.acquireAudioContext(),this.connOptions=Object.assign(Object.assign({},rJ),i),this.connOptions.rtcConfig&&(this.engine.rtcConfig=this.connOptions.rtcConfig),this.connOptions.peerConnectionTimeout&&(this.engine.peerConnectionTimeout=this.connOptions.peerConnectionTimeout);try{let i=yield this.connectSignal(e,t,this.engine,this.connOptions,this.options,n);this.applyJoinResponse(i),this.setupLocalParticipantEvents(),this.emit(o$.SignalConnected)}catch(t){yield this.engine.close(),this.recreateEngine();let e=new nv("could not establish signal connection",oW.ServerUnreachable);throw t instanceof Error&&(e.message="".concat(e.message,": ").concat(t.message)),t instanceof nv&&(e.reason=t.reason,e.status=t.status),this.log.debug("error trying to establish signal connection",Object.assign(Object.assign({},this.logContext),{error:t})),e}if(n.signal.aborted)throw yield this.engine.close(),this.recreateEngine(),new nv("Connection attempt aborted",oW.Cancelled);try{yield this.engine.waitForPCInitialConnection(this.connOptions.peerConnectionTimeout,n)}catch(e){throw yield this.engine.close(),this.recreateEngine(),e}nY()&&this.options.disconnectOnPageLeave&&(window.addEventListener("pagehide",this.onPageLeave),window.addEventListener("beforeunload",this.onPageLeave)),nY()&&document.addEventListener("freeze",this.onPageLeave),this.setAndEmitConnectionState(ae.Connected),this.emit(o$.Connected),this.registerConnectionReconcile()}),this.disconnect=function(){for(var e=arguments.length,i=Array(e),n=0;n<e;n++)i[n]=arguments[n];return ib(t,[...i],void 0,function(){var e=this;let t=!(arguments.length>0)||void 0===arguments[0]||arguments[0];return function*(){var i,n,r,s;let o=yield e.disconnectLock.lock();try{if(e.state===ae.Disconnected){e.log.debug("already disconnected",e.logContext);return}e.log.info("disconnect from room",Object.assign({},e.logContext)),(e.state===ae.Connecting||e.state===ae.Reconnecting||e.isResuming)&&(e.log.warn("abort connection attempt",e.logContext),null===(i=e.abortController)||void 0===i||i.abort(),null===(r=null===(n=e.connectFuture)||void 0===n?void 0:n.reject)||void 0===r||r.call(n,new nv("Client initiated disconnect",oW.Cancelled)),e.connectFuture=void 0),(null===(s=e.engine)||void 0===s?void 0:s.client.isDisconnected)||(yield e.engine.client.sendLeave()),e.engine&&(yield e.engine.close()),e.handleDisconnect(t,eH.CLIENT_INITIATED),e.engine=void 0}finally{o()}}()})},this.onPageLeave=()=>ib(this,void 0,void 0,function*(){this.log.info("Page leave detected, disconnecting",this.logContext),yield this.disconnect()}),this.startAudio=()=>ib(this,void 0,void 0,function*(){let e=[],t=nP();if(t&&"iOS"===t.os){let t="livekit-dummy-audio-el",i=document.getElementById(t);if(!i){(i=document.createElement("audio")).id=t,i.autoplay=!0,i.hidden=!0;let e=rt();e.enabled=!0;let n=new MediaStream([e]);i.srcObject=n,document.addEventListener("visibilitychange",()=>{i&&(i.srcObject=document.hidden?null:n,document.hidden||(this.log.debug("page visible again, triggering startAudio to resume playback and update playback status",this.logContext),this.startAudio()))}),document.body.append(i),this.once(o$.Disconnected,()=>{null==i||i.remove(),i=null})}e.push(i)}this.remoteParticipants.forEach(t=>{t.audioTrackPublications.forEach(t=>{t.track&&t.track.attachedElements.forEach(t=>{e.push(t)})})});try{yield Promise.all([this.acquireAudioContext(),...e.map(e=>(e.muted=!1,e.play()))]),this.handleAudioPlaybackStarted()}catch(e){throw this.handleAudioPlaybackFailed(e),e}}),this.startVideo=()=>ib(this,void 0,void 0,function*(){let e=[];for(let t of this.remoteParticipants.values())t.videoTrackPublications.forEach(t=>{var i;null===(i=t.track)||void 0===i||i.attachedElements.forEach(t=>{e.includes(t)||e.push(t)})});yield Promise.all(e.map(e=>e.play())).then(()=>{this.handleVideoPlaybackStarted()}).catch(e=>{"NotAllowedError"===e.name?this.handleVideoPlaybackFailed():this.log.warn("Resuming video playback failed, make sure you call `startVideo` directly in a user gesture handler",this.logContext)})}),this.handleRestarting=()=>{for(let e of(this.clearConnectionReconcile(),this.isResuming=!1,this.remoteParticipants.values()))this.handleParticipantDisconnected(e.identity,e);this.setAndEmitConnectionState(ae.Reconnecting)&&this.emit(o$.Reconnecting)},this.handleSignalRestarted=e=>ib(this,void 0,void 0,function*(){this.log.debug("signal reconnected to server, region ".concat(e.serverRegion),Object.assign(Object.assign({},this.logContext),{region:e.serverRegion})),this.bufferedEvents=[],this.applyJoinResponse(e);try{yield this.localParticipant.republishAllTracks(void 0,!0)}catch(e){this.log.error("error trying to re-publish tracks after reconnection",Object.assign(Object.assign({},this.logContext),{error:e}))}try{yield this.engine.waitForRestarted(),this.log.debug("fully reconnected to server",Object.assign(Object.assign({},this.logContext),{region:e.serverRegion}))}catch(e){return}this.setAndEmitConnectionState(ae.Connected),this.emit(o$.Reconnected),this.registerConnectionReconcile(),this.emitBufferedEvents()}),this.handleParticipantUpdates=e=>{e.forEach(e=>{var t;if(e.identity===this.localParticipant.identity){this.localParticipant.updateInfo(e);return}""===e.identity&&(e.identity=null!==(t=this.sidToIdentity.get(e.sid))&&void 0!==t?t:"");let i=this.remoteParticipants.get(e.identity);e.state===eZ.DISCONNECTED?this.handleParticipantDisconnected(e.identity,i):i=this.getOrCreateParticipant(e.identity,e)})},this.handleActiveSpeakersUpdate=e=>{let t=[],i={};e.forEach(e=>{if(i[e.sid]=!0,e.sid===this.localParticipant.sid)this.localParticipant.audioLevel=e.level,this.localParticipant.setIsSpeaking(!0),t.push(this.localParticipant);else{let i=this.getRemoteParticipantBySid(e.sid);i&&(i.audioLevel=e.level,i.setIsSpeaking(!0),t.push(i))}}),i[this.localParticipant.sid]||(this.localParticipant.audioLevel=0,this.localParticipant.setIsSpeaking(!1)),this.remoteParticipants.forEach(e=>{i[e.sid]||(e.audioLevel=0,e.setIsSpeaking(!1))}),this.activeSpeakers=t,this.emitWhenConnected(o$.ActiveSpeakersChanged,t)},this.handleSpeakersChanged=e=>{let t=new Map;this.activeSpeakers.forEach(e=>{let i=this.remoteParticipants.get(e.identity);i&&i.sid!==e.sid||t.set(e.sid,e)}),e.forEach(e=>{let i=this.getRemoteParticipantBySid(e.sid);e.sid===this.localParticipant.sid&&(i=this.localParticipant),i&&(i.audioLevel=e.level,i.setIsSpeaking(e.active),e.active?t.set(e.sid,i):t.delete(e.sid))});let i=Array.from(t.values());i.sort((e,t)=>t.audioLevel-e.audioLevel),this.activeSpeakers=i,this.emitWhenConnected(o$.ActiveSpeakersChanged,i)},this.handleStreamStateUpdate=e=>{e.streamStates.forEach(e=>{let t=this.getRemoteParticipantBySid(e.participantSid);if(!t)return;let i=t.getTrackPublicationBySid(e.trackSid);if(!i||!i.track)return;let n=nM.streamStateFromProto(e.state);n!==i.track.streamState&&(i.track.streamState=n,t.emit(oK.TrackStreamStateChanged,i,i.track.streamState),this.emitWhenConnected(o$.TrackStreamStateChanged,i,i.track.streamState,t))})},this.handleSubscriptionPermissionUpdate=e=>{let t=this.getRemoteParticipantBySid(e.participantSid);if(!t)return;let i=t.getTrackPublicationBySid(e.trackSid);i&&i.setAllowed(e.allowed)},this.handleSubscriptionError=e=>{let t=Array.from(this.remoteParticipants.values()).find(t=>t.trackPublications.has(e.trackSid));if(!t)return;let i=t.getTrackPublicationBySid(e.trackSid);i&&i.setSubscriptionError(e.err)},this.handleDataPacket=e=>{let t=this.remoteParticipants.get(e.participantIdentity);if("user"===e.value.case)this.handleUserPacket(t,e.value.value,e.kind);else if("transcription"===e.value.case)this.handleTranscription(t,e.value.value);else if("sipDtmf"===e.value.case)this.handleSipDtmf(t,e.value.value);else if("chatMessage"===e.value.case)this.handleChatMessage(t,e.value.value);else if("metrics"===e.value.case)this.handleMetrics(e.value.value,t);else if("streamHeader"===e.value.case)this.handleStreamHeader(e.value.value,e.participantIdentity);else if("streamChunk"===e.value.case)this.handleStreamChunk(e.value.value);else if("streamTrailer"===e.value.case)this.handleStreamTrailer(e.value.value);else if("rpcRequest"===e.value.case){let t=e.value.value;this.handleIncomingRpcRequest(e.participantIdentity,t.id,t.method,t.payload,t.responseTimeoutMs,t.version)}},this.handleUserPacket=(e,t,i)=>{this.emit(o$.DataReceived,t.payload,e,i,t.topic),null==e||e.emit(oK.DataReceived,t.payload,i)},this.handleSipDtmf=(e,t)=>{this.emit(o$.SipDTMFReceived,t,e),null==e||e.emit(oK.SipDTMFReceived,t)},this.bufferedSegments=new Map,this.handleTranscription=(e,t)=>{let i=t.transcribedParticipantIdentity===this.localParticipant.identity?this.localParticipant:this.getParticipantByIdentity(t.transcribedParticipantIdentity),n=null==i?void 0:i.trackPublications.get(t.trackId),r=function(e,t){return e.segments.map(e=>{var i;let{id:n,text:r,language:s,startTime:o,endTime:a,final:l}=e,c=null!==(i=t.get(n))&&void 0!==i?i:Date.now(),d=Date.now();return l?t.delete(n):t.set(n,c),{id:n,text:r,startTime:Number.parseInt(o.toString()),endTime:Number.parseInt(a.toString()),final:l,language:s,firstReceivedTime:c,lastReceivedTime:d}})}(t,this.transcriptionReceivedTimes);null==n||n.emit(oX.TranscriptionReceived,r),null==i||i.emit(oK.TranscriptionReceived,r,n),this.emit(o$.TranscriptionReceived,r,i,n)},this.handleChatMessage=(e,t)=>{let i=function(e){let{id:t,timestamp:i,message:n,editTimestamp:r}=e;return{id:t,timestamp:Number.parseInt(i.toString()),editTimestamp:r?Number.parseInt(r.toString()):void 0,message:n}}(t);this.emit(o$.ChatMessage,i,e)},this.handleMetrics=(e,t)=>{this.emit(o$.MetricsReceived,e,t)},this.handleAudioPlaybackStarted=()=>{this.canPlaybackAudio||(this.audioEnabled=!0,this.emit(o$.AudioPlaybackStatusChanged,!0))},this.handleAudioPlaybackFailed=e=>{this.log.warn("could not playback audio",Object.assign(Object.assign({},this.logContext),{error:e})),this.canPlaybackAudio&&(this.audioEnabled=!1,this.emit(o$.AudioPlaybackStatusChanged,!1))},this.handleVideoPlaybackStarted=()=>{this.isVideoPlaybackBlocked&&(this.isVideoPlaybackBlocked=!1,this.emit(o$.VideoPlaybackStatusChanged,!0))},this.handleVideoPlaybackFailed=()=>{this.isVideoPlaybackBlocked||(this.isVideoPlaybackBlocked=!0,this.emit(o$.VideoPlaybackStatusChanged,!1))},this.handleDeviceChange=()=>ib(this,void 0,void 0,function*(){var e;(null===(e=nP())||void 0===e?void 0:e.os)!=="iOS"&&(yield this.selectDefaultDevices()),this.emit(o$.MediaDevicesChanged)}),this.handleRoomUpdate=e=>{let t=this.roomInfo;this.roomInfo=e,t&&t.metadata!==e.metadata&&this.emitWhenConnected(o$.RoomMetadataChanged,e.metadata),(null==t?void 0:t.activeRecording)!==e.activeRecording&&this.emitWhenConnected(o$.RecordingStatusChanged,e.activeRecording)},this.handleConnectionQualityUpdate=e=>{e.updates.forEach(e=>{if(e.participantSid===this.localParticipant.sid){this.localParticipant.setConnectionQuality(e.quality);return}let t=this.getRemoteParticipantBySid(e.participantSid);t&&t.setConnectionQuality(e.quality)})},this.onLocalParticipantMetadataChanged=e=>{this.emit(o$.ParticipantMetadataChanged,e,this.localParticipant)},this.onLocalParticipantNameChanged=e=>{this.emit(o$.ParticipantNameChanged,e,this.localParticipant)},this.onLocalAttributesChanged=e=>{this.emit(o$.ParticipantAttributesChanged,e,this.localParticipant)},this.onLocalTrackMuted=e=>{this.emit(o$.TrackMuted,e,this.localParticipant)},this.onLocalTrackUnmuted=e=>{this.emit(o$.TrackUnmuted,e,this.localParticipant)},this.onTrackProcessorUpdate=e=>{var t;null===(t=null==e?void 0:e.onPublish)||void 0===t||t.call(e,this)},this.onLocalTrackPublished=e=>ib(this,void 0,void 0,function*(){var t,i,n,r,s,o;null===(t=e.track)||void 0===t||t.on(oX.TrackProcessorUpdate,this.onTrackProcessorUpdate),null===(i=e.track)||void 0===i||i.on(oX.Restarted,this.onLocalTrackRestarted),null===(s=null===(r=null===(n=e.track)||void 0===n?void 0:n.getProcessor())||void 0===r?void 0:r.onPublish)||void 0===s||s.call(r,this),this.emit(o$.LocalTrackPublished,e,this.localParticipant),rh(e.track)&&(yield e.track.checkForSilence())&&this.emit(o$.LocalAudioSilenceDetected,e);let a=yield null===(o=e.track)||void 0===o?void 0:o.getDeviceId(!1),l=rb(e.source);l&&a&&a!==this.localParticipant.activeDeviceMap.get(l)&&(this.localParticipant.activeDeviceMap.set(l,a),this.emit(o$.ActiveDeviceChanged,l,a))}),this.onLocalTrackUnpublished=e=>{var t,i;null===(t=e.track)||void 0===t||t.off(oX.TrackProcessorUpdate,this.onTrackProcessorUpdate),null===(i=e.track)||void 0===i||i.off(oX.Restarted,this.onLocalTrackRestarted),this.emit(o$.LocalTrackUnpublished,e,this.localParticipant)},this.onLocalTrackRestarted=e=>ib(this,void 0,void 0,function*(){let t=yield e.getDeviceId(!1),i=rb(e.source);i&&t&&t!==this.localParticipant.activeDeviceMap.get(i)&&(this.log.debug("local track restarted, setting ".concat(i," ").concat(t," active"),this.logContext),this.localParticipant.activeDeviceMap.set(i,t),this.emit(o$.ActiveDeviceChanged,i,t))}),this.onLocalConnectionQualityChanged=e=>{this.emit(o$.ConnectionQualityChanged,e,this.localParticipant)},this.onMediaDevicesError=(e,t)=>{this.emit(o$.MediaDevicesError,e,t)},this.onLocalParticipantPermissionsChanged=e=>{this.emit(o$.ParticipantPermissionsChanged,e,this.localParticipant)},this.onLocalChatMessageSent=e=>{this.emit(o$.ChatMessage,e,this.localParticipant)},this.setMaxListeners(100),this.remoteParticipants=new Map,this.sidToIdentity=new Map,this.options=Object.assign(Object.assign({},rK),e),this.log=im(null!==(i=this.options.loggerName)&&void 0!==i?i:oj.Room),this.transcriptionReceivedTimes=new Map,this.options.audioCaptureDefaults=Object.assign(Object.assign({},rG),null==e?void 0:e.audioCaptureDefaults),this.options.videoCaptureDefaults=Object.assign(Object.assign({},r$),null==e?void 0:e.videoCaptureDefaults),this.options.publishDefaults=Object.assign(Object.assign({},rH),null==e?void 0:e.publishDefaults),this.maybeCreateEngine(),this.disconnectLock=new y,this.localParticipant=new s_("","",this.engine,this.options,this.rpcHandlers),this.options.videoCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("videoinput",rn(this.options.videoCaptureDefaults.deviceId)),this.options.audioCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("audioinput",rn(this.options.audioCaptureDefaults.deviceId)),(null===(n=this.options.audioOutput)||void 0===n?void 0:n.deviceId)&&this.switchActiveDevice("audiooutput",rn(this.options.audioOutput.deviceId)).catch(e=>this.log.warn("Could not set audio output: ".concat(e.message),this.logContext)),this.options.e2ee&&this.setupE2EE(),nY()){let e=new AbortController;null===(r=navigator.mediaDevices)||void 0===r||r.addEventListener("devicechange",this.handleDeviceChange,{signal:e.signal}),sj.cleanupRegistry&&sj.cleanupRegistry.register(this,()=>{e.abort()})}}registerTextStreamHandler(e,t){if(this.textStreamHandlers.has(e))throw 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 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,n,r,s){return ib(this,void 0,void 0,function*(){if(yield this.engine.publishRpcAck(e,t),1!==s){yield this.engine.publishRpcResponse(e,t,null,rY.builtIn("UNSUPPORTED_VERSION"));return}let o=this.rpcHandlers.get(i);if(!o){yield this.engine.publishRpcResponse(e,t,null,rY.builtIn("UNSUPPORTED_METHOD"));return}let a=null,l=null;try{let s=yield o({requestId:t,callerIdentity:e,payload:n,responseTimeout:r});rQ(s)>15360?(a=rY.builtIn("RESPONSE_PAYLOAD_TOO_LARGE"),console.warn("RPC Response payload too large for ".concat(i))):l=s}catch(e){e instanceof rY?a=e:(console.warn("Uncaught error returned by RPC handler for ".concat(i,". Returning APPLICATION_ERROR instead."),e),a=rY.builtIn("APPLICATION_ERROR"))}yield this.engine.publishRpcResponse(e,t,l,a)})}setE2EEEnabled(e){return ib(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 rw(this.options.e2ee),this.e2eeManager.on(oq.ParticipantEncryptionStatusChanged,(e,t)=>{t.isLocal&&(this.isE2EEEnabled=e),this.emit(o$.ParticipantEncryptionStatusChanged,e,t)}),this.e2eeManager.on(oq.EncryptionError,e=>this.emit(o$.EncryptionError,e)),null===(e=this.e2eeManager)||void 0===e||e.setup(this))}get logContext(){var e;return{room:this.name,roomID:null===(e=this.roomInfo)||void 0===e?void 0:e.sid,participant:this.localParticipant.identity,pID:this.localParticipant.sid}}get isRecording(){var e,t;return null!==(t=null===(e=this.roomInfo)||void 0===e?void 0:e.activeRecording)&&void 0!==t&&t}getSid(){return ib(this,void 0,void 0,function*(){return this.state===ae.Disconnected?"":this.roomInfo&&""!==this.roomInfo.sid?this.roomInfo.sid:new Promise((e,t)=>{let i=t=>{""!==t.sid&&(this.engine.off(oJ.RoomUpdate,i),e(t.sid))};this.engine.on(oJ.RoomUpdate,i),this.once(o$.Disconnected,()=>{this.engine.off(oJ.RoomUpdate,i),t("Room disconnected before room server id was available")})})})}get name(){var e,t;return null!==(t=null===(e=this.roomInfo)||void 0===e?void 0:e.name)&&void 0!==t?t:""}get metadata(){var e;return null===(e=this.roomInfo)||void 0===e?void 0:e.metadata}get numParticipants(){var e,t;return null!==(t=null===(e=this.roomInfo)||void 0===e?void 0:e.numParticipants)&&void 0!==t?t:0}get numPublishers(){var e,t;return null!==(t=null===(e=this.roomInfo)||void 0===e?void 0:e.numPublishers)&&void 0!==t?t:0}maybeCreateEngine(){(!this.engine||this.engine.isClosed)&&(this.engine=new sg(this.options),this.engine.on(oJ.ParticipantUpdate,this.handleParticipantUpdates).on(oJ.RoomUpdate,this.handleRoomUpdate).on(oJ.SpeakersChanged,this.handleSpeakersChanged).on(oJ.StreamStateChanged,this.handleStreamStateUpdate).on(oJ.ConnectionQualityUpdate,this.handleConnectionQualityUpdate).on(oJ.SubscriptionError,this.handleSubscriptionError).on(oJ.SubscriptionPermissionUpdate,this.handleSubscriptionPermissionUpdate).on(oJ.MediaTrackAdded,(e,t,i)=>{this.onTrackAdded(e,t,i)}).on(oJ.Disconnected,e=>{this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e)}).on(oJ.ActiveSpeakersUpdate,this.handleActiveSpeakersUpdate).on(oJ.DataPacketReceived,this.handleDataPacket).on(oJ.Resuming,()=>{this.clearConnectionReconcile(),this.isResuming=!0,this.log.info("Resuming signal connection",this.logContext),this.setAndEmitConnectionState(ae.SignalReconnecting)&&this.emit(o$.SignalReconnecting)}).on(oJ.Resumed,()=>{this.registerConnectionReconcile(),this.isResuming=!1,this.log.info("Resumed signal connection",this.logContext),this.updateSubscriptions(),this.emitBufferedEvents(),this.setAndEmitConnectionState(ae.Connected)&&this.emit(o$.Reconnected)}).on(oJ.SignalResumed,()=>{this.bufferedEvents=[],(this.state===ae.Reconnecting||this.isResuming)&&this.sendSyncState()}).on(oJ.Restarting,this.handleRestarting).on(oJ.SignalRestarted,this.handleSignalRestarted).on(oJ.Offline,()=>{this.setAndEmitConnectionState(ae.Reconnecting)&&this.emit(o$.Reconnecting)}).on(oJ.DCBufferStatusChanged,(e,t)=>{this.emit(o$.DCBufferStatusChanged,e,t)}).on(oJ.LocalTrackSubscribed,e=>{let t=this.localParticipant.getTrackPublications().find(t=>{let{trackSid:i}=t;return i===e});if(!t){this.log.warn("could not find local track subscription for subscribed event",this.logContext);return}this.localParticipant.emit(oK.LocalTrackSubscribed,t),this.emitWhenConnected(o$.LocalTrackSubscribed,t,this.localParticipant)}).on(oJ.RoomMoved,e=>{this.log.debug("room moved",e),e.room&&this.handleRoomUpdate(e.room),this.remoteParticipants.forEach((e,t)=>{this.handleParticipantDisconnected(t,e)}),this.emit(o$.Moved,e.room.name),e.participant?this.handleParticipantUpdates([e.participant,...e.otherParticipants]):this.handleParticipantUpdates(e.otherParticipants)}),this.localParticipant&&this.localParticipant.setupEngine(this.engine),this.e2eeManager&&this.e2eeManager.setupEngine(this.engine))}static getLocalDevices(e){let t=!(arguments.length>1)||void 0===arguments[1]||arguments[1];return rP.getInstance().getDevices(e,t)}prepareConnection(e,t){return ib(this,void 0,void 0,function*(){if(this.state===ae.Disconnected){this.log.debug("prepareConnection to ".concat(e),this.logContext);try{if(nZ(new URL(e))&&t){this.regionUrlProvider=new sy(e,t);let i=yield this.regionUrlProvider.getNextBestRegionUrl();i&&this.state===ae.Disconnected&&(this.regionUrl=i,yield fetch(rr(i),{method:"HEAD"}),this.log.debug("prepared connection to ".concat(i),this.logContext))}else yield fetch(rr(e),{method:"HEAD"})}catch(e){this.log.warn("could not prepare connection",Object.assign(Object.assign({},this.logContext),{error:e}))}}})}getParticipantByIdentity(e){return this.localParticipant.identity===e?this.localParticipant:this.remoteParticipants.get(e)}clearConnectionFutures(){this.connectFuture=void 0}simulateScenario(e,t){return ib(this,void 0,void 0,function*(){let i,n=()=>{};switch(e){case"signal-reconnect":yield this.engine.client.handleOnClose("simulate disconnect");break;case"speaker":i=new ie({scenario:{case:"speakerUpdate",value:3}});break;case"node-failure":i=new ie({scenario:{case:"nodeFailure",value:!0}});break;case"server-leave":i=new ie({scenario:{case:"serverLeave",value:!0}});break;case"migration":i=new ie({scenario:{case:"migration",value:!0}});break;case"resume-reconnect":this.engine.failNext(),yield this.engine.client.handleOnClose("simulate resume-disconnect");break;case"disconnect-signal-on-resume":n=()=>ib(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),i=new ie({scenario:{case:"disconnectSignalOnResume",value:!0}});break;case"disconnect-signal-on-resume-no-messages":n=()=>ib(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),i=new ie({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 ie({scenario:{case:"switchCandidateProtocol",value:"force-tls"===e?2:1}}),n=()=>ib(this,void 0,void 0,function*(){let e=this.engine.client.onLeave;e&&e(new tz({reason:eH.CLIENT_INITIATED,action:tW.RECONNECT}))});break;case"subscriber-bandwidth":if(void 0===t||"number"!=typeof t)throw Error("subscriber-bandwidth requires a number as argument");i=new ie({scenario:{case:"subscriberBandwidth",value:ra(t)}});break;case"leave-full-reconnect":i=new ie({scenario:{case:"leaveRequestFullReconnect",value:!0}})}i&&(yield this.engine.client.sendSimulateScenario(i),yield n())})}get canPlaybackAudio(){return this.audioEnabled}get canPlaybackVideo(){return!this.isVideoPlaybackBlocked}getActiveDevice(e){return this.localParticipant.activeDeviceMap.get(e)}switchActiveDevice(e,t){return ib(this,arguments,void 0,function(e,t){var i=this;let n=!(arguments.length>2)||void 0===arguments[2]||arguments[2];return function*(){var r,s,o,a,l,c,d;let u=!0,h=!1,p=n?{exact:t}:t;if("audioinput"===e){h=0===i.localParticipant.audioTrackPublications.size;let t=null!==(r=i.getActiveDevice(e))&&void 0!==r?r:i.options.audioCaptureDefaults.deviceId;i.options.audioCaptureDefaults.deviceId=p;let n=Array.from(i.localParticipant.audioTrackPublications.values()).filter(e=>e.source===nM.Source.Microphone);try{u=(yield Promise.all(n.map(e=>{var t;return null===(t=e.audioTrack)||void 0===t?void 0:t.setDeviceId(p)}))).every(e=>!0===e)}catch(e){throw i.options.audioCaptureDefaults.deviceId=t,e}let s=n.some(e=>{var t,i;return null!==(i=null===(t=e.track)||void 0===t?void 0:t.isMuted)&&void 0!==i&&i});u&&s&&(h=!0)}else if("videoinput"===e){h=0===i.localParticipant.videoTrackPublications.size;let t=null!==(s=i.getActiveDevice(e))&&void 0!==s?s:i.options.videoCaptureDefaults.deviceId;i.options.videoCaptureDefaults.deviceId=p;let n=Array.from(i.localParticipant.videoTrackPublications.values()).filter(e=>e.source===nM.Source.Camera);try{u=(yield Promise.all(n.map(e=>{var t;return null===(t=e.videoTrack)||void 0===t?void 0:t.setDeviceId(p)}))).every(e=>!0===e)}catch(e){throw i.options.videoCaptureDefaults.deviceId=t,e}let r=n.some(e=>{var t,i;return null!==(i=null===(t=e.track)||void 0===t?void 0:t.isMuted)&&void 0!==i&&i});u&&r&&(h=!0)}else if("audiooutput"===e){if(h=!0,!nG()&&!i.options.webAudioMix||i.options.webAudioMix&&i.audioContext&&!("setSinkId"in i.audioContext))throw Error("cannot switch audio output, the current browser does not support it");i.options.webAudioMix&&(t=null!==(o=yield rP.getInstance().normalizeDeviceId("audiooutput",t))&&void 0!==o?o:""),null!==(a=(d=i.options).audioOutput)&&void 0!==a||(d.audioOutput={});let n=null!==(l=i.getActiveDevice(e))&&void 0!==l?l:i.options.audioOutput.deviceId;i.options.audioOutput.deviceId=t;try{i.options.webAudioMix&&(null===(c=i.audioContext)||void 0===c||c.setSinkId(t)),yield Promise.all(Array.from(i.remoteParticipants.values()).map(e=>e.setAudioOutput({deviceId:t})))}catch(e){throw i.options.audioOutput.deviceId=n,e}}return h&&(i.localParticipant.activeDeviceMap.set(e,t),i.emit(o$.ActiveDeviceChanged,e,t)),u}()})}setupLocalParticipantEvents(){this.localParticipant.on(oK.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).on(oK.ParticipantNameChanged,this.onLocalParticipantNameChanged).on(oK.AttributesChanged,this.onLocalAttributesChanged).on(oK.TrackMuted,this.onLocalTrackMuted).on(oK.TrackUnmuted,this.onLocalTrackUnmuted).on(oK.LocalTrackPublished,this.onLocalTrackPublished).on(oK.LocalTrackUnpublished,this.onLocalTrackUnpublished).on(oK.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).on(oK.MediaDevicesError,this.onMediaDevicesError).on(oK.AudioStreamAcquired,this.startAudio).on(oK.ChatMessage,this.onLocalChatMessageSent).on(oK.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged)}recreateEngine(){var e;null===(e=this.engine)||void 0===e||e.close(),this.engine=void 0,this.isResuming=!1,this.remoteParticipants.clear(),this.sidToIdentity.clear(),this.bufferedEvents=[],this.maybeCreateEngine()}onTrackAdded(e,t,i){let n;if(this.state===ae.Connecting||this.state===ae.Reconnecting){let n=()=>{this.onTrackAdded(e,t,i),r()},r=()=>{this.off(o$.Reconnected,n),this.off(o$.Connected,n),this.off(o$.Disconnected,r)};this.once(o$.Reconnected,n),this.once(o$.Connected,n),this.once(o$.Disconnected,r);return}if(this.state===ae.Disconnected){this.log.warn("skipping incoming track after Room disconnected",this.logContext);return}if("ended"===e.readyState){this.log.info("skipping incoming track as it already ended",this.logContext);return}let r=function(e){let t=e.split("|");return t.length>1?[t[0],e.substr(t[0].length+1)]:[e,""]}(t.id),s=r[0],o=r[1],a=e.id;if(o&&o.startsWith("TR")&&(a=o),s===this.localParticipant.sid){this.log.warn("tried to create RemoteParticipant for local participant",this.logContext);return}let l=Array.from(this.remoteParticipants.values()).find(e=>e.sid===s);if(!l){this.log.error("Tried to add a track for a participant, that's not present. Sid: ".concat(s),this.logContext);return}this.options.adaptiveStream&&(n="object"==typeof this.options.adaptiveStream?this.options.adaptiveStream:{}),l.addSubscribedMediaTrack(e,a,t,i,n)}handleDisconnect(){var e;let t=!(arguments.length>0)||void 0===arguments[0]||arguments[0],i=arguments.length>1?arguments[1]:void 0;if(this.clearConnectionReconcile(),this.isResuming=!1,this.bufferedEvents=[],this.transcriptionReceivedTimes.clear(),this.state!==ae.Disconnected){this.regionUrl=void 0;try{this.remoteParticipants.forEach(e=>{e.trackPublications.forEach(t=>{e.unpublishTrack(t.trackSid)})}),this.localParticipant.trackPublications.forEach(e=>{var i,n,r;e.track&&this.localParticipant.unpublishTrack(e.track,t),t?(null===(i=e.track)||void 0===i||i.detach(),null===(n=e.track)||void 0===n||n.stop()):null===(r=e.track)||void 0===r||r.stopMonitor()}),this.localParticipant.off(oK.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).off(oK.ParticipantNameChanged,this.onLocalParticipantNameChanged).off(oK.AttributesChanged,this.onLocalAttributesChanged).off(oK.TrackMuted,this.onLocalTrackMuted).off(oK.TrackUnmuted,this.onLocalTrackUnmuted).off(oK.LocalTrackPublished,this.onLocalTrackPublished).off(oK.LocalTrackUnpublished,this.onLocalTrackUnpublished).off(oK.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).off(oK.MediaDevicesError,this.onMediaDevicesError).off(oK.AudioStreamAcquired,this.startAudio).off(oK.ChatMessage,this.onLocalChatMessageSent).off(oK.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&&"boolean"==typeof this.options.webAudioMix&&(this.audioContext.close(),this.audioContext=void 0),nY()&&(window.removeEventListener("beforeunload",this.onPageLeave),window.removeEventListener("pagehide",this.onPageLeave),window.removeEventListener("freeze",this.onPageLeave),null===(e=navigator.mediaDevices)||void 0===e||e.removeEventListener("devicechange",this.handleDeviceChange))}finally{this.setAndEmitConnectionState(ae.Disconnected),this.emit(o$.Disconnected,i)}}}handleParticipantDisconnected(e,t){var i;this.remoteParticipants.delete(e),t&&(t.trackPublications.forEach(e=>{t.unpublishTrack(e.trackSid,!0)}),this.emit(o$.ParticipantDisconnected,t),t.setDisconnected(),null===(i=this.localParticipant)||void 0===i||i.handleParticipantDisconnected(t.identity))}handleStreamHeader(e,t){return ib(this,void 0,void 0,function*(){var i;if("byteHeader"===e.contentHeader.case){let n;let r=this.byteStreamHandlers.get(e.topic);if(!r){this.log.debug("ignoring incoming byte stream due to no handler for topic",e.topic);return}let s={id:e.streamId,name:null!==(i=e.contentHeader.value.name)&&void 0!==i?i:"unknown",mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:ro(e.timestamp),attributes:e.attributes},o=new ReadableStream({start:t=>{n=t,this.byteStreamControllers.set(e.streamId,{info:s,controller:n,startTime:Date.now()})}});r(new sk(s,o,ro(e.totalLength)),{identity:t})}else if("textHeader"===e.contentHeader.case){let i;let n=this.textStreamHandlers.get(e.topic);if(!n){this.log.debug("ignoring incoming text stream due to no handler for topic",e.topic);return}let r={id:e.streamId,mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:Number(e.timestamp),attributes:e.attributes},s=new ReadableStream({start:t=>{i=t,this.textStreamControllers.set(e.streamId,{info:r,controller:i,startTime:Date.now()})}});n(new sT(r,s,ro(e.totalLength)),{identity:t})}})}handleStreamChunk(e){let t=this.byteStreamControllers.get(e.streamId);t&&e.content.length>0&&t.controller.enqueue(e);let i=this.textStreamControllers.get(e.streamId);i&&e.content.length>0&&i.controller.enqueue(e)}handleStreamTrailer(e){let 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));let 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))}selectDefaultDevices(){return ib(this,void 0,void 0,function*(){var e,t,i;let n=rP.getInstance().previousDevices,r=yield rP.getInstance().getDevices(void 0,!1),s=nP();if((null==s?void 0:s.name)==="Chrome"&&"iOS"!==s.os)for(let e of r){let t=n.find(t=>t.deviceId===e.deviceId);t&&""!==t.label&&t.kind===e.kind&&t.label!==e.label&&"default"===this.getActiveDevice(e.kind)&&this.emit(o$.ActiveDeviceChanged,e.kind,e.deviceId)}for(let s of["audiooutput","audioinput","videoinput"]){let o="audioinput"===s?nM.Source.Microphone:"videoinput"===s?nM.Source.Camera:nM.Source.Unknown,a=this.localParticipant.getTrackPublication(o);if(a&&(null===(e=a.track)||void 0===e?void 0:e.isUserProvided))continue;let l=r.filter(e=>e.kind===s),c=this.getActiveDevice(s);if(c===(null===(t=n.filter(e=>e.kind===s)[0])||void 0===t?void 0:t.deviceId)&&l.length>0&&(null===(i=l[0])||void 0===i?void 0:i.deviceId)!==c){yield this.switchActiveDevice(s,l[0].deviceId);continue}("audioinput"!==s||nJ())&&"videoinput"!==s&&(!(l.length>0)||l.find(e=>e.deviceId===this.getActiveDevice(s))||"audiooutput"===s&&nJ()||(yield this.switchActiveDevice(s,l[0].deviceId)))}})}acquireAudioContext(){return ib(this,void 0,void 0,function*(){var e,t;if("boolean"!=typeof this.options.webAudioMix&&this.options.webAudioMix.audioContext?this.audioContext=this.options.webAudioMix.audioContext:this.audioContext&&"closed"!==this.audioContext.state||(this.audioContext=null!==(e=ry())&&void 0!==e?e:void 0),this.options.webAudioMix&&this.remoteParticipants.forEach(e=>e.setAudioContext(this.audioContext)),this.localParticipant.setAudioContext(this.audioContext),this.audioContext&&"suspended"===this.audioContext.state)try{yield Promise.race([this.audioContext.resume(),nq(200)])}catch(e){this.log.warn("Could not resume audio context",Object.assign(Object.assign({},this.logContext),{error:e}))}let i=(null===(t=this.audioContext)||void 0===t?void 0:t.state)==="running";i!==this.canPlaybackAudio&&(this.audioEnabled=i,this.emit(o$.AudioPlaybackStatusChanged,i))})}createParticipant(e,t){var i;let n;return n=t?sL.fromParticipantInfo(this.engine.client,t,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}):new sL(this.engine.client,"",e,void 0,void 0,void 0,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}),this.options.webAudioMix&&n.setAudioContext(this.audioContext),(null===(i=this.options.audioOutput)||void 0===i?void 0:i.deviceId)&&n.setAudioOutput(this.options.audioOutput).catch(e=>this.log.warn("Could not set audio output: ".concat(e.message),this.logContext)),n}getOrCreateParticipant(e,t){if(this.remoteParticipants.has(e)){let i=this.remoteParticipants.get(e);return t&&i.updateInfo(t)&&this.sidToIdentity.set(t.sid,t.identity),i}let i=this.createParticipant(e,t);return this.remoteParticipants.set(e,i),this.sidToIdentity.set(t.sid,t.identity),this.emitWhenConnected(o$.ParticipantConnected,i),i.on(oK.TrackPublished,e=>{this.emitWhenConnected(o$.TrackPublished,e,i)}).on(oK.TrackSubscribed,(e,t)=>{e.kind===nM.Kind.Audio?(e.on(oX.AudioPlaybackStarted,this.handleAudioPlaybackStarted),e.on(oX.AudioPlaybackFailed,this.handleAudioPlaybackFailed)):e.kind===nM.Kind.Video&&(e.on(oX.VideoPlaybackFailed,this.handleVideoPlaybackFailed),e.on(oX.VideoPlaybackStarted,this.handleVideoPlaybackStarted)),this.emit(o$.TrackSubscribed,e,t,i)}).on(oK.TrackUnpublished,e=>{this.emit(o$.TrackUnpublished,e,i)}).on(oK.TrackUnsubscribed,(e,t)=>{this.emit(o$.TrackUnsubscribed,e,t,i)}).on(oK.TrackMuted,e=>{this.emitWhenConnected(o$.TrackMuted,e,i)}).on(oK.TrackUnmuted,e=>{this.emitWhenConnected(o$.TrackUnmuted,e,i)}).on(oK.ParticipantMetadataChanged,e=>{this.emitWhenConnected(o$.ParticipantMetadataChanged,e,i)}).on(oK.ParticipantNameChanged,e=>{this.emitWhenConnected(o$.ParticipantNameChanged,e,i)}).on(oK.AttributesChanged,e=>{this.emitWhenConnected(o$.ParticipantAttributesChanged,e,i)}).on(oK.ConnectionQualityChanged,e=>{this.emitWhenConnected(o$.ConnectionQualityChanged,e,i)}).on(oK.ParticipantPermissionsChanged,e=>{this.emitWhenConnected(o$.ParticipantPermissionsChanged,e,i)}).on(oK.TrackSubscriptionStatusChanged,(e,t)=>{this.emitWhenConnected(o$.TrackSubscriptionStatusChanged,e,t,i)}).on(oK.TrackSubscriptionFailed,(e,t)=>{this.emit(o$.TrackSubscriptionFailed,e,i,t)}).on(oK.TrackSubscriptionPermissionChanged,(e,t)=>{this.emitWhenConnected(o$.TrackSubscriptionPermissionChanged,e,t,i)}).on(oK.Active,()=>{this.emitWhenConnected(o$.ParticipantActive,i),i.kind===e0.AGENT&&this.localParticipant.setActiveAgent(i)}),t&&i.updateInfo(t),i}sendSyncState(){let e=Array.from(this.remoteParticipants.values()).reduce((e,t)=>(e.push(...t.getTrackPublications()),e),[]),t=this.localParticipant.getTrackPublications();this.engine.sendSyncState(e,t)}updateSubscriptions(){for(let t of this.remoteParticipants.values())for(let i of t.videoTrackPublications.values()){var e;i.isSubscribed&&(e=i)&&!e.isLocal&&i.emitTrackUpdate()}}getRemoteParticipantBySid(e){let t=this.sidToIdentity.get(e);if(t)return this.remoteParticipants.get(t)}registerConnectionReconcile(){this.clearConnectionReconcile();let e=0;this.connectionReconcileInterval=nA.setInterval(()=>{this.engine&&!this.engine.isClosed&&this.engine.verifyTransport()?e=0:(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,eH.STATE_MISMATCH)))},4e3)}clearConnectionReconcile(){this.connectionReconcileInterval&&nA.clearInterval(this.connectionReconcileInterval)}setAndEmitConnectionState(e){return e!==this.state&&(this.state=e,this.emit(o$.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=Array(t>1?t-1:0),n=1;n<t;n++)i[n-1]=arguments[n];if(this.state===ae.Reconnecting||this.isResuming||!this.engine||this.engine.pendingReconnect)this.bufferedEvents.push([e,i]);else if(this.state===ae.Connected)return this.emit(e,...i);return!1}simulateParticipants(e){return ib(this,void 0,void 0,function*(){var t,i;let n=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 eJ({sid:"RM_SIMULATED",name:"simulated-room",emptyTimeout:0,maxParticipants:0,creationTime:j.parse(new Date().getTime()),metadata:"",numParticipants:1,numPublishers:1,turnPassword:"",enabledCodecs:[],activeRecording:!1}),this.localParticipant.updateInfo(new eQ({identity:"simulated-local",name:"local-name"})),this.setupLocalParticipantEvents(),this.emit(o$.SignalConnected),this.emit(o$.Connected),this.setAndEmitConnectionState(ae.Connected),n.video){let e=new sM(nM.Kind.Video,new e5({source:eB.CAMERA,sid:Math.floor(1e4*Math.random()).toString(),type:eV.AUDIO,name:"video-dummy"}),new sc(n.useRealTracks?(yield window.navigator.mediaDevices.getUserMedia({video:!0})).getVideoTracks()[0]:re(160*(null!==(t=r.aspectRatios[0])&&void 0!==t?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(e),this.localParticipant.emit(oK.LocalTrackPublished,e)}if(n.audio){let e=new sM(nM.Kind.Audio,new e5({source:eB.MICROPHONE,sid:Math.floor(1e4*Math.random()).toString(),type:eV.AUDIO}),new r6(n.useRealTracks?(yield navigator.mediaDevices.getUserMedia({audio:!0})).getAudioTracks()[0]:rt(),void 0,!1,this.audioContext,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(e),this.localParticipant.emit(oK.LocalTrackPublished,e)}for(let e=0;e<r.count-1;e+=1){let t=new eQ({sid:Math.floor(1e4*Math.random()).toString(),identity:"simulated-".concat(e),state:eZ.ACTIVE,tracks:[],joinedAt:j.parse(Date.now())}),n=this.getOrCreateParticipant(t.identity,t);if(r.video){let s=re(160*(null!==(i=r.aspectRatios[e%r.aspectRatios.length])&&void 0!==i?i:1),160,!1,!0),o=new e5({source:eB.CAMERA,sid:Math.floor(1e4*Math.random()).toString(),type:eV.AUDIO});n.addSubscribedMediaTrack(s,o.sid,new MediaStream([s]),new RTCRtpReceiver),t.tracks=[...t.tracks,o]}if(r.audio){let e=rt(),i=new e5({source:eB.MICROPHONE,sid:Math.floor(1e4*Math.random()).toString(),type:eV.AUDIO});n.addSubscribedMediaTrack(e,i.sid,new MediaStream([e]),new RTCRtpReceiver),t.tracks=[...t.tracks,i]}n.updateInfo(t)}})}emit(e){for(var t=arguments.length,i=Array(t>1?t-1:0),n=1;n<t;n++)i[n-1]=arguments[n];if(e!==o$.ActiveSpeakersChanged&&e!==o$.TranscriptionReceived){let t=(function e(t){return t.map(t=>t?Array.isArray(t)?e(t):"object"==typeof t?"logContext"in t?t.logContext:void 0:t:void 0)})(i).filter(e=>void 0!==e);this.log.debug("room event ".concat(e),Object.assign(Object.assign({},this.logContext),{event:e,args:t}))}return super.emit(e,...i)}}sj.cleanupRegistry="undefined"!=typeof FinalizationRegistry&&new FinalizationRegistry(e=>{e()}),!function(e){e[e.IDLE=0]="IDLE",e[e.RUNNING=1]="RUNNING",e[e.SKIPPED=2]="SKIPPED",e[e.SUCCESS=3]="SUCCESS",e[e.FAILED=4]="FAILED"}(at||(at={}));let sU=Math.min,sF=Math.max,sV=Math.round,sB=Math.floor,sq=e=>({x:e,y:e}),sz={left:"right",right:"left",bottom:"top",top:"bottom"},sW={start:"end",end:"start"};function sH(e,t){return"function"==typeof e?e(t):e}function sG(e){return e.split("-")[0]}function s$(e){return e.split("-")[1]}function sK(e){return"x"===e?"y":"x"}function sJ(e){return"y"===e?"height":"width"}function sX(e){return["top","bottom"].includes(sG(e))?"y":"x"}function sY(e){return e.replace(/start|end/g,e=>sW[e])}function sQ(e){return e.replace(/left|right|bottom|top/g,e=>sz[e])}function sZ(e){let{x:t,y:i,width:n,height:r}=e;return{width:n,height:r,top:i,left:t,right:t+n,bottom:i+r,x:t,y:i}}function s0(e,t,i){let n,{reference:r,floating:s}=e,o=sX(t),a=sK(sX(t)),l=sJ(a),c=sG(t),d="y"===o,u=r.x+r.width/2-s.width/2,h=r.y+r.height/2-s.height/2,p=r[l]/2-s[l]/2;switch(c){case"top":n={x:u,y:r.y-s.height};break;case"bottom":n={x:u,y:r.y+r.height};break;case"right":n={x:r.x+r.width,y:h};break;case"left":n={x:r.x-s.width,y:h};break;default:n={x:r.x,y:r.y}}switch(s$(t)){case"start":n[a]-=p*(i&&d?-1:1);break;case"end":n[a]+=p*(i&&d?-1:1)}return n}let s1=async(e,t,i)=>{let{placement:n="bottom",strategy:r="absolute",middleware:s=[],platform:o}=i,a=s.filter(Boolean),l=await (null==o.isRTL?void 0:o.isRTL(t)),c=await o.getElementRects({reference:e,floating:t,strategy:r}),{x:d,y:u}=s0(c,n,l),h=n,p={},m=0;for(let i=0;i<a.length;i++){let{name:s,fn:f}=a[i],{x:g,y:v,data:y,reset:b}=await f({x:d,y:u,initialPlacement:n,placement:h,strategy:r,middlewareData:p,rects:c,platform:o,elements:{reference:e,floating:t}});d=g??d,u=v??u,p={...p,[s]:{...p[s],...y}},b&&m<=50&&(m++,"object"==typeof b&&(b.placement&&(h=b.placement),b.rects&&(c=!0===b.rects?await o.getElementRects({reference:e,floating:t,strategy:r}):b.rects),{x:d,y:u}=s0(c,h,l)),i=-1)}return{x:d,y:u,placement:h,strategy:r,middlewareData:p}};async function s2(e,t){var i;void 0===t&&(t={});let{x:n,y:r,platform:s,rects:o,elements:a,strategy:l}=e,{boundary:c="clippingAncestors",rootBoundary:d="viewport",elementContext:u="floating",altBoundary:h=!1,padding:p=0}=sH(t,e),m="number"!=typeof p?{top:0,right:0,bottom:0,left:0,...p}:{top:p,right:p,bottom:p,left:p},f=a[h?"floating"===u?"reference":"floating":u],g=sZ(await s.getClippingRect({element:null==(i=await (null==s.isElement?void 0:s.isElement(f)))||i?f:f.contextElement||await (null==s.getDocumentElement?void 0:s.getDocumentElement(a.floating)),boundary:c,rootBoundary:d,strategy:l})),v="floating"===u?{x:n,y:r,width:o.floating.width,height:o.floating.height}:o.reference,y=await (null==s.getOffsetParent?void 0:s.getOffsetParent(a.floating)),b=await (null==s.isElement?void 0:s.isElement(y))&&await (null==s.getScale?void 0:s.getScale(y))||{x:1,y:1},k=sZ(s.convertOffsetParentRelativeRectToViewportRelativeRect?await s.convertOffsetParentRelativeRectToViewportRelativeRect({elements:a,rect:v,offsetParent:y,strategy:l}):v);return{top:(g.top-k.top+m.top)/b.y,bottom:(k.bottom-g.bottom+m.bottom)/b.y,left:(g.left-k.left+m.left)/b.x,right:(k.right-g.right+m.right)/b.x}}async function s3(e,t){let{placement:i,platform:n,elements:r}=e,s=await (null==n.isRTL?void 0:n.isRTL(r.floating)),o=sG(i),a=s$(i),l="y"===sX(i),c=["left","top"].includes(o)?-1:1,d=s&&l?-1:1,u=sH(t,e),{mainAxis:h,crossAxis:p,alignmentAxis:m}="number"==typeof u?{mainAxis:u,crossAxis:0,alignmentAxis:null}:{mainAxis:u.mainAxis||0,crossAxis:u.crossAxis||0,alignmentAxis:u.alignmentAxis};return a&&"number"==typeof m&&(p="end"===a?-1*m:m),l?{x:p*d,y:h*c}:{x:h*c,y:p*d}}function s5(){return"u">typeof window}function s4(e){return s8(e)?(e.nodeName||"").toLowerCase():"#document"}function s6(e){var t;return(null==e||null==(t=e.ownerDocument)?void 0:t.defaultView)||window}function s9(e){var t;return null==(t=(s8(e)?e.ownerDocument:e.document)||window.document)?void 0:t.documentElement}function s8(e){return!!s5()&&(e instanceof Node||e instanceof s6(e).Node)}function s7(e){return!!s5()&&(e instanceof Element||e instanceof s6(e).Element)}function oe(e){return!!s5()&&(e instanceof HTMLElement||e instanceof s6(e).HTMLElement)}function ot(e){return!(!s5()||typeof ShadowRoot>"u")&&(e instanceof ShadowRoot||e instanceof s6(e).ShadowRoot)}function oi(e){let{overflow:t,overflowX:i,overflowY:n,display:r}=oa(e);return/auto|scroll|overlay|hidden|clip/.test(t+n+i)&&!["inline","contents"].includes(r)}function on(e){return[":popover-open",":modal"].some(t=>{try{return e.matches(t)}catch{return!1}})}function or(e){let t=os(),i=s7(e)?oa(e):e;return["transform","translate","scale","rotate","perspective"].some(e=>!!i[e]&&"none"!==i[e])||!!i.containerType&&"normal"!==i.containerType||!t&&!!i.backdropFilter&&"none"!==i.backdropFilter||!t&&!!i.filter&&"none"!==i.filter||["transform","translate","scale","rotate","perspective","filter"].some(e=>(i.willChange||"").includes(e))||["paint","layout","strict","content"].some(e=>(i.contain||"").includes(e))}function os(){return!(typeof CSS>"u")&&!!CSS.supports&&CSS.supports("-webkit-backdrop-filter","none")}function oo(e){return["html","body","#document"].includes(s4(e))}function oa(e){return s6(e).getComputedStyle(e)}function ol(e){return s7(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function oc(e){if("html"===s4(e))return e;let t=e.assignedSlot||e.parentNode||ot(e)&&e.host||s9(e);return ot(t)?t.host:t}function od(e,t,i){var n;void 0===t&&(t=[]),void 0===i&&(i=!0);let r=function e(t){let i=oc(t);return oo(i)?t.ownerDocument?t.ownerDocument.body:t.body:oe(i)&&oi(i)?i:e(i)}(e),s=r===(null==(n=e.ownerDocument)?void 0:n.body),o=s6(r);if(s){let e=ou(o);return t.concat(o,o.visualViewport||[],oi(r)?r:[],e&&i?od(e):[])}return t.concat(r,od(r,[],i))}function ou(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}function oh(e){let t=oa(e),i=parseFloat(t.width)||0,n=parseFloat(t.height)||0,r=oe(e),s=r?e.offsetWidth:i,o=r?e.offsetHeight:n,a=sV(i)!==s||sV(n)!==o;return a&&(i=s,n=o),{width:i,height:n,$:a}}function op(e){return s7(e)?e:e.contextElement}function om(e){let t=op(e);if(!oe(t))return sq(1);let i=t.getBoundingClientRect(),{width:n,height:r,$:s}=oh(t),o=(s?sV(i.width):i.width)/n,a=(s?sV(i.height):i.height)/r;return o&&Number.isFinite(o)||(o=1),a&&Number.isFinite(a)||(a=1),{x:o,y:a}}let of=sq(0);function og(e){let t=s6(e);return os()&&t.visualViewport?{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}:of}function ov(e,t,i,n){var r;void 0===t&&(t=!1),void 0===i&&(i=!1);let s=e.getBoundingClientRect(),o=op(e),a=sq(1);t&&(n?s7(n)&&(a=om(n)):a=om(e));let l=(void 0===(r=i)&&(r=!1),n&&(!r||n===s6(o))&&r)?og(o):sq(0),c=(s.left+l.x)/a.x,d=(s.top+l.y)/a.y,u=s.width/a.x,h=s.height/a.y;if(o){let e=s6(o),t=n&&s7(n)?s6(n):n,i=e,r=ou(i);for(;r&&n&&t!==i;){let e=om(r),t=r.getBoundingClientRect(),n=oa(r),s=t.left+(r.clientLeft+parseFloat(n.paddingLeft))*e.x,o=t.top+(r.clientTop+parseFloat(n.paddingTop))*e.y;c*=e.x,d*=e.y,u*=e.x,h*=e.y,c+=s,d+=o,r=ou(i=s6(r))}}return sZ({width:u,height:h,x:c,y:d})}function oy(e,t){let i=ol(e).scrollLeft;return t?t.left+i:ov(s9(e)).left+i}function ob(e,t,i){void 0===i&&(i=!1);let n=e.getBoundingClientRect();return{x:n.left+t.scrollLeft-(i?0:oy(e,n)),y:n.top+t.scrollTop}}function ok(e,t,i){let n;if("viewport"===t)n=function(e,t){let i=s6(e),n=s9(e),r=i.visualViewport,s=n.clientWidth,o=n.clientHeight,a=0,l=0;if(r){s=r.width,o=r.height;let e=os();(!e||e&&"fixed"===t)&&(a=r.offsetLeft,l=r.offsetTop)}return{width:s,height:o,x:a,y:l}}(e,i);else if("document"===t)n=function(e){let t=s9(e),i=ol(e),n=e.ownerDocument.body,r=sF(t.scrollWidth,t.clientWidth,n.scrollWidth,n.clientWidth),s=sF(t.scrollHeight,t.clientHeight,n.scrollHeight,n.clientHeight),o=-i.scrollLeft+oy(e),a=-i.scrollTop;return"rtl"===oa(n).direction&&(o+=sF(t.clientWidth,n.clientWidth)-r),{width:r,height:s,x:o,y:a}}(s9(e));else if(s7(t))n=function(e,t){let i=ov(e,!0,"fixed"===t),n=i.top+e.clientTop,r=i.left+e.clientLeft,s=oe(e)?om(e):sq(1),o=e.clientWidth*s.x;return{width:o,height:e.clientHeight*s.y,x:r*s.x,y:n*s.y}}(t,i);else{let i=og(e);n={x:t.x-i.x,y:t.y-i.y,width:t.width,height:t.height}}return sZ(n)}function oT(e){return"static"===oa(e).position}function oS(e,t){if(!oe(e)||"fixed"===oa(e).position)return null;if(t)return t(e);let i=e.offsetParent;return s9(e)===i&&(i=i.ownerDocument.body),i}function oC(e,t){let i=s6(e);if(on(e))return i;if(!oe(e)){let t=oc(e);for(;t&&!oo(t);){if(s7(t)&&!oT(t))return t;t=oc(t)}return i}let n=oS(e,t);for(;n&&["table","td","th"].includes(s4(n))&&oT(n);)n=oS(n,t);return n&&oo(n)&&oT(n)&&!or(n)?i:n||function(e){let t=oc(e);for(;oe(t)&&!oo(t);){if(or(t))return t;if(on(t))break;t=oc(t)}return null}(e)||i}let ow=async function(e){let t=this.getOffsetParent||oC,i=this.getDimensions,n=await i(e.floating);return{reference:function(e,t,i){let n=oe(t),r=s9(t),s="fixed"===i,o=ov(e,!0,s,t),a={scrollLeft:0,scrollTop:0},l=sq(0);if(n||!n&&!s){if(("body"!==s4(t)||oi(r))&&(a=ol(t)),n){let e=ov(t,!0,s,t);l.x=e.x+t.clientLeft,l.y=e.y+t.clientTop}else r&&(l.x=oy(r))}let c=!r||n||s?sq(0):ob(r,a);return{x:o.left+a.scrollLeft-l.x-c.x,y:o.top+a.scrollTop-l.y-c.y,width:o.width,height:o.height}}(e.reference,await t(e.floating),e.strategy),floating:{x:0,y:0,width:n.width,height:n.height}}},oE={convertOffsetParentRelativeRectToViewportRelativeRect:function(e){let{elements:t,rect:i,offsetParent:n,strategy:r}=e,s="fixed"===r,o=s9(n),a=!!t&&on(t.floating);if(n===o||a&&s)return i;let l={scrollLeft:0,scrollTop:0},c=sq(1),d=sq(0),u=oe(n);if((u||!u&&!s)&&(("body"!==s4(n)||oi(o))&&(l=ol(n)),oe(n))){let e=ov(n);c=om(n),d.x=e.x+n.clientLeft,d.y=e.y+n.clientTop}let h=!o||u||s?sq(0):ob(o,l,!0);return{width:i.width*c.x,height:i.height*c.y,x:i.x*c.x-l.scrollLeft*c.x+d.x+h.x,y:i.y*c.y-l.scrollTop*c.y+d.y+h.y}},getDocumentElement:s9,getClippingRect:function(e){let{element:t,boundary:i,rootBoundary:n,strategy:r}=e,s=[..."clippingAncestors"===i?on(t)?[]:function(e,t){let i=t.get(e);if(i)return i;let n=od(e,[],!1).filter(e=>s7(e)&&"body"!==s4(e)),r=null,s="fixed"===oa(e).position,o=s?oc(e):e;for(;s7(o)&&!oo(o);){let t=oa(o),i=or(o);i||"fixed"!==t.position||(r=null),(s?!i&&!r:!i&&"static"===t.position&&!!r&&["absolute","fixed"].includes(r.position)||oi(o)&&!i&&function e(t,i){let n=oc(t);return!(n===i||!s7(n)||oo(n))&&("fixed"===oa(n).position||e(n,i))}(e,o))?n=n.filter(e=>e!==o):r=t,o=oc(o)}return t.set(e,n),n}(t,this._c):[].concat(i),n],o=s[0],a=s.reduce((e,i)=>{let n=ok(t,i,r);return e.top=sF(n.top,e.top),e.right=sU(n.right,e.right),e.bottom=sU(n.bottom,e.bottom),e.left=sF(n.left,e.left),e},ok(t,o,r));return{width:a.right-a.left,height:a.bottom-a.top,x:a.left,y:a.top}},getOffsetParent:oC,getElementRects:ow,getClientRects:function(e){return Array.from(e.getClientRects())},getDimensions:function(e){let{width:t,height:i}=oh(e);return{width:t,height:i}},getScale:om,isElement:s7,isRTL:function(e){return"rtl"===oa(e).direction}};function oP(e,t){return e.x===t.x&&e.y===t.y&&e.width===t.width&&e.height===t.height}let ox=(e,t,i)=>{let n=new Map,r={platform:oE,...i},s={...r.platform,_c:n};return s1(e,t,{...r,platform:s})};var oR="u">typeof globalThis?globalThis:"u">typeof window?window:"u">typeof global?global:"u">typeof self?self:{};function oO(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var oA,oI,oM,oD,o_,oN,oL,oj,oU,oF,oV,oB,oq,oz,oW,oH,oG,o$,oK,oJ,oX,oY,oQ,oZ,o0,o1,o2,o3,o5,o4,o6,o9,o8,o7,ae,at,ai,an={exports:{}},ar=an.exports;let as=oO(function(){var e;return ai||(ai=1,e=function(){var e=function(){},t="undefined",i=typeof window!==t&&typeof window.navigator!==t&&/Trident\/|MSIE /.test(window.navigator.userAgent),n=["trace","debug","info","warn","error"],r={},s=null;function o(e,t){var i=e[t];if("function"==typeof i.bind)return i.bind(e);try{return Function.prototype.bind.call(i,e)}catch{return function(){return Function.prototype.apply.apply(i,[e,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 l(){for(var i=this.getLevel(),r=0;r<n.length;r++){var s=n[r];this[s]=r<i?e:this.methodFactory(s,i,this.name)}if(this.log=this.debug,typeof console===t&&i<this.levels.SILENT)return"No console available for logging"}function c(e){return function(){typeof console!==t&&(l.call(this),this[e].apply(this,arguments))}}function d(n,r,s){var l;return"debug"===(l=n)&&(l="log"),typeof console!==t&&("trace"===l&&i?a:void 0!==console[l]?o(console,l):void 0!==console.log?o(console,"log"):e)||c.apply(this,arguments)}function u(e,i){var o,a,c,u=this,h="loglevel";function p(){var e;if(!(typeof window===t||!h)){try{e=window.localStorage[h]}catch{}if(typeof e===t)try{var i=window.document.cookie,n=encodeURIComponent(h),r=i.indexOf(n+"=");-1!==r&&(e=/^([^;]+)/.exec(i.slice(r+n.length+1))[1])}catch{}return void 0===u.levels[e]&&(e=void 0),e}}function m(e){var t=e;if("string"==typeof t&&void 0!==u.levels[t.toUpperCase()]&&(t=u.levels[t.toUpperCase()]),"number"==typeof t&&t>=0&&t<=u.levels.SILENT)return t;throw TypeError("log.setLevel() called with invalid level: "+e)}"string"==typeof e?h+=":"+e:"symbol"==typeof e&&(h=void 0),u.name=e,u.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},u.methodFactory=i||d,u.getLevel=function(){return c??a??o},u.setLevel=function(e,i){return c=m(e),!1!==i&&function(e){var i=(n[e]||"silent").toUpperCase();if(!(typeof window===t||!h)){try{window.localStorage[h]=i;return}catch{}try{window.document.cookie=encodeURIComponent(h)+"="+i+";"}catch{}}}(c),l.call(u)},u.setDefaultLevel=function(e){a=m(e),p()||u.setLevel(e,!1)},u.resetLevel=function(){c=null,function(){if(!(typeof window===t||!h)){try{window.localStorage.removeItem(h)}catch{}try{window.document.cookie=encodeURIComponent(h)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}(),l.call(u)},u.enableAll=function(e){u.setLevel(u.levels.TRACE,e)},u.disableAll=function(e){u.setLevel(u.levels.SILENT,e)},u.rebuild=function(){if(s!==u&&(o=m(s.getLevel())),l.call(u),s===u)for(var e in r)r[e].rebuild()},o=m(s?s.getLevel():"WARN");var f=p();null!=f&&(c=m(f)),l.call(u)}(s=new u).getLogger=function(e){if("symbol"!=typeof e&&"string"!=typeof e||""===e)throw TypeError("You must supply a name when creating a logger.");var t=r[e];return t||(t=r[e]=new u(e,s.methodFactory)),t};var h=typeof window!==t?window.log:void 0;return s.noConflict=function(){return typeof window!==t&&window.log===s&&(window.log=h),s},s.getLoggers=function(){return r},s.default=s,s},an.exports?an.exports=e():ar.log=e()),an.exports}());var ao=function(e,t){return(ao=Object.setPrototypeOf||({__proto__:[]})instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i])})(e,t)};function aa(e,t){if("function"!=typeof t&&null!==t)throw TypeError("Class extends value "+String(t)+" is not a constructor or null");function i(){this.constructor=e}ao(e,t),e.prototype=null===t?Object.create(t):(i.prototype=t.prototype,new i)}function al(e,t){var i,n,r,s={label:0,sent:function(){if(1&r[0])throw r[1];return r[1]},trys:[],ops:[]},o=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return o.next=a(0),o.throw=a(1),o.return=a(2),"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function a(a){return function(l){return function(a){if(i)throw TypeError("Generator is already executing.");for(;o&&(o=0,a[0]&&(s=0)),s;)try{if(i=1,n&&(r=2&a[0]?n.return:a[0]?n.throw||((r=n.return)&&r.call(n),0):n.next)&&!(r=r.call(n,a[1])).done)return r;switch(n=0,r&&(a=[2&a[0],r.value]),a[0]){case 0:case 1:r=a;break;case 4:return s.label++,{value:a[1],done:!1};case 5:s.label++,n=a[1],a=[0];continue;case 7:a=s.ops.pop(),s.trys.pop();continue;default:if(!(r=(r=s.trys).length>0&&r[r.length-1])&&(6===a[0]||2===a[0])){s=0;continue}if(3===a[0]&&(!r||a[1]>r[0]&&a[1]<r[3])){s.label=a[1];break}if(6===a[0]&&s.label<r[1]){s.label=r[1],r=a;break}if(r&&s.label<r[2]){s.label=r[2],s.ops.push(a);break}r[2]&&s.ops.pop(),s.trys.pop();continue}a=t.call(e,s)}catch(e){a=[6,e],n=0}finally{i=r=0}if(5&a[0])throw a[1];return{value:a[0]?a[1]:void 0,done:!0}}([a,l])}}}function ac(e){var t="function"==typeof Symbol&&Symbol.iterator,i=t&&e[t],n=0;if(i)return i.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function ad(e,t){var i="function"==typeof Symbol&&e[Symbol.iterator];if(!i)return e;var n,r,s=i.call(e),o=[];try{for(;(void 0===t||t-- >0)&&!(n=s.next()).done;)o.push(n.value)}catch(e){r={error:e}}finally{try{n&&!n.done&&(i=s.return)&&i.call(s)}finally{if(r)throw r.error}}return o}function au(e,t,i){if(i||2==arguments.length)for(var n,r=0,s=t.length;r<s;r++)!n&&r in t||(n||(n=Array.prototype.slice.call(t,0,r)),n[r]=t[r]);return e.concat(n||Array.prototype.slice.call(t))}function ah(e){return this instanceof ah?(this.v=e,this):new ah(e)}function ap(e){return"function"==typeof e}function am(e){var t=e(function(e){Error.call(e),e.stack=Error().stack});return t.prototype=Object.create(Error.prototype),t.prototype.constructor=t,t}var af=am(function(e){return function(t){e(this),this.message=t?t.length+` errors occurred during unsubscription:
1
+ (()=>{var e={};e.id=931,e.ids=[931],e.modules={2934:e=>{"use strict";e.exports=require("next/dist/client/components/action-async-storage.external.js")},4580:e=>{"use strict";e.exports=require("next/dist/client/components/request-async-storage.external.js")},5869:e=>{"use strict";e.exports=require("next/dist/client/components/static-generation-async-storage.external.js")},399:e=>{"use strict";e.exports=require("next/dist/compiled/next-server/app-page.runtime.prod.js")},5315:e=>{"use strict";e.exports=require("path")},7360:e=>{"use strict";e.exports=require("url")},8148:(e,t,i)=>{"use strict";i.r(t),i.d(t,{GlobalError:()=>o.a,__next_app__:()=>h,originalPathname:()=>u,pages:()=>d,routeModule:()=>p,tree:()=>c}),i(908),i(1506),i(5866);var n=i(3191),r=i(8716),s=i(7922),o=i.n(s),a=i(5231),l={};for(let e in a)0>["default","tree","pages","GlobalError","originalPathname","__next_app__","routeModule"].indexOf(e)&&(l[e]=()=>a[e]);i.d(t,l);let c=["",{children:["__PAGE__",{},{page:[()=>Promise.resolve().then(i.bind(i,908)),"/tmp/build-via-sdist-yrh8rni2/voice_mode-4.5.0/voice_mode/frontend/app/page.tsx"],metadata:{icon:[async e=>(await Promise.resolve().then(i.bind(i,7481))).default(e)],apple:[],openGraph:[],twitter:[],manifest:void 0}}]},{layout:[()=>Promise.resolve().then(i.bind(i,1506)),"/tmp/build-via-sdist-yrh8rni2/voice_mode-4.5.0/voice_mode/frontend/app/layout.tsx"],"not-found":[()=>Promise.resolve().then(i.t.bind(i,5866,23)),"next/dist/client/components/not-found-error"],metadata:{icon:[async e=>(await Promise.resolve().then(i.bind(i,7481))).default(e)],apple:[],openGraph:[],twitter:[],manifest:void 0}}],d=["/tmp/build-via-sdist-yrh8rni2/voice_mode-4.5.0/voice_mode/frontend/app/page.tsx"],u="/page",h={require:i,loadChunk:()=>Promise.resolve()},p=new n.AppPageRouteModule({definition:{kind:r.x.APP_PAGE,page:"/page",pathname:"/",bundlePath:"",filename:"",appPaths:[]},userland:{loaderTree:c}})},3277:(e,t,i)=>{Promise.resolve().then(i.bind(i,5337))},9169:(e,t,i)=>{Promise.resolve().then(i.t.bind(i,2994,23)),Promise.resolve().then(i.t.bind(i,6114,23)),Promise.resolve().then(i.t.bind(i,9727,23)),Promise.resolve().then(i.t.bind(i,9671,23)),Promise.resolve().then(i.t.bind(i,1868,23)),Promise.resolve().then(i.t.bind(i,4759,23))},1131:()=>{},5337:(e,t,i)=>{"use strict";let n,r,s,o;i.r(t),i.d(t,{default:()=>fb});var a,l,c,d,u=i(326);function h(){return u.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:u.jsx("path",{d:"M3.33398 3.33334L12.6673 12.6667M12.6673 3.33334L3.33398 12.6667",stroke:"currentColor","stroke-width":"2","stroke-linecap":"square"})})}var p=i(7577);function m(e){(0,p.useRef)(null);let[t,i]=(0,p.useState)(!1),n=(0,p.useRef)(!1);return["listening","thinking","speaking"].includes(e.state)&&!1==n.current&&(n.current=!0),u.jsx(u.Fragment,{children:t?(0,u.jsxs)("div",{className:"fixed text-sm left-1/2 max-w-[90vw] -translate-x-1/2 flex top-6 items-center gap-4 bg-[#1F1F1F] px-4 py-3 rounded-lg",children:[u.jsx("div",{children:u.jsx("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:u.jsx("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M9.85068 3.63564C10.8197 2.00589 13.1793 2.00589 14.1484 3.63564L21.6323 16.2223C22.6232 17.8888 21.4223 20 19.4835 20H4.51555C2.57676 20 1.37584 17.8888 2.36671 16.2223L9.85068 3.63564ZM12 8.5C12.2761 8.5 12.5 8.72386 12.5 9V13.5C12.5 13.7761 12.2761 14 12 14C11.7239 14 11.5 13.7761 11.5 13.5V9C11.5 8.72386 11.7239 8.5 12 8.5ZM12.75 16C12.75 16.4142 12.4142 16.75 12 16.75C11.5858 16.75 11.25 16.4142 11.25 16C11.25 15.5858 11.5858 15.25 12 15.25C12.4142 15.25 12.75 15.5858 12.75 16Z",fill:"#666666"})})}),u.jsx("p",{className:"text-pretty w-max",children:"It's quiet... too quiet. Is your agent lost? Ensure your agent is properly configured and running on your machine."}),u.jsx("a",{href:"https://docs.livekit.io/agents/quickstarts/s2s/",target:"_blank",className:"underline whitespace-nowrap",children:"View guide"}),u.jsx("button",{onClick:()=>i(!1),children:u.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:u.jsx("path",{d:"M3.16602 3.16666L12.8327 12.8333M12.8327 3.16666L3.16602 12.8333",stroke:"#999999",strokeWidth:"1.5",strokeLinecap:"square"})})})]}):null})}var f=Object.defineProperty,g=(e,t,i)=>t in e?f(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i,v=(e,t,i)=>g(e,"symbol"!=typeof t?t+"":t,i);class y{constructor(){v(this,"_locking"),v(this,"_locks"),this._locking=Promise.resolve(),this._locks=0}isLocked(){return this._locks>0}lock(){let e;this._locks+=1;let t=new Promise(t=>e=()=>{this._locks-=1,t()}),i=this._locking.then(()=>e);return this._locking=this._locking.then(()=>t),i}}function b(e,t){if(!e)throw Error(t)}function k(e){if("number"!=typeof e)throw Error("invalid int 32: "+typeof e);if(!Number.isInteger(e)||e>2147483647||e<-2147483648)throw Error("invalid int 32: "+e)}function T(e){if("number"!=typeof e)throw Error("invalid uint 32: "+typeof e);if(!Number.isInteger(e)||e>4294967295||e<0)throw Error("invalid uint 32: "+e)}function S(e){if("number"!=typeof e)throw Error("invalid float 32: "+typeof e);if(Number.isFinite(e)&&(e>34028234663852886e22||e<-34028234663852886e22))throw Error("invalid float 32: "+e)}let C=Symbol("@bufbuild/protobuf/enum-type");function w(e,t,i,n){e[C]=E(t,i.map(t=>({no:t.no,name:t.name,localName:e[t.no]})))}function E(e,t,i){let n=Object.create(null),r=Object.create(null),s=[];for(let e of t){let t=P(e);s.push(t),n[e.name]=t,r[e.no]=t}return{typeName:e,values:s,findName:e=>n[e],findNumber:e=>r[e]}}function P(e){return"localName"in e?e:Object.assign(Object.assign({},e),{localName:e.name})}class x{equals(e){return this.getType().runtime.util.equals(this.getType(),this,e)}clone(){return this.getType().runtime.util.clone(this)}fromBinary(e,t){let i=this.getType().runtime.bin,n=i.makeReadOptions(t);return i.readMessage(this,n.readerFactory(e),e.byteLength,n),this}fromJson(e,t){let i=this.getType(),n=i.runtime.json,r=n.makeReadOptions(t);return n.readMessage(i,e,r,this),this}fromJsonString(e,t){let i;try{i=JSON.parse(e)}catch(e){throw Error("cannot decode ".concat(this.getType().typeName," from JSON: ").concat(e instanceof Error?e.message:String(e)))}return this.fromJson(i,t)}toBinary(e){let t=this.getType().runtime.bin,i=t.makeWriteOptions(e),n=i.writerFactory();return t.writeMessage(this,n,i),n.finish()}toJson(e){let t=this.getType().runtime.json,i=t.makeWriteOptions(e);return t.writeMessage(this,i)}toJsonString(e){var t;return JSON.stringify(this.toJson(e),null,null!==(t=null==e?void 0:e.prettySpaces)&&void 0!==t?t:0)}toJSON(){return this.toJson({emitDefaultValues:!0})}getType(){return Object.getPrototypeOf(this).constructor}}function R(){let e=0,t=0;for(let i=0;i<28;i+=7){let n=this.buf[this.pos++];if(e|=(127&n)<<i,(128&n)==0)return this.assertBounds(),[e,t]}let i=this.buf[this.pos++];if(e|=(15&i)<<28,t=(112&i)>>4,(128&i)==0)return this.assertBounds(),[e,t];for(let i=3;i<=31;i+=7){let n=this.buf[this.pos++];if(t|=(127&n)<<i,(128&n)==0)return this.assertBounds(),[e,t]}throw Error("invalid varint")}function O(e,t,i){for(let n=0;n<28;n+=7){let r=e>>>n,s=!(r>>>7==0&&0==t),o=(s?128|r:r)&255;if(i.push(o),!s)return}let n=e>>>28&15|(7&t)<<4,r=t>>3!=0;if(i.push((r?128|n:n)&255),r){for(let e=3;e<31;e+=7){let n=t>>>e,r=n>>>7!=0,s=(r?128|n:n)&255;if(i.push(s),!r)return}i.push(t>>>31&1)}}function A(e){let t="-"===e[0];t&&(e=e.slice(1));let i=0,n=0;function r(t,r){let s=Number(e.slice(t,r));n*=1e6,(i=1e6*i+s)>=4294967296&&(n+=i/4294967296|0,i%=4294967296)}return r(-24,-18),r(-18,-12),r(-12,-6),r(-6),t?D(i,n):M(i,n)}function I(e,t){if({lo:e,hi:t}={lo:e>>>0,hi:t>>>0},t<=2097151)return String(4294967296*t+e);let i=16777215&e,n=(e>>>24|t<<8)&16777215,r=t>>16&65535,s=i+6777216*n+6710656*r,o=n+8147497*r,a=2*r;return s>=1e7&&(o+=Math.floor(s/1e7),s%=1e7),o>=1e7&&(a+=Math.floor(o/1e7),o%=1e7),a.toString()+_(o)+_(s)}function M(e,t){return{lo:0|e,hi:0|t}}function D(e,t){return t=~t,e?e=~e+1:t+=1,M(e,t)}let _=e=>{let t=String(e);return"0000000".slice(t.length)+t};function N(e,t){if(e>=0){for(;e>127;)t.push(127&e|128),e>>>=7;t.push(e)}else{for(let i=0;i<9;i++)t.push(127&e|128),e>>=7;t.push(1)}}function L(){let e=this.buf[this.pos++],t=127&e;if((128&e)==0||(t|=(127&(e=this.buf[this.pos++]))<<7,(128&e)==0)||(t|=(127&(e=this.buf[this.pos++]))<<14,(128&e)==0)||(t|=(127&(e=this.buf[this.pos++]))<<21,(128&e)==0))return this.assertBounds(),t;t|=(15&(e=this.buf[this.pos++]))<<28;for(let t=5;(128&e)!=0&&t<10;t++)e=this.buf[this.pos++];if((128&e)!=0)throw Error("invalid varint");return this.assertBounds(),t>>>0}let j=function(){let e=new DataView(new ArrayBuffer(8));if("function"==typeof BigInt&&"function"==typeof e.getBigInt64&&"function"==typeof e.getBigUint64&&"function"==typeof e.setBigInt64&&"function"==typeof e.setBigUint64&&("object"!=typeof process||"object"!=typeof process.env||"1"!==process.env.BUF_BIGINT_DISABLE)){let t=BigInt("-9223372036854775808"),i=BigInt("9223372036854775807"),n=BigInt("0"),r=BigInt("18446744073709551615");return{zero:BigInt(0),supported:!0,parse(e){let n="bigint"==typeof e?e:BigInt(e);if(n>i||n<t)throw Error("int64 invalid: ".concat(e));return n},uParse(e){let t="bigint"==typeof e?e:BigInt(e);if(t>r||t<n)throw Error("uint64 invalid: ".concat(e));return t},enc(t){return e.setBigInt64(0,this.parse(t),!0),{lo:e.getInt32(0,!0),hi:e.getInt32(4,!0)}},uEnc(t){return e.setBigInt64(0,this.uParse(t),!0),{lo:e.getInt32(0,!0),hi:e.getInt32(4,!0)}},dec:(t,i)=>(e.setInt32(0,t,!0),e.setInt32(4,i,!0),e.getBigInt64(0,!0)),uDec:(t,i)=>(e.setInt32(0,t,!0),e.setInt32(4,i,!0),e.getBigUint64(0,!0))}}let t=e=>b(/^-?[0-9]+$/.test(e),"int64 invalid: ".concat(e)),i=e=>b(/^[0-9]+$/.test(e),"uint64 invalid: ".concat(e));return{zero:"0",supported:!1,parse:e=>("string"!=typeof e&&(e=e.toString()),t(e),e),uParse:e=>("string"!=typeof e&&(e=e.toString()),i(e),e),enc:e=>("string"!=typeof e&&(e=e.toString()),t(e),A(e)),uEnc:e=>("string"!=typeof e&&(e=e.toString()),i(e),A(e)),dec:(e,t)=>(function(e,t){let i=M(e,t),n=2147483648&i.hi;n&&(i=D(i.lo,i.hi));let r=I(i.lo,i.hi);return n?"-"+r:r})(e,t),uDec:(e,t)=>I(e,t)}}();function U(e,t,i){if(t===i)return!0;if(e==oM.BYTES){if(!(t instanceof Uint8Array)||!(i instanceof Uint8Array)||t.length!==i.length)return!1;for(let e=0;e<t.length;e++)if(t[e]!==i[e])return!1;return!0}switch(e){case oM.UINT64:case oM.FIXED64:case oM.INT64:case oM.SFIXED64:case oM.SINT64:return t==i}return!1}function F(e,t){switch(e){case oM.BOOL:return!1;case oM.UINT64:case oM.FIXED64:case oM.INT64:case oM.SFIXED64:case oM.SINT64:return 0==t?j.zero:"0";case oM.DOUBLE:case oM.FLOAT:return 0;case oM.BYTES:return new Uint8Array(0);case oM.STRING:return"";default:return 0}}function V(e,t){switch(e){case oM.BOOL:return!1===t;case oM.STRING:return""===t;case oM.BYTES:return t instanceof Uint8Array&&!t.byteLength;default:return 0==t}}(function(e){e[e.DOUBLE=1]="DOUBLE",e[e.FLOAT=2]="FLOAT",e[e.INT64=3]="INT64",e[e.UINT64=4]="UINT64",e[e.INT32=5]="INT32",e[e.FIXED64=6]="FIXED64",e[e.FIXED32=7]="FIXED32",e[e.BOOL=8]="BOOL",e[e.STRING=9]="STRING",e[e.BYTES=12]="BYTES",e[e.UINT32=13]="UINT32",e[e.SFIXED32=15]="SFIXED32",e[e.SFIXED64=16]="SFIXED64",e[e.SINT32=17]="SINT32",e[e.SINT64=18]="SINT64"})(oM||(oM={})),function(e){e[e.BIGINT=0]="BIGINT",e[e.STRING=1]="STRING"}(oD||(oD={})),function(e){e[e.Varint=0]="Varint",e[e.Bit64=1]="Bit64",e[e.LengthDelimited=2]="LengthDelimited",e[e.StartGroup=3]="StartGroup",e[e.EndGroup=4]="EndGroup",e[e.Bit32=5]="Bit32"}(o_||(o_={}));class B{constructor(e){this.stack=[],this.textEncoder=null!=e?e:new TextEncoder,this.chunks=[],this.buf=[]}finish(){this.chunks.push(new Uint8Array(this.buf));let e=0;for(let t=0;t<this.chunks.length;t++)e+=this.chunks[t].length;let t=new Uint8Array(e),i=0;for(let e=0;e<this.chunks.length;e++)t.set(this.chunks[e],i),i+=this.chunks[e].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 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(T(e);e>127;)this.buf.push(127&e|128),e>>>=7;return this.buf.push(e),this}int32(e){return k(e),N(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){S(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){T(e);let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!0),this.raw(t)}sfixed32(e){k(e);let t=new Uint8Array(4);return new DataView(t.buffer).setInt32(0,e,!0),this.raw(t)}sint32(e){return k(e),N(e=(e<<1^e>>31)>>>0,this.buf),this}sfixed64(e){let t=new Uint8Array(8),i=new DataView(t.buffer),n=j.enc(e);return i.setInt32(0,n.lo,!0),i.setInt32(4,n.hi,!0),this.raw(t)}fixed64(e){let t=new Uint8Array(8),i=new DataView(t.buffer),n=j.uEnc(e);return i.setInt32(0,n.lo,!0),i.setInt32(4,n.hi,!0),this.raw(t)}int64(e){let t=j.enc(e);return O(t.lo,t.hi,this.buf),this}sint64(e){let t=j.enc(e),i=t.hi>>31;return O(t.lo<<1^i,(t.hi<<1|t.lo>>>31)^i,this.buf),this}uint64(e){let t=j.uEnc(e);return O(t.lo,t.hi,this.buf),this}}class q{constructor(e,t){this.varint64=R,this.uint32=L,this.buf=e,this.len=e.length,this.pos=0,this.view=new DataView(e.buffer,e.byteOffset,e.byteLength),this.textDecoder=null!=t?t:new TextDecoder}tag(){let e=this.uint32(),t=e>>>3,i=7&e;if(t<=0||i<0||i>5)throw Error("illegal tag: field no "+t+" wire type "+i);return[t,i]}skip(e,t){let i=this.pos;switch(e){case o_.Varint:for(;128&this.buf[this.pos++];);break;case o_.Bit64:this.pos+=4;case o_.Bit32:this.pos+=4;break;case o_.LengthDelimited:let n=this.uint32();this.pos+=n;break;case o_.StartGroup:for(;;){let[e,i]=this.tag();if(i===o_.EndGroup){if(void 0!==t&&e!==t)throw Error("invalid end group tag");break}this.skip(i,e)}break;default:throw Error("cant skip wire type "+e)}return this.assertBounds(),this.buf.subarray(i,this.pos)}assertBounds(){if(this.pos>this.len)throw RangeError("premature EOF")}int32(){return 0|this.uint32()}sint32(){let e=this.uint32();return e>>>1^-(1&e)}int64(){return j.dec(...this.varint64())}uint64(){return j.uDec(...this.varint64())}sint64(){let[e,t]=this.varint64(),i=-(1&e);return e=(e>>>1|(1&t)<<31)^i,t=t>>>1^i,j.dec(e,t)}bool(){let[e,t]=this.varint64();return 0!==e||0!==t}fixed32(){return this.view.getUint32((this.pos+=4)-4,!0)}sfixed32(){return this.view.getInt32((this.pos+=4)-4,!0)}fixed64(){return j.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return j.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 W(e){let t=e.field.localName,i=Object.create(null);return i[t]=function(e){let t=e.field;if(t.repeated)return[];if(void 0!==t.default)return t.default;switch(t.kind){case"enum":return t.T.values[0].no;case"scalar":return F(t.T,t.L);case"message":let i=t.T,n=new i;return i.fieldWrapper?i.fieldWrapper.unwrapField(n):n;case"map":throw"map fields are not allowed to be extensions"}}(e),[i,()=>i[t]]}let z="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),H=[];for(let e=0;e<z.length;e++)H[z[e].charCodeAt(0)]=e;H["-".charCodeAt(0)]=z.indexOf("+"),H["_".charCodeAt(0)]=z.indexOf("/");let G={dec(e){let t=3*e.length/4;"="==e[e.length-2]?t-=2:"="==e[e.length-1]&&(t-=1);let i=new Uint8Array(t),n=0,r=0,s,o=0;for(let t=0;t<e.length;t++){if(void 0===(s=H[e.charCodeAt(t)]))switch(e[t]){case"=":r=0;case"\n":case"\r":case" ":case" ":continue;default:throw Error("invalid base64 string.")}switch(r){case 0:o=s,r=1;break;case 1:i[n++]=o<<2|(48&s)>>4,o=s,r=2;break;case 2:i[n++]=(15&o)<<4|(60&s)>>2,o=s,r=3;break;case 3:i[n++]=(3&o)<<6|s,r=0}}if(1==r)throw Error("invalid base64 string.");return i.subarray(0,n)},enc(e){let t="",i=0,n,r=0;for(let s=0;s<e.length;s++)switch(n=e[s],i){case 0:t+=z[n>>2],r=(3&n)<<4,i=1;break;case 1:t+=z[r|n>>4],r=(15&n)<<2,i=2;break;case 2:t+=z[r|n>>6]+z[63&n],i=0}return i&&(t+=z[r]+"=",1==i&&(t+="=")),t}};function $(e,t){let i=e.getType();return t.extendee.typeName===i.typeName&&!!i.runtime.bin.listUnknownFields(e).find(e=>e.no==t.field.no)}function K(e,t){b(e.extendee.typeName==t.getType().typeName,"extension ".concat(e.typeName," can only be applied to message ").concat(e.extendee.typeName))}function J(e,t){let i=e.localName;if(e.repeated)return t[i].length>0;if(e.oneof)return t[e.oneof.localName].case===i;switch(e.kind){case"enum":case"scalar":if(e.opt||e.req)return void 0!==t[i];if("enum"==e.kind)return t[i]!==e.T.values[0].no;return!V(e.T,t[i]);case"message":return void 0!==t[i];case"map":return Object.keys(t[i]).length>0}}function X(e,t){let i=e.localName,n=!e.opt&&!e.req;if(e.repeated)t[i]=[];else if(e.oneof)t[e.oneof.localName]={case:void 0};else switch(e.kind){case"map":t[i]={};break;case"enum":t[i]=n?e.T.values[0].no:void 0;break;case"scalar":t[i]=n?F(e.T,e.L):void 0;break;case"message":t[i]=void 0}}function Y(e,t){if(null===e||"object"!=typeof e||!Object.getOwnPropertyNames(x.prototype).every(t=>t in e&&"function"==typeof e[t]))return!1;let i=e.getType();return null!==i&&"function"==typeof i&&"typeName"in i&&"string"==typeof i.typeName&&(void 0===t||i.typeName==t.typeName)}function Q(e,t){return Y(t)||!e.fieldWrapper?t:e.fieldWrapper.wrapField(t)}oM.DOUBLE,oM.FLOAT,oM.INT64,oM.UINT64,oM.INT32,oM.UINT32,oM.BOOL,oM.STRING,oM.BYTES;let Z={ignoreUnknownFields:!1},ee={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0},et=Symbol(),ei=Symbol();function en(e){if(null===e)return"null";switch(typeof e){case"object":return Array.isArray(e)?"array":"object";case"string":return e.length>100?"string":'"'.concat(e.split('"').join('\\"'),'"');default:return String(e)}}function er(e,t,i,n,r){let s=i.localName;if(i.repeated){if(b("map"!=i.kind),null===t)return;if(!Array.isArray(t))throw Error("cannot decode field ".concat(r.typeName,".").concat(i.name," from JSON: ").concat(en(t)));let o=e[s];for(let e of t){if(null===e)throw Error("cannot decode field ".concat(r.typeName,".").concat(i.name," from JSON: ").concat(en(e)));switch(i.kind){case"message":o.push(i.T.fromJson(e,n));break;case"enum":let t=eo(i.T,e,n.ignoreUnknownFields,!0);t!==ei&&o.push(t);break;case"scalar":try{o.push(es(i.T,e,i.L,!0))}catch(n){let t="cannot decode field ".concat(r.typeName,".").concat(i.name," from JSON: ").concat(en(e));throw n instanceof Error&&n.message.length>0&&(t+=": ".concat(n.message)),Error(t)}}}}else if("map"==i.kind){if(null===t)return;if("object"!=typeof t||Array.isArray(t))throw Error("cannot decode field ".concat(r.typeName,".").concat(i.name," from JSON: ").concat(en(t)));let o=e[s];for(let[e,s]of Object.entries(t)){let a;if(null===s)throw Error("cannot decode field ".concat(r.typeName,".").concat(i.name," from JSON: map value null"));try{a=function(e,t){if(e===oM.BOOL)switch(t){case"true":t=!0;break;case"false":t=!1}return es(e,t,oD.BIGINT,!0).toString()}(i.K,e)}catch(n){let e="cannot decode map key for field ".concat(r.typeName,".").concat(i.name," from JSON: ").concat(en(t));throw n instanceof Error&&n.message.length>0&&(e+=": ".concat(n.message)),Error(e)}switch(i.V.kind){case"message":o[a]=i.V.T.fromJson(s,n);break;case"enum":let l=eo(i.V.T,s,n.ignoreUnknownFields,!0);l!==ei&&(o[a]=l);break;case"scalar":try{o[a]=es(i.V.T,s,oD.BIGINT,!0)}catch(n){let e="cannot decode map value for field ".concat(r.typeName,".").concat(i.name," from JSON: ").concat(en(t));throw n instanceof Error&&n.message.length>0&&(e+=": ".concat(n.message)),Error(e)}}}}else switch(i.oneof&&(e=e[i.oneof.localName]={case:s},s="value"),i.kind){case"message":let o=i.T;if(null===t&&"google.protobuf.Value"!=o.typeName)return;let a=e[s];Y(a)?a.fromJson(t,n):(e[s]=a=o.fromJson(t,n),o.fieldWrapper&&!i.oneof&&(e[s]=o.fieldWrapper.unwrapField(a)));break;case"enum":let l=eo(i.T,t,n.ignoreUnknownFields,!1);switch(l){case et:X(i,e);break;case ei:break;default:e[s]=l}break;case"scalar":try{let n=es(i.T,t,i.L,!1);n===et?X(i,e):e[s]=n}catch(n){let e="cannot decode field ".concat(r.typeName,".").concat(i.name," from JSON: ").concat(en(t));throw n instanceof Error&&n.message.length>0&&(e+=": ".concat(n.message)),Error(e)}}}function es(e,t,i,n){if(null===t)return n?F(e,i):et;switch(e){case oM.DOUBLE:case oM.FLOAT:if("NaN"===t)return Number.NaN;if("Infinity"===t)return Number.POSITIVE_INFINITY;if("-Infinity"===t)return Number.NEGATIVE_INFINITY;if(""===t||"string"==typeof t&&t.trim().length!==t.length||"string"!=typeof t&&"number"!=typeof t)break;let r=Number(t);if(Number.isNaN(r)||!Number.isFinite(r))break;return e==oM.FLOAT&&S(r),r;case oM.INT32:case oM.FIXED32:case oM.SFIXED32:case oM.SINT32:case oM.UINT32:let s;if("number"==typeof t?s=t:"string"==typeof t&&t.length>0&&t.trim().length===t.length&&(s=Number(t)),void 0===s)break;return e==oM.UINT32||e==oM.FIXED32?T(s):k(s),s;case oM.INT64:case oM.SFIXED64:case oM.SINT64:if("number"!=typeof t&&"string"!=typeof t)break;let o=j.parse(t);return i?o.toString():o;case oM.FIXED64:case oM.UINT64:if("number"!=typeof t&&"string"!=typeof t)break;let a=j.uParse(t);return i?a.toString():a;case oM.BOOL:if("boolean"!=typeof t)break;return t;case oM.STRING:if("string"!=typeof t)break;try{encodeURIComponent(t)}catch(e){throw Error("invalid UTF8")}return t;case oM.BYTES:if(""===t)return new Uint8Array(0);if("string"!=typeof t)break;return G.dec(t)}throw Error()}function eo(e,t,i,n){if(null===t)return"google.protobuf.NullValue"==e.typeName?0:n?e.values[0].no:et;switch(typeof t){case"number":if(Number.isInteger(t))return t;break;case"string":let r=e.findName(t);if(void 0!==r)return r.no;if(i)return ei}throw Error("cannot decode enum ".concat(e.typeName," from JSON: ").concat(en(t)))}function ea(e,t,i){if("map"==e.kind){b("object"==typeof t&&null!=t);let n={},r=Object.entries(t);switch(e.V.kind){case"scalar":for(let[t,i]of r)n[t.toString()]=ec(e.V.T,i);break;case"message":for(let[e,t]of r)n[e.toString()]=t.toJson(i);break;case"enum":let s=e.V.T;for(let[e,t]of r)n[e.toString()]=el(s,t,i.enumAsInteger)}return i.emitDefaultValues||r.length>0?n:void 0}if(e.repeated){b(Array.isArray(t));let n=[];switch(e.kind){case"scalar":for(let i=0;i<t.length;i++)n.push(ec(e.T,t[i]));break;case"enum":for(let r=0;r<t.length;r++)n.push(el(e.T,t[r],i.enumAsInteger));break;case"message":for(let e=0;e<t.length;e++)n.push(t[e].toJson(i))}return i.emitDefaultValues||n.length>0?n:void 0}switch(e.kind){case"scalar":return ec(e.T,t);case"enum":return el(e.T,t,i.enumAsInteger);case"message":return Q(e.T,t).toJson(i)}}function el(e,t,i){var n;if(b("number"==typeof t),"google.protobuf.NullValue"==e.typeName)return null;if(i)return t;let r=e.findNumber(t);return null!==(n=null==r?void 0:r.name)&&void 0!==n?n:t}function ec(e,t){switch(e){case oM.INT32:case oM.SFIXED32:case oM.SINT32:case oM.FIXED32:case oM.UINT32:return b("number"==typeof t),t;case oM.FLOAT:case oM.DOUBLE:if(b("number"==typeof t),Number.isNaN(t))return"NaN";if(t===Number.POSITIVE_INFINITY)return"Infinity";if(t===Number.NEGATIVE_INFINITY)return"-Infinity";return t;case oM.STRING:return b("string"==typeof t),t;case oM.BOOL:return b("boolean"==typeof t),t;case oM.UINT64:case oM.FIXED64:case oM.INT64:case oM.SFIXED64:case oM.SINT64:return b("bigint"==typeof t||"string"==typeof t||"number"==typeof t),t.toString();case oM.BYTES:return b(t instanceof Uint8Array),G.enc(t)}}let ed=Symbol("@bufbuild/protobuf/unknown-fields"),eu={readUnknownFields:!0,readerFactory:e=>new q(e)},eh={writeUnknownFields:!0,writerFactory:()=>new B};function ep(e,t,i,n,r){let{repeated:s,localName:o}=i;switch(i.oneof&&((e=e[i.oneof.localName]).case!=o&&delete e.value,e.case=o,o="value"),i.kind){case"scalar":case"enum":let a="enum"==i.kind?oM.INT32:i.T,l=eg;if("scalar"==i.kind&&i.L>0&&(l=ef),s){let i=e[o];if(n==o_.LengthDelimited&&a!=oM.STRING&&a!=oM.BYTES){let e=t.uint32()+t.pos;for(;t.pos<e;)i.push(l(t,a))}else i.push(l(t,a))}else e[o]=l(t,a);break;case"message":let c=i.T;s?e[o].push(em(t,new c,r,i)):Y(e[o])?em(t,e[o],r,i):(e[o]=em(t,new c,r,i),!c.fieldWrapper||i.oneof||i.repeated||(e[o]=c.fieldWrapper.unwrapField(e[o])));break;case"map":let[d,u]=function(e,t,i){let n,r;let s=t.uint32(),o=t.pos+s;for(;t.pos<o;){let[s]=t.tag();switch(s){case 1:n=eg(t,e.K);break;case 2:switch(e.V.kind){case"scalar":r=eg(t,e.V.T);break;case"enum":r=t.int32();break;case"message":r=em(t,new e.V.T,i,void 0)}}}if(void 0===n&&(n=F(e.K,oD.BIGINT)),"string"!=typeof n&&"number"!=typeof n&&(n=n.toString()),void 0===r)switch(e.V.kind){case"scalar":r=F(e.V.T,oD.BIGINT);break;case"enum":r=e.V.T.values[0].no;break;case"message":r=new e.V.T}return[n,r]}(i,t,r);e[o][d]=u}}function em(e,t,i,n){let r=t.getType().runtime.bin,s=null==n?void 0:n.delimited;return r.readMessage(t,e,s?n.no:e.uint32(),i,s),t}function ef(e,t){let i=eg(e,t);return"bigint"==typeof i?i.toString():i}function eg(e,t){switch(t){case oM.STRING:return e.string();case oM.BOOL:return e.bool();case oM.DOUBLE:return e.double();case oM.FLOAT:return e.float();case oM.INT32:return e.int32();case oM.INT64:return e.int64();case oM.UINT64:return e.uint64();case oM.FIXED64:return e.fixed64();case oM.BYTES:return e.bytes();case oM.FIXED32:return e.fixed32();case oM.SFIXED32:return e.sfixed32();case oM.SFIXED64:return e.sfixed64();case oM.SINT64:return e.sint64();case oM.UINT32:return e.uint32();case oM.SINT32:return e.sint32()}}function ev(e,t,i,n){b(void 0!==t);let r=e.repeated;switch(e.kind){case"scalar":case"enum":let s="enum"==e.kind?oM.INT32:e.T;if(r){if(b(Array.isArray(t)),e.packed)(function(e,t,i,n){if(!n.length)return;e.tag(i,o_.LengthDelimited).fork();let[,r]=ek(t);for(let t=0;t<n.length;t++)e[r](n[t]);e.join()})(i,s,e.no,t);else for(let n of t)eb(i,s,e.no,n)}else eb(i,s,e.no,t);break;case"message":if(r)for(let r of(b(Array.isArray(t)),t))ey(i,n,e,r);else ey(i,n,e,t);break;case"map":for(let[r,s]of(b("object"==typeof t&&null!=t),Object.entries(t)))(function(e,t,i,n,r){e.tag(i.no,o_.LengthDelimited),e.fork();let s=n;switch(i.K){case oM.INT32:case oM.FIXED32:case oM.UINT32:case oM.SFIXED32:case oM.SINT32:s=Number.parseInt(n);break;case oM.BOOL:b("true"==n||"false"==n),s="true"==n}switch(eb(e,i.K,1,s),i.V.kind){case"scalar":eb(e,i.V.T,2,r);break;case"enum":eb(e,oM.INT32,2,r);break;case"message":b(void 0!==r),e.tag(2,o_.LengthDelimited).bytes(r.toBinary(t))}e.join()})(i,n,e,r,s)}}function ey(e,t,i,n){let r=Q(i.T,n);i.delimited?e.tag(i.no,o_.StartGroup).raw(r.toBinary(t)).tag(i.no,o_.EndGroup):e.tag(i.no,o_.LengthDelimited).bytes(r.toBinary(t))}function eb(e,t,i,n){b(void 0!==n);let[r,s]=ek(t);e.tag(i,r)[s](n)}function ek(e){let t=o_.Varint;switch(e){case oM.BYTES:case oM.STRING:t=o_.LengthDelimited;break;case oM.DOUBLE:case oM.FIXED64:case oM.SFIXED64:t=o_.Bit64;break;case oM.FIXED32:case oM.SFIXED32:case oM.FLOAT:t=o_.Bit32}return[t,oM[e].toLowerCase()]}function eT(e){if(void 0===e)return e;if(Y(e))return e.clone();if(e instanceof Uint8Array){let t=new Uint8Array(e.byteLength);return t.set(e),t}return e}function eS(e){return e instanceof Uint8Array?e:new Uint8Array(e)}class eC{constructor(e,t){this._fields=e,this._normalizer=t}findJsonName(e){if(!this.jsonNames){let e={};for(let t of this.list())e[t.jsonName]=e[t.name]=t;this.jsonNames=e}return this.jsonNames[e]}find(e){if(!this.numbers){let e={};for(let t of this.list())e[t.no]=t;this.numbers=e}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){let e;this.members=[];let t=this.members;for(let i of this.list())i.oneof?i.oneof!==e&&(e=i.oneof,t.push(e)):t.push(i)}return this.members}}function ew(e,t){let i=eP(e);return t?i:eI(eA(i))}let eE=eP;function eP(e){let t=!1,i=[];for(let n=0;n<e.length;n++){let r=e.charAt(n);switch(r){case"_":t=!0;break;case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":i.push(r),t=!1;break;default:t&&(t=!1,r=r.toUpperCase()),i.push(r)}}return i.join("")}let ex=new Set(["constructor","toString","toJSON","valueOf"]),eR=new Set(["getType","clone","equals","fromBinary","fromJson","fromJsonString","toBinary","toJson","toJsonString","toObject"]),eO=e=>"".concat(e,"$"),eA=e=>eR.has(e)?eO(e):e,eI=e=>ex.has(e)?eO(e):e;class eM{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=ew(e,!1)}addField(e){b(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 e=0;e<this.fields.length;e++)this._lookup[this.fields[e].localName]=this.fields[e]}return this._lookup[e]}}let eD=(oA=e=>new eC(e,e=>(function(e,t){var i,n,r,s,o,a;let l;let c=[];for(let t of"function"==typeof e?e():e){if(t.localName=ew(t.name,void 0!==t.oneof),t.jsonName=null!==(i=t.jsonName)&&void 0!==i?i:eE(t.name),t.repeated=null!==(n=t.repeated)&&void 0!==n&&n,"scalar"==t.kind&&(t.L=null!==(r=t.L)&&void 0!==r?r:oD.BIGINT),t.delimited=null!==(s=t.delimited)&&void 0!==s&&s,t.req=null!==(o=t.req)&&void 0!==o&&o,t.opt=null!==(a=t.opt)&&void 0!==a&&a,void 0===t.packed&&(t.packed="enum"==t.kind||"scalar"==t.kind&&t.T!=oM.BYTES&&t.T!=oM.STRING),void 0!==t.oneof){let e="string"==typeof t.oneof?t.oneof:t.oneof.name;l&&l.name==e||(l=new eM(e)),t.oneof=l,l.addField(t)}c.push(t)}return c})(e)),oI=e=>{for(let t of e.getType().fields.byMember()){if(t.opt)continue;let i=t.localName;if(t.repeated){e[i]=[];continue}switch(t.kind){case"oneof":e[i]={case:void 0};break;case"enum":e[i]=0;break;case"map":e[i]={};break;case"scalar":e[i]=F(t.T,t.L)}}},{syntax:"proto3",json:{makeReadOptions:function(e){return e?Object.assign(Object.assign({},Z),e):Z},makeWriteOptions:function(e){return e?Object.assign(Object.assign({},ee),e):ee},readMessage(e,t,i,n){if(null==t||Array.isArray(t)||"object"!=typeof t)throw Error("cannot decode message ".concat(e.typeName," from JSON: ").concat(en(t)));n=null!=n?n:new e;let r=new Map,s=i.typeRegistry;for(let[o,a]of Object.entries(t)){let t=e.fields.findJsonName(o);if(t){if(t.oneof){if(null===a&&"scalar"==t.kind)continue;let i=r.get(t.oneof);if(void 0!==i)throw Error("cannot decode message ".concat(e.typeName,' from JSON: multiple keys for oneof "').concat(t.oneof.name,'" present: "').concat(i,'", "').concat(o,'"'));r.set(t.oneof,o)}er(n,a,t,i,e)}else{let t=!1;if((null==s?void 0:s.findExtension)&&o.startsWith("[")&&o.endsWith("]")){let r=s.findExtension(o.substring(1,o.length-1));if(r&&r.extendee.typeName==e.typeName){t=!0;let[e,s]=W(r);er(e,a,r.field,i,r),function(e,t,i,n){K(t,e);let r=t.runtime.bin.makeReadOptions(n),s=t.runtime.bin.makeWriteOptions(n);if($(e,t)){let i=e.getType().runtime.bin.listUnknownFields(e).filter(e=>e.no!=t.field.no);for(let t of(e.getType().runtime.bin.discardUnknownFields(e),i))e.getType().runtime.bin.onUnknownField(e,t.no,t.wireType,t.data)}let o=s.writerFactory(),a=t.field;a.opt||a.repeated||"enum"!=a.kind&&"scalar"!=a.kind||(a=Object.assign(Object.assign({},t.field),{opt:!0})),t.runtime.bin.writeField(a,i,o,s);let l=r.readerFactory(o.finish());for(;l.pos<l.len;){let[t,i]=l.tag(),n=l.skip(i,t);e.getType().runtime.bin.onUnknownField(e,t,i,n)}}(n,r,s(),i)}}if(!t&&!i.ignoreUnknownFields)throw Error("cannot decode message ".concat(e.typeName,' from JSON: key "').concat(o,'" is unknown'))}}return n},writeMessage(e,t){let i;let n=e.getType(),r={};try{for(i of n.fields.byNumber()){if(!J(i,e)){var s;if(i.req)throw"required field not set";if(!t.emitDefaultValues||!((s=i).repeated||"map"==s.kind||!s.oneof&&"message"!=s.kind&&!s.opt&&!s.req))continue}let n=i.oneof?e[i.oneof.localName].value:e[i.localName],o=ea(i,n,t);void 0!==o&&(r[t.useProtoFieldName?i.name:i.jsonName]=o)}let o=t.typeRegistry;if(null==o?void 0:o.findExtensionFor)for(let i of n.runtime.bin.listUnknownFields(e)){let s=o.findExtensionFor(n.typeName,i.no);if(s&&$(e,s)){let i=function(e,t,i){K(t,e);let n=t.runtime.bin.makeReadOptions(i),r=function(e,t){if(!t.repeated&&("enum"==t.kind||"scalar"==t.kind)){for(let i=e.length-1;i>=0;--i)if(e[i].no==t.no)return[e[i]];return[]}return e.filter(e=>e.no===t.no)}(e.getType().runtime.bin.listUnknownFields(e),t.field),[s,o]=W(t);for(let e of r)t.runtime.bin.readField(s,n.readerFactory(e.data),t.field,e.wireType,n);return o()}(e,s,t),n=ea(s.field,i,t);void 0!==n&&(r[s.field.jsonName]=n)}}}catch(r){let e=i?"cannot encode field ".concat(n.typeName,".").concat(i.name," to JSON"):"cannot encode message ".concat(n.typeName," to JSON"),t=r instanceof Error?r.message:String(r);throw Error(e+(t.length>0?": ".concat(t):""))}return r},readScalar:(e,t,i)=>es(e,t,null!=i?i:oD.BIGINT,!0),writeScalar(e,t,i){if(void 0!==t&&(i||V(e,t)))return ec(e,t)},debug:en},bin:{makeReadOptions:function(e){return e?Object.assign(Object.assign({},eu),e):eu},makeWriteOptions:function(e){return e?Object.assign(Object.assign({},eh),e):eh},listUnknownFields(e){var t;return null!==(t=e[ed])&&void 0!==t?t:[]},discardUnknownFields(e){delete e[ed]},writeUnknownFields(e,t){let i=e[ed];if(i)for(let e of i)t.tag(e.no,e.wireType).raw(e.data)},onUnknownField(e,t,i,n){Array.isArray(e[ed])||(e[ed]=[]),e[ed].push({no:t,wireType:i,data:n})},readMessage(e,t,i,n,r){let s,o;let a=e.getType(),l=r?t.len:t.pos+i;for(;t.pos<l&&([s,o]=t.tag(),!0!==r||o!=o_.EndGroup);){let i=a.fields.find(s);if(!i){let i=t.skip(o,s);n.readUnknownFields&&this.onUnknownField(e,s,o,i);continue}ep(e,t,i,o,n)}if(r&&(o!=o_.EndGroup||s!==i))throw Error("invalid end group tag")},readField:ep,writeMessage(e,t,i){let n=e.getType();for(let r of n.fields.byNumber()){if(!J(r,e)){if(r.req)throw Error("cannot encode field ".concat(n.typeName,".").concat(r.name," to binary: required field not set"));continue}let s=r.oneof?e[r.oneof.localName].value:e[r.localName];ev(r,s,t,i)}return i.writeUnknownFields&&this.writeUnknownFields(e,t),t},writeField(e,t,i,n){void 0!==t&&ev(e,t,i,n)}},util:Object.assign(Object.assign({},{setEnumType:w,initPartial(e,t){if(void 0!==e)for(let i of t.getType().fields.byMember()){let n=i.localName;if(null!=e[n])switch(i.kind){case"oneof":let r=e[n].case;if(void 0===r)continue;let s=i.findField(r),o=e[n].value;s&&"message"==s.kind&&!Y(o,s.T)?o=new s.T(o):s&&"scalar"===s.kind&&s.T===oM.BYTES&&(o=eS(o)),t[n]={case:r,value:o};break;case"scalar":case"enum":let a=e[n];i.T===oM.BYTES&&(a=i.repeated?a.map(eS):eS(a)),t[n]=a;break;case"map":switch(i.V.kind){case"scalar":case"enum":if(i.V.T===oM.BYTES)for(let[i,r]of Object.entries(e[n]))t[n][i]=eS(r);else Object.assign(t[n],e[n]);break;case"message":let l=i.V.T;for(let i of Object.keys(e[n])){let r=e[n][i];l.fieldWrapper||(r=new l(r)),t[n][i]=r}}break;case"message":let c=i.T;if(i.repeated)t[n]=e[n].map(e=>Y(e,c)?e:new c(e));else{let i=e[n];c.fieldWrapper?"google.protobuf.BytesValue"===c.typeName?t[n]=eS(i):t[n]=i:t[n]=Y(i,c)?i:new c(i)}}}},equals:(e,t,i)=>t===i||!!t&&!!i&&e.fields.byMember().every(e=>{let n=t[e.localName],r=i[e.localName];if(e.repeated){if(n.length!==r.length)return!1;switch(e.kind){case"message":return n.every((t,i)=>e.T.equals(t,r[i]));case"scalar":return n.every((t,i)=>U(e.T,t,r[i]));case"enum":return n.every((e,t)=>U(oM.INT32,e,r[t]))}throw Error("repeated cannot contain ".concat(e.kind))}switch(e.kind){case"message":let s=n,o=r;return e.T.fieldWrapper&&(void 0===s||Y(s)||(s=e.T.fieldWrapper.wrapField(s)),void 0===o||Y(o)||(o=e.T.fieldWrapper.wrapField(o))),e.T.equals(s,o);case"enum":return U(oM.INT32,n,r);case"scalar":return U(e.T,n,r);case"oneof":if(n.case!==r.case)return!1;let a=e.findField(n.case);if(void 0===a)return!0;switch(a.kind){case"message":return a.T.equals(n.value,r.value);case"enum":return U(oM.INT32,n.value,r.value);case"scalar":return U(a.T,n.value,r.value)}throw Error("oneof cannot contain ".concat(a.kind));case"map":let l=Object.keys(n).concat(Object.keys(r));switch(e.V.kind){case"message":let c=e.V.T;return l.every(e=>c.equals(n[e],r[e]));case"enum":return l.every(e=>U(oM.INT32,n[e],r[e]));case"scalar":let d=e.V.T;return l.every(e=>U(d,n[e],r[e]))}}}),clone(e){let t=e.getType(),i=new t;for(let n of t.fields.byMember()){let t;let r=e[n.localName];if(n.repeated)t=r.map(eT);else if("map"==n.kind)for(let[e,s]of(t=i[n.localName],Object.entries(r)))t[e]=eT(s);else t="oneof"==n.kind?n.findField(r.case)?{case:r.case,value:eT(r.value)}:{case:void 0}:eT(r);i[n.localName]=t}for(let n of t.runtime.bin.listUnknownFields(e))t.runtime.bin.onUnknownField(i,n.no,n.wireType,n.data);return i}}),{newFieldList:oA,initFields:oI}),makeMessageType(e,t,i){return function(e,t,i,n){var r;let s=null!==(r=null==n?void 0:n.localName)&&void 0!==r?r:t.substring(t.lastIndexOf(".")+1),o={[s]:function(t){e.util.initFields(this),e.util.initPartial(t,this)}}[s];return Object.setPrototypeOf(o.prototype,new x),Object.assign(o,{runtime:e,typeName:t,fields:e.util.newFieldList(i),fromBinary:(e,t)=>new o().fromBinary(e,t),fromJson:(e,t)=>new o().fromJson(e,t),fromJsonString:(e,t)=>new o().fromJsonString(e,t),equals:(t,i)=>e.util.equals(o,t,i)}),o}(this,e,t,i)},makeEnum:function(e,t,i){let n={};for(let e of t){let t=P(e);n[t.localName]=t.no,n[t.no]=t.localName}return w(n,e,t),n},makeEnumType:E,getEnumType:function(e){let t=e[C];return b(t,"missing enum type on enum object"),t},makeExtension(e,t,i){var n;let r;return n=this,{typeName:e,extendee:t,get field(){if(!r){let t="function"==typeof i?i():i;t.name=e.split(".").pop(),t.jsonName="[".concat(e,"]"),r=n.util.newFieldList([t]).list()[0]}return r},runtime:n}}});class e_ extends x{constructor(e){super(),this.seconds=j.zero,this.nanos=0,eD.util.initPartial(e,this)}fromJson(e,t){if("string"!=typeof e)throw Error("cannot decode google.protobuf.Timestamp from JSON: ".concat(eD.json.debug(e)));let 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 Error("cannot decode google.protobuf.Timestamp from JSON: invalid RFC 3339 string");let n=Date.parse(i[1]+"-"+i[2]+"-"+i[3]+"T"+i[4]+":"+i[5]+":"+i[6]+(i[8]?i[8]:"Z"));if(Number.isNaN(n))throw Error("cannot decode google.protobuf.Timestamp from JSON: invalid RFC 3339 string");if(n<Date.parse("0001-01-01T00:00:00Z")||n>Date.parse("9999-12-31T23:59:59Z"))throw 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=j.parse(n/1e3),this.nanos=0,i[7]&&(this.nanos=parseInt("1"+i[7]+"0".repeat(9-i[7].length))-1e9),this}toJson(e){let t=1e3*Number(this.seconds);if(t<Date.parse("0001-01-01T00:00:00Z")||t>Date.parse("9999-12-31T23:59:59Z"))throw 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 Error("cannot encode google.protobuf.Timestamp to JSON: nanos must not be negative");let i="Z";if(this.nanos>0){let e=(this.nanos+1e9).toString().substring(1);i="000000"===e.substring(3)?"."+e.substring(0,3)+"Z":"000"===e.substring(6)?"."+e.substring(0,6)+"Z":"."+e+"Z"}return new Date(t).toISOString().replace(".000Z",i)}toDate(){return new Date(1e3*Number(this.seconds)+Math.ceil(this.nanos/1e6))}static now(){return e_.fromDate(new Date)}static fromDate(e){let t=e.getTime();return new e_({seconds:j.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 eD.util.equals(e_,e,t)}}e_.runtime=eD,e_.typeName="google.protobuf.Timestamp",e_.fields=eD.util.newFieldList(()=>[{no:1,name:"seconds",kind:"scalar",T:3},{no:2,name:"nanos",kind:"scalar",T:5}]);let eN=eD.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:eL,repeated:!0},{no:5,name:"events",kind:"message",T:eU,repeated:!0}]),eL=eD.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:ej,repeated:!0},{no:5,name:"rid",kind:"scalar",T:13}]),ej=eD.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}]),eU=eD.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}]),eF=eD.makeEnum("livekit.BackupCodecPolicy",[{no:0,name:"PREFER_REGRESSION"},{no:1,name:"SIMULCAST"},{no:2,name:"REGRESSION"}]),eV=eD.makeEnum("livekit.TrackType",[{no:0,name:"AUDIO"},{no:1,name:"VIDEO"},{no:2,name:"DATA"}]),eB=eD.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"}]),eq=eD.makeEnum("livekit.VideoQuality",[{no:0,name:"LOW"},{no:1,name:"MEDIUM"},{no:2,name:"HIGH"},{no:3,name:"OFF"}]),eW=eD.makeEnum("livekit.ConnectionQuality",[{no:0,name:"POOR"},{no:1,name:"GOOD"},{no:2,name:"EXCELLENT"},{no:3,name:"LOST"}]),ez=eD.makeEnum("livekit.ClientConfigSetting",[{no:0,name:"UNSET"},{no:1,name:"DISABLED"},{no:2,name:"ENABLED"}]),eH=eD.makeEnum("livekit.DisconnectReason",[{no:0,name:"UNKNOWN_REASON"},{no:1,name:"CLIENT_INITIATED"},{no:2,name:"DUPLICATE_IDENTITY"},{no:3,name:"SERVER_SHUTDOWN"},{no:4,name:"PARTICIPANT_REMOVED"},{no:5,name:"ROOM_DELETED"},{no:6,name:"STATE_MISMATCH"},{no:7,name:"JOIN_FAILURE"},{no:8,name:"MIGRATION"},{no:9,name:"SIGNAL_CLOSE"},{no:10,name:"ROOM_CLOSED"},{no:11,name:"USER_UNAVAILABLE"},{no:12,name:"USER_REJECTED"},{no:13,name:"SIP_TRUNK_FAILURE"},{no:14,name:"CONNECTION_TIMEOUT"},{no:15,name:"MEDIA_FAILURE"}]),eG=eD.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"}]),e$=eD.makeEnum("livekit.SubscriptionError",[{no:0,name:"SE_UNKNOWN"},{no:1,name:"SE_CODEC_UNSUPPORTED"},{no:2,name:"SE_TRACK_NOTFOUND"}]),eK=eD.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"}]),eJ=eD.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:eX,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:tv}]),eX=eD.makeMessageType("livekit.Codec",()=>[{no:1,name:"mime",kind:"scalar",T:9},{no:2,name:"fmtp_line",kind:"scalar",T:9}]),eY=eD.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:eD.getEnumType(eB),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}]),eQ=eD.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:eD.getEnumType(eZ)},{no:4,name:"tracks",kind:"message",T:e5,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:eY},{no:12,name:"region",kind:"scalar",T:9},{no:13,name:"is_publisher",kind:"scalar",T:8},{no:14,name:"kind",kind:"enum",T:eD.getEnumType(e0)},{no:15,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:16,name:"disconnect_reason",kind:"enum",T:eD.getEnumType(eH)},{no:18,name:"kind_details",kind:"enum",T:eD.getEnumType(e1),repeated:!0}]),eZ=eD.makeEnum("livekit.ParticipantInfo.State",[{no:0,name:"JOINING"},{no:1,name:"JOINED"},{no:2,name:"ACTIVE"},{no:3,name:"DISCONNECTED"}]),e0=eD.makeEnum("livekit.ParticipantInfo.Kind",[{no:0,name:"STANDARD"},{no:1,name:"INGRESS"},{no:2,name:"EGRESS"},{no:3,name:"SIP"},{no:4,name:"AGENT"}]),e1=eD.makeEnum("livekit.ParticipantInfo.KindDetail",[{no:0,name:"CLOUD_AGENT"},{no:1,name:"FORWARDED"}]),e2=eD.makeEnum("livekit.Encryption.Type",[{no:0,name:"NONE"},{no:1,name:"GCM"},{no:2,name:"CUSTOM"}]),e3=eD.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:e4,repeated:!0}]),e5=eD.makeMessageType("livekit.TrackInfo",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"type",kind:"enum",T:eD.getEnumType(eV)},{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:eD.getEnumType(eB)},{no:10,name:"layers",kind:"message",T:e4,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:e3,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:eD.getEnumType(e2)},{no:17,name:"stream",kind:"scalar",T:9},{no:18,name:"version",kind:"message",T:tv},{no:19,name:"audio_features",kind:"enum",T:eD.getEnumType(eK),repeated:!0},{no:20,name:"backup_codec_policy",kind:"enum",T:eD.getEnumType(eF)}]),e4=eD.makeMessageType("livekit.VideoLayer",()=>[{no:1,name:"quality",kind:"enum",T:eD.getEnumType(eq)},{no:2,name:"width",kind:"scalar",T:13},{no:3,name:"height",kind:"scalar",T:13},{no:4,name:"bitrate",kind:"scalar",T:13},{no:5,name:"ssrc",kind:"scalar",T:13},{no:6,name:"spatial_layer",kind:"scalar",T:5},{no:7,name:"rid",kind:"scalar",T:9}]),e6=eD.makeMessageType("livekit.DataPacket",()=>[{no:1,name:"kind",kind:"enum",T:eD.getEnumType(e9)},{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:te,oneof:"value"},{no:3,name:"speaker",kind:"message",T:e8,oneof:"value"},{no:6,name:"sip_dtmf",kind:"message",T:tt,oneof:"value"},{no:7,name:"transcription",kind:"message",T:ti,oneof:"value"},{no:8,name:"metrics",kind:"message",T:eN,oneof:"value"},{no:9,name:"chat_message",kind:"message",T:tr,oneof:"value"},{no:10,name:"rpc_request",kind:"message",T:ts,oneof:"value"},{no:11,name:"rpc_ack",kind:"message",T:to,oneof:"value"},{no:12,name:"rpc_response",kind:"message",T:ta,oneof:"value"},{no:13,name:"stream_header",kind:"message",T:tT,oneof:"value"},{no:14,name:"stream_chunk",kind:"message",T:tS,oneof:"value"},{no:15,name:"stream_trailer",kind:"message",T:tC,oneof:"value"},{no:16,name:"sequence",kind:"scalar",T:13},{no:17,name:"participant_sid",kind:"scalar",T:9}]),e9=eD.makeEnum("livekit.DataPacket.Kind",[{no:0,name:"RELIABLE"},{no:1,name:"LOSSY"}]),e8=eD.makeMessageType("livekit.ActiveSpeakerUpdate",()=>[{no:1,name:"speakers",kind:"message",T:e7,repeated:!0}]),e7=eD.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}]),te=eD.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}]),tt=eD.makeMessageType("livekit.SipDTMF",()=>[{no:3,name:"code",kind:"scalar",T:13},{no:4,name:"digit",kind:"scalar",T:9}]),ti=eD.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:tn,repeated:!0}]),tn=eD.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}]),tr=eD.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}]),ts=eD.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}]),to=eD.makeMessageType("livekit.RpcAck",()=>[{no:1,name:"request_id",kind:"scalar",T:9}]),ta=eD.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:tl,oneof:"value"}]),tl=eD.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}]),tc=eD.makeMessageType("livekit.ParticipantTracks",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"track_sids",kind:"scalar",T:9,repeated:!0}]),td=eD.makeMessageType("livekit.ServerInfo",()=>[{no:1,name:"edition",kind:"enum",T:eD.getEnumType(tu)},{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}]),tu=eD.makeEnum("livekit.ServerInfo.Edition",[{no:0,name:"Standard"},{no:1,name:"Cloud"}]),th=eD.makeMessageType("livekit.ClientInfo",()=>[{no:1,name:"sdk",kind:"enum",T:eD.getEnumType(tp)},{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}]),tp=eD.makeEnum("livekit.ClientInfo.SDK",[{no:0,name:"UNKNOWN"},{no:1,name:"JS"},{no:2,name:"SWIFT"},{no:3,name:"ANDROID"},{no:4,name:"FLUTTER"},{no:5,name:"GO"},{no:6,name:"UNITY"},{no:7,name:"REACT_NATIVE"},{no:8,name:"RUST"},{no:9,name:"PYTHON"},{no:10,name:"CPP"},{no:11,name:"UNITY_WEB"},{no:12,name:"NODE"},{no:13,name:"UNREAL"},{no:14,name:"ESP32"}]),tm=eD.makeMessageType("livekit.ClientConfiguration",()=>[{no:1,name:"video",kind:"message",T:tf},{no:2,name:"screen",kind:"message",T:tf},{no:3,name:"resume_connection",kind:"enum",T:eD.getEnumType(ez)},{no:4,name:"disabled_codecs",kind:"message",T:tg},{no:5,name:"force_relay",kind:"enum",T:eD.getEnumType(ez)}]),tf=eD.makeMessageType("livekit.VideoConfiguration",()=>[{no:1,name:"hardware_encoder",kind:"enum",T:eD.getEnumType(ez)}]),tg=eD.makeMessageType("livekit.DisabledCodecs",()=>[{no:1,name:"codecs",kind:"message",T:eX,repeated:!0},{no:2,name:"publish",kind:"message",T:eX,repeated:!0}]),tv=eD.makeMessageType("livekit.TimedVersion",()=>[{no:1,name:"unix_micro",kind:"scalar",T:3},{no:2,name:"ticks",kind:"scalar",T:5}]),ty=eD.makeEnum("livekit.DataStream.OperationType",[{no:0,name:"CREATE"},{no:1,name:"UPDATE"},{no:2,name:"DELETE"},{no:3,name:"REACTION"}]),tb=eD.makeMessageType("livekit.DataStream.TextHeader",()=>[{no:1,name:"operation_type",kind:"enum",T:eD.getEnumType(ty)},{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"}),tk=eD.makeMessageType("livekit.DataStream.ByteHeader",()=>[{no:1,name:"name",kind:"scalar",T:9}],{localName:"DataStream_ByteHeader"}),tT=eD.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:eD.getEnumType(e2)},{no:8,name:"attributes",kind:"map",K:9,V:{kind:"scalar",T:9}},{no:9,name:"text_header",kind:"message",T:tb,oneof:"content_header"},{no:10,name:"byte_header",kind:"message",T:tk,oneof:"content_header"}],{localName:"DataStream_Header"}),tS=eD.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"}),tC=eD.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"}),tw=eD.makeEnum("livekit.SignalTarget",[{no:0,name:"PUBLISHER"},{no:1,name:"SUBSCRIBER"}]),tE=eD.makeEnum("livekit.StreamState",[{no:0,name:"ACTIVE"},{no:1,name:"PAUSED"}]),tP=eD.makeEnum("livekit.CandidateProtocol",[{no:0,name:"UDP"},{no:1,name:"TCP"},{no:2,name:"TLS"}]),tx=eD.makeMessageType("livekit.SignalRequest",()=>[{no:1,name:"offer",kind:"message",T:tj,oneof:"message"},{no:2,name:"answer",kind:"message",T:tj,oneof:"message"},{no:3,name:"trickle",kind:"message",T:tI,oneof:"message"},{no:4,name:"add_track",kind:"message",T:tA,oneof:"message"},{no:5,name:"mute",kind:"message",T:tM,oneof:"message"},{no:6,name:"subscription",kind:"message",T:tF,oneof:"message"},{no:7,name:"track_setting",kind:"message",T:tV,oneof:"message"},{no:8,name:"leave",kind:"message",T:tW,oneof:"message"},{no:10,name:"update_layers",kind:"message",T:tH,oneof:"message"},{no:11,name:"subscription_permission",kind:"message",T:t5,oneof:"message"},{no:12,name:"sync_state",kind:"message",T:t9,oneof:"message"},{no:13,name:"simulate",kind:"message",T:ie,oneof:"message"},{no:14,name:"ping",kind:"scalar",T:3,oneof:"message"},{no:15,name:"update_metadata",kind:"message",T:tG,oneof:"message"},{no:16,name:"ping_req",kind:"message",T:it,oneof:"message"},{no:17,name:"update_audio_track",kind:"message",T:tB,oneof:"message"},{no:18,name:"update_video_track",kind:"message",T:tq,oneof:"message"}]),tR=eD.makeMessageType("livekit.SignalResponse",()=>[{no:1,name:"join",kind:"message",T:tD,oneof:"message"},{no:2,name:"answer",kind:"message",T:tj,oneof:"message"},{no:3,name:"offer",kind:"message",T:tj,oneof:"message"},{no:4,name:"trickle",kind:"message",T:tI,oneof:"message"},{no:5,name:"update",kind:"message",T:tU,oneof:"message"},{no:6,name:"track_published",kind:"message",T:tN,oneof:"message"},{no:8,name:"leave",kind:"message",T:tW,oneof:"message"},{no:9,name:"mute",kind:"message",T:tM,oneof:"message"},{no:10,name:"speakers_changed",kind:"message",T:tK,oneof:"message"},{no:11,name:"room_update",kind:"message",T:tJ,oneof:"message"},{no:12,name:"connection_quality",kind:"message",T:tY,oneof:"message"},{no:13,name:"stream_state_update",kind:"message",T:tZ,oneof:"message"},{no:14,name:"subscribed_quality_update",kind:"message",T:t2,oneof:"message"},{no:15,name:"subscription_permission_update",kind:"message",T:t4,oneof:"message"},{no:16,name:"refresh_token",kind:"scalar",T:9,oneof:"message"},{no:17,name:"track_unpublished",kind:"message",T:tL,oneof:"message"},{no:18,name:"pong",kind:"scalar",T:3,oneof:"message"},{no:19,name:"reconnect",kind:"message",T:t_,oneof:"message"},{no:20,name:"pong_resp",kind:"message",T:ii,oneof:"message"},{no:21,name:"subscription_response",kind:"message",T:io,oneof:"message"},{no:22,name:"request_response",kind:"message",T:ia,oneof:"message"},{no:23,name:"track_subscribed",kind:"message",T:ic,oneof:"message"},{no:24,name:"room_moved",kind:"message",T:t6,oneof:"message"}]),tO=eD.makeMessageType("livekit.SimulcastCodec",()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"cid",kind:"scalar",T:9}]),tA=eD.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:eD.getEnumType(eV)},{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:eD.getEnumType(eB)},{no:9,name:"layers",kind:"message",T:e4,repeated:!0},{no:10,name:"simulcast_codecs",kind:"message",T:tO,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:eD.getEnumType(e2)},{no:15,name:"stream",kind:"scalar",T:9},{no:16,name:"backup_codec_policy",kind:"enum",T:eD.getEnumType(eF)},{no:17,name:"audio_features",kind:"enum",T:eD.getEnumType(eK),repeated:!0}]),tI=eD.makeMessageType("livekit.TrickleRequest",()=>[{no:1,name:"candidateInit",kind:"scalar",T:9},{no:2,name:"target",kind:"enum",T:eD.getEnumType(tw)},{no:3,name:"final",kind:"scalar",T:8}]),tM=eD.makeMessageType("livekit.MuteTrackRequest",()=>[{no:1,name:"sid",kind:"scalar",T:9},{no:2,name:"muted",kind:"scalar",T:8}]),tD=eD.makeMessageType("livekit.JoinResponse",()=>[{no:1,name:"room",kind:"message",T:eJ},{no:2,name:"participant",kind:"message",T:eQ},{no:3,name:"other_participants",kind:"message",T:eQ,repeated:!0},{no:4,name:"server_version",kind:"scalar",T:9},{no:5,name:"ice_servers",kind:"message",T:t$,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:tm},{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:td},{no:13,name:"sif_trailer",kind:"scalar",T:12},{no:14,name:"enabled_publish_codecs",kind:"message",T:eX,repeated:!0},{no:15,name:"fast_publish",kind:"scalar",T:8}]),t_=eD.makeMessageType("livekit.ReconnectResponse",()=>[{no:1,name:"ice_servers",kind:"message",T:t$,repeated:!0},{no:2,name:"client_configuration",kind:"message",T:tm},{no:3,name:"server_info",kind:"message",T:td},{no:4,name:"last_message_seq",kind:"scalar",T:13}]),tN=eD.makeMessageType("livekit.TrackPublishedResponse",()=>[{no:1,name:"cid",kind:"scalar",T:9},{no:2,name:"track",kind:"message",T:e5}]),tL=eD.makeMessageType("livekit.TrackUnpublishedResponse",()=>[{no:1,name:"track_sid",kind:"scalar",T:9}]),tj=eD.makeMessageType("livekit.SessionDescription",()=>[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"sdp",kind:"scalar",T:9},{no:3,name:"id",kind:"scalar",T:13}]),tU=eD.makeMessageType("livekit.ParticipantUpdate",()=>[{no:1,name:"participants",kind:"message",T:eQ,repeated:!0}]),tF=eD.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:tc,repeated:!0}]),tV=eD.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:eD.getEnumType(eq)},{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}]),tB=eD.makeMessageType("livekit.UpdateLocalAudioTrack",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"features",kind:"enum",T:eD.getEnumType(eK),repeated:!0}]),tq=eD.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}]),tW=eD.makeMessageType("livekit.LeaveRequest",()=>[{no:1,name:"can_reconnect",kind:"scalar",T:8},{no:2,name:"reason",kind:"enum",T:eD.getEnumType(eH)},{no:3,name:"action",kind:"enum",T:eD.getEnumType(tz)},{no:4,name:"regions",kind:"message",T:ir}]),tz=eD.makeEnum("livekit.LeaveRequest.Action",[{no:0,name:"DISCONNECT"},{no:1,name:"RESUME"},{no:2,name:"RECONNECT"}]),tH=eD.makeMessageType("livekit.UpdateVideoLayers",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"layers",kind:"message",T:e4,repeated:!0}]),tG=eD.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}]),t$=eD.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}]),tK=eD.makeMessageType("livekit.SpeakersChanged",()=>[{no:1,name:"speakers",kind:"message",T:e7,repeated:!0}]),tJ=eD.makeMessageType("livekit.RoomUpdate",()=>[{no:1,name:"room",kind:"message",T:eJ}]),tX=eD.makeMessageType("livekit.ConnectionQualityInfo",()=>[{no:1,name:"participant_sid",kind:"scalar",T:9},{no:2,name:"quality",kind:"enum",T:eD.getEnumType(eW)},{no:3,name:"score",kind:"scalar",T:2}]),tY=eD.makeMessageType("livekit.ConnectionQualityUpdate",()=>[{no:1,name:"updates",kind:"message",T:tX,repeated:!0}]),tQ=eD.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:eD.getEnumType(tE)}]),tZ=eD.makeMessageType("livekit.StreamStateUpdate",()=>[{no:1,name:"stream_states",kind:"message",T:tQ,repeated:!0}]),t0=eD.makeMessageType("livekit.SubscribedQuality",()=>[{no:1,name:"quality",kind:"enum",T:eD.getEnumType(eq)},{no:2,name:"enabled",kind:"scalar",T:8}]),t1=eD.makeMessageType("livekit.SubscribedCodec",()=>[{no:1,name:"codec",kind:"scalar",T:9},{no:2,name:"qualities",kind:"message",T:t0,repeated:!0}]),t2=eD.makeMessageType("livekit.SubscribedQualityUpdate",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"subscribed_qualities",kind:"message",T:t0,repeated:!0},{no:3,name:"subscribed_codecs",kind:"message",T:t1,repeated:!0}]),t3=eD.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}]),t5=eD.makeMessageType("livekit.SubscriptionPermission",()=>[{no:1,name:"all_participants",kind:"scalar",T:8},{no:2,name:"track_permissions",kind:"message",T:t3,repeated:!0}]),t4=eD.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}]),t6=eD.makeMessageType("livekit.RoomMovedResponse",()=>[{no:1,name:"room",kind:"message",T:eJ},{no:2,name:"token",kind:"scalar",T:9},{no:3,name:"participant",kind:"message",T:eQ},{no:4,name:"other_participants",kind:"message",T:eQ,repeated:!0}]),t9=eD.makeMessageType("livekit.SyncState",()=>[{no:1,name:"answer",kind:"message",T:tj},{no:2,name:"subscription",kind:"message",T:tF},{no:3,name:"publish_tracks",kind:"message",T:tN,repeated:!0},{no:4,name:"data_channels",kind:"message",T:t7,repeated:!0},{no:5,name:"offer",kind:"message",T:tj},{no:6,name:"track_sids_disabled",kind:"scalar",T:9,repeated:!0},{no:7,name:"datachannel_receive_states",kind:"message",T:t8,repeated:!0}]),t8=eD.makeMessageType("livekit.DataChannelReceiveState",()=>[{no:1,name:"publisher_sid",kind:"scalar",T:9},{no:2,name:"last_seq",kind:"scalar",T:13}]),t7=eD.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:eD.getEnumType(tw)}]),ie=eD.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:eD.getEnumType(tP),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"}]),it=eD.makeMessageType("livekit.Ping",()=>[{no:1,name:"timestamp",kind:"scalar",T:3},{no:2,name:"rtt",kind:"scalar",T:3}]),ii=eD.makeMessageType("livekit.Pong",()=>[{no:1,name:"last_ping_timestamp",kind:"scalar",T:3},{no:2,name:"timestamp",kind:"scalar",T:3}]),ir=eD.makeMessageType("livekit.RegionSettings",()=>[{no:1,name:"regions",kind:"message",T:is,repeated:!0}]),is=eD.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}]),io=eD.makeMessageType("livekit.SubscriptionResponse",()=>[{no:1,name:"track_sid",kind:"scalar",T:9},{no:2,name:"err",kind:"enum",T:eD.getEnumType(e$)}]),ia=eD.makeMessageType("livekit.RequestResponse",()=>[{no:1,name:"request_id",kind:"scalar",T:13},{no:2,name:"reason",kind:"enum",T:eD.getEnumType(il)},{no:3,name:"message",kind:"scalar",T:9}]),il=eD.makeEnum("livekit.RequestResponse.Reason",[{no:0,name:"OK"},{no:1,name:"NOT_FOUND"},{no:2,name:"NOT_ALLOWED"},{no:3,name:"LIMIT_EXCEEDED"}]),ic=eD.makeMessageType("livekit.TrackSubscribed",()=>[{no:1,name:"track_sid",kind:"scalar",T:9}]);var id={exports:{}},iu=id.exports,ih=function(){var e;return oN||(oN=1,e=function(){var e=function(){},t="undefined",i=typeof window!==t&&typeof window.navigator!==t&&/Trident\/|MSIE /.test(window.navigator.userAgent),n=["trace","debug","info","warn","error"],r={},s=null;function o(e,t){var i=e[t];if("function"==typeof i.bind)return i.bind(e);try{return Function.prototype.bind.call(i,e)}catch(t){return function(){return Function.prototype.apply.apply(i,[e,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 l(){for(var i=this.getLevel(),r=0;r<n.length;r++){var s=n[r];this[s]=r<i?e:this.methodFactory(s,i,this.name)}if(this.log=this.debug,typeof console===t&&i<this.levels.SILENT)return"No console available for logging"}function c(e){return function(){typeof console!==t&&(l.call(this),this[e].apply(this,arguments))}}function d(n,r,s){var l;return"debug"===(l=n)&&(l="log"),typeof console!==t&&("trace"===l&&i?a:void 0!==console[l]?o(console,l):void 0!==console.log?o(console,"log"):e)||c.apply(this,arguments)}function u(e,i){var o,a,c,u=this,h="loglevel";function p(){var e;if(typeof window!==t&&h){try{e=window.localStorage[h]}catch(e){}if(typeof e===t)try{var i=window.document.cookie,n=encodeURIComponent(h),r=i.indexOf(n+"=");-1!==r&&(e=/^([^;]+)/.exec(i.slice(r+n.length+1))[1])}catch(e){}return void 0===u.levels[e]&&(e=void 0),e}}function m(e){var t=e;if("string"==typeof t&&void 0!==u.levels[t.toUpperCase()]&&(t=u.levels[t.toUpperCase()]),"number"==typeof t&&t>=0&&t<=u.levels.SILENT)return t;throw TypeError("log.setLevel() called with invalid level: "+e)}"string"==typeof e?h+=":"+e:"symbol"==typeof e&&(h=void 0),u.name=e,u.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},u.methodFactory=i||d,u.getLevel=function(){return null!=c?c:null!=a?a:o},u.setLevel=function(e,i){return c=m(e),!1!==i&&function(e){var i=(n[e]||"silent").toUpperCase();if(typeof window!==t&&h){try{window.localStorage[h]=i;return}catch(e){}try{window.document.cookie=encodeURIComponent(h)+"="+i+";"}catch(e){}}}(c),l.call(u)},u.setDefaultLevel=function(e){a=m(e),p()||u.setLevel(e,!1)},u.resetLevel=function(){c=null,function(){if(typeof window!==t&&h){try{window.localStorage.removeItem(h)}catch(e){}try{window.document.cookie=encodeURIComponent(h)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch(e){}}}(),l.call(u)},u.enableAll=function(e){u.setLevel(u.levels.TRACE,e)},u.disableAll=function(e){u.setLevel(u.levels.SILENT,e)},u.rebuild=function(){if(s!==u&&(o=m(s.getLevel())),l.call(u),s===u)for(var e in r)r[e].rebuild()},o=m(s?s.getLevel():"WARN");var f=p();null!=f&&(c=m(f)),l.call(u)}(s=new u).getLogger=function(e){if("symbol"!=typeof e&&"string"!=typeof e||""===e)throw TypeError("You must supply a name when creating a logger.");var t=r[e];return t||(t=r[e]=new u(e,s.methodFactory)),t};var h=typeof window!==t?window.log:void 0;return s.noConflict=function(){return typeof window!==t&&window.log===s&&(window.log=h),s},s.getLoggers=function(){return r},s.default=s,s},id.exports?id.exports=e():iu.log=e()),id.exports}();(function(e){e[e.trace=0]="trace",e[e.debug=1]="debug",e[e.info=2]="info",e[e.warn=3]="warn",e[e.error=4]="error",e[e.silent=5]="silent"})(oL||(oL={})),function(e){e.Default="livekit",e.Room="livekit-room",e.Participant="livekit-participant",e.Track="livekit-track",e.Publication="livekit-track-publication",e.Engine="livekit-engine",e.Signal="livekit-signal",e.PCManager="livekit-pc-manager",e.PCTransport="livekit-pc-transport",e.E2EE="lk-e2ee"}(oj||(oj={}));let ip=ih.getLogger("livekit");function im(e){let t=ih.getLogger(e);return t.setDefaultLevel(ip.getLevel()),t}Object.values(oj).map(e=>ih.getLogger(e)),ip.setDefaultLevel(oL.info);let ig=ih.getLogger("lk-e2ee"),iv=[0,300,1200,2700,4800,7e3,7e3,7e3,7e3,7e3];class iy{constructor(e){this._retryDelays=void 0!==e?[...e]:iv}nextRetryDelayInMs(e){if(e.retryCount>=this._retryDelays.length)return null;let t=this._retryDelays[e.retryCount];return e.retryCount<=1?t:t+1e3*Math.random()}}function ib(e,t,i,n){return new(i||(i=Promise))(function(r,s){function o(e){try{l(n.next(e))}catch(e){s(e)}}function a(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):((t=e.value)instanceof i?t:new i(function(e){e(t)})).then(o,a)}l((n=n.apply(e,t||[])).next())})}function ik(e){if(!Symbol.asyncIterator)throw TypeError("Symbol.asyncIterator is not defined.");var t,i=e[Symbol.asyncIterator];return i?i.call(e):(e=function(e){var t="function"==typeof Symbol&&Symbol.iterator,i=t&&e[t],n=0;if(i)return i.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}(e),t={},n("next"),n("throw"),n("return"),t[Symbol.asyncIterator]=function(){return this},t);function n(i){t[i]=e[i]&&function(t){return new Promise(function(n,r){(function(e,t,i,n){Promise.resolve(n).then(function(t){e({value:t,done:i})},t)})(n,r,(t=e[i](t)).done,t.value)})}}}"function"==typeof SuppressedError&&SuppressedError;var iT={exports:{}},iS=function(){if(oU)return iT.exports;oU=1;var e,t="object"==typeof Reflect?Reflect:null,i=t&&"function"==typeof t.apply?t.apply:function(e,t,i){return Function.prototype.apply.call(e,t,i)};e=t&&"function"==typeof t.ownKeys?t.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var n=Number.isNaN||function(e){return e!=e};function r(){r.init.call(this)}iT.exports=r,iT.exports.once=function(e,t){return new Promise(function(i,n){var r;function s(i){e.removeListener(t,o),n(i)}function o(){"function"==typeof e.removeListener&&e.removeListener("error",s),i([].slice.call(arguments))}m(e,t,o,{once:!0}),"error"!==t&&(r={once:!0},"function"==typeof e.on&&m(e,"error",s,r))})},r.EventEmitter=r,r.prototype._events=void 0,r.prototype._eventsCount=0,r.prototype._maxListeners=void 0;var s=10;function o(e){if("function"!=typeof e)throw TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function a(e){return void 0===e._maxListeners?r.defaultMaxListeners:e._maxListeners}function l(e,t,i,n){if(o(i),void 0===(s=e._events)?(s=e._events=Object.create(null),e._eventsCount=0):(void 0!==s.newListener&&(e.emit("newListener",t,i.listener?i.listener:i),s=e._events),l=s[t]),void 0===l)l=s[t]=i,++e._eventsCount;else if("function"==typeof l?l=s[t]=n?[i,l]:[l,i]:n?l.unshift(i):l.push(i),(r=a(e))>0&&l.length>r&&!l.warned){l.warned=!0;var r,s,l,c=Error("Possible EventEmitter memory leak detected. "+l.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");c.name="MaxListenersExceededWarning",c.emitter=e,c.type=t,c.count=l.length,console&&console.warn&&console.warn(c)}return e}function c(){if(!this.fired)return(this.target.removeListener(this.type,this.wrapFn),this.fired=!0,0==arguments.length)?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function d(e,t,i){var n={fired:!1,wrapFn:void 0,target:e,type:t,listener:i},r=c.bind(n);return r.listener=i,n.wrapFn=r,r}function u(e,t,i){var n=e._events;if(void 0===n)return[];var r=n[t];return void 0===r?[]:"function"==typeof r?i?[r.listener||r]:[r]:i?function(e){for(var t=Array(e.length),i=0;i<t.length;++i)t[i]=e[i].listener||e[i];return t}(r):p(r,r.length)}function h(e){var t=this._events;if(void 0!==t){var i=t[e];if("function"==typeof i)return 1;if(void 0!==i)return i.length}return 0}function p(e,t){for(var i=Array(t),n=0;n<t;++n)i[n]=e[n];return i}function m(e,t,i,n){if("function"==typeof e.on)n.once?e.once(t,i):e.on(t,i);else if("function"==typeof e.addEventListener)e.addEventListener(t,function r(s){n.once&&e.removeEventListener(t,r),i(s)});else throw TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof e)}return Object.defineProperty(r,"defaultMaxListeners",{enumerable:!0,get:function(){return s},set:function(e){if("number"!=typeof e||e<0||n(e))throw RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+e+".");s=e}}),r.init=function(){(void 0===this._events||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},r.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||n(e))throw RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+e+".");return this._maxListeners=e,this},r.prototype.getMaxListeners=function(){return a(this)},r.prototype.emit=function(e){for(var t=[],n=1;n<arguments.length;n++)t.push(arguments[n]);var r="error"===e,s=this._events;if(void 0!==s)r=r&&void 0===s.error;else if(!r)return!1;if(r){if(t.length>0&&(o=t[0]),o instanceof Error)throw o;var o,a=Error("Unhandled error."+(o?" ("+o.message+")":""));throw a.context=o,a}var l=s[e];if(void 0===l)return!1;if("function"==typeof l)i(l,this,t);else for(var c=l.length,d=p(l,c),n=0;n<c;++n)i(d[n],this,t);return!0},r.prototype.addListener=function(e,t){return l(this,e,t,!1)},r.prototype.on=r.prototype.addListener,r.prototype.prependListener=function(e,t){return l(this,e,t,!0)},r.prototype.once=function(e,t){return o(t),this.on(e,d(this,e,t)),this},r.prototype.prependOnceListener=function(e,t){return o(t),this.prependListener(e,d(this,e,t)),this},r.prototype.removeListener=function(e,t){var i,n,r,s,a;if(o(t),void 0===(n=this._events)||void 0===(i=n[e]))return this;if(i===t||i.listener===t)0==--this._eventsCount?this._events=Object.create(null):(delete n[e],n.removeListener&&this.emit("removeListener",e,i.listener||t));else if("function"!=typeof i){for(r=-1,s=i.length-1;s>=0;s--)if(i[s]===t||i[s].listener===t){a=i[s].listener,r=s;break}if(r<0)return this;0===r?i.shift():function(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}(i,r),1===i.length&&(n[e]=i[0]),void 0!==n.removeListener&&this.emit("removeListener",e,a||t)}return this},r.prototype.off=r.prototype.removeListener,r.prototype.removeAllListeners=function(e){var t,i,n;if(void 0===(i=this._events))return this;if(void 0===i.removeListener)return 0==arguments.length?(this._events=Object.create(null),this._eventsCount=0):void 0!==i[e]&&(0==--this._eventsCount?this._events=Object.create(null):delete i[e]),this;if(0==arguments.length){var r,s=Object.keys(i);for(n=0;n<s.length;++n)"removeListener"!==(r=s[n])&&this.removeAllListeners(r);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if("function"==typeof(t=i[e]))this.removeListener(e,t);else if(void 0!==t)for(n=t.length-1;n>=0;n--)this.removeListener(e,t[n]);return this},r.prototype.listeners=function(e){return u(this,e,!0)},r.prototype.rawListeners=function(e){return u(this,e,!1)},r.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):h.call(e,t)},r.prototype.listenerCount=h,r.prototype.eventNames=function(){return this._eventsCount>0?e(this._events):[]},iT.exports}();let iC=!0,iw=!0;function iE(e,t,i){let n=e.match(t);return n&&n.length>=i&&parseFloat(n[i],10)}function iP(e,t,i){if(!e.RTCPeerConnection)return;let n=e.RTCPeerConnection.prototype,r=n.addEventListener;n.addEventListener=function(e,n){if(e!==t)return r.apply(this,arguments);let s=e=>{let t=i(e);t&&(n.handleEvent?n.handleEvent(t):n(t))};return this._eventMap=this._eventMap||{},this._eventMap[t]||(this._eventMap[t]=new Map),this._eventMap[t].set(n,s),r.apply(this,[e,s])};let s=n.removeEventListener;n.removeEventListener=function(e,i){if(e!==t||!this._eventMap||!this._eventMap[t]||!this._eventMap[t].has(i))return s.apply(this,arguments);let n=this._eventMap[t].get(i);return this._eventMap[t].delete(i),0===this._eventMap[t].size&&delete this._eventMap[t],0===Object.keys(this._eventMap).length&&delete this._eventMap,s.apply(this,[e,n])},Object.defineProperty(n,"on"+t,{get(){return this["_on"+t]},set(e){this["_on"+t]&&(this.removeEventListener(t,this["_on"+t]),delete this["_on"+t]),e&&this.addEventListener(t,this["_on"+t]=e)},enumerable:!0,configurable:!0})}function ix(e){return"boolean"!=typeof e?Error("Argument type: "+typeof e+". Please use a boolean."):(iC=e,e?"adapter.js logging disabled":"adapter.js logging enabled")}function iR(e){return"boolean"!=typeof e?Error("Argument type: "+typeof e+". Please use a boolean."):(iw=!e,"adapter.js deprecation warnings "+(e?"disabled":"enabled"))}function iO(){"object"!=typeof window||iC||"undefined"==typeof console||"function"!=typeof console.log||console.log.apply(console,arguments)}function iA(e,t){iw&&console.warn(e+" is deprecated, please use "+t+" instead.")}function iI(e){return"[object Object]"===Object.prototype.toString.call(e)}function iM(e,t,i){let n=i?"outbound-rtp":"inbound-rtp",r=new Map;if(null===t)return r;let s=[];return e.forEach(e=>{"track"===e.type&&e.trackIdentifier===t.id&&s.push(e)}),s.forEach(t=>{e.forEach(i=>{i.type===n&&i.trackId===t.id&&function e(t,i,n){!i||n.has(i.id)||(n.set(i.id,i),Object.keys(i).forEach(r=>{r.endsWith("Id")?e(t,t.get(i[r]),n):r.endsWith("Ids")&&i[r].forEach(i=>{e(t,t.get(i),n)})}))}(e,i,r)})}),r}function iD(e,t){let i=e&&e.navigator;if(!i.mediaDevices)return;let n=function(e){if("object"!=typeof e||e.mandatory||e.optional)return e;let t={};return Object.keys(e).forEach(i=>{if("require"===i||"advanced"===i||"mediaSource"===i)return;let n="object"==typeof e[i]?e[i]:{ideal:e[i]};void 0!==n.exact&&"number"==typeof n.exact&&(n.min=n.max=n.exact);let r=function(e,t){return e?e+t.charAt(0).toUpperCase()+t.slice(1):"deviceId"===t?"sourceId":t};if(void 0!==n.ideal){t.optional=t.optional||[];let e={};"number"==typeof n.ideal?(e[r("min",i)]=n.ideal,t.optional.push(e),(e={})[r("max",i)]=n.ideal):e[r("",i)]=n.ideal,t.optional.push(e)}void 0!==n.exact&&"number"!=typeof n.exact?(t.mandatory=t.mandatory||{},t.mandatory[r("",i)]=n.exact):["min","max"].forEach(e=>{void 0!==n[e]&&(t.mandatory=t.mandatory||{},t.mandatory[r(e,i)]=n[e])})}),e.advanced&&(t.optional=(t.optional||[]).concat(e.advanced)),t},r=function(e,r){if(t.version>=61)return r(e);if((e=JSON.parse(JSON.stringify(e)))&&"object"==typeof e.audio){let t=function(e,t,i){t in e&&!(i in e)&&(e[i]=e[t],delete e[t])};t((e=JSON.parse(JSON.stringify(e))).audio,"autoGainControl","googAutoGainControl"),t(e.audio,"noiseSuppression","googNoiseSuppression"),e.audio=n(e.audio)}if(e&&"object"==typeof e.video){let s=e.video.facingMode;s=s&&("object"==typeof s?s:{ideal:s});let o=t.version<66;if(s&&("user"===s.exact||"environment"===s.exact||"user"===s.ideal||"environment"===s.ideal)&&!(i.mediaDevices.getSupportedConstraints&&i.mediaDevices.getSupportedConstraints().facingMode&&!o)){let t;if(delete e.video.facingMode,"environment"===s.exact||"environment"===s.ideal?t=["back","rear"]:("user"===s.exact||"user"===s.ideal)&&(t=["front"]),t)return i.mediaDevices.enumerateDevices().then(i=>{let o=(i=i.filter(e=>"videoinput"===e.kind)).find(e=>t.some(t=>e.label.toLowerCase().includes(t)));return!o&&i.length&&t.includes("back")&&(o=i[i.length-1]),o&&(e.video.deviceId=s.exact?{exact:o.deviceId}:{ideal:o.deviceId}),e.video=n(e.video),iO("chrome: "+JSON.stringify(e)),r(e)})}e.video=n(e.video)}return iO("chrome: "+JSON.stringify(e)),r(e)},s=function(e){return t.version>=64?e:{name:({PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"})[e.name]||e.name,message:e.message,constraint:e.constraint||e.constraintName,toString(){return this.name+(this.message&&": ")+this.message}}};if(i.getUserMedia=(function(e,t,n){r(e,e=>{i.webkitGetUserMedia(e,t,e=>{n&&n(s(e))})})}).bind(i),i.mediaDevices.getUserMedia){let e=i.mediaDevices.getUserMedia.bind(i.mediaDevices);i.mediaDevices.getUserMedia=function(t){return r(t,t=>e(t).then(e=>{if(t.audio&&!e.getAudioTracks().length||t.video&&!e.getVideoTracks().length)throw e.getTracks().forEach(e=>{e.stop()}),new DOMException("","NotFoundError");return e},e=>Promise.reject(s(e))))}}}function i_(e){e.MediaStream=e.MediaStream||e.webkitMediaStream}function iN(e){if("object"!=typeof e||!e.RTCPeerConnection||"ontrack"in e.RTCPeerConnection.prototype)iP(e,"track",e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e));else{Object.defineProperty(e.RTCPeerConnection.prototype,"ontrack",{get(){return this._ontrack},set(e){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=e)},enumerable:!0,configurable:!0});let t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=t=>{t.stream.addEventListener("addtrack",i=>{let n;n=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find(e=>e.track&&e.track.id===i.track.id):{track:i.track};let r=new Event("track");r.track=i.track,r.receiver=n,r.transceiver={receiver:n},r.streams=[t.stream],this.dispatchEvent(r)}),t.stream.getTracks().forEach(i=>{let n;n=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find(e=>e.track&&e.track.id===i.id):{track:i};let r=new Event("track");r.track=i,r.receiver=n,r.transceiver={receiver:n},r.streams=[t.stream],this.dispatchEvent(r)})},this.addEventListener("addstream",this._ontrackpoly)),t.apply(this,arguments)}}}function iL(e){if("object"==typeof e&&e.RTCPeerConnection&&!("getSenders"in e.RTCPeerConnection.prototype)&&"createDTMFSender"in e.RTCPeerConnection.prototype){let t=function(e,t){return{track:t,get dtmf(){return void 0===this._dtmf&&("audio"===t.kind?this._dtmf=e.createDTMFSender(t):this._dtmf=null),this._dtmf},_pc:e}};if(!e.RTCPeerConnection.prototype.getSenders){e.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};let i=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,n){let r=i.apply(this,arguments);return r||(r=t(this,e),this._senders.push(r)),r};let n=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){n.apply(this,arguments);let t=this._senders.indexOf(e);-1!==t&&this._senders.splice(t,1)}}let i=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._senders=this._senders||[],i.apply(this,[e]),e.getTracks().forEach(e=>{this._senders.push(t(this,e))})};let n=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){this._senders=this._senders||[],n.apply(this,[e]),e.getTracks().forEach(e=>{let t=this._senders.find(t=>t.track===e);t&&this._senders.splice(this._senders.indexOf(t),1)})}}else if("object"==typeof e&&e.RTCPeerConnection&&"getSenders"in e.RTCPeerConnection.prototype&&"createDTMFSender"in e.RTCPeerConnection.prototype&&e.RTCRtpSender&&!("dtmf"in e.RTCRtpSender.prototype)){let t=e.RTCPeerConnection.prototype.getSenders;e.RTCPeerConnection.prototype.getSenders=function(){let e=t.apply(this,[]);return e.forEach(e=>e._pc=this),e},Object.defineProperty(e.RTCRtpSender.prototype,"dtmf",{get(){return void 0===this._dtmf&&("audio"===this.track.kind?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}})}}function ij(e){if(!("object"==typeof e&&e.RTCPeerConnection&&e.RTCRtpSender&&e.RTCRtpReceiver))return;if(!("getStats"in e.RTCRtpSender.prototype)){let t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){let e=t.apply(this,[]);return e.forEach(e=>e._pc=this),e});let i=e.RTCPeerConnection.prototype.addTrack;i&&(e.RTCPeerConnection.prototype.addTrack=function(){let e=i.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){let e=this;return this._pc.getStats().then(t=>iM(t,e.track,!0))}}if(!("getStats"in e.RTCRtpReceiver.prototype)){let t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){let e=t.apply(this,[]);return e.forEach(e=>e._pc=this),e}),iP(e,"track",e=>(e.receiver._pc=e.srcElement,e)),e.RTCRtpReceiver.prototype.getStats=function(){let e=this;return this._pc.getStats().then(t=>iM(t,e.track,!1))}}if(!("getStats"in e.RTCRtpSender.prototype&&"getStats"in e.RTCRtpReceiver.prototype))return;let t=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof e.MediaStreamTrack){let e,t,i;let n=arguments[0];return(this.getSenders().forEach(t=>{t.track===n&&(e?i=!0:e=t)}),this.getReceivers().forEach(e=>(e.track===n&&(t?i=!0:t=e),e.track===n)),i||e&&t)?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):e?e.getStats():t?t.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return t.apply(this,arguments)}}function iU(e){e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map(e=>this._shimmedLocalStreams[e][0])};let t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,i){if(!i)return t.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};let n=t.apply(this,arguments);return this._shimmedLocalStreams[i.id]?-1===this._shimmedLocalStreams[i.id].indexOf(n)&&this._shimmedLocalStreams[i.id].push(n):this._shimmedLocalStreams[i.id]=[i,n],n};let i=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._shimmedLocalStreams=this._shimmedLocalStreams||{},e.getTracks().forEach(e=>{if(this.getSenders().find(t=>t.track===e))throw new DOMException("Track already exists.","InvalidAccessError")});let t=this.getSenders();i.apply(this,arguments);let n=this.getSenders().filter(e=>-1===t.indexOf(e));this._shimmedLocalStreams[e.id]=[e].concat(n)};let n=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[e.id],n.apply(this,arguments)};let r=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},e&&Object.keys(this._shimmedLocalStreams).forEach(t=>{let i=this._shimmedLocalStreams[t].indexOf(e);-1!==i&&this._shimmedLocalStreams[t].splice(i,1),1===this._shimmedLocalStreams[t].length&&delete this._shimmedLocalStreams[t]}),r.apply(this,arguments)}}function iF(e,t){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&t.version>=65)return iU(e);let i=e.RTCPeerConnection.prototype.getLocalStreams;e.RTCPeerConnection.prototype.getLocalStreams=function(){let e=i.apply(this);return this._reverseStreams=this._reverseStreams||{},e.map(e=>this._reverseStreams[e.id])};let n=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(t){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},t.getTracks().forEach(e=>{if(this.getSenders().find(t=>t.track===e))throw new DOMException("Track already exists.","InvalidAccessError")}),!this._reverseStreams[t.id]){let i=new e.MediaStream(t.getTracks());this._streams[t.id]=i,this._reverseStreams[i.id]=t,t=i}n.apply(this,[t])};let r=e.RTCPeerConnection.prototype.removeStream;function s(e,t){let i=t.sdp;return Object.keys(e._reverseStreams||[]).forEach(t=>{let n=e._reverseStreams[t],r=e._streams[n.id];i=i.replace(RegExp(r.id,"g"),n.id)}),new RTCSessionDescription({type:t.type,sdp:i})}e.RTCPeerConnection.prototype.removeStream=function(e){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},r.apply(this,[this._streams[e.id]||e]),delete this._reverseStreams[this._streams[e.id]?this._streams[e.id].id:e.id],delete this._streams[e.id]},e.RTCPeerConnection.prototype.addTrack=function(t,i){if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");let n=[].slice.call(arguments,1);if(1!==n.length||!n[0].getTracks().find(e=>e===t))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(e=>e.track===t))throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};let r=this._streams[i.id];if(r)r.addTrack(t),Promise.resolve().then(()=>{this.dispatchEvent(new Event("negotiationneeded"))});else{let n=new e.MediaStream([t]);this._streams[i.id]=n,this._reverseStreams[n.id]=i,this.addStream(n)}return this.getSenders().find(e=>e.track===t)},["createOffer","createAnswer"].forEach(function(t){let i=e.RTCPeerConnection.prototype[t];e.RTCPeerConnection.prototype[t]=({[t](){let e=arguments,t=arguments.length&&"function"==typeof arguments[0];return t?i.apply(this,[t=>{let i=s(this,t);e[0].apply(null,[i])},t=>{e[1]&&e[1].apply(null,t)},arguments[2]]):i.apply(this,arguments).then(e=>s(this,e))}})[t]});let o=e.RTCPeerConnection.prototype.setLocalDescription;e.RTCPeerConnection.prototype.setLocalDescription=function(){var e,t;let i;return arguments.length&&arguments[0].type&&(arguments[0]=(e=this,t=arguments[0],i=t.sdp,Object.keys(e._reverseStreams||[]).forEach(t=>{let n=e._reverseStreams[t],r=e._streams[n.id];i=i.replace(RegExp(n.id,"g"),r.id)}),new RTCSessionDescription({type:t.type,sdp:i}))),o.apply(this,arguments)};let a=Object.getOwnPropertyDescriptor(e.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(e.RTCPeerConnection.prototype,"localDescription",{get(){let e=a.get.apply(this);return""===e.type?e:s(this,e)}}),e.RTCPeerConnection.prototype.removeTrack=function(e){let t;if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!e._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(e._pc!==this)throw new DOMException("Sender was not created by this connection.","InvalidAccessError");this._streams=this._streams||{},Object.keys(this._streams).forEach(i=>{this._streams[i].getTracks().find(t=>e.track===t)&&(t=this._streams[i])}),t&&(1===t.getTracks().length?this.removeStream(this._reverseStreams[t.id]):t.removeTrack(e.track),this.dispatchEvent(new Event("negotiationneeded")))}}function iV(e,t){!e.RTCPeerConnection&&e.webkitRTCPeerConnection&&(e.RTCPeerConnection=e.webkitRTCPeerConnection),e.RTCPeerConnection&&t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(t){let i=e.RTCPeerConnection.prototype[t];e.RTCPeerConnection.prototype[t]=({[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),i.apply(this,arguments)}})[t]})}function iB(e,t){iP(e,"negotiationneeded",e=>{let i=e.target;if(!(t.version<72)&&(!i.getConfiguration||"plan-b"!==i.getConfiguration().sdpSemantics)||"stable"===i.signalingState)return e})}var iq=Object.freeze({__proto__:null,fixNegotiationNeeded:iB,shimAddTrackRemoveTrack:iF,shimAddTrackRemoveTrackWithNative:iU,shimGetSendersWithDtmf:iL,shimGetUserMedia:iD,shimMediaStream:i_,shimOnTrack:iN,shimPeerConnection:iV,shimSenderReceiverGetStats:ij});function iW(e,t){let i=e&&e.navigator,n=e&&e.MediaStreamTrack;if(i.getUserMedia=function(e,t,n){iA("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),i.mediaDevices.getUserMedia(e).then(t,n)},!(t.version>55&&"autoGainControl"in i.mediaDevices.getSupportedConstraints())){let e=function(e,t,i){t in e&&!(i in e)&&(e[i]=e[t],delete e[t])},t=i.mediaDevices.getUserMedia.bind(i.mediaDevices);if(i.mediaDevices.getUserMedia=function(i){return"object"==typeof i&&"object"==typeof i.audio&&(e((i=JSON.parse(JSON.stringify(i))).audio,"autoGainControl","mozAutoGainControl"),e(i.audio,"noiseSuppression","mozNoiseSuppression")),t(i)},n&&n.prototype.getSettings){let t=n.prototype.getSettings;n.prototype.getSettings=function(){let i=t.apply(this,arguments);return e(i,"mozAutoGainControl","autoGainControl"),e(i,"mozNoiseSuppression","noiseSuppression"),i}}if(n&&n.prototype.applyConstraints){let t=n.prototype.applyConstraints;n.prototype.applyConstraints=function(i){return"audio"===this.kind&&"object"==typeof i&&(e(i=JSON.parse(JSON.stringify(i)),"autoGainControl","mozAutoGainControl"),e(i,"noiseSuppression","mozNoiseSuppression")),t.apply(this,[i])}}}}function iz(e){"object"==typeof e&&e.RTCTrackEvent&&"receiver"in e.RTCTrackEvent.prototype&&!("transceiver"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function iH(e,t){if("object"!=typeof e||!(e.RTCPeerConnection||e.mozRTCPeerConnection))return;!e.RTCPeerConnection&&e.mozRTCPeerConnection&&(e.RTCPeerConnection=e.mozRTCPeerConnection),t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(t){let i=e.RTCPeerConnection.prototype[t];e.RTCPeerConnection.prototype[t]=({[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),i.apply(this,arguments)}})[t]});let i={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},n=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){let[e,r,s]=arguments;return n.apply(this,[e||null]).then(e=>{if(t.version<53&&!r)try{e.forEach(e=>{e.type=i[e.type]||e.type})}catch(t){if("TypeError"!==t.name)throw t;e.forEach((t,n)=>{e.set(n,Object.assign({},t,{type:i[t.type]||t.type}))})}return e}).then(r,s)}}function iG(e){if(!("object"==typeof e&&e.RTCPeerConnection&&e.RTCRtpSender)||e.RTCRtpSender&&"getStats"in e.RTCRtpSender.prototype)return;let t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){let e=t.apply(this,[]);return e.forEach(e=>e._pc=this),e});let i=e.RTCPeerConnection.prototype.addTrack;i&&(e.RTCPeerConnection.prototype.addTrack=function(){let e=i.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}function i$(e){if(!("object"==typeof e&&e.RTCPeerConnection&&e.RTCRtpSender)||e.RTCRtpSender&&"getStats"in e.RTCRtpReceiver.prototype)return;let t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){let e=t.apply(this,[]);return e.forEach(e=>e._pc=this),e}),iP(e,"track",e=>(e.receiver._pc=e.srcElement,e)),e.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function iK(e){!e.RTCPeerConnection||"removeStream"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.removeStream=function(e){iA("removeStream","removeTrack"),this.getSenders().forEach(t=>{t.track&&e.getTracks().includes(t.track)&&this.removeTrack(t)})})}function iJ(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel)}function iX(e){if(!("object"==typeof e&&e.RTCPeerConnection))return;let t=e.RTCPeerConnection.prototype.addTransceiver;t&&(e.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let e=arguments[1]&&arguments[1].sendEncodings;void 0===e&&(e=[]);let i=(e=[...e]).length>0;i&&e.forEach(e=>{if("rid"in e&&!/^[a-z0-9]{0,16}$/i.test(e.rid))throw TypeError("Invalid RID value provided.");if("scaleResolutionDownBy"in e&&!(parseFloat(e.scaleResolutionDownBy)>=1))throw RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in e&&!(parseFloat(e.maxFramerate)>=0))throw RangeError("max_framerate must be >= 0.0")});let n=t.apply(this,arguments);if(i){let{sender:t}=n,i=t.getParameters();"encodings"in i&&(1!==i.encodings.length||0!==Object.keys(i.encodings[0]).length)||(i.encodings=e,t.sendEncodings=e,this.setParametersPromises.push(t.setParameters(i).then(()=>{delete t.sendEncodings}).catch(()=>{delete t.sendEncodings})))}return n})}function iY(e){if(!("object"==typeof e&&e.RTCRtpSender))return;let t=e.RTCRtpSender.prototype.getParameters;t&&(e.RTCRtpSender.prototype.getParameters=function(){let e=t.apply(this,arguments);return"encodings"in e||(e.encodings=[].concat(this.sendEncodings||[{}])),e})}function iQ(e){if(!("object"==typeof e&&e.RTCPeerConnection))return;let t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>t.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):t.apply(this,arguments)}}function iZ(e){if(!("object"==typeof e&&e.RTCPeerConnection))return;let t=e.RTCPeerConnection.prototype.createAnswer;e.RTCPeerConnection.prototype.createAnswer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>t.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):t.apply(this,arguments)}}var i0=Object.freeze({__proto__:null,shimAddTransceiver:iX,shimCreateAnswer:iZ,shimCreateOffer:iQ,shimGetDisplayMedia:function(e,t){e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||!e.navigator.mediaDevices||(e.navigator.mediaDevices.getDisplayMedia=function(i){if(!(i&&i.video)){let e=new DOMException("getDisplayMedia without video constraints is undefined");return e.name="NotFoundError",e.code=8,Promise.reject(e)}return!0===i.video?i.video={mediaSource:t}:i.video.mediaSource=t,e.navigator.mediaDevices.getUserMedia(i)})},shimGetParameters:iY,shimGetUserMedia:iW,shimOnTrack:iz,shimPeerConnection:iH,shimRTCDataChannel:iJ,shimReceiverGetStats:i$,shimRemoveStream:iK,shimSenderGetStats:iG});function i1(e){if("object"==typeof e&&e.RTCPeerConnection){if("getLocalStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in e.RTCPeerConnection.prototype)){let t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addStream=function(e){this._localStreams||(this._localStreams=[]),this._localStreams.includes(e)||this._localStreams.push(e),e.getAudioTracks().forEach(i=>t.call(this,i,e)),e.getVideoTracks().forEach(i=>t.call(this,i,e))},e.RTCPeerConnection.prototype.addTrack=function(e){for(var i=arguments.length,n=Array(i>1?i-1:0),r=1;r<i;r++)n[r-1]=arguments[r];return n&&n.forEach(e=>{this._localStreams?this._localStreams.includes(e)||this._localStreams.push(e):this._localStreams=[e]}),t.apply(this,arguments)}}"removeStream"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.removeStream=function(e){this._localStreams||(this._localStreams=[]);let t=this._localStreams.indexOf(e);if(-1===t)return;this._localStreams.splice(t,1);let i=e.getTracks();this.getSenders().forEach(e=>{i.includes(e.track)&&this.removeTrack(e)})})}}function i2(e){if("object"==typeof e&&e.RTCPeerConnection&&("getRemoteStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]}),!("onaddstream"in e.RTCPeerConnection.prototype))){Object.defineProperty(e.RTCPeerConnection.prototype,"onaddstream",{get(){return this._onaddstream},set(e){this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=e),this.addEventListener("track",this._onaddstreampoly=e=>{e.streams.forEach(e=>{if(this._remoteStreams||(this._remoteStreams=[]),this._remoteStreams.includes(e))return;this._remoteStreams.push(e);let t=new Event("addstream");t.stream=e,this.dispatchEvent(t)})})}});let t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){let e=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(t){t.streams.forEach(t=>{if(e._remoteStreams||(e._remoteStreams=[]),e._remoteStreams.indexOf(t)>=0)return;e._remoteStreams.push(t);let i=new Event("addstream");i.stream=t,e.dispatchEvent(i)})}),t.apply(e,arguments)}}}function i3(e){if("object"!=typeof e||!e.RTCPeerConnection)return;let t=e.RTCPeerConnection.prototype,i=t.createOffer,n=t.createAnswer,r=t.setLocalDescription,s=t.setRemoteDescription,o=t.addIceCandidate;t.createOffer=function(e,t){let n=arguments.length>=2?arguments[2]:arguments[0],r=i.apply(this,[n]);return t?(r.then(e,t),Promise.resolve()):r},t.createAnswer=function(e,t){let i=arguments.length>=2?arguments[2]:arguments[0],r=n.apply(this,[i]);return t?(r.then(e,t),Promise.resolve()):r};let a=function(e,t,i){let n=r.apply(this,[e]);return i?(n.then(t,i),Promise.resolve()):n};t.setLocalDescription=a,a=function(e,t,i){let n=s.apply(this,[e]);return i?(n.then(t,i),Promise.resolve()):n},t.setRemoteDescription=a,a=function(e,t,i){let n=o.apply(this,[e]);return i?(n.then(t,i),Promise.resolve()):n},t.addIceCandidate=a}function i5(e){let t=e&&e.navigator;if(t.mediaDevices&&t.mediaDevices.getUserMedia){let e=t.mediaDevices,i=e.getUserMedia.bind(e);t.mediaDevices.getUserMedia=e=>i(i4(e))}!t.getUserMedia&&t.mediaDevices&&t.mediaDevices.getUserMedia&&(t.getUserMedia=(function(e,i,n){t.mediaDevices.getUserMedia(e).then(i,n)}).bind(t))}function i4(e){return e&&void 0!==e.video?Object.assign({},e,{video:function e(t){return iI(t)?Object.keys(t).reduce(function(i,n){let r=iI(t[n]),s=r?e(t[n]):t[n],o=r&&!Object.keys(s).length;return void 0===s||o?i:Object.assign(i,{[n]:s})},{}):t}(e.video)}):e}function i6(e){if(!e.RTCPeerConnection)return;let t=e.RTCPeerConnection;e.RTCPeerConnection=function(e,i){if(e&&e.iceServers){let t=[];for(let i=0;i<e.iceServers.length;i++){let n=e.iceServers[i];void 0===n.urls&&n.url?(iA("RTCIceServer.url","RTCIceServer.urls"),(n=JSON.parse(JSON.stringify(n))).urls=n.url,delete n.url,t.push(n)):t.push(e.iceServers[i])}e.iceServers=t}return new t(e,i)},e.RTCPeerConnection.prototype=t.prototype,"generateCertificate"in t&&Object.defineProperty(e.RTCPeerConnection,"generateCertificate",{get:()=>t.generateCertificate})}function i9(e){"object"==typeof e&&e.RTCTrackEvent&&"receiver"in e.RTCTrackEvent.prototype&&!("transceiver"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function i8(e){let t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(e){if(e){void 0!==e.offerToReceiveAudio&&(e.offerToReceiveAudio=!!e.offerToReceiveAudio);let t=this.getTransceivers().find(e=>"audio"===e.receiver.track.kind);!1===e.offerToReceiveAudio&&t?"sendrecv"===t.direction?t.setDirection?t.setDirection("sendonly"):t.direction="sendonly":"recvonly"===t.direction&&(t.setDirection?t.setDirection("inactive"):t.direction="inactive"):!0!==e.offerToReceiveAudio||t||this.addTransceiver("audio",{direction:"recvonly"}),void 0!==e.offerToReceiveVideo&&(e.offerToReceiveVideo=!!e.offerToReceiveVideo);let i=this.getTransceivers().find(e=>"video"===e.receiver.track.kind);!1===e.offerToReceiveVideo&&i?"sendrecv"===i.direction?i.setDirection?i.setDirection("sendonly"):i.direction="sendonly":"recvonly"===i.direction&&(i.setDirection?i.setDirection("inactive"):i.direction="inactive"):!0!==e.offerToReceiveVideo||i||this.addTransceiver("video",{direction:"recvonly"})}return t.apply(this,arguments)}}function i7(e){"object"!=typeof e||e.AudioContext||(e.AudioContext=e.webkitAudioContext)}var ne=Object.freeze({__proto__:null,shimAudioContext:i7,shimCallbacksAPI:i3,shimConstraints:i4,shimCreateOfferLegacy:i8,shimGetUserMedia:i5,shimLocalStreamsAPI:i1,shimRTCIceServerUrls:i6,shimRemoteStreamsAPI:i2,shimTrackEventTransceiver:i9}),nt={exports:{}},ni=(oF||(oF=1,function(e){let t={};t.generateIdentifier=function(){return Math.random().toString(36).substring(2,12)},t.localCName=t.generateIdentifier(),t.splitLines=function(e){return e.trim().split("\n").map(e=>e.trim())},t.splitSections=function(e){return e.split("\nm=").map((e,t)=>(t>0?"m="+e:e).trim()+"\r\n")},t.getDescription=function(e){let i=t.splitSections(e);return i&&i[0]},t.getMediaSections=function(e){let i=t.splitSections(e);return i.shift(),i},t.matchPrefix=function(e,i){return t.splitLines(e).filter(e=>0===e.indexOf(i))},t.parseCandidate=function(e){let t;let i={foundation:(t=0===e.indexOf("a=candidate:")?e.substring(12).split(" "):e.substring(10).split(" "))[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 e=8;e<t.length;e+=2)switch(t[e]){case"raddr":i.relatedAddress=t[e+1];break;case"rport":i.relatedPort=parseInt(t[e+1],10);break;case"tcptype":i.tcpType=t[e+1];break;case"ufrag":i.ufrag=t[e+1],i.usernameFragment=t[e+1];break;default:void 0===i[t[e]]&&(i[t[e]]=t[e+1])}return i},t.writeCandidate=function(e){let t=[];t.push(e.foundation);let i=e.component;"rtp"===i?t.push(1):"rtcp"===i?t.push(2):t.push(i),t.push(e.protocol.toUpperCase()),t.push(e.priority),t.push(e.address||e.ip),t.push(e.port);let n=e.type;return t.push("typ"),t.push(n),"host"!==n&&e.relatedAddress&&e.relatedPort&&(t.push("raddr"),t.push(e.relatedAddress),t.push("rport"),t.push(e.relatedPort)),e.tcpType&&"tcp"===e.protocol.toLowerCase()&&(t.push("tcptype"),t.push(e.tcpType)),(e.usernameFragment||e.ufrag)&&(t.push("ufrag"),t.push(e.usernameFragment||e.ufrag)),"candidate:"+t.join(" ")},t.parseIceOptions=function(e){return e.substring(14).split(" ")},t.parseRtpMap=function(e){let t=e.substring(9).split(" "),i={payloadType:parseInt(t.shift(),10)};return t=t[0].split("/"),i.name=t[0],i.clockRate=parseInt(t[1],10),i.channels=3===t.length?parseInt(t[2],10):1,i.numChannels=i.channels,i},t.writeRtpMap=function(e){let t=e.payloadType;void 0!==e.preferredPayloadType&&(t=e.preferredPayloadType);let i=e.channels||e.numChannels||1;return"a=rtpmap:"+t+" "+e.name+"/"+e.clockRate+(1!==i?"/"+i:"")+"\r\n"},t.parseExtmap=function(e){let t=e.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(" ")}},t.writeExtmap=function(e){return"a=extmap:"+(e.id||e.preferredId)+(e.direction&&"sendrecv"!==e.direction?"/"+e.direction:"")+" "+e.uri+(e.attributes?" "+e.attributes:"")+"\r\n"},t.parseFmtp=function(e){let t;let i={},n=e.substring(e.indexOf(" ")+1).split(";");for(let e=0;e<n.length;e++)i[(t=n[e].trim().split("="))[0].trim()]=t[1];return i},t.writeFmtp=function(e){let t="",i=e.payloadType;if(void 0!==e.preferredPayloadType&&(i=e.preferredPayloadType),e.parameters&&Object.keys(e.parameters).length){let n=[];Object.keys(e.parameters).forEach(t=>{void 0!==e.parameters[t]?n.push(t+"="+e.parameters[t]):n.push(t)}),t+="a=fmtp:"+i+" "+n.join(";")+"\r\n"}return t},t.parseRtcpFb=function(e){let t=e.substring(e.indexOf(" ")+1).split(" ");return{type:t.shift(),parameter:t.join(" ")}},t.writeRtcpFb=function(e){let t="",i=e.payloadType;return void 0!==e.preferredPayloadType&&(i=e.preferredPayloadType),e.rtcpFeedback&&e.rtcpFeedback.length&&e.rtcpFeedback.forEach(e=>{t+="a=rtcp-fb:"+i+" "+e.type+(e.parameter&&e.parameter.length?" "+e.parameter:"")+"\r\n"}),t},t.parseSsrcMedia=function(e){let t=e.indexOf(" "),i={ssrc:parseInt(e.substring(7,t),10)},n=e.indexOf(":",t);return n>-1?(i.attribute=e.substring(t+1,n),i.value=e.substring(n+1)):i.attribute=e.substring(t+1),i},t.parseSsrcGroup=function(e){let t=e.substring(13).split(" ");return{semantics:t.shift(),ssrcs:t.map(e=>parseInt(e,10))}},t.getMid=function(e){let i=t.matchPrefix(e,"a=mid:")[0];if(i)return i.substring(6)},t.parseFingerprint=function(e){let t=e.substring(14).split(" ");return{algorithm:t[0].toLowerCase(),value:t[1].toUpperCase()}},t.getDtlsParameters=function(e,i){return{role:"auto",fingerprints:t.matchPrefix(e+i,"a=fingerprint:").map(t.parseFingerprint)}},t.writeDtlsParameters=function(e,t){let i="a=setup:"+t+"\r\n";return e.fingerprints.forEach(e=>{i+="a=fingerprint:"+e.algorithm+" "+e.value+"\r\n"}),i},t.parseCryptoLine=function(e){let t=e.substring(9).split(" ");return{tag:parseInt(t[0],10),cryptoSuite:t[1],keyParams:t[2],sessionParams:t.slice(3)}},t.writeCryptoLine=function(e){return"a=crypto:"+e.tag+" "+e.cryptoSuite+" "+("object"==typeof e.keyParams?t.writeCryptoKeyParams(e.keyParams):e.keyParams)+(e.sessionParams?" "+e.sessionParams.join(" "):"")+"\r\n"},t.parseCryptoKeyParams=function(e){if(0!==e.indexOf("inline:"))return null;let t=e.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}},t.writeCryptoKeyParams=function(e){return e.keyMethod+":"+e.keySalt+(e.lifeTime?"|"+e.lifeTime:"")+(e.mkiValue&&e.mkiLength?"|"+e.mkiValue+":"+e.mkiLength:"")},t.getCryptoParameters=function(e,i){return t.matchPrefix(e+i,"a=crypto:").map(t.parseCryptoLine)},t.getIceParameters=function(e,i){let n=t.matchPrefix(e+i,"a=ice-ufrag:")[0],r=t.matchPrefix(e+i,"a=ice-pwd:")[0];return n&&r?{usernameFragment:n.substring(12),password:r.substring(10)}:null},t.writeIceParameters=function(e){let t="a=ice-ufrag:"+e.usernameFragment+"\r\na=ice-pwd:"+e.password+"\r\n";return e.iceLite&&(t+="a=ice-lite\r\n"),t},t.parseRtpParameters=function(e){let i={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},n=t.splitLines(e)[0].split(" ");i.profile=n[2];for(let r=3;r<n.length;r++){let s=n[r],o=t.matchPrefix(e,"a=rtpmap:"+s+" ")[0];if(o){let n=t.parseRtpMap(o),r=t.matchPrefix(e,"a=fmtp:"+s+" ");switch(n.parameters=r.length?t.parseFmtp(r[0]):{},n.rtcpFeedback=t.matchPrefix(e,"a=rtcp-fb:"+s+" ").map(t.parseRtcpFb),i.codecs.push(n),n.name.toUpperCase()){case"RED":case"ULPFEC":i.fecMechanisms.push(n.name.toUpperCase())}}}t.matchPrefix(e,"a=extmap:").forEach(e=>{i.headerExtensions.push(t.parseExtmap(e))});let r=t.matchPrefix(e,"a=rtcp-fb:* ").map(t.parseRtcpFb);return i.codecs.forEach(e=>{r.forEach(t=>{e.rtcpFeedback.find(e=>e.type===t.type&&e.parameter===t.parameter)||e.rtcpFeedback.push(t)})}),i},t.writeRtpDescription=function(e,i){let n="";n+="m="+e+" "+(i.codecs.length>0?"9":"0")+" "+(i.profile||"UDP/TLS/RTP/SAVPF")+" "+i.codecs.map(e=>void 0!==e.preferredPayloadType?e.preferredPayloadType:e.payloadType).join(" ")+"\r\nc=IN IP4 0.0.0.0\r\na=rtcp:9 IN IP4 0.0.0.0\r\n",i.codecs.forEach(e=>{n+=t.writeRtpMap(e)+t.writeFmtp(e)+t.writeRtcpFb(e)});let r=0;return i.codecs.forEach(e=>{e.maxptime>r&&(r=e.maxptime)}),r>0&&(n+="a=maxptime:"+r+"\r\n"),i.headerExtensions&&i.headerExtensions.forEach(e=>{n+=t.writeExtmap(e)}),n},t.parseRtpEncodingParameters=function(e){let i;let n=[],r=t.parseRtpParameters(e),s=-1!==r.fecMechanisms.indexOf("RED"),o=-1!==r.fecMechanisms.indexOf("ULPFEC"),a=t.matchPrefix(e,"a=ssrc:").map(e=>t.parseSsrcMedia(e)).filter(e=>"cname"===e.attribute),l=a.length>0&&a[0].ssrc,c=t.matchPrefix(e,"a=ssrc-group:FID").map(e=>e.substring(17).split(" ").map(e=>parseInt(e,10)));c.length>0&&c[0].length>1&&c[0][0]===l&&(i=c[0][1]),r.codecs.forEach(e=>{if("RTX"===e.name.toUpperCase()&&e.parameters.apt){let t={ssrc:l,codecPayloadType:parseInt(e.parameters.apt,10)};l&&i&&(t.rtx={ssrc:i}),n.push(t),s&&((t=JSON.parse(JSON.stringify(t))).fec={ssrc:l,mechanism:o?"red+ulpfec":"red"},n.push(t))}}),0===n.length&&l&&n.push({ssrc:l});let d=t.matchPrefix(e,"b=");return d.length&&(d=0===d[0].indexOf("b=TIAS:")?parseInt(d[0].substring(7),10):0===d[0].indexOf("b=AS:")?950*parseInt(d[0].substring(5),10)-16e3:void 0,n.forEach(e=>{e.maxBitrate=d})),n},t.parseRtcpParameters=function(e){let i={},n=t.matchPrefix(e,"a=ssrc:").map(e=>t.parseSsrcMedia(e)).filter(e=>"cname"===e.attribute)[0];n&&(i.cname=n.value,i.ssrc=n.ssrc);let r=t.matchPrefix(e,"a=rtcp-rsize");i.reducedSize=r.length>0,i.compound=0===r.length;let s=t.matchPrefix(e,"a=rtcp-mux");return i.mux=s.length>0,i},t.writeRtcpParameters=function(e){let t="";return e.reducedSize&&(t+="a=rtcp-rsize\r\n"),e.mux&&(t+="a=rtcp-mux\r\n"),void 0!==e.ssrc&&e.cname&&(t+="a=ssrc:"+e.ssrc+" cname:"+e.cname+"\r\n"),t},t.parseMsid=function(e){let i;let n=t.matchPrefix(e,"a=msid:");if(1===n.length)return{stream:(i=n[0].substring(7).split(" "))[0],track:i[1]};let r=t.matchPrefix(e,"a=ssrc:").map(e=>t.parseSsrcMedia(e)).filter(e=>"msid"===e.attribute);if(r.length>0)return{stream:(i=r[0].value.split(" "))[0],track:i[1]}},t.parseSctpDescription=function(e){let i;let n=t.parseMLine(e),r=t.matchPrefix(e,"a=max-message-size:");r.length>0&&(i=parseInt(r[0].substring(19),10)),isNaN(i)&&(i=65536);let s=t.matchPrefix(e,"a=sctp-port:");if(s.length>0)return{port:parseInt(s[0].substring(12),10),protocol:n.fmt,maxMessageSize:i};let o=t.matchPrefix(e,"a=sctpmap:");if(o.length>0){let e=o[0].substring(10).split(" ");return{port:parseInt(e[0],10),protocol:e[1],maxMessageSize:i}}},t.writeSctpDescription=function(e,t){let i=[];return i="DTLS/SCTP"!==e.protocol?["m="+e.kind+" 9 "+e.protocol+" "+t.protocol+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctp-port:"+t.port+"\r\n"]:["m="+e.kind+" 9 "+e.protocol+" "+t.port+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctpmap:"+t.port+" "+t.protocol+" 65535\r\n"],void 0!==t.maxMessageSize&&i.push("a=max-message-size:"+t.maxMessageSize+"\r\n"),i.join("")},t.generateSessionId=function(){return Math.random().toString().substr(2,22)},t.writeSessionBoilerplate=function(e,i,n){return"v=0\r\no="+(n||"thisisadapterortc")+" "+(e||t.generateSessionId())+" "+(void 0!==i?i:2)+" IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\n"},t.getDirection=function(e,i){let n=t.splitLines(e);for(let e=0;e<n.length;e++)switch(n[e]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return n[e].substring(2)}return i?t.getDirection(i):"sendrecv"},t.getKind=function(e){return t.splitLines(e)[0].split(" ")[0].substring(2)},t.isRejected=function(e){return"0"===e.split(" ",2)[1]},t.parseMLine=function(e){let i=t.splitLines(e)[0].substring(2).split(" ");return{kind:i[0],port:parseInt(i[1],10),protocol:i[2],fmt:i.slice(3).join(" ")}},t.parseOLine=function(e){let i=t.matchPrefix(e,"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]}},t.isValidSDP=function(e){if("string"!=typeof e||0===e.length)return!1;let i=t.splitLines(e);for(let e=0;e<i.length;e++)if(i[e].length<2||"="!==i[e].charAt(1))return!1;return!0},e.exports=t}(nt)),nt.exports),nn=function(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}(ni),nr=function(e,t){return t.forEach(function(t){t&&"string"!=typeof t&&!Array.isArray(t)&&Object.keys(t).forEach(function(i){if("default"!==i&&!(i in e)){var n=Object.getOwnPropertyDescriptor(t,i);Object.defineProperty(e,i,n.get?n:{enumerable:!0,get:function(){return t[i]}})}})}),Object.freeze(e)}({__proto__:null,default:nn},[ni]);function ns(e){if(!e.RTCIceCandidate||e.RTCIceCandidate&&"foundation"in e.RTCIceCandidate.prototype)return;let t=e.RTCIceCandidate;e.RTCIceCandidate=function(e){if("object"==typeof e&&e.candidate&&0===e.candidate.indexOf("a=")&&((e=JSON.parse(JSON.stringify(e))).candidate=e.candidate.substring(2)),e.candidate&&e.candidate.length){let i=new t(e),n=nn.parseCandidate(e.candidate);for(let e in n)e in i||Object.defineProperty(i,e,{value:n[e]});return i.toJSON=function(){return{candidate:i.candidate,sdpMid:i.sdpMid,sdpMLineIndex:i.sdpMLineIndex,usernameFragment:i.usernameFragment}},i}return new t(e)},e.RTCIceCandidate.prototype=t.prototype,iP(e,"icecandidate",t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new e.RTCIceCandidate(t.candidate),writable:"false"}),t))}function no(e){!e.RTCIceCandidate||e.RTCIceCandidate&&"relayProtocol"in e.RTCIceCandidate.prototype||iP(e,"icecandidate",e=>{if(e.candidate){let t=nn.parseCandidate(e.candidate.candidate);"relay"===t.type&&(e.candidate.relayProtocol=({0:"tls",1:"tcp",2:"udp"})[t.priority>>24])}return e})}function na(e,t){if(!e.RTCPeerConnection)return;"sctp"in e.RTCPeerConnection.prototype||Object.defineProperty(e.RTCPeerConnection.prototype,"sctp",{get(){return void 0===this._sctp?null:this._sctp}});let i=function(e){if(!e||!e.sdp)return!1;let t=nn.splitSections(e.sdp);return t.shift(),t.some(e=>{let t=nn.parseMLine(e);return t&&"application"===t.kind&&-1!==t.protocol.indexOf("SCTP")})},n=function(e){let t=e.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(null===t||t.length<2)return -1;let i=parseInt(t[1],10);return i!=i?-1:i},r=function(e){let i=65536;return"firefox"===t.browser&&(i=t.version<57?-1===e?16384:2147483637:t.version<60?57===t.version?65535:65536:2147483637),i},s=function(e,i){let n=65536;"firefox"===t.browser&&57===t.version&&(n=65535);let r=nn.matchPrefix(e.sdp,"a=max-message-size:");return r.length>0?n=parseInt(r[0].substring(19),10):"firefox"===t.browser&&-1!==i&&(n=2147483637),n},o=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,"chrome"===t.browser&&t.version>=76){let{sdpSemantics:e}=this.getConfiguration();"plan-b"===e&&Object.defineProperty(this,"sctp",{get(){return void 0===this._sctp?null:this._sctp},enumerable:!0,configurable:!0})}if(i(arguments[0])){let e;let t=n(arguments[0]),i=r(t),o=s(arguments[0],t);e=0===i&&0===o?Number.POSITIVE_INFINITY:0===i||0===o?Math.max(i,o):Math.min(i,o);let a={};Object.defineProperty(a,"maxMessageSize",{get:()=>e}),this._sctp=a}return o.apply(this,arguments)}}function nl(e){if(!(e.RTCPeerConnection&&"createDataChannel"in e.RTCPeerConnection.prototype))return;function t(e,t){let i=e.send;e.send=function(){let n=arguments[0],r=n.length||n.size||n.byteLength;if("open"===e.readyState&&t.sctp&&r>t.sctp.maxMessageSize)throw TypeError("Message too large (can send a maximum of "+t.sctp.maxMessageSize+" bytes)");return i.apply(e,arguments)}}let i=e.RTCPeerConnection.prototype.createDataChannel;e.RTCPeerConnection.prototype.createDataChannel=function(){let e=i.apply(this,arguments);return t(e,this),e},iP(e,"datachannel",e=>(t(e.channel,e.target),e))}function nc(e){if(!e.RTCPeerConnection||"connectionState"in e.RTCPeerConnection.prototype)return;let t=e.RTCPeerConnection.prototype;Object.defineProperty(t,"connectionState",{get(){return({completed:"connected",checking:"connecting"})[this.iceConnectionState]||this.iceConnectionState},enumerable:!0,configurable:!0}),Object.defineProperty(t,"onconnectionstatechange",{get(){return this._onconnectionstatechange||null},set(e){this._onconnectionstatechange&&(this.removeEventListener("connectionstatechange",this._onconnectionstatechange),delete this._onconnectionstatechange),e&&this.addEventListener("connectionstatechange",this._onconnectionstatechange=e)},enumerable:!0,configurable:!0}),["setLocalDescription","setRemoteDescription"].forEach(e=>{let i=t[e];t[e]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=e=>{let t=e.target;if(t._lastConnectionState!==t.connectionState){t._lastConnectionState=t.connectionState;let i=new Event("connectionstatechange",e);t.dispatchEvent(i)}return e},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),i.apply(this,arguments)}})}function nd(e,t){if(!e.RTCPeerConnection||"chrome"===t.browser&&t.version>=71||"safari"===t.browser&&t._safariVersion>=13.1)return;let i=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(t){if(t&&t.sdp&&-1!==t.sdp.indexOf("\na=extmap-allow-mixed")){let i=t.sdp.split("\n").filter(e=>"a=extmap-allow-mixed"!==e.trim()).join("\n");e.RTCSessionDescription&&t instanceof e.RTCSessionDescription?arguments[0]=new e.RTCSessionDescription({type:t.type,sdp:i}):t.sdp=i}return i.apply(this,arguments)}}function nu(e,t){if(!(e.RTCPeerConnection&&e.RTCPeerConnection.prototype))return;let i=e.RTCPeerConnection.prototype.addIceCandidate;i&&0!==i.length&&(e.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?("chrome"===t.browser&&t.version<78||"firefox"===t.browser&&t.version<68||"safari"===t.browser)&&arguments[0]&&""===arguments[0].candidate?Promise.resolve():i.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}function nh(e,t){if(!(e.RTCPeerConnection&&e.RTCPeerConnection.prototype))return;let i=e.RTCPeerConnection.prototype.setLocalDescription;i&&0!==i.length&&(e.RTCPeerConnection.prototype.setLocalDescription=function(){let e=arguments[0]||{};if("object"!=typeof e||e.type&&e.sdp)return i.apply(this,arguments);if(!(e={type:e.type,sdp:e.sdp}).type)switch(this.signalingState){case"stable":case"have-local-offer":case"have-remote-pranswer":e.type="offer";break;default:e.type="answer"}return e.sdp||"offer"!==e.type&&"answer"!==e.type?i.apply(this,[e]):("offer"===e.type?this.createOffer:this.createAnswer).apply(this).then(e=>i.apply(this,[e]))})}var np=Object.freeze({__proto__:null,removeExtmapAllowMixed:nd,shimAddIceCandidateNullOrEmpty:nu,shimConnectionState:nc,shimMaxMessageSize:na,shimParameterlessSetLocalDescription:nh,shimRTCIceCandidate:ns,shimRTCIceCandidateRelayProtocol:no,shimSendThrowTypeError:nl});!function(){let{window:e}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{shimChrome:!0,shimFirefox:!0,shimSafari:!0},i=function(e){let t={browser:null,version:null};if(void 0===e||!e.navigator||!e.navigator.userAgent)return t.browser="Not a browser.",t;let{navigator:i}=e;if(i.userAgentData&&i.userAgentData.brands){let e=i.userAgentData.brands.find(e=>"Chromium"===e.brand);if(e)return{browser:"chrome",version:parseInt(e.version,10)}}return i.mozGetUserMedia?(t.browser="firefox",t.version=parseInt(iE(i.userAgent,/Firefox\/(\d+)\./,1))):i.webkitGetUserMedia||!1===e.isSecureContext&&e.webkitRTCPeerConnection?(t.browser="chrome",t.version=parseInt(iE(i.userAgent,/Chrom(e|ium)\/(\d+)\./,2))):e.RTCPeerConnection&&i.userAgent.match(/AppleWebKit\/(\d+)\./)?(t.browser="safari",t.version=parseInt(iE(i.userAgent,/AppleWebKit\/(\d+)\./,1)),t.supportsUnifiedPlan=e.RTCRtpTransceiver&&"currentDirection"in e.RTCRtpTransceiver.prototype,t._safariVersion=iE(i.userAgent,/Version\/(\d+(\.?\d+))/,1)):t.browser="Not a supported browser.",t}(e),n={browserDetails:i,commonShim:np,extractVersion:iE,disableLog:ix,disableWarnings:iR,sdp:nr};switch(i.browser){case"chrome":if(!iq||!iV||!t.shimChrome){iO("Chrome shim is not included in this adapter release.");break}if(null===i.version){iO("Chrome shim can not determine version, not shimming.");break}iO("adapter.js shimming chrome."),n.browserShim=iq,nu(e,i),nh(e),iD(e,i),i_(e),iV(e,i),iN(e),iF(e,i),iL(e),ij(e),iB(e,i),ns(e),no(e),nc(e),na(e,i),nl(e),nd(e,i);break;case"firefox":if(!i0||!iH||!t.shimFirefox){iO("Firefox shim is not included in this adapter release.");break}iO("adapter.js shimming firefox."),n.browserShim=i0,nu(e,i),nh(e),iW(e,i),iH(e,i),iz(e),iK(e),iG(e),i$(e),iJ(e),iX(e),iY(e),iQ(e),iZ(e),ns(e),nc(e),na(e,i),nl(e);break;case"safari":if(!ne||!t.shimSafari){iO("Safari shim is not included in this adapter release.");break}iO("adapter.js shimming safari."),n.browserShim=ne,nu(e,i),nh(e),i6(e),i8(e),i3(e),i1(e),i2(e),i9(e),i5(e),i7(e),ns(e),no(e),na(e,i),nl(e),nd(e,i);break;default:iO("Unsupported browser!")}}({window:"undefined"==typeof window?void 0:window});let nm="lk_e2ee";function nf(){return void 0!==window.RTCRtpScriptTransform}(function(e){e.SetKey="setKey",e.RatchetRequest="ratchetRequest",e.KeyRatcheted="keyRatcheted"})(oV||(oV={})),(oB||(oB={})).KeyRatcheted="keyRatcheted",function(e){e.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",e.EncryptionError="encryptionError"}(oq||(oq={})),(oW||(oW={})).Error="cryptorError";class ng extends Error{constructor(e,t){super(t||"an error has occured"),this.name="LiveKitError",this.code=e}}!function(e){e[e.NotAllowed=0]="NotAllowed",e[e.ServerUnreachable=1]="ServerUnreachable",e[e.InternalError=2]="InternalError",e[e.Cancelled=3]="Cancelled",e[e.LeaveRequest=4]="LeaveRequest",e[e.Timeout=5]="Timeout"}(oz||(oz={}));class nv extends ng{constructor(e,t,i,n){super(1,e),this.name="ConnectionError",this.status=i,this.reason=t,this.context=n,this.reasonName=oz[t]}}class ny extends ng{constructor(e){super(21,null!=e?e:"device is unsupported"),this.name="DeviceUnsupportedError"}}class nb extends ng{constructor(e){super(20,null!=e?e:"track is invalid"),this.name="TrackInvalidError"}}class nk extends ng{constructor(e){super(10,null!=e?e:"unsupported server"),this.name="UnsupportedServer"}}class nT extends ng{constructor(e){super(12,null!=e?e:"unexpected connection state"),this.name="UnexpectedConnectionState"}}class nS extends ng{constructor(e){super(13,null!=e?e:"unable to negotiate"),this.name="NegotiationError"}}class nC extends ng{constructor(e,t){super(15,e),this.name="PublishTrackError",this.status=t}}class nw extends ng{constructor(e,t){super(15,e),this.reason=t,this.reasonName="string"==typeof t?t:il[t]}}(function(e){e.PermissionDenied="PermissionDenied",e.NotFound="NotFound",e.DeviceInUse="DeviceInUse",e.Other="Other"})(oH||(oH={})),function(e){e.getFailure=function(t){if(t&&"name"in t)return"NotFoundError"===t.name||"DevicesNotFoundError"===t.name?e.NotFound:"NotAllowedError"===t.name||"PermissionDeniedError"===t.name?e.PermissionDenied:"NotReadableError"===t.name||"TrackStartError"===t.name?e.DeviceInUse:e.Other}}(oH||(oH={})),function(e){e[e.InvalidKey=0]="InvalidKey",e[e.MissingKey=1]="MissingKey",e[e.InternalError=2]="InternalError"}(oG||(oG={})),function(e){e.Connected="connected",e.Reconnecting="reconnecting",e.SignalReconnecting="signalReconnecting",e.Reconnected="reconnected",e.Disconnected="disconnected",e.ConnectionStateChanged="connectionStateChanged",e.Moved="moved",e.MediaDevicesChanged="mediaDevicesChanged",e.ParticipantConnected="participantConnected",e.ParticipantDisconnected="participantDisconnected",e.TrackPublished="trackPublished",e.TrackSubscribed="trackSubscribed",e.TrackSubscriptionFailed="trackSubscriptionFailed",e.TrackUnpublished="trackUnpublished",e.TrackUnsubscribed="trackUnsubscribed",e.TrackMuted="trackMuted",e.TrackUnmuted="trackUnmuted",e.LocalTrackPublished="localTrackPublished",e.LocalTrackUnpublished="localTrackUnpublished",e.LocalAudioSilenceDetected="localAudioSilenceDetected",e.ActiveSpeakersChanged="activeSpeakersChanged",e.ParticipantMetadataChanged="participantMetadataChanged",e.ParticipantNameChanged="participantNameChanged",e.ParticipantAttributesChanged="participantAttributesChanged",e.ParticipantActive="participantActive",e.RoomMetadataChanged="roomMetadataChanged",e.DataReceived="dataReceived",e.SipDTMFReceived="sipDTMFReceived",e.TranscriptionReceived="transcriptionReceived",e.ConnectionQualityChanged="connectionQualityChanged",e.TrackStreamStateChanged="trackStreamStateChanged",e.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",e.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",e.AudioPlaybackStatusChanged="audioPlaybackChanged",e.VideoPlaybackStatusChanged="videoPlaybackChanged",e.MediaDevicesError="mediaDevicesError",e.ParticipantPermissionsChanged="participantPermissionsChanged",e.SignalConnected="signalConnected",e.RecordingStatusChanged="recordingStatusChanged",e.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",e.EncryptionError="encryptionError",e.DCBufferStatusChanged="dcBufferStatusChanged",e.ActiveDeviceChanged="activeDeviceChanged",e.ChatMessage="chatMessage",e.LocalTrackSubscribed="localTrackSubscribed",e.MetricsReceived="metricsReceived"}(o$||(o$={})),function(e){e.TrackPublished="trackPublished",e.TrackSubscribed="trackSubscribed",e.TrackSubscriptionFailed="trackSubscriptionFailed",e.TrackUnpublished="trackUnpublished",e.TrackUnsubscribed="trackUnsubscribed",e.TrackMuted="trackMuted",e.TrackUnmuted="trackUnmuted",e.LocalTrackPublished="localTrackPublished",e.LocalTrackUnpublished="localTrackUnpublished",e.LocalTrackCpuConstrained="localTrackCpuConstrained",e.LocalSenderCreated="localSenderCreated",e.ParticipantMetadataChanged="participantMetadataChanged",e.ParticipantNameChanged="participantNameChanged",e.DataReceived="dataReceived",e.SipDTMFReceived="sipDTMFReceived",e.TranscriptionReceived="transcriptionReceived",e.IsSpeakingChanged="isSpeakingChanged",e.ConnectionQualityChanged="connectionQualityChanged",e.TrackStreamStateChanged="trackStreamStateChanged",e.TrackSubscriptionPermissionChanged="trackSubscriptionPermissionChanged",e.TrackSubscriptionStatusChanged="trackSubscriptionStatusChanged",e.TrackCpuConstrained="trackCpuConstrained",e.MediaDevicesError="mediaDevicesError",e.AudioStreamAcquired="audioStreamAcquired",e.ParticipantPermissionsChanged="participantPermissionsChanged",e.PCTrackAdded="pcTrackAdded",e.AttributesChanged="attributesChanged",e.LocalTrackSubscribed="localTrackSubscribed",e.ChatMessage="chatMessage",e.Active="active"}(oK||(oK={})),function(e){e.TransportsCreated="transportsCreated",e.Connected="connected",e.Disconnected="disconnected",e.Resuming="resuming",e.Resumed="resumed",e.Restarting="restarting",e.Restarted="restarted",e.SignalResumed="signalResumed",e.SignalRestarted="signalRestarted",e.Closing="closing",e.MediaTrackAdded="mediaTrackAdded",e.ActiveSpeakersUpdate="activeSpeakersUpdate",e.DataPacketReceived="dataPacketReceived",e.RTPVideoMapUpdate="rtpVideoMapUpdate",e.DCBufferStatusChanged="dcBufferStatusChanged",e.ParticipantUpdate="participantUpdate",e.RoomUpdate="roomUpdate",e.SpeakersChanged="speakersChanged",e.StreamStateChanged="streamStateChanged",e.ConnectionQualityUpdate="connectionQualityUpdate",e.SubscriptionError="subscriptionError",e.SubscriptionPermissionUpdate="subscriptionPermissionUpdate",e.RemoteMute="remoteMute",e.SubscribedQualityUpdate="subscribedQualityUpdate",e.LocalTrackUnpublished="localTrackUnpublished",e.LocalTrackSubscribed="localTrackSubscribed",e.Offline="offline",e.SignalRequestResponse="signalRequestResponse",e.SignalConnected="signalConnected",e.RoomMoved="roomMoved"}(oJ||(oJ={})),function(e){e.Message="message",e.Muted="muted",e.Unmuted="unmuted",e.Restarted="restarted",e.Ended="ended",e.Subscribed="subscribed",e.Unsubscribed="unsubscribed",e.CpuConstrained="cpuConstrained",e.UpdateSettings="updateSettings",e.UpdateSubscription="updateSubscription",e.AudioPlaybackStarted="audioPlaybackStarted",e.AudioPlaybackFailed="audioPlaybackFailed",e.AudioSilenceDetected="audioSilenceDetected",e.VisibilityChanged="visibilityChanged",e.VideoDimensionsChanged="videoDimensionsChanged",e.VideoPlaybackStarted="videoPlaybackStarted",e.VideoPlaybackFailed="videoPlaybackFailed",e.ElementAttached="elementAttached",e.ElementDetached="elementDetached",e.UpstreamPaused="upstreamPaused",e.UpstreamResumed="upstreamResumed",e.SubscriptionPermissionChanged="subscriptionPermissionChanged",e.SubscriptionStatusChanged="subscriptionStatusChanged",e.SubscriptionFailed="subscriptionFailed",e.TrackProcessorUpdate="trackProcessorUpdate",e.AudioTrackFeatureUpdate="audioTrackFeatureUpdate",e.TranscriptionReceived="transcriptionReceived",e.TimeSyncUpdate="timeSyncUpdate",e.PreConnectBufferFlushed="preConnectBufferFlushed"}(oX||(oX={}));let nE=/version\/(\d+(\.?_?\d+)+)/i;function nP(e){let t=!(arguments.length>1)||void 0===arguments[1]||arguments[1];if(void 0===e&&"undefined"==typeof navigator)return;let i=(null!=e?e:navigator.userAgent).toLowerCase();if(void 0===n||t){let e=nx.find(e=>{let{test:t}=e;return t.test(i)});n=null==e?void 0:e.describe(i)}return n}let nx=[{test:/firefox|iceweasel|fxios/i,describe:e=>({name:"Firefox",version:nR(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,e),os:e.toLowerCase().includes("fxios")?"iOS":void 0,osVersion:nO(e)})},{test:/chrom|crios|crmo/i,describe:e=>({name:"Chrome",version:nR(/(?:chrome|chromium|crios|crmo)\/(\d+(\.?_?\d+)+)/i,e),os:e.toLowerCase().includes("crios")?"iOS":void 0,osVersion:nO(e)})},{test:/safari|applewebkit/i,describe:e=>({name:"Safari",version:nR(nE,e),os:e.includes("mobile/")?"iOS":"macOS",osVersion:nO(e)})}];function nR(e,t){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1,n=t.match(e);return n&&n.length>=i&&n[i]||""}function nO(e){return e.includes("mac os")?nR(/\(.+?(\d+_\d+(:?_\d+)?)/,e,1).replace(/_/g,"."):void 0}class nA{}nA.setTimeout=function(){return setTimeout(...arguments)},nA.setInterval=function(){return setInterval(...arguments)},nA.clearTimeout=function(){return clearTimeout(...arguments)},nA.clearInterval=function(){return clearInterval(...arguments)};let nI=[];!function(e){e[e.LOW=0]="LOW",e[e.MEDIUM=1]="MEDIUM",e[e.HIGH=2]="HIGH"}(oY||(oY={}));class nM extends iS.EventEmitter{constructor(e,t){var i;let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};super(),this.attachedElements=[],this.isMuted=!1,this.streamState=nM.StreamState.Active,this.isInBackground=!1,this._currentBitrate=0,this.log=ip,this.appVisibilityChangedListener=()=>{this.backgroundTimeout&&clearTimeout(this.backgroundTimeout),"hidden"===document.visibilityState?this.backgroundTimeout=setTimeout(()=>this.handleAppVisibilityChanged(),5e3):this.handleAppVisibilityChanged()},this.log=im(null!==(i=n.loggerName)&&void 0!==i?i:oj.Track),this.loggerContextCb=n.loggerContextCb,this.setMaxListeners(100),this.kind=t,this._mediaStreamTrack=e,this._mediaStreamID=e.id,this.source=nM.Source.Unknown}get logContext(){var e;return Object.assign(Object.assign({},null===(e=this.loggerContextCb)||void 0===e?void 0:e.call(this)),rT(this))}get currentBitrate(){return this._currentBitrate}get mediaStreamTrack(){return this._mediaStreamTrack}get mediaStreamID(){return this._mediaStreamID}attach(e){let t="audio";this.kind===nM.Kind.Video&&(t="video"),0===this.attachedElements.length&&this.kind===nM.Kind.Video&&this.addAppVisibilityListener(),e||("audio"===t&&(nI.forEach(t=>{null!==t.parentElement||e||(e=t)}),e&&nI.splice(nI.indexOf(e),1)),e||(e=document.createElement(t))),this.attachedElements.includes(e)||this.attachedElements.push(e),nD(this.mediaStreamTrack,e);let i=e.srcObject.getTracks(),n=i.some(e=>"audio"===e.kind);return e.play().then(()=>{this.emit(n?oX.AudioPlaybackStarted:oX.VideoPlaybackStarted)}).catch(t=>{"NotAllowedError"===t.name?this.emit(n?oX.AudioPlaybackFailed:oX.VideoPlaybackFailed,t):"AbortError"===t.name?ip.debug("".concat(n?"audio":"video"," playback aborted, likely due to new play request")):ip.warn("could not playback ".concat(n?"audio":"video"),t),n&&e&&i.some(e=>"video"===e.kind)&&"NotAllowedError"===t.name&&(e.muted=!0,e.play().catch(()=>{}))}),this.emit(oX.ElementAttached,e),e}detach(e){try{if(e){n_(this.mediaStreamTrack,e);let t=this.attachedElements.indexOf(e);return t>=0&&(this.attachedElements.splice(t,1),this.recycleElement(e),this.emit(oX.ElementDetached,e)),e}let t=[];return this.attachedElements.forEach(e=>{n_(this.mediaStreamTrack,e),t.push(e),this.recycleElement(e),this.emit(oX.ElementDetached,e)}),this.attachedElements=[],t}finally{0===this.attachedElements.length&&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=im(e.loggerName)),e.loggerContextCb&&(this.loggerContextCb=e.loggerContextCb)}recycleElement(e){if(e instanceof HTMLAudioElement){let t=!0;e.pause(),nI.forEach(e=>{e.parentElement||(t=!1)}),t&&nI.push(e)}}handleAppVisibilityChanged(){return ib(this,void 0,void 0,function*(){this.isInBackground="hidden"===document.visibilityState,this.isInBackground||this.kind!==nM.Kind.Video||setTimeout(()=>this.attachedElements.forEach(e=>e.play().catch(()=>{})),0)})}addAppVisibilityListener(){nY()?(this.isInBackground="hidden"===document.visibilityState,document.addEventListener("visibilitychange",this.appVisibilityChangedListener)):this.isInBackground=!1}removeAppVisibilityListener(){nY()&&document.removeEventListener("visibilitychange",this.appVisibilityChangedListener)}}function nD(e,t){let i,n;t.srcObject instanceof MediaStream?i=t.srcObject:i=new MediaStream,(n="audio"===e.kind?i.getAudioTracks():i.getVideoTracks()).includes(e)||(n.forEach(e=>{i.removeTrack(e)}),i.addTrack(e)),nK()&&t instanceof HTMLVideoElement||(t.autoplay=!0),t.muted=0===i.getAudioTracks().length,t instanceof HTMLVideoElement&&(t.playsInline=!0),t.srcObject!==i&&(t.srcObject=i,(nK()||n$())&&t instanceof HTMLVideoElement&&setTimeout(()=>{t.srcObject=i,t.play().catch(()=>{})},0))}function n_(e,t){if(t.srcObject instanceof MediaStream){let i=t.srcObject;i.removeTrack(e),i.getTracks().length>0?t.srcObject=i:t.srcObject=null}}!function(e){var t,i,n;let r,s,o;(t=r=e.Kind||(e.Kind={})).Audio="audio",t.Video="video",t.Unknown="unknown",(i=s=e.Source||(e.Source={})).Camera="camera",i.Microphone="microphone",i.ScreenShare="screen_share",i.ScreenShareAudio="screen_share_audio",i.Unknown="unknown",(n=o=e.StreamState||(e.StreamState={})).Active="active",n.Paused="paused",n.Unknown="unknown",e.kindToProto=function(e){switch(e){case r.Audio:return eV.AUDIO;case r.Video:return eV.VIDEO;default:return eV.DATA}},e.kindFromProto=function(e){switch(e){case eV.AUDIO:return r.Audio;case eV.VIDEO:return r.Video;default:return r.Unknown}},e.sourceToProto=function(e){switch(e){case s.Camera:return eB.CAMERA;case s.Microphone:return eB.MICROPHONE;case s.ScreenShare:return eB.SCREEN_SHARE;case s.ScreenShareAudio:return eB.SCREEN_SHARE_AUDIO;default:return eB.UNKNOWN}},e.sourceFromProto=function(e){switch(e){case eB.CAMERA:return s.Camera;case eB.MICROPHONE:return s.Microphone;case eB.SCREEN_SHARE:return s.ScreenShare;case eB.SCREEN_SHARE_AUDIO:return s.ScreenShareAudio;default:return s.Unknown}},e.streamStateFromProto=function(e){switch(e){case tE.ACTIVE:return o.Active;case tE.PAUSED:return o.Paused;default:return o.Unknown}}}(nM||(nM={}));class nN{constructor(e,t,i,n,r){if("object"==typeof e)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(void 0!==t&&void 0!==i)this.width=e,this.height=t,this.aspectRatio=e/t,this.encoding={maxBitrate:i,maxFramerate:n,priority:r};else throw 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}}}let nL=["vp8","h264"],nj=["vp8","h264","vp9","av1","h265"];(function(e){e[e.PREFER_REGRESSION=0]="PREFER_REGRESSION",e[e.SIMULCAST=1]="SIMULCAST",e[e.REGRESSION=2]="REGRESSION"})(oQ||(oQ={})),function(e){e.telephone={maxBitrate:12e3},e.speech={maxBitrate:24e3},e.music={maxBitrate:48e3},e.musicStereo={maxBitrate:64e3},e.musicHighQuality={maxBitrate:96e3},e.musicHighQualityStereo={maxBitrate:128e3}}(oZ||(oZ={}));let nU={h90:new nN(160,90,9e4,20),h180:new nN(320,180,16e4,20),h216:new nN(384,216,18e4,20),h360:new nN(640,360,45e4,20),h540:new nN(960,540,8e5,25),h720:new nN(1280,720,17e5,30),h1080:new nN(1920,1080,3e6,30),h1440:new nN(2560,1440,5e6,30),h2160:new nN(3840,2160,8e6,30)},nF={h120:new nN(160,120,7e4,20),h180:new nN(240,180,125e3,20),h240:new nN(320,240,14e4,20),h360:new nN(480,360,33e4,20),h480:new nN(640,480,5e5,20),h540:new nN(720,540,6e5,25),h720:new nN(960,720,13e5,30),h1080:new nN(1440,1080,23e5,30),h1440:new nN(1920,1440,38e5,30)},nV={h360fps3:new nN(640,360,2e5,3,"medium"),h360fps15:new nN(640,360,4e5,15,"medium"),h720fps5:new nN(1280,720,8e5,5,"medium"),h720fps15:new nN(1280,720,15e5,15,"medium"),h720fps30:new nN(1280,720,2e6,30,"medium"),h1080fps15:new nN(1920,1080,25e5,15,"medium"),h1080fps30:new nN(1920,1080,5e6,30,"medium"),original:new nN(0,0,7e6,30,"medium")},nB="https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension";function nq(e){return ib(this,void 0,void 0,function*(){return new Promise(t=>nA.setTimeout(t,e))})}function nW(){return"addTransceiver"in RTCPeerConnection.prototype}function nz(){return"addTrack"in RTCPeerConnection.prototype}function nH(e){return"av1"===e||"vp9"===e}function nG(e){return!(!document||nJ())&&(e||(e=document.createElement("audio")),"setSinkId"in e)}function n$(){var e;return(null===(e=nP())||void 0===e?void 0:e.name)==="Firefox"}function nK(){var e;return(null===(e=nP())||void 0===e?void 0:e.name)==="Safari"}function nJ(){let e=nP();return(null==e?void 0:e.name)==="Safari"||(null==e?void 0:e.os)==="iOS"}function nX(){var e,t;return!!nY()&&(null!==(t=null===(e=navigator.userAgentData)||void 0===e?void 0:e.mobile)&&void 0!==t?t:/Tablet|iPad|Mobile|Android|BlackBerry/.test(navigator.userAgent))}function nY(){return"undefined"!=typeof document}function nQ(){return"ReactNative"==navigator.product}function nZ(e){return e.hostname.endsWith(".livekit.cloud")||e.hostname.endsWith(".livekit.run")}function n0(){if(global&&global.LiveKitReactNativeGlobal)return global.LiveKitReactNativeGlobal}function n1(){if(!nQ())return;let e=n0();if(e)return e.platform}function n2(){if(nY())return window.devicePixelRatio;if(nQ()){let e=n0();if(e)return e.devicePixelRatio}return 1}function n3(e,t){let i=e.split("."),n=t.split("."),r=Math.min(i.length,n.length);for(let e=0;e<r;++e){let t=parseInt(i[e],10),s=parseInt(n[e],10);if(t>s)return 1;if(t<s)return -1;if(e===r-1&&t===s)return 0}return""===e&&""!==t?-1:""===t?1:i.length==n.length?0:i.length<n.length?-1:1}function n5(e){for(let t of e)t.target.handleResize(t)}function n4(e){for(let t of e)t.target.handleVisibilityChanged(t)}let n6=null,n9=()=>(n6||(n6=new ResizeObserver(n5)),n6),n8=null,n7=()=>(n8||(n8=new IntersectionObserver(n4,{root:null,rootMargin:"0px"})),n8);function re(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:16,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:16,i=arguments.length>2&&void 0!==arguments[2]&&arguments[2],n=arguments.length>3&&void 0!==arguments[3]&&arguments[3],r=document.createElement("canvas");r.width=e,r.height=t;let s=r.getContext("2d");null==s||s.fillRect(0,0,r.width,r.height),n&&s&&(s.beginPath(),s.arc(e/2,t/2,50,0,2*Math.PI,!0),s.closePath(),s.fillStyle="grey",s.fill());let[o]=r.captureStream().getTracks();if(!o)throw Error("Could not get empty media stream video track");return o.enabled=i,o}function rt(){if(!r){let e=new AudioContext,t=e.createOscillator(),i=e.createGain();i.gain.setValueAtTime(0,0);let n=e.createMediaStreamDestination();if(t.connect(i),i.connect(n),t.start(),[r]=n.stream.getAudioTracks(),!r)throw Error("Could not get empty media stream audio track");r.enabled=!1}return r.clone()}class ri{get isResolved(){return this._isResolved}constructor(e,t){this._isResolved=!1,this.onFinally=t,this.promise=new Promise((t,i)=>ib(this,void 0,void 0,function*(){this.resolve=t,this.reject=i,e&&(yield e(t,i))})).finally(()=>{var e;this._isResolved=!0,null===(e=this.onFinally)||void 0===e||e.call(this)})}}function rn(e){if("string"==typeof e||"number"==typeof e)return e;if(Array.isArray(e))return e[0];if(e.exact)return Array.isArray(e.exact)?e.exact[0]:e.exact;if(e.ideal)return Array.isArray(e.ideal)?e.ideal[0]:e.ideal;throw Error("could not unwrap constraint")}function rr(e){return e.startsWith("ws")?e.replace(/^(ws)/,"http"):e}function rs(e){switch(e.reason){case oz.LeaveRequest:return e.context;case oz.Cancelled:return eH.CLIENT_INITIATED;case oz.NotAllowed:return eH.USER_REJECTED;case oz.ServerUnreachable:return eH.JOIN_FAILURE;default:return eH.UNKNOWN_REASON}}function ro(e){return void 0!==e?Number(e):void 0}function ra(e){return void 0!==e?BigInt(e):void 0}function rl(e){return!!e&&!(e instanceof MediaStreamTrack)&&e.isLocal}function rc(e){return!!e&&e.kind==nM.Kind.Audio}function rd(e){return!!e&&e.kind==nM.Kind.Video}function ru(e){return rl(e)&&rd(e)}function rh(e){return rl(e)&&rc(e)}function rp(e){return!!e&&!e.isLocal}function rm(e){return rp(e)&&rd(e)}function rf(e,t,i){var n,r,s,o;let{optionsWithoutProcessor:a,audioProcessor:l,videoProcessor:c}=rS(null!=e?e:{}),d=null==t?void 0:t.processor,u=null==i?void 0:i.processor,h=null!=a?a:{};return!0===h.audio&&(h.audio={}),!0===h.video&&(h.video={}),h.audio&&(rg(h.audio,t),null!==(n=(s=h.audio).deviceId)&&void 0!==n||(s.deviceId={ideal:"default"}),(l||d)&&(h.audio.processor=null!=l?l:d)),h.video&&(rg(h.video,i),null!==(r=(o=h.video).deviceId)&&void 0!==r||(o.deviceId={ideal:"default"}),(c||u)&&(h.video.processor=null!=c?c:u)),h}function rg(e,t){return Object.keys(t).forEach(i=>{void 0===e[i]&&(e[i]=t[i])}),e}function rv(e){var t,i,n,r;let s={};if(e.video){if("object"==typeof e.video){let i={},r=e.video;Object.keys(r).forEach(e=>{"resolution"===e?rg(i,r.resolution):i[e]=r[e]}),s.video=i,null!==(t=(n=s.video).deviceId)&&void 0!==t||(n.deviceId={ideal:"default"})}else s.video=!!e.video&&{deviceId:{ideal:"default"}}}else s.video=!1;return e.audio?"object"==typeof e.audio?(s.audio=e.audio,null!==(i=(r=s.audio).deviceId)&&void 0!==i||(r.deviceId={ideal:"default"})):s.audio={deviceId:{ideal:"default"}}:s.audio=!1,s}function ry(){var e;let t="undefined"!=typeof window&&(window.AudioContext||window.webkitAudioContext);if(t){let i=new t({latencyHint:"interactive"});if("suspended"===i.state&&"undefined"!=typeof window&&(null===(e=window.document)||void 0===e?void 0:e.body)){let e=()=>ib(this,void 0,void 0,function*(){var t;try{"suspended"===i.state&&(yield i.resume())}catch(e){console.warn("Error trying to auto-resume audio context",e)}null===(t=window.document.body)||void 0===t||t.removeEventListener("click",e)});window.document.body.addEventListener("click",e)}return i}}function rb(e){return e===nM.Source.Microphone?"audioinput":e===nM.Source.Camera?"videoinput":void 0}function rk(e){return e.split("/")[1].toLowerCase()}function rT(e){return"mediaStreamTrack"in e?{trackID:e.sid,source:e.source,muted:e.isMuted,enabled:e.mediaStreamTrack.enabled,kind:e.kind,streamID:e.mediaStreamID,streamTrackID:e.mediaStreamTrack.id}:{trackID:e.trackSid,enabled:e.isEnabled,muted:e.isMuted,trackInfo:Object.assign({mimeType:e.mimeType,name:e.trackName,encrypted:e.isEncrypted,kind:e.kind,source:e.source},e.track?rT(e.track):{})}}function rS(e){let t,i;let n=Object.assign({},e);return"object"==typeof n.audio&&n.audio.processor&&(t=n.audio.processor,n.audio=Object.assign(Object.assign({},n.audio),{processor:void 0})),"object"==typeof n.video&&n.video.processor&&(i=n.video.processor,n.video=Object.assign(Object.assign({},n.video),{processor:void 0})),{audioProcessor:t,videoProcessor:i,optionsWithoutProcessor:void 0===n?n:"function"!=typeof structuredClone?JSON.parse(JSON.stringify(n)):"object"==typeof n&&null!==n?structuredClone(Object.assign({},n)):structuredClone(n)}}function rC(e,t){return e.width*e.height<t.width*t.height}class rw extends iS.EventEmitter{constructor(e){super(),this.onWorkerMessage=e=>{var t,i;let{kind:n,data:r}=e.data;switch(n){case"error":ip.error(r.error.message),this.emit(oq.EncryptionError,r.error);break;case"initAck":r.enabled&&this.keyProvider.getKeys().forEach(e=>{this.postKey(e)});break;case"enable":if(r.enabled&&this.keyProvider.getKeys().forEach(e=>{this.postKey(e)}),this.encryptionEnabled!==r.enabled&&r.participantIdentity===(null===(t=this.room)||void 0===t?void 0:t.localParticipant.identity))this.emit(oq.ParticipantEncryptionStatusChanged,r.enabled,this.room.localParticipant),this.encryptionEnabled=r.enabled;else if(r.participantIdentity){let e=null===(i=this.room)||void 0===i?void 0:i.getParticipantByIdentity(r.participantIdentity);if(!e)throw TypeError("couldn't set encryption status, participant not found".concat(r.participantIdentity));this.emit(oq.ParticipantEncryptionStatusChanged,r.enabled,e)}break;case"ratchetKey":this.keyProvider.emit(oV.KeyRatcheted,r.ratchetResult,r.participantIdentity,r.keyIndex)}},this.onWorkerError=e=>{ip.error("e2ee worker encountered an error:",{error:e.error}),this.emit(oq.EncryptionError,e.error)},this.keyProvider=e.keyProvider,this.worker=e.worker,this.encryptionEnabled=!1}setup(e){if(!(void 0!==window.RTCRtpSender&&void 0!==window.RTCRtpSender.prototype.createEncodedStreams||nf()))throw new ny("tried to setup end-to-end encryption on an unsupported browser");if(ip.info("setting up e2ee"),e!==this.room){this.room=e,this.setupEventListeners(e,this.keyProvider);let t={kind:"init",data:{keyProviderOptions:this.keyProvider.getOptions(),loglevel:ig.getLevel()}};this.worker&&(ip.info("initializing worker",{worker:this.worker}),this.worker.onmessage=this.onWorkerMessage,this.worker.onerror=this.onWorkerError,this.worker.postMessage(t))}}setParticipantCryptorEnabled(e,t){ip.debug("set e2ee to ".concat(e," for participant ").concat(t)),this.postEnable(e,t)}setSifTrailer(e){e&&0!==e.length?this.postSifTrailer(e):ip.warn("ignoring server sent trailer as it's empty")}setupEngine(e){e.on(oJ.RTPVideoMapUpdate,e=>{this.postRTPMap(e)})}setupEventListeners(e,t){e.on(o$.TrackPublished,(e,t)=>this.setParticipantCryptorEnabled(e.trackInfo.encryption!==e2.NONE,t.identity)),e.on(o$.ConnectionStateChanged,t=>{t===ae.Connected&&e.remoteParticipants.forEach(e=>{e.trackPublications.forEach(t=>{this.setParticipantCryptorEnabled(t.trackInfo.encryption!==e2.NONE,e.identity)})})}).on(o$.TrackUnsubscribed,(e,t,i)=>{var n;let r={kind:"removeTransform",data:{participantIdentity:i.identity,trackId:e.mediaStreamID}};null===(n=this.worker)||void 0===n||n.postMessage(r)}).on(o$.TrackSubscribed,(e,t,i)=>{this.setupE2EEReceiver(e,i.identity,t.trackInfo)}).on(o$.SignalConnected,()=>{if(!this.room)throw TypeError("expected room to be present on signal connect");t.getKeys().forEach(e=>{this.postKey(e)}),this.setParticipantCryptorEnabled(this.room.localParticipant.isE2EEEnabled,this.room.localParticipant.identity)}),e.localParticipant.on(oK.LocalSenderCreated,(e,t)=>ib(this,void 0,void 0,function*(){this.setupE2EESender(t,e)})),t.on(oV.SetKey,e=>this.postKey(e)).on(oV.RatchetRequest,(e,t)=>this.postRatchetRequest(e,t))}postRatchetRequest(e,t){if(!this.worker)throw Error("could not ratchet key, worker is missing");this.worker.postMessage({kind:"ratchetRequest",data:{participantIdentity:e,keyIndex:t}})}postKey(e){var t;let{key:i,participantIdentity:n,keyIndex:r}=e;if(!this.worker)throw Error("could not set key, worker is missing");let s={kind:"setKey",data:{participantIdentity:n,isPublisher:n===(null===(t=this.room)||void 0===t?void 0:t.localParticipant.identity),key:i,keyIndex:r}};this.worker.postMessage(s)}postEnable(e,t){if(this.worker)this.worker.postMessage({kind:"enable",data:{enabled:e,participantIdentity:t}});else throw 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(!(null===(t=this.room)||void 0===t?void 0:t.localParticipant.identity))throw TypeError("could not post rtp map, local participant identity is missing");let 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");this.worker.postMessage({kind:"setSifTrailer",data:{trailer:e}})}setupE2EEReceiver(e,t,i){if(e.receiver){if(!(null==i?void 0:i.mimeType)||""===i.mimeType)throw TypeError("MimeType missing from trackInfo, cannot set up E2EE cryptor");this.handleReceiver(e.receiver,e.mediaStreamID,t,"video"===e.kind?rk(i.mimeType):void 0)}}setupE2EESender(e,t){if(!rl(e)||!t){t||ip.warn("early return because sender is not ready");return}this.handleSender(t,e.mediaStreamID,void 0)}handleReceiver(e,t,i,n){return ib(this,void 0,void 0,function*(){if(this.worker){if(nf())e.transform=new RTCRtpScriptTransform(this.worker,{kind:"decode",participantIdentity:i,trackId:t,codec:n});else{if(nm in e&&n){this.worker.postMessage({kind:"updateCodec",data:{trackId:t,codec:n,participantIdentity:i}});return}let r=e.writableStream,s=e.readableStream;if(!r||!s){let t=e.createEncodedStreams();e.writableStream=t.writable,r=t.writable,e.readableStream=t.readable,s=t.readable}let o={kind:"decode",data:{readableStream:s,writableStream:r,trackId:t,codec:n,participantIdentity:i,isReuse:nm in e}};this.worker.postMessage(o,[s,r])}e[nm]=!0}})}handleSender(e,t,i){var n;if(!(nm in e)&&this.worker){if(!(null===(n=this.room)||void 0===n?void 0:n.localParticipant.identity)||""===this.room.localParticipant.identity)throw TypeError("local identity needs to be known in order to set up encrypted sender");if(nf()){ip.info("initialize script transform");let n={kind:"encode",participantIdentity:this.room.localParticipant.identity,trackId:t,codec:i};e.transform=new RTCRtpScriptTransform(this.worker,n)}else{ip.info("initialize encoded streams");let n=e.createEncodedStreams(),r={kind:"encode",data:{readableStream:n.readable,writableStream:n.writable,codec:i,trackId:t,participantIdentity:this.room.localParticipant.identity,isReuse:!1}};this.worker.postMessage(r,[n.readable,n.writable])}e[nm]=!0}}}let rE="default";class rP{constructor(){this._previousDevices=[]}static getInstance(){return void 0===this.instance&&(this.instance=new rP),this.instance}get previousDevices(){return this._previousDevices}getDevices(e){return ib(this,arguments,void 0,function(e){var t=this;let i=!(arguments.length>1)||void 0===arguments[1]||arguments[1];return function*(){var n;if((null===(n=rP.userMediaPromiseMap)||void 0===n?void 0:n.size)>0){ip.debug("awaiting getUserMedia promise");try{e?yield rP.userMediaPromiseMap.get(e):yield Promise.all(rP.userMediaPromiseMap.values())}catch(e){ip.warn("error waiting for media permissons")}}let r=yield navigator.mediaDevices.enumerateDevices();if(i&&!(nK()&&t.hasDeviceInUse(e))&&(0===r.filter(t=>t.kind===e).length||r.some(t=>{let i=""===t.label,n=!e||t.kind===e;return i&&n}))){let t=yield navigator.mediaDevices.getUserMedia({video:"audioinput"!==e&&"audiooutput"!==e,audio:"videoinput"!==e&&{deviceId:{ideal:"default"}}});r=yield navigator.mediaDevices.enumerateDevices(),t.getTracks().forEach(e=>{e.stop()})}return t._previousDevices=r,e&&(r=r.filter(t=>t.kind===e)),r}()})}normalizeDeviceId(e,t,i){return ib(this,void 0,void 0,function*(){if(t!==rE)return t;let n=yield this.getDevices(e),r=n.find(e=>e.deviceId===rE);if(!r){ip.warn("could not reliably determine default device");return}let s=n.find(e=>e.deviceId!==rE&&e.groupId===(null!=i?i:r.groupId));if(!s){ip.warn("could not reliably determine default device");return}return null==s?void 0:s.deviceId})}hasDeviceInUse(e){return e?rP.userMediaPromiseMap.has(e):rP.userMediaPromiseMap.size>0}}rP.mediaDeviceKinds=["audioinput","audiooutput","videoinput"],rP.userMediaPromiseMap=new Map,function(e){e[e.WAITING=0]="WAITING",e[e.RUNNING=1]="RUNNING",e[e.COMPLETED=2]="COMPLETED"}(o0||(o0={}));class rx{constructor(){this.pendingTasks=new Map,this.taskMutex=new y,this.nextTaskIndex=0}run(e){return ib(this,void 0,void 0,function*(){let t={id:this.nextTaskIndex++,enqueuedAt:Date.now(),status:o0.WAITING};this.pendingTasks.set(t.id,t);let i=yield this.taskMutex.lock();try{return t.executedAt=Date.now(),t.status=o0.RUNNING,yield e()}finally{t.status=o0.COMPLETED,this.pendingTasks.delete(t.id),i()}})}flush(){return ib(this,void 0,void 0,function*(){return this.run(()=>ib(this,void 0,void 0,function*(){}))})}snapshot(){return Array.from(this.pendingTasks.values())}}function rR(e,t){var i;return e.pathname="".concat((i=e.pathname).endsWith("/")?i:"".concat(i,"/")).concat(t),e.toString()}let rO=["syncState","trickle","offer","answer","simulate","leave"];!function(e){e[e.CONNECTING=0]="CONNECTING",e[e.CONNECTED=1]="CONNECTED",e[e.RECONNECTING=2]="RECONNECTING",e[e.DISCONNECTING=3]="DISCONNECTING",e[e.DISCONNECTED=4]="DISCONNECTED"}(o1||(o1={}));class rA{get currentState(){return this.state}get isDisconnected(){return this.state===o1.DISCONNECTING||this.state===o1.DISCONNECTED}get isEstablishingConnection(){return this.state===o1.CONNECTING||this.state===o1.RECONNECTING}getNextRequestId(){return this._requestId+=1,this._requestId}constructor(){var e;let t=arguments.length>0&&void 0!==arguments[0]&&arguments[0],i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};this.rtt=0,this.state=o1.DISCONNECTED,this.log=ip,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=im(null!==(e=i.loggerName)&&void 0!==e?e:oj.Signal),this.loggerContextCb=i.loggerContextCb,this.useJSON=t,this.requestQueue=new rx,this.queuedRequests=[],this.closingLock=new y,this.connectionLock=new y,this.state=o1.DISCONNECTED}get logContext(){var e,t;return null!==(t=null===(e=this.loggerContextCb)||void 0===e?void 0:e.call(this))&&void 0!==t?t:{}}join(e,t,i,n){return ib(this,void 0,void 0,function*(){return this.state=o1.CONNECTING,this.options=i,yield this.connect(e,t,i,n)})}reconnect(e,t,i,n){return ib(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=o1.RECONNECTING,this.clearPingInterval(),yield this.connect(e,t,Object.assign(Object.assign({},this.options),{reconnect:!0,sid:i,reconnectReason:n}))})}connect(e,t,i,n){this.connectOptions=i;let r=function(e,t){let i=new URL(e.startsWith("http")?e.replace(/^(http)/,"ws"):e);return t.forEach((e,t)=>{i.searchParams.set(t,e)}),rR(i,"rtc")}(e,function(e,t,i){var n;let r=new URLSearchParams;return r.set("access_token",e),i.reconnect&&(r.set("reconnect","1"),i.sid&&r.set("sid",i.sid)),r.set("auto_subscribe",i.autoSubscribe?"1":"0"),r.set("sdk",nQ()?"reactnative":"js"),r.set("version",t.version),r.set("protocol",t.protocol.toString()),t.deviceModel&&r.set("device_model",t.deviceModel),t.os&&r.set("os",t.os),t.osVersion&&r.set("os_version",t.osVersion),t.browser&&r.set("browser",t.browser),t.browserVersion&&r.set("browser_version",t.browserVersion),i.adaptiveStream&&r.set("adaptive_stream","1"),i.reconnectReason&&r.set("reconnect_reason",i.reconnectReason.toString()),(null===(n=navigator.connection)||void 0===n?void 0:n.type)&&r.set("network",navigator.connection.type),r}(t,function(){var e;let t=new th({sdk:tp.JS,protocol:16,version:"2.15.4"});return nQ()&&(t.os=null!==(e=n1())&&void 0!==e?e:""),t}(),i)),s=rR(new URL(rr(r)),"validate");return new Promise((e,t)=>ib(this,void 0,void 0,function*(){let o=yield this.connectionLock.lock();try{let o=()=>ib(this,void 0,void 0,function*(){this.close(),clearTimeout(a),t(new nv("room connection has been cancelled (signal)",oz.Cancelled))}),a=setTimeout(()=>{this.close(),t(new nv("room connection has timed out (signal)",oz.ServerUnreachable))},i.websocketTimeout);(null==n?void 0:n.aborted)&&o(),null==n||n.addEventListener("abort",o);let l=new URL(r);l.searchParams.has("access_token")&&l.searchParams.set("access_token","<redacted>"),this.log.debug("connecting to ".concat(l),Object.assign({reconnect:i.reconnect,reconnectReason:i.reconnectReason},this.logContext)),this.ws&&(yield this.close(!1)),this.ws=new WebSocket(r),this.ws.binaryType="arraybuffer",this.ws.onopen=()=>{clearTimeout(a)},this.ws.onerror=e=>ib(this,void 0,void 0,function*(){if(this.state!==o1.CONNECTED){this.state=o1.DISCONNECTED,clearTimeout(a);try{let i=yield fetch(s);if(i.status.toFixed(0).startsWith("4")){let e=yield i.text();t(new nv(e,oz.NotAllowed,i.status))}else t(new nv("Encountered unknown websocket error during connection: ".concat(e.toString()),oz.InternalError,i.status))}catch(e){t(new nv(e instanceof Error?e.message:"server was not reachable",oz.ServerUnreachable))}return}this.handleWSError(e)}),this.ws.onmessage=r=>ib(this,void 0,void 0,function*(){var s,a,l;let c;if("string"==typeof r.data){let e=JSON.parse(r.data);c=tR.fromJson(e,{ignoreUnknownFields:!0})}else if(r.data instanceof ArrayBuffer)c=tR.fromBinary(new Uint8Array(r.data));else{this.log.error("could not decode websocket message: ".concat(typeof r.data),this.logContext);return}if(this.state!==o1.CONNECTED){let r=!1;if((null===(s=c.message)||void 0===s?void 0:s.case)==="join"?(this.state=o1.CONNECTED,null==n||n.removeEventListener("abort",o),this.pingTimeoutDuration=c.message.value.pingTimeout,this.pingIntervalDuration=c.message.value.pingInterval,this.pingTimeoutDuration&&this.pingTimeoutDuration>0&&(this.log.debug("ping config",Object.assign(Object.assign({},this.logContext),{timeout:this.pingTimeoutDuration,interval:this.pingIntervalDuration})),this.startPingInterval()),e(c.message.value)):this.state===o1.RECONNECTING&&"leave"!==c.message.case?(this.state=o1.CONNECTED,null==n||n.removeEventListener("abort",o),this.startPingInterval(),(null===(a=c.message)||void 0===a?void 0:a.case)==="reconnect"?e(c.message.value):(this.log.debug("declaring signal reconnected without reconnect response received",this.logContext),e(void 0),r=!0)):this.isEstablishingConnection&&"leave"===c.message.case?t(new nv("Received leave request while trying to (re)connect",oz.LeaveRequest,void 0,c.message.value.reason)):i.reconnect||t(new nv("did not receive join response, got ".concat(null===(l=c.message)||void 0===l?void 0:l.case," instead"),oz.InternalError)),!r)return}this.signalLatency&&(yield nq(this.signalLatency)),this.handleSignalResponse(c)}),this.ws.onclose=e=>{this.isEstablishingConnection&&t(new nv("Websocket got closed during a (re)connection attempt",oz.InternalError)),this.log.warn("websocket closed",Object.assign(Object.assign({},this.logContext),{reason:e.reason,code:e.code,wasClean:e.wasClean,state:this.state})),this.handleOnClose(e.reason)}}finally{o()}}))}close(){return ib(this,arguments,void 0,function(){var e=this;let t=!(arguments.length>0)||void 0===arguments[0]||arguments[0];return function*(){let i=yield e.closingLock.lock();try{if(e.clearPingInterval(),t&&(e.state=o1.DISCONNECTING),e.ws){e.ws.onmessage=null,e.ws.onopen=null,e.ws.onclose=null;let t=new Promise(t=>{e.ws?e.ws.onclose=()=>{t()}:t()});e.ws.readyState<e.ws.CLOSING&&(e.ws.close(),yield Promise.race([t,nq(250)])),e.ws=void 0}}finally{t&&(e.state=o1.DISCONNECTED),i()}}()})}sendOffer(e,t){this.log.debug("sending offer",Object.assign(Object.assign({},this.logContext),{offerSdp:e.sdp})),this.sendRequest({case:"offer",value:rM(e,t)})}sendAnswer(e,t){return this.log.debug("sending answer",Object.assign(Object.assign({},this.logContext),{answerSdp:e.sdp})),this.sendRequest({case:"answer",value:rM(e,t)})}sendIceCandidate(e,t){return this.log.debug("sending ice candidate",Object.assign(Object.assign({},this.logContext),{candidate:e})),this.sendRequest({case:"trickle",value:new tI({candidateInit:JSON.stringify(e),target:t})})}sendMuteTrack(e,t){return this.sendRequest({case:"mute",value:new tM({sid:e,muted:t})})}sendAddTrack(e){return this.sendRequest({case:"addTrack",value:e})}sendUpdateLocalMetadata(e,t){return ib(this,arguments,void 0,function(e,t){var i=this;let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return function*(){let r=i.getNextRequestId();return yield i.sendRequest({case:"updateMetadata",value:new tG({requestId:r,metadata:e,name:t,attributes:n})}),r}()})}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 tH({trackSid:e,layers:t})})}sendUpdateSubscriptionPermissions(e,t){return this.sendRequest({case:"subscriptionPermission",value:new t5({allParticipants:e,trackPermissions:t})})}sendSimulateScenario(e){return this.sendRequest({case:"simulate",value:e})}sendPing(){return Promise.all([this.sendRequest({case:"ping",value:j.parse(Date.now())}),this.sendRequest({case:"pingReq",value:new it({timestamp:j.parse(Date.now()),rtt:j.parse(this.rtt)})})])}sendUpdateLocalAudioTrack(e,t){return this.sendRequest({case:"updateAudioTrack",value:new tB({trackSid:e,features:t})})}sendLeave(){return this.sendRequest({case:"leave",value:new tW({reason:eH.CLIENT_INITIATED,action:tz.DISCONNECT})})}sendRequest(e){return ib(this,arguments,void 0,function(e){var t=this;let i=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return function*(){if(!i&&!function(e){let t=rO.indexOf(e.case)>=0;return ip.trace("request allowed to bypass queue:",{canPass:t,req:e}),t}(e)&&t.state===o1.RECONNECTING){t.queuedRequests.push(()=>ib(t,void 0,void 0,function*(){yield this.sendRequest(e,!0)}));return}if(i||(yield t.requestQueue.flush()),t.signalLatency&&(yield nq(t.signalLatency)),t.isDisconnected){t.log.debug("skipping signal request (type: ".concat(e.case,") - SignalClient disconnected"));return}if(!t.ws||t.ws.readyState!==t.ws.OPEN){t.log.error("cannot send signal request before connected, type: ".concat(null==e?void 0:e.case),t.logContext);return}let n=new tx({message:e});try{t.useJSON?t.ws.send(n.toJsonString()):t.ws.send(n.toBinary())}catch(e){t.log.error("error sending signal message",Object.assign(Object.assign({},t.logContext),{error:e}))}}()})}handleSignalResponse(e){var t,i;let n=e.message;if(void 0==n){this.log.debug("received unsupported message",this.logContext);return}let r=!1;if("answer"===n.case){let e=rI(n.value);this.onAnswer&&this.onAnswer(e,n.value.id)}else if("offer"===n.case){let e=rI(n.value);this.onOffer&&this.onOffer(e,n.value.id)}else if("trickle"===n.case){let e=JSON.parse(n.value.candidateInit);this.onTrickle&&this.onTrickle(e,n.value.target)}else"update"===n.case?this.onParticipantUpdate&&this.onParticipantUpdate(null!==(t=n.value.participants)&&void 0!==t?t:[]):"trackPublished"===n.case?this.onLocalTrackPublished&&this.onLocalTrackPublished(n.value):"speakersChanged"===n.case?this.onSpeakersChanged&&this.onSpeakersChanged(null!==(i=n.value.speakers)&&void 0!==i?i:[]):"leave"===n.case?this.onLeave&&this.onLeave(n.value):"mute"===n.case?this.onRemoteMuteChanged&&this.onRemoteMuteChanged(n.value.sid,n.value.muted):"roomUpdate"===n.case?this.onRoomUpdate&&n.value.room&&this.onRoomUpdate(n.value.room):"connectionQuality"===n.case?this.onConnectionQuality&&this.onConnectionQuality(n.value):"streamStateUpdate"===n.case?this.onStreamStateUpdate&&this.onStreamStateUpdate(n.value):"subscribedQualityUpdate"===n.case?this.onSubscribedQualityUpdate&&this.onSubscribedQualityUpdate(n.value):"subscriptionPermissionUpdate"===n.case?this.onSubscriptionPermissionUpdate&&this.onSubscriptionPermissionUpdate(n.value):"refreshToken"===n.case?this.onTokenRefresh&&this.onTokenRefresh(n.value):"trackUnpublished"===n.case?this.onLocalTrackUnpublished&&this.onLocalTrackUnpublished(n.value):"subscriptionResponse"===n.case?this.onSubscriptionError&&this.onSubscriptionError(n.value):"pong"===n.case||("pongResp"===n.case?(this.rtt=Date.now()-Number.parseInt(n.value.lastPingTimestamp.toString()),this.resetPingTimeout(),r=!0):"requestResponse"===n.case?this.onRequestResponse&&this.onRequestResponse(n.value):"trackSubscribed"===n.case?this.onLocalTrackSubscribed&&this.onLocalTrackSubscribed(n.value.trackSid):"roomMoved"===n.case?(this.onTokenRefresh&&this.onTokenRefresh(n.value.token),this.onRoomMoved&&this.onRoomMoved(n.value)):this.log.debug("unsupported message",Object.assign(Object.assign({},this.logContext),{msgCase:n.case})));r||this.resetPingTimeout()}setReconnected(){for(;this.queuedRequests.length>0;){let e=this.queuedRequests.shift();e&&this.requestQueue.run(e)}}handleOnClose(e){return ib(this,void 0,void 0,function*(){if(this.state===o1.DISCONNECTED)return;let 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=nA.setTimeout(()=>{this.log.warn("ping timeout triggered. last pong received at: ".concat(new Date(Date.now()-1e3*this.pingTimeoutDuration).toUTCString()),this.logContext),this.handleOnClose("ping timeout")},1e3*this.pingTimeoutDuration)}clearPingTimeout(){this.pingTimeout&&nA.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=nA.setInterval(()=>{this.sendPing()},1e3*this.pingIntervalDuration)}clearPingInterval(){this.log.debug("clearing ping interval",this.logContext),this.clearPingTimeout(),this.pingInterval&&nA.clearInterval(this.pingInterval)}}function rI(e){let t={type:"offer",sdp:e.sdp};switch(e.type){case"answer":case"offer":case"pranswer":case"rollback":t.type=e.type}return t}function rM(e,t){return new tj({sdp:e.sdp,type:e.type,id:t})}class rD{constructor(){this.buffer=[],this._totalSize=0}push(e){this.buffer.push(e),this._totalSize+=e.data.byteLength}pop(){let e=this.buffer.shift();return e&&(this._totalSize-=e.data.byteLength),e}getAll(){return this.buffer.slice()}popToSequence(e){for(;this.buffer.length>0;)if(this.buffer[0].sequence<=e)this.pop();else break}alignBufferedAmount(e){for(;this.buffer.length>0;){let t=this.buffer[0];if(this._totalSize-t.data.byteLength<=e)break;this.pop()}}get length(){return this.buffer.length}}class r_{constructor(e){this._map=new Map,this._lastCleanup=0,this.ttl=e}set(e,t){let i=Date.now();i-this._lastCleanup>this.ttl/2&&this.cleanup();let n=i+this.ttl;return this._map.set(e,{value:t,expiresAt:n}),this}get(e){let t=this._map.get(e);if(t){if(t.expiresAt<Date.now()){this._map.delete(e);return}return t.value}}has(e){let t=this._map.get(e);return!!t&&(!(t.expiresAt<Date.now())||(this._map.delete(e),!1))}delete(e){return this._map.delete(e)}clear(){this._map.clear()}cleanup(){let e=Date.now();for(let[t,i]of this._map.entries())i.expiresAt<e&&this._map.delete(t);this._lastCleanup=e}get size(){return this.cleanup(),this._map.size}forEach(e){for(let[t,i]of(this.cleanup(),this._map.entries()))i.expiresAt>=Date.now()&&e(i.value,t,this.asValueMap())}map(e){this.cleanup();let t=[],i=this.asValueMap();for(let[n,r]of i.entries())t.push(e(r,n,i));return t}asValueMap(){let e=new Map;for(let[t,i]of this._map.entries())i.expiresAt>=Date.now()&&e.set(t,i.value);return e}}var rN={},rL={},rj={exports:{}};function rU(){if(o2)return rj.exports;o2=1;var e=rj.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 null!=e.address?"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 null!=e.subtype?"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 null!=e.sessionConfig?"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+=(null!=e.raddr?" raddr %s rport %d":"%v%v")+(null!=e.tcptype?" tcptype %s":"%v"),null!=e.generation&&(t+=" generation %d"),t+=(null!=e["network-id"]?" network-id %d":"%v")+(null!=e["network-cost"]?" network-cost %d":"%v")}},{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 null!=e.attribute&&(t+=" %s",null!=e.value&&(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 null!=e.maxMessageSize?"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: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: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"+(null!=e.clksrcExt?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(e){return"mediaclk:"+((null!=e.id?"id=%s %s":"%v%s")+(null!=e.mediaClockValue?"=%s":"")+(null!=e.rateNumerator?" rate=%s":""))+(null!=e.rateDenominator?"/%s":"")}},{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(e).forEach(function(t){e[t].forEach(function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")})}),rj.exports}var rF=function(){if(o6)return rN;o6=1;var e,t,i,n,r,s,o=(o3||(o3=1,e=function(e){return String(Number(e))===e?Number(e):e},t=function(t,i,n,r){if(r&&!n)i[r]=e(t[1]);else for(var s=0;s<n.length;s+=1)null!=t[s+1]&&(i[n[s]]=e(t[s+1]))},i=function(e,i,n){var r=e.name&&e.names;e.push&&!i[e.push]?i[e.push]=[]:r&&!i[e.name]&&(i[e.name]={});var s=e.push?{}:r?i[e.name]:i;t(n.match(e.reg),s,e.names,e.name),e.push&&i[e.push].push(s)},n=rU(),r=RegExp.prototype.test.bind(/^([a-z])=(.*)/),rL.parse=function(e){var t={},s=[],o=t;return e.split(/(\r\n|\r|\n)/).filter(r).forEach(function(e){var t=e[0],r=e.slice(2);"m"===t&&(s.push({rtp:[],fmtp:[]}),o=s[s.length-1]);for(var a=0;a<(n[t]||[]).length;a+=1){var l=n[t][a];if(l.reg.test(r))return i(l,o,r)}}),t.media=s,t},s=function(t,i){var n=i.split(/=(.+)/,2);return 2===n.length?t[n[0]]=e(n[1]):1===n.length&&i.length>1&&(t[n[0]]=void 0),t},rL.parseParams=function(e){return e.split(/;\s?/).reduce(s,{})},rL.parseFmtpConfig=rL.parseParams,rL.parsePayloads=function(e){return e.toString().split(" ").map(Number)},rL.parseRemoteCandidates=function(t){for(var i=[],n=t.split(" ").map(e),r=0;r<n.length;r+=3)i.push({component:n[r],ip:n[r+1],port:n[r+2]});return i},rL.parseImageAttributes=function(e){return e.split(" ").map(function(e){return e.substring(1,e.length-1).split(",").reduce(s,{})})},rL.parseSimulcastStreamList=function(t){return t.split(";").map(function(t){return t.split(",").map(function(t){var i,n=!1;return"~"!==t[0]?i=e(t):(i=e(t.substring(1,t.length)),n=!0),{scid:i,paused:n}})})}),rL),a=function(){if(o4)return o5;o4=1;var e=rU(),t=/%[sdv%]/g,i=function(e){var i=1,n=arguments,r=n.length;return e.replace(t,function(e){if(i>=r)return e;var t=n[i];switch(i+=1,e){case"%%":return"%";case"%s":return String(t);case"%d":return Number(t);case"%v":return""}})},n=function(e,t,n){var r=[e+"="+(t.format instanceof Function?t.format(t.push?n:n[t.name]):t.format)];if(t.names)for(var s=0;s<t.names.length;s+=1){var o=t.names[s];t.name?r.push(n[t.name][o]):r.push(n[t.names[s]])}else r.push(n[t.name]);return i.apply(null,r)},r=["v","o","s","i","u","e","p","c","b","t","r","z","a"],s=["i","c","b","a"];return o5=function(t,i){i=i||{},null==t.version&&(t.version=0),null==t.name&&(t.name=" "),t.media.forEach(function(e){null==e.payloads&&(e.payloads="")});var o=i.outerOrder||r,a=i.innerOrder||s,l=[];return o.forEach(function(i){e[i].forEach(function(e){e.name in t&&null!=t[e.name]?l.push(n(i,e,t)):e.push in t&&null!=t[e.push]&&t[e.push].forEach(function(t){l.push(n(i,e,t))})})}),t.media.forEach(function(t){l.push(n("m",e.m[0],t)),a.forEach(function(i){e[i].forEach(function(e){e.name in t&&null!=t[e.name]?l.push(n(i,e,t)):e.push in t&&null!=t[e.push]&&t[e.push].forEach(function(t){l.push(n(i,e,t))})})})}),l.join("\r\n")+"\r\n"}}(),l=rU();return rN.grammar=l,rN.write=a,rN.parse=o.parse,rN.parseParams=o.parseParams,rN.parseFmtpConfig=o.parseFmtpConfig,rN.parsePayloads=o.parsePayloads,rN.parseRemoteCandidates=o.parseRemoteCandidates,rN.parseImageAttributes=o.parseImageAttributes,rN.parseSimulcastStreamList=o.parseSimulcastStreamList,rN}();function rV(e,t,i){void 0===t&&(t=50),void 0===i&&(i={});var n,r,s,o=null!=(n=i.isImmediate)&&n,a=null!=(r=i.callback)&&r,l=i.maxWait,c=Date.now(),d=[],u=function(){var i=[].slice.call(arguments),n=this;return new Promise(function(r,u){var h=o&&void 0===s;if(void 0!==s&&clearTimeout(s),s=setTimeout(function(){if(s=void 0,c=Date.now(),!o){var t=e.apply(n,i);a&&a(t),d.forEach(function(e){return(0,e.resolve)(t)}),d=[]}},function(){if(void 0!==l){var e=Date.now()-c;if(e+t>=l)return l-e}return t}()),h){var p=e.apply(n,i);return a&&a(p),r(p)}d.push({resolve:r,reject:u})})};return u.cancel=function(e){void 0!==s&&clearTimeout(s),d.forEach(function(t){return(0,t.reject)(e)}),d=[]},u}let rB={NegotiationStarted:"negotiationStarted",NegotiationComplete:"negotiationComplete",RTPVideoPayloadTypes:"rtpVideoPayloadTypes"};class rq extends iS.EventEmitter{get pc(){return this._pc||(this._pc=this.createPC()),this._pc}constructor(e){var t;let i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};super(),this.log=ip,this.ddExtID=0,this.latestOfferId=0,this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate=!1,this.trackBitrates=[],this.remoteStereoMids=[],this.remoteNackMids=[],this.negotiate=rV(e=>ib(this,void 0,void 0,function*(){this.emit(rB.NegotiationStarted);try{yield this.createAndSendOffer()}catch(t){if(e)e(t);else throw t}}),20),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=im(null!==(t=i.loggerName)&&void 0!==t?t:oj.PCTransport),this.loggerOptions=i,this.config=e,this._pc=this.createPC(),this.offerLock=new y}createPC(){let e=new RTCPeerConnection(this.config);return e.onicecandidate=e=>{var t;e.candidate&&(null===(t=this.onIceCandidate)||void 0===t||t.call(this,e.candidate))},e.onicecandidateerror=e=>{var t;null===(t=this.onIceCandidateError)||void 0===t||t.call(this,e)},e.oniceconnectionstatechange=()=>{var t;null===(t=this.onIceConnectionStateChange)||void 0===t||t.call(this,e.iceConnectionState)},e.onsignalingstatechange=()=>{var t;null===(t=this.onSignalingStatechange)||void 0===t||t.call(this,e.signalingState)},e.onconnectionstatechange=()=>{var t;null===(t=this.onConnectionStateChange)||void 0===t||t.call(this,e.connectionState)},e.ondatachannel=e=>{var t;null===(t=this.onDataChannel)||void 0===t||t.call(this,e)},e.ontrack=e=>{var t;null===(t=this.onTrack)||void 0===t||t.call(this,e)},e}get logContext(){var e,t;return Object.assign({},null===(t=(e=this.loggerOptions).loggerContextCb)||void 0===t?void 0:t.call(e))}get isICEConnected(){return null!==this._pc&&("connected"===this.pc.iceConnectionState||"completed"===this.pc.iceConnectionState)}addIceCandidate(e){return ib(this,void 0,void 0,function*(){if(this.pc.remoteDescription&&!this.restartingIce)return this.pc.addIceCandidate(e);this.pendingCandidates.push(e)})}setRemoteDescription(e,t){return ib(this,void 0,void 0,function*(){var i;let n;if("answer"===e.type&&this.latestOfferId>0&&t>0&&t!==this.latestOfferId)return this.log.warn("ignoring answer for old offer",Object.assign(Object.assign({},this.logContext),{offerId:t,latestOfferId:this.latestOfferId})),!1;if("offer"===e.type){let{stereoMids:t,nackMids:i}=function(e){var t;let i=[],n=[],r=rF.parse(null!==(t=e.sdp)&&void 0!==t?t:""),s=0;return r.media.forEach(e=>{var t;"audio"===e.type&&(e.rtp.some(e=>"opus"===e.codec&&(s=e.payload,!0)),(null===(t=e.rtcpFb)||void 0===t?void 0:t.some(e=>e.payload===s&&"nack"===e.type))&&n.push(e.mid),e.fmtp.some(t=>t.payload===s&&(t.config.includes("sprop-stereo=1")&&i.push(e.mid),!0)))}),{stereoMids:i,nackMids:n}}(e);this.remoteStereoMids=t,this.remoteNackMids=i}else if("answer"===e.type){let t=rF.parse(null!==(i=e.sdp)&&void 0!==i?i:"");t.media.forEach(e=>{"audio"===e.type&&this.trackBitrates.some(t=>{if(!t.transceiver||e.mid!=t.transceiver.mid)return!1;let i=0;if(e.rtp.some(e=>e.codec.toUpperCase()===t.codec.toUpperCase()&&(i=e.payload,!0)),0===i)return!0;let n=!1;for(let r of e.fmtp)if(r.payload===i){r.config=r.config.split(";").filter(e=>!e.includes("maxaveragebitrate")).join(";"),t.maxbr>0&&(r.config+=";maxaveragebitrate=".concat(1e3*t.maxbr)),n=!0;break}return!n&&t.maxbr>0&&e.fmtp.push({payload:i,config:"maxaveragebitrate=".concat(1e3*t.maxbr)}),!0})}),n=rF.write(t)}return yield this.setMungedSDP(e,n,!0),this.pendingCandidates.forEach(e=>{this.pc.addIceCandidate(e)}),this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate?(this.renegotiate=!1,yield this.createAndSendOffer()):"answer"===e.type&&(this.emit(rB.NegotiationComplete),e.sdp&&rF.parse(e.sdp).media.forEach(e=>{"video"===e.type&&this.emit(rB.RTPVideoPayloadTypes,e.rtp)})),!0})}createAndSendOffer(e){return ib(this,void 0,void 0,function*(){var t;let i=yield this.offerLock.lock();try{if(void 0===this.onOffer)return;if((null==e?void 0:e.iceRestart)&&(this.log.debug("restarting ICE",this.logContext),this.restartingIce=!0),this._pc&&"have-local-offer"===this._pc.signalingState){let t=this._pc.remoteDescription;if((null==e?void 0:e.iceRestart)&&t)yield this._pc.setRemoteDescription(t);else{this.renegotiate=!0;return}}else if(!this._pc||"closed"===this._pc.signalingState){this.log.warn("could not createOffer with closed peer connection",this.logContext);return}this.log.debug("starting to negotiate",this.logContext);let i=this.latestOfferId+1;this.latestOfferId=i;let n=yield this.pc.createOffer(e);this.log.debug("original offer",Object.assign({sdp:n.sdp},this.logContext));let r=rF.parse(null!==(t=n.sdp)&&void 0!==t?t:"");if(r.media.forEach(e=>{rz(e),"audio"===e.type?rW(e,[],[]):"video"===e.type&&this.trackBitrates.some(t=>{if(!e.msid||!t.cid||!e.msid.includes(t.cid))return!1;let i=0;if(e.rtp.some(e=>e.codec.toUpperCase()===t.codec.toUpperCase()&&(i=e.payload,!0)),0===i||(nH(t.codec)&&!nK()&&this.ensureVideoDDExtensionForSVC(e,r),"av1"!==t.codec))return!0;let n=Math.round(.7*t.maxbr);for(let t of e.fmtp)if(t.payload===i){t.config.includes("x-google-start-bitrate")||(t.config+=";x-google-start-bitrate=".concat(n));break}return!0})}),this.latestOfferId>i){this.log.warn("latestOfferId mismatch",Object.assign(Object.assign({},this.logContext),{latestOfferId:this.latestOfferId,offerId:i}));return}yield this.setMungedSDP(n,rF.write(r)),this.onOffer(n,this.latestOfferId)}finally{i()}})}createAndSetAnswer(){return ib(this,void 0,void 0,function*(){var e;let t=yield this.pc.createAnswer(),i=rF.parse(null!==(e=t.sdp)&&void 0!==e?e:"");return i.media.forEach(e=>{rz(e),"audio"===e.type&&rW(e,this.remoteStereoMids,this.remoteNackMids)}),yield this.setMungedSDP(t,rF.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 nT("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 nT("PC closed, cannot configure");return null===(t=this._pc)||void 0===t?void 0:t.setConfiguration(e)}canRemoveTrack(){var e;return!!(null===(e=this._pc)||void 0===e?void 0:e.removeTrack)}removeTrack(e){var t;return null===(t=this._pc)||void 0===t?void 0:t.removeTrack(e)}getConnectionState(){var e,t;return null!==(t=null===(e=this._pc)||void 0===e?void 0:e.connectionState)&&void 0!==t?t:"closed"}getICEConnectionState(){var e,t;return null!==(t=null===(e=this._pc)||void 0===e?void 0:e.iceConnectionState)&&void 0!==t?t:"closed"}getSignallingState(){var e,t;return null!==(t=null===(e=this._pc)||void 0===e?void 0:e.signalingState)&&void 0!==t?t:"closed"}getTransceivers(){var e,t;return null!==(t=null===(e=this._pc)||void 0===e?void 0:e.getTransceivers())&&void 0!==t?t:[]}getSenders(){var e,t;return null!==(t=null===(e=this._pc)||void 0===e?void 0:e.getSenders())&&void 0!==t?t:[]}getLocalDescription(){var e;return null===(e=this._pc)||void 0===e?void 0:e.localDescription}getRemoteDescription(){var e;return null===(e=this.pc)||void 0===e?void 0:e.remoteDescription}getStats(){return this.pc.getStats()}getConnectedAddress(){return ib(this,void 0,void 0,function*(){var e;if(!this._pc)return;let t="",i=new Map,n=new Map;if((yield this._pc.getStats()).forEach(e=>{switch(e.type){case"transport":t=e.selectedCandidatePairId;break;case"candidate-pair":""===t&&e.selected&&(t=e.id),i.set(e.id,e);break;case"remote-candidate":n.set(e.id,"".concat(e.address,":").concat(e.port))}}),""===t)return;let r=null===(e=i.get(t))||void 0===e?void 0:e.remoteCandidateId;if(void 0!==r)return n.get(r)})}setMungedSDP(e,t,i){return ib(this,void 0,void 0,function*(){if(t){let n=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(i){this.log.warn("not able to set ".concat(e.type,", falling back to unmodified sdp"),Object.assign(Object.assign({},this.logContext),{error:i,sdp:t})),e.sdp=n}}try{i?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e)}catch(r){let t="unknown error";r instanceof Error?t=r.message:"string"==typeof r&&(t=r);let n={error:t,sdp:e.sdp};throw!i&&this.pc.remoteDescription&&(n.remoteSdp=this.pc.remoteDescription),this.log.error("unable to set ".concat(e.type),Object.assign(Object.assign({},this.logContext),{fields:n})),new nS(t)}})}ensureVideoDDExtensionForSVC(e,t){var i,n;if(!(null===(i=e.ext)||void 0===i?void 0:i.some(e=>e.uri===nB))){if(0===this.ddExtID){let e=0;t.media.forEach(t=>{var i;"video"===t.type&&(null===(i=t.ext)||void 0===i||i.forEach(t=>{t.value>e&&(e=t.value)}))}),this.ddExtID=e+1}null===(n=e.ext)||void 0===n||n.push({value:this.ddExtID,uri:nB})}}}function rW(e,t,i){let n=0;e.rtp.some(e=>"opus"===e.codec&&(n=e.payload,!0)),n>0&&(e.rtcpFb||(e.rtcpFb=[]),i.includes(e.mid)&&!e.rtcpFb.some(e=>e.payload===n&&"nack"===e.type)&&e.rtcpFb.push({payload:n,type:"nack"}),t.includes(e.mid)&&e.fmtp.some(e=>e.payload===n&&(e.config.includes("stereo=1")||(e.config+=";stereo=1"),!0)))}function rz(e){if(e.connection){let t=e.connection.ip.indexOf(":")>=0;(4===e.connection.version&&t||6===e.connection.version&&!t)&&(e.connection.ip="0.0.0.0",e.connection.version=4)}}let rH={audioPreset:oZ.music,dtx:!0,red:!0,forceStereo:!1,simulcast:!0,screenShareEncoding:nV.h1080fps15.encoding,stopMicTrackOnMute:!1,videoCodec:"vp8",backupCodec:!0,preConnectBuffer:!1},rG={deviceId:{ideal:"default"},autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0,voiceIsolation:!0},r$={deviceId:{ideal:"default"},resolution:nU.h720.resolution},rK={adaptiveStream:!1,dynacast:!1,stopLocalTrackOnUnpublish:!0,reconnectPolicy:new iy,disconnectOnPageLeave:!0,webAudioMix:!1},rJ={autoSubscribe:!0,maxRetries:1,peerConnectionTimeout:15e3,websocketTimeout:15e3};!function(e){e[e.NEW=0]="NEW",e[e.CONNECTING=1]="CONNECTING",e[e.CONNECTED=2]="CONNECTED",e[e.FAILED=3]="FAILED",e[e.CLOSING=4]="CLOSING",e[e.CLOSED=5]="CLOSED"}(o9||(o9={}));class rX{get needsPublisher(){return this.isPublisherConnectionRequired}get needsSubscriber(){return this.isSubscriberConnectionRequired}get currentState(){return this.state}constructor(e,t,i){var n;this.peerConnectionTimeout=rJ.peerConnectionTimeout,this.log=ip,this.updateState=()=>{var e;let t=this.state,i=this.requiredTransports.map(e=>e.getConnectionState());i.every(e=>"connected"===e)?this.state=o9.CONNECTED:i.some(e=>"failed"===e)?this.state=o9.FAILED:i.some(e=>"connecting"===e)?this.state=o9.CONNECTING:i.every(e=>"closed"===e)?this.state=o9.CLOSED:i.some(e=>"closed"===e)?this.state=o9.CLOSING:i.every(e=>"new"===e)&&(this.state=o9.NEW),t!==this.state&&(this.log.debug("pc state change: from ".concat(o9[t]," to ").concat(o9[this.state]),this.logContext),null===(e=this.onStateChange)||void 0===e||e.call(this,this.state,this.publisher.getConnectionState(),this.subscriber.getConnectionState()))},this.log=im(null!==(n=i.loggerName)&&void 0!==n?n:oj.PCManager),this.loggerOptions=i,this.isPublisherConnectionRequired=!t,this.isSubscriberConnectionRequired=t,this.publisher=new rq(e,i),this.subscriber=new rq(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=e=>{var t;null===(t=this.onIceCandidate)||void 0===t||t.call(this,e,tw.PUBLISHER)},this.subscriber.onIceCandidate=e=>{var t;null===(t=this.onIceCandidate)||void 0===t||t.call(this,e,tw.SUBSCRIBER)},this.subscriber.onDataChannel=e=>{var t;null===(t=this.onDataChannel)||void 0===t||t.call(this,e)},this.subscriber.onTrack=e=>{var t;null===(t=this.onTrack)||void 0===t||t.call(this,e)},this.publisher.onOffer=(e,t)=>{var i;null===(i=this.onPublisherOffer)||void 0===i||i.call(this,e,t)},this.state=o9.NEW,this.connectionLock=new y,this.remoteOfferLock=new y}get logContext(){var e,t;return Object.assign({},null===(t=(e=this.loggerOptions).loggerContextCb)||void 0===t?void 0:t.call(e))}requirePublisher(){let e=!(arguments.length>0)||void 0===arguments[0]||arguments[0];this.isPublisherConnectionRequired=e,this.updateState()}requireSubscriber(){let e=!(arguments.length>0)||void 0===arguments[0]||arguments[0];this.isSubscriberConnectionRequired=e,this.updateState()}createAndSendPublisherOffer(e){return this.publisher.createAndSendOffer(e)}setPublisherAnswer(e,t){return this.publisher.setRemoteDescription(e,t)}removeTrack(e){return this.publisher.removeTrack(e)}close(){return ib(this,void 0,void 0,function*(){if(this.publisher&&"closed"!==this.publisher.getSignallingState()){let e=this.publisher;for(let t of e.getSenders())try{e.canRemoveTrack()&&e.removeTrack(t)}catch(e){this.log.warn("could not removeTrack",Object.assign(Object.assign({},this.logContext),{error:e}))}}yield Promise.all([this.publisher.close(),this.subscriber.close()]),this.updateState()})}triggerIceRestart(){return ib(this,void 0,void 0,function*(){this.subscriber.restartingIce=!0,this.needsPublisher&&(yield this.createAndSendPublisherOffer({iceRestart:!0}))})}addIceCandidate(e,t){return ib(this,void 0,void 0,function*(){t===tw.PUBLISHER?yield this.publisher.addIceCandidate(e):yield this.subscriber.addIceCandidate(e)})}createSubscriberAnswerFromOffer(e,t){return ib(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()}));let i=yield this.remoteOfferLock.lock();try{if(!(yield this.subscriber.setRemoteDescription(e,t)))return;return yield this.subscriber.createAndSetAnswer()}finally{i()}})}updateConfiguration(e,t){this.publisher.setConfiguration(e),this.subscriber.setConfiguration(e),t&&this.triggerIceRestart()}ensurePCTransportConnection(e,t){return ib(this,void 0,void 0,function*(){var i;let n=yield this.connectionLock.lock();try{this.isPublisherConnectionRequired&&"connected"!==this.publisher.getConnectionState()&&"connecting"!==this.publisher.getConnectionState()&&(this.log.debug("negotiation required, start negotiating",this.logContext),this.publisher.negotiate()),yield Promise.all(null===(i=this.requiredTransports)||void 0===i?void 0:i.map(i=>this.ensureTransportConnected(i,e,t)))}finally{n()}})}negotiate(e){return ib(this,void 0,void 0,function*(){return new Promise((t,i)=>ib(this,void 0,void 0,function*(){let n=setTimeout(()=>{i("negotiation timed out")},this.peerConnectionTimeout);e.signal.addEventListener("abort",()=>{clearTimeout(n),i("negotiation aborted")}),this.publisher.once(rB.NegotiationStarted,()=>{e.signal.aborted||this.publisher.once(rB.NegotiationComplete,()=>{clearTimeout(n),t()})}),yield this.publisher.negotiate(e=>{clearTimeout(n),i(e)})}))})}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===tw.PUBLISHER?this.publisher.getConnectedAddress():e===tw.SUBSCRIBER?this.publisher.getConnectedAddress():this.requiredTransports[0].getConnectedAddress()}get requiredTransports(){let e=[];return this.isPublisherConnectionRequired&&e.push(this.publisher),this.isSubscriberConnectionRequired&&e.push(this.subscriber),e}ensureTransportConnected(e,t){return ib(this,arguments,void 0,function(e,t){var i=this;let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:this.peerConnectionTimeout;return function*(){if("connected"!==e.getConnectionState())return new Promise((e,r)=>ib(i,void 0,void 0,function*(){let i=()=>{this.log.warn("abort transport connection",this.logContext),nA.clearTimeout(s),r(new nv("room connection has been cancelled",oz.Cancelled))};(null==t?void 0:t.signal.aborted)&&i(),null==t||t.signal.addEventListener("abort",i);let s=nA.setTimeout(()=>{null==t||t.signal.removeEventListener("abort",i),r(new nv("could not establish pc connection",oz.InternalError))},n);for(;this.state!==o9.CONNECTED;)if(yield nq(50),null==t?void 0:t.signal.aborted){r(new nv("room connection has been cancelled",oz.Cancelled));return}nA.clearTimeout(s),null==t||t.signal.removeEventListener("abort",i),e()}))}()})}}class rY extends Error{constructor(e,t,i){super(t),this.code=e,this.message=rZ(t,rY.MAX_MESSAGE_BYTES),this.data=i?rZ(i,rY.MAX_DATA_BYTES):void 0}static fromProto(e){return new rY(e.code,e.message,e.data)}toProto(){return new tl({code:this.code,message:this.message,data:this.data})}static builtIn(e,t){return new rY(rY.ErrorCode[e],rY.ErrorMessage[e],t)}}function rQ(e){return new TextEncoder().encode(e).length}function rZ(e,t){if(rQ(e)<=t)return e;let i=0,n=e.length,r=new TextEncoder;for(;i<n;){let s=Math.floor((i+n+1)/2);r.encode(e.slice(0,s)).length<=t?i=s:n=s-1}return e.slice(0,i)}function r0(e,t){let i,n;return t?("bytesReceived"in e?(i=e.bytesReceived,n=t.bytesReceived):"bytesSent"in e&&(i=e.bytesSent,n=t.bytesSent),void 0===i||void 0===n||void 0===e.timestamp||void 0===t.timestamp)?0:(i-n)*8e3/(e.timestamp-t.timestamp):0}rY.MAX_MESSAGE_BYTES=256,rY.MAX_DATA_BYTES=15360,rY.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},rY.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"};let r1="undefined"!=typeof MediaRecorder;class r2{constructor(){throw Error("MediaRecorder is not available in this environment")}}let r3=r1?MediaRecorder:r2;class r5 extends r3{constructor(e,t){let i,n;if(!r1)throw Error("MediaRecorder is not available in this environment");super(new MediaStream([e.mediaStreamTrack]),t);let r=()=>void 0===n,s=()=>{this.removeEventListener("dataavailable",i),this.removeEventListener("stop",s),this.removeEventListener("error",o),null==n||n.close(),n=void 0},o=e=>{null==n||n.error(e),this.removeEventListener("dataavailable",i),this.removeEventListener("stop",s),this.removeEventListener("error",o),n=void 0};this.byteStream=new ReadableStream({start:e=>{n=e,i=t=>ib(this,void 0,void 0,function*(){let i;if(t.data.arrayBuffer)i=new Uint8Array((yield t.data.arrayBuffer()));else if(t.data.byteArray)i=t.data.byteArray;else throw Error("no data available!");r()||e.enqueue(i)}),this.addEventListener("dataavailable",i)},cancel:()=>{s()}}),this.addEventListener("stop",s),this.addEventListener("error",o)}}class r4 extends nM{get sender(){return this._sender}set sender(e){this._sender=e}get constraints(){return this._constraints}get hasPreConnectBuffer(){return!!this.localTrackRecorder}constructor(e,t,i){let n=arguments.length>3&&void 0!==arguments[3]&&arguments[3],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=rV(()=>ib(this,void 0,void 0,function*(){yield this.pauseUpstream()}),5e3),this.handleTrackUnmuteEvent=()=>ib(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(oX.Ended,this)},this.reacquireTrack=!1,this.providedByUser=n,this.muteLock=new y,this.pauseUpstreamLock=new y,this.processorLock=new y,this.restartLock=new y,this.setMediaStreamTrack(e,!0),this._constraints=e.getConstraints(),i&&(this._constraints=i)}get id(){return this._mediaStreamTrack.id}get dimensions(){if(this.kind!==nM.Kind.Video)return;let{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 null!==(t=null===(e=this.processor)||void 0===e?void 0:e.processedTrack)&&void 0!==t?t:this._mediaStreamTrack}get isLocal(){return!0}getSourceTrackSettings(){return this._mediaStreamTrack.getSettings()}setMediaStreamTrack(e,t){return ib(this,void 0,void 0,function*(){var i;let n;if(e!==this._mediaStreamTrack||t){if(this._mediaStreamTrack&&(this.attachedElements.forEach(e=>{n_(this._mediaStreamTrack,e)}),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()),this.processor&&e){let t=yield this.processorLock.lock();try{if(this.log.debug("restarting processor",this.logContext),"unknown"===this.kind)throw TypeError("cannot set processor on track of unknown kind");this.processorElement&&(nD(e,this.processorElement),this.processorElement.muted=!0),yield this.processor.restart({track:e,kind:this.kind,element:this.processorElement}),n=this.processor.processedTrack}finally{t()}}this.sender&&(null===(i=this.sender.transport)||void 0===i?void 0:i.state)!=="closed"&&(yield this.sender.replaceTrack(null!=n?n:e)),this.providedByUser||this._mediaStreamTrack===e||this._mediaStreamTrack.stop(),this._mediaStreamTrack=e,e&&(this._mediaStreamTrack.enabled=!this.isMuted,yield this.resumeUpstream(),this.attachedElements.forEach(t=>{nD(null!=n?n:e,t)}))}})}waitForDimensions(){return ib(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1e3;return function*(){var i;if(e.kind===nM.Kind.Audio)throw Error("cannot get dimensions for audio tracks");(null===(i=nP())||void 0===i?void 0:i.os)==="iOS"&&(yield nq(10));let n=Date.now();for(;Date.now()-n<t;){let t=e.dimensions;if(t)return t;yield nq(50)}throw new nb("unable to get track dimensions after timeout")}()})}setDeviceId(e){return ib(this,void 0,void 0,function*(){return this._constraints.deviceId===e&&this._mediaStreamTrack.getSettings().deviceId===rn(e)||(this._constraints.deviceId=e,!!this.isMuted||(yield this.restartTrack(),rn(e)===this._mediaStreamTrack.getSettings().deviceId))})}getDeviceId(){return ib(this,arguments,void 0,function(){var e=this;let t=!(arguments.length>0)||void 0===arguments[0]||arguments[0];return function*(){if(e.source===nM.Source.ScreenShare)return;let{deviceId:i,groupId:n}=e._mediaStreamTrack.getSettings(),r=e.kind===nM.Kind.Audio?"audioinput":"videoinput";return t?rP.getInstance().normalizeDeviceId(r,i,n):i}()})}mute(){return ib(this,void 0,void 0,function*(){return this.setTrackMuted(!0),this})}unmute(){return ib(this,void 0,void 0,function*(){return this.setTrackMuted(!1),this})}replaceTrack(e,t){return ib(this,void 0,void 0,function*(){let i,n;if(!this.sender)throw new nb("unable to replace an unpublished track");return"boolean"==typeof t?i=t:void 0!==t&&(i=t.userProvidedTrack,n=t.stopProcessor),this.providedByUser=null==i||i,this.log.debug("replace MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(e),n&&this.processor&&(yield this.stopProcessor()),this})}restart(e){return ib(this,void 0,void 0,function*(){this.manuallyStopped=!1;let t=yield this.restartLock.lock();try{e||(e=this._constraints);let{deviceId:t,facingMode:i}=e,n=function(e,t){var i={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&0>t.indexOf(n)&&(i[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var r=0,n=Object.getOwnPropertySymbols(e);r<n.length;r++)0>t.indexOf(n[r])&&Object.prototype.propertyIsEnumerable.call(e,n[r])&&(i[n[r]]=e[n[r]]);return i}(e,["deviceId","facingMode"]);this.log.debug("restarting track with constraints",Object.assign(Object.assign({},this.logContext),{constraints:e}));let r={audio:!1,video:!1};this.kind===nM.Kind.Video?r.video=!t&&!i||{deviceId:t,facingMode:i}:r.audio=!t||{deviceId:t},this.attachedElements.forEach(e=>{n_(this.mediaStreamTrack,e)}),this._mediaStreamTrack.removeEventListener("ended",this.handleEnded),this._mediaStreamTrack.stop();let s=(yield navigator.mediaDevices.getUserMedia(r)).getTracks()[0];return yield s.applyConstraints(n),s.addEventListener("ended",this.handleEnded),this.log.debug("re-acquired MediaStreamTrack",this.logContext),yield this.setMediaStreamTrack(s),this._constraints=e,this.emit(oX.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?oX.Muted:oX.Unmuted,this))}get needsReAcquisition(){return"live"!==this._mediaStreamTrack.readyState||this._mediaStreamTrack.muted||!this._mediaStreamTrack.enabled||this.reacquireTrack}handleAppVisibilityChanged(){let e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return ib(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),!nX()||(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),null===(e=this.processor)||void 0===e||e.destroy(),this.processor=void 0}pauseUpstream(){return ib(this,void 0,void 0,function*(){var e;let t=yield this.pauseUpstreamLock.lock();try{if(!0===this._isUpstreamPaused)return;if(!this.sender){this.log.warn("unable to pause upstream for an unpublished track",this.logContext);return}this._isUpstreamPaused=!0,this.emit(oX.UpstreamPaused,this);let t=nP();if((null==t?void 0:t.name)==="Safari"&&0>n3(t.version,"12.0"))throw new ny("pauseUpstream is not supported on Safari < 12.");(null===(e=this.sender.transport)||void 0===e?void 0:e.state)!=="closed"&&(yield this.sender.replaceTrack(null))}finally{t()}})}resumeUpstream(){return ib(this,void 0,void 0,function*(){var e;let t=yield this.pauseUpstreamLock.lock();try{if(!1===this._isUpstreamPaused)return;if(!this.sender){this.log.warn("unable to resume upstream for an unpublished track",this.logContext);return}this._isUpstreamPaused=!1,this.emit(oX.UpstreamResumed,this),(null===(e=this.sender.transport)||void 0===e?void 0:e.state)!=="closed"&&(yield this.sender.replaceTrack(this.mediaStreamTrack))}finally{t()}})}getRTCStatsReport(){return ib(this,void 0,void 0,function*(){var e;if(null===(e=this.sender)||void 0===e?void 0:e.getStats)return yield this.sender.getStats()})}setProcessor(e){return ib(this,arguments,void 0,function(e){var t=this;let i=!(arguments.length>1)||void 0===arguments[1]||arguments[1];return function*(){var n;let r=yield t.processorLock.lock();try{t.log.debug("setting up processor",t.logContext);let r=document.createElement(t.kind),s={kind:t.kind,track:t._mediaStreamTrack,element:r,audioContext:t.audioContext};if(yield e.init(s),t.log.debug("processor initialized",t.logContext),t.processor&&(yield t.stopProcessor()),"unknown"===t.kind)throw TypeError("cannot set processor on track of unknown kind");if(nD(t._mediaStreamTrack,r),r.muted=!0,r.play().catch(e=>{e instanceof DOMException&&"AbortError"===e.name?(t.log.warn("failed to play processor element, retrying",Object.assign(Object.assign({},t.logContext),{error:e})),setTimeout(()=>{r.play().catch(e=>{t.log.error("failed to play processor element",Object.assign(Object.assign({},t.logContext),{err:e}))})},100)):t.log.error("failed to play processor element",Object.assign(Object.assign({},t.logContext),{error:e}))}),t.processor=e,t.processorElement=r,t.processor.processedTrack){for(let e of t.attachedElements)e!==t.processorElement&&i&&(n_(t._mediaStreamTrack,e),nD(t.processor.processedTrack,e));yield null===(n=t.sender)||void 0===n?void 0:n.replaceTrack(t.processor.processedTrack)}t.emit(oX.TrackProcessorUpdate,t.processor)}finally{r()}}()})}getProcessor(){return this.processor}stopProcessor(){return ib(this,arguments,void 0,function(){var e=this;let t=!(arguments.length>0)||void 0===arguments[0]||arguments[0];return function*(){var i,n;e.processor&&(e.log.debug("stopping processor",e.logContext),null===(i=e.processor.processedTrack)||void 0===i||i.stop(),yield e.processor.destroy(),e.processor=void 0,t||(null===(n=e.processorElement)||void 0===n||n.remove(),e.processorElement=void 0),yield e._mediaStreamTrack.applyConstraints(e._constraints),yield e.setMediaStreamTrack(e._mediaStreamTrack,!0),e.emit(oX.TrackProcessorUpdate))}()})}startPreConnectBuffer(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:100;if(!r1){this.log.warn("MediaRecorder is not available, cannot start preconnect buffer",this.logContext);return}if(this.localTrackRecorder){this.log.warn("preconnect buffer already started");return}{let e="audio/webm;codecs=opus";MediaRecorder.isTypeSupported(e)||(e="video/mp4"),this.localTrackRecorder=new r5(this,{mimeType:e})}this.localTrackRecorder.start(e),this.autoStopPreConnectBuffer=setTimeout(()=>{this.log.warn("preconnect buffer timed out, stopping recording automatically",this.logContext),this.stopPreConnectBuffer()},1e4)}stopPreConnectBuffer(){clearTimeout(this.autoStopPreConnectBuffer),this.localTrackRecorder&&(this.localTrackRecorder.stop(),this.localTrackRecorder=void 0)}getPreConnectBuffer(){var e;return null===(e=this.localTrackRecorder)||void 0===e?void 0:e.byteStream}getPreConnectBufferMimeType(){var e;return null===(e=this.localTrackRecorder)||void 0===e?void 0:e.mimeType}}class r6 extends r4{get enhancedNoiseCancellation(){return this.isKrispNoiseFilterEnabled}constructor(e,t){let i=!(arguments.length>2)||void 0===arguments[2]||arguments[2],n=arguments.length>3?arguments[3]:void 0,r=arguments.length>4?arguments[4]:void 0;super(e,nM.Kind.Audio,t,i,r),this.stopOnMute=!1,this.isKrispNoiseFilterEnabled=!1,this.monitorSender=()=>ib(this,void 0,void 0,function*(){let e;if(!this.sender){this._currentBitrate=0;return}try{e=yield this.getSenderStats()}catch(e){this.log.error("could not get audio sender stats",Object.assign(Object.assign({},this.logContext),{error:e}));return}e&&this.prevStats&&(this._currentBitrate=r0(e,this.prevStats)),this.prevStats=e}),this.handleKrispNoiseFilterEnable=()=>{this.isKrispNoiseFilterEnabled=!0,this.log.debug("Krisp noise filter enabled",this.logContext),this.emit(oX.AudioTrackFeatureUpdate,this,eK.TF_ENHANCED_NOISE_CANCELLATION,!0)},this.handleKrispNoiseFilterDisable=()=>{this.isKrispNoiseFilterEnabled=!1,this.log.debug("Krisp noise filter disabled",this.logContext),this.emit(oX.AudioTrackFeatureUpdate,this,eK.TF_ENHANCED_NOISE_CANCELLATION,!1)},this.audioContext=n,this.checkForSilence()}mute(){let e=Object.create(null,{mute:{get:()=>super.mute}});return ib(this,void 0,void 0,function*(){let t=yield this.muteLock.lock();try{if(this.isMuted)return this.log.debug("Track already muted",this.logContext),this;return this.source===nM.Source.Microphone&&this.stopOnMute&&!this.isUserProvided&&(this.log.debug("stopping mic track",this.logContext),this._mediaStreamTrack.stop()),yield e.mute.call(this),this}finally{t()}})}unmute(){let e=Object.create(null,{unmute:{get:()=>super.unmute}});return ib(this,void 0,void 0,function*(){let t=yield this.muteLock.lock();try{if(!this.isMuted)return this.log.debug("Track already unmuted",this.logContext),this;let t=this._constraints.deviceId&&this._mediaStreamTrack.getSettings().deviceId!==rn(this._constraints.deviceId);return this.source===nM.Source.Microphone&&(this.stopOnMute||"ended"===this._mediaStreamTrack.readyState||t)&&!this.isUserProvided&&(this.log.debug("reacquiring mic track",this.logContext),yield this.restartTrack()),yield e.unmute.call(this),this}finally{t()}})}restartTrack(e){return ib(this,void 0,void 0,function*(){let t;if(e){let i=rv({audio:e});"boolean"!=typeof i.audio&&(t=i.audio)}yield this.restart(t)})}restart(e){let t=Object.create(null,{restart:{get:()=>super.restart}});return ib(this,void 0,void 0,function*(){let i=yield t.restart.call(this,e);return this.checkForSilence(),i})}startMonitor(){nY()&&!this.monitorInterval&&(this.monitorInterval=setInterval(()=>{this.monitorSender()},2e3))}setProcessor(e){return ib(this,void 0,void 0,function*(){var t;let i=yield this.processorLock.lock();try{if(!nQ()&&!this.audioContext)throw Error("Audio context needs to be set on LocalAudioTrack in order to enable processors");this.processor&&(yield this.stopProcessor());let 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 null===(t=this.sender)||void 0===t?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(oX.TrackProcessorUpdate,this.processor)}finally{i()}})}setAudioContext(e){this.audioContext=e}getSenderStats(){return ib(this,void 0,void 0,function*(){var e;let t;if(null===(e=this.sender)||void 0===e?void 0:e.getStats)return(yield this.sender.getStats()).forEach(e=>{"outbound-rtp"===e.type&&(t={type:"audio",streamId:e.id,packetsSent:e.packetsSent,packetsLost:e.packetsLost,bytesSent:e.bytesSent,timestamp:e.timestamp,roundTripTime:e.roundTripTime,jitter:e.jitter})}),t})}checkForSilence(){return ib(this,void 0,void 0,function*(){let e=yield function(e){return ib(this,arguments,void 0,function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:200;return function*(){let i=ry();if(i){let n=i.createAnalyser();n.fftSize=2048;let r=new Uint8Array(n.frequencyBinCount);i.createMediaStreamSource(new MediaStream([e.mediaStreamTrack])).connect(n),yield nq(t),n.getByteTimeDomainData(r);let s=r.some(e=>128!==e&&0!==e);return i.close(),!s}return!1}()})}(this);return e&&(this.isMuted||this.log.warn("silence detected on local audio track",this.logContext),this.emit(oX.AudioSilenceDetected)),e})}}let r9=Object.values(nU),r8=Object.values(nF),r7=Object.values(nV),se=[nU.h180,nU.h360],st=[nF.h180,nF.h360],si=e=>[{scaleResolutionDownBy:2,fps:e.encoding.maxFramerate}].map(t=>{var i,n;return new nN(Math.floor(e.width/t.scaleResolutionDownBy),Math.floor(e.height/t.scaleResolutionDownBy),Math.max(15e4,Math.floor(e.encoding.maxBitrate/(Math.pow(t.scaleResolutionDownBy,2)*((null!==(i=e.encoding.maxFramerate)&&void 0!==i?i:30)/(null!==(n=t.fps)&&void 0!==n?n:30))))),t.fps,e.encoding.priority)}),sn=["q","h","f"];function sr(e,t,i,n){var r,s,o;let a;let l=null==n?void 0:n.videoEncoding;e&&(l=null==n?void 0:n.screenShareEncoding);let c=null==n?void 0:n.simulcast,d=null==n?void 0:n.scalabilityMode,u=null==n?void 0:n.videoCodec;if(!l&&!c&&!d||!t||!i)return[{}];l||(l=function(e,t,i,n){let r=function(e,t,i){if(e)return r7;let n=t>i?t/i:i/t;return Math.abs(n-16/9)<Math.abs(n-4/3)?r9:r8}(e,t,i),{encoding:s}=r[0],o=Math.max(t,i);for(let e=0;e<r.length;e+=1){let t=r[e];if(s=t.encoding,t.width>=o)break}if(n)switch(n){case"av1":case"h265":(s=Object.assign({},s)).maxBitrate=.7*s.maxBitrate;break;case"vp9":(s=Object.assign({},s)).maxBitrate=.85*s.maxBitrate}return s}(e,t,i,u),ip.debug("using video encoding",l));let h=l.maxFramerate,p=new nN(t,i,l.maxBitrate,l.maxFramerate,l.priority);if(d&&nH(u)){let e=new sl(d),t=[];if(e.spatial>3)throw Error("unsupported scalabilityMode: ".concat(d));let i=nP();if(nJ()||nQ()||(null==i?void 0:i.name)==="Chrome"&&0>n3(null==i?void 0:i.version,"113")){let n="h"==e.suffix?2:3,r=((o=i)||(o=nP()),(null==o?void 0:o.name)==="Safari"&&n3(o.version,"18.3")>0||(null==o?void 0:o.os)==="iOS"&&!!(null==o?void 0:o.osVersion)&&n3(o.osVersion,"18.3")>0);for(let i=0;i<e.spatial;i+=1)t.push({rid:sn[2-i],maxBitrate:l.maxBitrate/Math.pow(n,i),maxFramerate:p.encoding.maxFramerate,scaleResolutionDownBy:r?Math.pow(2,i):void 0});t[0].scalabilityMode=d}else t.push({maxBitrate:l.maxBitrate,maxFramerate:p.encoding.maxFramerate,scalabilityMode:d});return p.encoding.priority&&(t[0].priority=p.encoding.priority,t[0].networkPriority=p.encoding.priority),ip.debug("using svc encoding",{encodings:t}),t}if(!c)return[l];let m=[];if((m=e?null!==(r=sa(null==n?void 0:n.screenShareSimulcastLayers))&&void 0!==r?r:ss(e,p):null!==(s=sa(null==n?void 0:n.videoSimulcastLayers))&&void 0!==s?s:ss(e,p)).length>0){let e=m[0];m.length>1&&([,a]=m);let n=Math.max(t,i);if(n>=960&&a)return so(t,i,[e,a,p],h);if(n>=480)return so(t,i,[e,p],h)}return so(t,i,[p])}function ss(e,t){if(e)return si(t);let{width:i,height:n}=t,r=i>n?i/n:n/i;return Math.abs(r-16/9)<Math.abs(r-4/3)?se:st}function so(e,t,i,n){let r=[];if(i.forEach((i,s)=>{if(s>=sn.length)return;let o={rid:sn[s],scaleResolutionDownBy:Math.max(1,Math.min(e,t)/Math.min(i.width,i.height)),maxBitrate:i.encoding.maxBitrate},a=n&&i.encoding.maxFramerate?Math.min(n,i.encoding.maxFramerate):i.encoding.maxFramerate;a&&(o.maxFramerate=a);let l=n$()||0===s;i.encoding.priority&&l&&(o.priority=i.encoding.priority,o.networkPriority=i.encoding.priority),r.push(o)}),nQ()&&"ios"===n1()){let e;r.forEach(t=>{e?t.maxFramerate&&t.maxFramerate>e&&(e=t.maxFramerate):e=t.maxFramerate});let t=!0;r.forEach(i=>{var n;i.maxFramerate!=e&&(t&&(t=!1,ip.info("Simulcast on iOS React-Native requires all encodings to share the same framerate.")),ip.info('Setting framerate of encoding "'.concat(null!==(n=i.rid)&&void 0!==n?n:"",'" to ').concat(e)),i.maxFramerate=e)})}return r}function sa(e){if(e)return e.sort((e,t)=>{let{encoding:i}=e,{encoding:n}=t;return i.maxBitrate>n.maxBitrate?1:i.maxBitrate<n.maxBitrate?-1:i.maxBitrate===n.maxBitrate&&i.maxFramerate&&n.maxFramerate?i.maxFramerate>n.maxFramerate?1:-1:0})}class sl{constructor(e){let t=e.match(/^L(\d)T(\d)(h|_KEY|_KEY_SHIFT){0,1}$/);if(!t)throw 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(null!==(e=this.suffix)&&void 0!==e?e:"")}}class sc extends r4{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)||void 0===arguments[2]||arguments[2],n=arguments.length>3?arguments[3]:void 0;super(e,nM.Kind.Video,t,i,n),this.simulcastCodecs=new Map,this.degradationPreference="balanced",this.isCpuConstrained=!1,this.optimizeForPerformance=!1,this.monitorSender=()=>ib(this,void 0,void 0,function*(){let e;if(!this.sender){this._currentBitrate=0;return}try{e=yield this.getSenderStats()}catch(e){this.log.error("could not get video sender stats",Object.assign(Object.assign({},this.logContext),{error:e}));return}let t=new Map(e.map(e=>[e.rid,e])),i=e.some(e=>"cpu"===e.qualityLimitationReason);if(i!==this.isCpuConstrained&&(this.isCpuConstrained=i,this.isCpuConstrained&&this.emit(oX.CpuConstrained)),this.prevStats){let e=0;t.forEach((t,i)=>{var n;let r=null===(n=this.prevStats)||void 0===n?void 0:n.get(i);e+=r0(t,r)}),this._currentBitrate=e}this.prevStats=t}),this.senderLock=new y}get isSimulcast(){return!!this.sender&&this.sender.getParameters().encodings.length>1}startMonitor(e){var t;if(this.signalClient=e,!nY())return;let i=null===(t=this.sender)||void 0===t?void 0:t.getParameters();i&&(this.encodings=i.encodings),this.monitorInterval||(this.monitorInterval=setInterval(()=>{this.monitorSender()},2e3))}stop(){this._mediaStreamTrack.getConstraints(),this.simulcastCodecs.forEach(e=>{e.mediaStreamTrack.stop()}),super.stop()}pauseUpstream(){let e=Object.create(null,{pauseUpstream:{get:()=>super.pauseUpstream}});return ib(this,void 0,void 0,function*(){yield e.pauseUpstream.call(this);try{for(var t,i,n,r,s,o,a=!0,l=ik(this.simulcastCodecs.values());!(t=(o=yield l.next()).done);a=!0)r=o.value,a=!1,yield null===(s=r.sender)||void 0===s?void 0:s.replaceTrack(null)}catch(e){i={error:e}}finally{try{!a&&!t&&(n=l.return)&&(yield n.call(l))}finally{if(i)throw i.error}}})}resumeUpstream(){let e=Object.create(null,{resumeUpstream:{get:()=>super.resumeUpstream}});return ib(this,void 0,void 0,function*(){yield e.resumeUpstream.call(this);try{for(var t,i,n,r,s,o,a=!0,l=ik(this.simulcastCodecs.values());!(t=(o=yield l.next()).done);a=!0)r=o.value,a=!1,yield null===(s=r.sender)||void 0===s?void 0:s.replaceTrack(r.mediaStreamTrack)}catch(e){i={error:e}}finally{try{!a&&!t&&(n=l.return)&&(yield n.call(l))}finally{if(i)throw i.error}}})}mute(){let e=Object.create(null,{mute:{get:()=>super.mute}});return ib(this,void 0,void 0,function*(){let t=yield this.muteLock.lock();try{if(this.isMuted)return this.log.debug("Track already muted",this.logContext),this;return this.source!==nM.Source.Camera||this.isUserProvided||(this.log.debug("stopping camera track",this.logContext),this._mediaStreamTrack.stop()),yield e.mute.call(this),this}finally{t()}})}unmute(){let e=Object.create(null,{unmute:{get:()=>super.unmute}});return ib(this,void 0,void 0,function*(){let t=yield this.muteLock.lock();try{if(!this.isMuted)return this.log.debug("Track already unmuted",this.logContext),this;return this.source!==nM.Source.Camera||this.isUserProvided||(this.log.debug("reacquiring camera track",this.logContext),yield this.restartTrack()),yield e.unmute.call(this),this}finally{t()}})}setTrackMuted(e){for(let t of(super.setTrackMuted(e),this.simulcastCodecs.values()))t.mediaStreamTrack.enabled=!e}getSenderStats(){return ib(this,void 0,void 0,function*(){var e;if(!(null===(e=this.sender)||void 0===e?void 0:e.getStats))return[];let t=[],i=yield this.sender.getStats();return i.forEach(e=>{var n;if("outbound-rtp"===e.type){let r={type:"video",streamId:e.id,frameHeight:e.frameHeight,frameWidth:e.frameWidth,framesPerSecond:e.framesPerSecond,framesSent:e.framesSent,firCount:e.firCount,pliCount:e.pliCount,nackCount:e.nackCount,packetsSent:e.packetsSent,bytesSent:e.bytesSent,qualityLimitationReason:e.qualityLimitationReason,qualityLimitationDurations:e.qualityLimitationDurations,qualityLimitationResolutionChanges:e.qualityLimitationResolutionChanges,rid:null!==(n=e.rid)&&void 0!==n?n:e.id,retransmittedPacketsSent:e.retransmittedPacketsSent,targetBitrate:e.targetBitrate,timestamp:e.timestamp},s=i.get(e.remoteId);s&&(r.jitter=s.jitter,r.packetsLost=s.packetsLost,r.roundTripTime=s.roundTripTime),t.push(r)}}),t.sort((e,t)=>{var i,n;return(null!==(i=t.frameWidth)&&void 0!==i?i:0)-(null!==(n=e.frameWidth)&&void 0!==n?n:0)}),t})}setPublishingQuality(e){let t=[];for(let i=oY.LOW;i<=oY.HIGH;i+=1)t.push(new t0({quality:i,enabled:i<=e}));this.log.debug("setting publishing quality. max quality ".concat(e),this.logContext),this.setPublishingLayers(nH(this.codec),t)}restartTrack(e){return ib(this,void 0,void 0,function*(){let t;if(e){let i=rv({video:e});"boolean"!=typeof i.video&&(t=i.video)}yield this.restart(t),this.isCpuConstrained=!1;try{for(var i,n,r,s,o,a,l=!0,c=ik(this.simulcastCodecs.values());!(i=(a=yield c.next()).done);l=!0)s=a.value,l=!1,s.sender&&(null===(o=s.sender.transport)||void 0===o?void 0:o.state)!=="closed"&&(s.mediaStreamTrack=this.mediaStreamTrack.clone(),yield s.sender.replaceTrack(s.mediaStreamTrack))}catch(e){n={error:e}}finally{try{!l&&!i&&(r=c.return)&&(yield r.call(c))}finally{if(n)throw n.error}}})}setProcessor(e){let t=Object.create(null,{setProcessor:{get:()=>super.setProcessor}});return ib(this,arguments,void 0,function(e){var i=this;let n=!(arguments.length>1)||void 0===arguments[1]||arguments[1];return function*(){if(yield t.setProcessor.call(i,e,n),null===(l=i.processor)||void 0===l?void 0:l.processedTrack)try{for(var r,s,o,a,l,c,d,u=!0,h=ik(i.simulcastCodecs.values());!(r=(d=yield h.next()).done);u=!0)a=d.value,u=!1,yield null===(c=a.sender)||void 0===c?void 0:c.replaceTrack(i.processor.processedTrack)}catch(e){s={error:e}}finally{try{!u&&!r&&(o=h.return)&&(yield o.call(h))}finally{if(s)throw s.error}}}()})}setDegradationPreference(e){return ib(this,void 0,void 0,function*(){if(this.degradationPreference=e,this.sender)try{this.log.debug("setting degradationPreference to ".concat(e),this.logContext);let t=this.sender.getParameters();t.degradationPreference=e,this.sender.setParameters(t)}catch(e){this.log.warn("failed to set degradationPreference",Object.assign({error:e},this.logContext))}})}addSimulcastTrack(e,t){if(this.simulcastCodecs.has(e)){this.log.error("".concat(e," already added, skipping adding simulcast codec"),this.logContext);return}let i={codec:e,mediaStreamTrack:this.mediaStreamTrack.clone(),sender:void 0,encodings:t};return this.simulcastCodecs.set(e,i),i}setSimulcastTrackSender(e,t){let i=this.simulcastCodecs.get(e);i&&(i.sender=t,setTimeout(()=>{this.subscribedCodecs&&this.setPublishingCodecs(this.subscribedCodecs)},5e3))}setPublishingCodecs(e){return ib(this,void 0,void 0,function*(){var t,i,n,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(nH(e[0].codec),e[0].qualities),[];this.subscribedCodecs=e;let l=[];try{for(t=!0,i=ik(e);!(r=(n=yield i.next()).done);t=!0)if(a=n.value,t=!1,this.codec&&this.codec!==a.codec){let e=this.simulcastCodecs.get(a.codec);if(this.log.debug("try setPublishingCodec for ".concat(a.codec),Object.assign(Object.assign({},this.logContext),{simulcastCodecInfo:e})),e&&e.sender)e.encodings&&(this.log.debug("try setPublishingLayersForSender ".concat(a.codec),this.logContext),yield sd(e.sender,e.encodings,a.qualities,this.senderLock,nH(a.codec),this.log,this.logContext));else for(let e of a.qualities)if(e.enabled){l.push(a.codec);break}}else yield this.setPublishingLayers(nH(a.codec),a.qualities)}catch(e){s={error:e}}finally{try{!t&&!r&&(o=i.return)&&(yield o.call(i))}finally{if(s)throw s.error}}return l})}setPublishingLayers(e,t){return ib(this,void 0,void 0,function*(){if(this.optimizeForPerformance){this.log.info("skipping setPublishingLayers due to optimized publishing performance",Object.assign(Object.assign({},this.logContext),{qualities:t}));return}this.log.debug("setting publishing layers",Object.assign(Object.assign({},this.logContext),{qualities:t})),this.sender&&this.encodings&&(yield sd(this.sender,this.encodings,t,this.senderLock,e,this.log,this.logContext))})}prioritizePerformance(){return ib(this,void 0,void 0,function*(){if(!this.sender)throw Error("sender not found");let e=yield this.senderLock.lock();try{this.optimizeForPerformance=!0;let e=this.sender.getParameters();e.encodings=e.encodings.map((e,t)=>{var i;return Object.assign(Object.assign({},e),{active:0===t,scaleResolutionDownBy:Math.max(1,Math.ceil((null!==(i=this.mediaStreamTrack.getSettings().height)&&void 0!==i?i:360)/360)),scalabilityMode:0===t&&nH(this.codec)?"L1T3":void 0,maxFramerate:0===t?15:0,maxBitrate:0===t?e.maxBitrate:0})}),this.log.debug("setting performance optimised encodings",Object.assign(Object.assign({},this.logContext),{encodings:e.encodings})),this.encodings=e.encodings,yield this.sender.setParameters(e)}catch(e){this.log.error("failed to set performance optimised encodings",Object.assign(Object.assign({},this.logContext),{error:e})),this.optimizeForPerformance=!1}finally{e()}})}handleAppVisibilityChanged(){let e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return ib(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),nX()&&this.isInBackground&&this.source===nM.Source.Camera&&(this._mediaStreamTrack.enabled=!1)})}}function sd(e,t,i,n,r,s,o){return ib(this,void 0,void 0,function*(){let a=yield n.lock();s.debug("setPublishingLayersForSender",Object.assign(Object.assign({},o),{sender:e,qualities:i,senderEncodings:t}));try{let n=e.getParameters(),{encodings:a}=n;if(!a)return;if(a.length!==t.length){s.warn("cannot set publishing layers, encodings mismatch",Object.assign(Object.assign({},o),{encodings:a,senderEncodings:t}));return}let l=!1;r&&i.some(e=>e.enabled)&&i.forEach(e=>e.enabled=!0),a.forEach((e,n)=>{var r;let a=null!==(r=e.rid)&&void 0!==r?r:"";""===a&&(a="q");let c=su(a),d=i.find(e=>e.quality===c);d&&e.active!==d.enabled&&(l=!0,e.active=d.enabled,s.debug("setting layer ".concat(d.quality," to ").concat(e.active?"enabled":"disabled"),o),n$()&&(d.enabled?(e.scaleResolutionDownBy=t[n].scaleResolutionDownBy,e.maxBitrate=t[n].maxBitrate,e.maxFrameRate=t[n].maxFrameRate):(e.scaleResolutionDownBy=4,e.maxBitrate=10,e.maxFrameRate=2)))}),l&&(n.encodings=a,s.debug("setting encodings",Object.assign(Object.assign({},o),{encodings:n.encodings})),yield e.setParameters(n))}finally{a()}})}function su(e){switch(e){case"f":default:return oY.HIGH;case"h":return oY.MEDIUM;case"q":return oY.LOW}}function sh(e,t,i,n){if(!i)return[new e4({quality:oY.HIGH,width:e,height:t,bitrate:0,ssrc:0})];if(n){let n=new sl(i[0].scalabilityMode),r=[],s="h"==n.suffix?1.5:2,o="h"==n.suffix?2:3;for(let a=0;a<n.spatial;a+=1)r.push(new e4({quality:Math.min(oY.HIGH,n.spatial-1)-a,width:Math.ceil(e/Math.pow(s,a)),height:Math.ceil(t/Math.pow(s,a)),bitrate:i[0].maxBitrate?Math.ceil(i[0].maxBitrate/Math.pow(o,a)):0,ssrc:0}));return r}return i.map(i=>{var n,r,s;let o=null!==(n=i.scaleResolutionDownBy)&&void 0!==n?n:1;return new e4({quality:su(null!==(r=i.rid)&&void 0!==r?r:""),width:Math.ceil(e/o),height:Math.ceil(t/o),bitrate:null!==(s=i.maxBitrate)&&void 0!==s?s:0,ssrc:0})})}let sp="_lossy",sm="_reliable",sf="leave-reconnect";!function(e){e[e.New=0]="New",e[e.Connected=1]="Connected",e[e.Disconnected=2]="Disconnected",e[e.Reconnecting=3]="Reconnecting",e[e.Closed=4]="Closed"}(o8||(o8={}));class sg extends iS.EventEmitter{get isClosed(){return this._isClosed}get pendingReconnect(){return!!this.reconnectTimeout}constructor(e){var t;super(),this.options=e,this.rtcConfig={},this.peerConnectionTimeout=rJ.peerConnectionTimeout,this.fullReconnectOnNext=!1,this.latestRemoteOfferId=0,this.subscriberPrimary=!1,this.pcState=o8.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=ip,this.reliableDataSequence=1,this.reliableMessageBuffer=new rD,this.reliableReceivedState=new r_(3e4),this.handleDataChannel=e=>ib(this,[e],void 0,function(e){var t=this;let{channel:i}=e;return function*(){if(i){if(i.label===sm)t.reliableDCSub=i;else{if(i.label!==sp)return;t.lossyDCSub=i}t.log.debug("on data channel ".concat(i.id,", ").concat(i.label),t.logContext),i.onmessage=t.handleDataMessage}}()}),this.handleDataMessage=e=>ib(this,void 0,void 0,function*(){var t,i;let n=yield this.dataProcessLock.lock();try{let n;if(e.data instanceof ArrayBuffer)n=e.data;else if(e.data instanceof Blob)n=yield e.data.arrayBuffer();else{this.log.error("unsupported data type",Object.assign(Object.assign({},this.logContext),{data:e.data}));return}let r=e6.fromBinary(new Uint8Array(n));if(r.sequence>0&&""!==r.participantSid){let e=this.reliableReceivedState.get(r.participantSid);if(e&&r.sequence<=e)return;this.reliableReceivedState.set(r.participantSid,r.sequence)}(null===(t=r.value)||void 0===t?void 0:t.case)==="speaker"?this.emit(oJ.ActiveSpeakersUpdate,r.value.value.speakers):((null===(i=r.value)||void 0===i?void 0:i.case)==="user"&&function(e,t){let i=e.participantIdentity?e.participantIdentity:t.participantIdentity;e.participantIdentity=i,t.participantIdentity=i;let n=0!==e.destinationIdentities.length?e.destinationIdentities:t.destinationIdentities;e.destinationIdentities=n,t.destinationIdentities=n}(r,r.value.value),this.emit(oJ.DataPacketReceived,r))}finally{n()}}),this.handleDataError=e=>{let t=0===e.currentTarget.maxRetransmits?"lossy":"reliable";if(e instanceof ErrorEvent&&e.error){let{error:i}=e.error;this.log.error("DataChannel error on ".concat(t,": ").concat(e.message),Object.assign(Object.assign({},this.logContext),{error:i}))}else this.log.error("Unknown DataChannel error on ".concat(t),Object.assign(Object.assign({},this.logContext),{event:e}))},this.handleBufferedAmountLow=e=>{let t=0===e.currentTarget.maxRetransmits?e9.LOSSY:e9.RELIABLE;this.updateAndEmitDCBufferStatus(t)},this.handleDisconnect=(e,t)=>{if(this._isClosed)return;this.log.warn("".concat(e," disconnected"),this.logContext),0===this.reconnectAttempts&&(this.reconnectStart=Date.now());let i=Date.now()-this.reconnectStart,n=this.getNextRetryDelay({elapsedMs:i,retryCount:this.reconnectAttempts});if(null===n){(e=>{this.log.warn("could not recover connection after ".concat(this.reconnectAttempts," attempts, ").concat(e,"ms. giving up"),this.logContext),this.emit(oJ.Disconnected),this.close()})(i);return}e===sf&&(n=0),this.log.debug("reconnecting in ".concat(n,"ms"),this.logContext),this.clearReconnectTimeout(),this.token&&this.regionUrlProvider&&this.regionUrlProvider.updateToken(this.token),this.reconnectTimeout=nA.setTimeout(()=>this.attemptReconnect(t).finally(()=>this.reconnectTimeout=void 0),n)},this.waitForRestarted=()=>new Promise((e,t)=>{this.pcState===o8.Connected&&e();let i=()=>{this.off(oJ.Disconnected,n),e()},n=()=>{this.off(oJ.Restarted,i),t()};this.once(oJ.Restarted,i),this.once(oJ.Disconnected,n)}),this.updateAndEmitDCBufferStatus=e=>{let t=this.isBufferStatusLow(e);void 0!==t&&t!==this.dcBufferStatus.get(e)&&(this.dcBufferStatus.set(e,t),this.emit(oJ.DCBufferStatusChanged,t,e))},this.isBufferStatusLow=e=>{let t=this.dataChannelForKind(e);if(t)return e===e9.RELIABLE&&this.reliableMessageBuffer.alignBufferedAmount(t.bufferedAmount),t.bufferedAmount<=t.bufferedAmountLowThreshold},this.handleBrowserOnLine=()=>{this.client.currentState===o1.RECONNECTING&&(this.clearReconnectTimeout(),this.attemptReconnect(eG.RR_SIGNAL_DISCONNECTED))},this.log=im(null!==(t=e.loggerName)&&void 0!==t?t:oj.Engine),this.loggerOptions={loggerName:e.loggerName,loggerContextCb:()=>this.logContext},this.client=new rA(void 0,this.loggerOptions),this.client.signalLatency=this.options.expSignalLatency,this.reconnectPolicy=this.options.reconnectPolicy,this.registerOnLineListener(),this.closingLock=new y,this.dataProcessLock=new y,this.dcBufferStatus=new Map([[e9.LOSSY,!0],[e9.RELIABLE,!0]]),this.client.onParticipantUpdate=e=>this.emit(oJ.ParticipantUpdate,e),this.client.onConnectionQuality=e=>this.emit(oJ.ConnectionQualityUpdate,e),this.client.onRoomUpdate=e=>this.emit(oJ.RoomUpdate,e),this.client.onSubscriptionError=e=>this.emit(oJ.SubscriptionError,e),this.client.onSubscriptionPermissionUpdate=e=>this.emit(oJ.SubscriptionPermissionUpdate,e),this.client.onSpeakersChanged=e=>this.emit(oJ.SpeakersChanged,e),this.client.onStreamStateUpdate=e=>this.emit(oJ.StreamStateChanged,e),this.client.onRequestResponse=e=>this.emit(oJ.SignalRequestResponse,e)}get logContext(){var e,t,i,n,r,s;return{room:null===(t=null===(e=this.latestJoinResponse)||void 0===e?void 0:e.room)||void 0===t?void 0:t.name,roomID:null===(n=null===(i=this.latestJoinResponse)||void 0===i?void 0:i.room)||void 0===n?void 0:n.sid,participant:null===(s=null===(r=this.latestJoinResponse)||void 0===r?void 0:r.participant)||void 0===s?void 0:s.identity,pID:this.participantSid}}join(e,t,i,n){return ib(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();let r=yield this.client.join(e,t,i,n);return this._isClosed=!1,this.latestJoinResponse=r,this.subscriberPrimary=r.subscriberPrimary,this.pcManager||(yield this.configure(r)),(!this.subscriberPrimary||r.fastPublish)&&this.negotiate(),this.clientConfiguration=r.clientConfiguration,this.emit(oJ.SignalConnected,r),r}catch(r){if(r instanceof nv&&r.reason===oz.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,n);throw r}})}close(){return ib(this,void 0,void 0,function*(){let e=yield this.closingLock.lock();if(this.isClosed){e();return}try{this._isClosed=!0,this.joinAttempts=0,this.emit(oJ.Closing),this.removeAllListeners(),this.deregisterOnLineListener(),this.clearPendingReconnect(),yield this.cleanupPeerConnections(),yield this.cleanupClient()}finally{e()}})}cleanupPeerConnections(){return ib(this,void 0,void 0,function*(){var e;yield null===(e=this.pcManager)||void 0===e?void 0:e.close(),this.pcManager=void 0;let t=e=>{e&&(e.close(),e.onbufferedamountlow=null,e.onclose=null,e.onclosing=null,e.onerror=null,e.onmessage=null,e.onopen=null)};t(this.lossyDC),t(this.lossyDCSub),t(this.reliableDC),t(this.reliableDCSub),this.lossyDC=void 0,this.lossyDCSub=void 0,this.reliableDC=void 0,this.reliableDCSub=void 0,this.reliableMessageBuffer=new rD,this.reliableDataSequence=1,this.reliableReceivedState.clear()})}cleanupClient(){return ib(this,void 0,void 0,function*(){yield this.client.close(),this.client.resetCallbacks()})}addTrack(e){if(this.pendingTrackResolvers[e.cid])throw new nb("a track with the same ID has already been published");return new Promise((t,i)=>{let n=setTimeout(()=>{delete this.pendingTrackResolvers[e.cid],i(new nv("publication of local track timed out, no response from server",oz.Timeout))},1e4);this.pendingTrackResolvers[e.cid]={resolve:e=>{clearTimeout(n),t(e)},reject:()=>{clearTimeout(n),i(Error("Cancelled publication by calling unpublish"))}},this.client.sendAddTrack(e)})}removeTrack(e){if(e.track&&this.pendingTrackResolvers[e.track.id]){let{reject:t}=this.pendingTrackResolvers[e.track.id];t&&t(),delete this.pendingTrackResolvers[e.track.id]}try{return this.pcManager.removeTrack(e),!0}catch(e){this.log.warn("failed to remove track",Object.assign(Object.assign({},this.logContext),{error:e}))}return!1}updateMuteStatus(e,t){this.client.sendMuteTrack(e,t)}get dataSubscriberReadyState(){var e;return null===(e=this.reliableDCSub)||void 0===e?void 0:e.readyState}getConnectedServerAddress(){return ib(this,void 0,void 0,function*(){var e;return null===(e=this.pcManager)||void 0===e?void 0:e.getConnectedAddress()})}setRegionUrlProvider(e){this.regionUrlProvider=e}configure(e){return ib(this,void 0,void 0,function*(){var t,i,n;if(this.pcManager&&this.pcManager.currentState!==o9.NEW)return;this.participantSid=null===(t=e.participant)||void 0===t?void 0:t.sid;let r=this.makeRTCConfiguration(e);this.pcManager=new rX(r,e.subscriberPrimary,this.loggerOptions),this.emit(oJ.TransportsCreated,this.pcManager.publisher,this.pcManager.subscriber),this.pcManager.onIceCandidate=(e,t)=>{this.client.sendIceCandidate(e,t)},this.pcManager.onPublisherOffer=(e,t)=>{this.client.sendOffer(e,t)},this.pcManager.onDataChannel=this.handleDataChannel,this.pcManager.onStateChange=(t,i,n)=>ib(this,void 0,void 0,function*(){if(this.log.debug("primary PC state changed ".concat(t),this.logContext),["closed","disconnected","failed"].includes(i)&&(this.publisherConnectionPromise=void 0),t===o9.CONNECTED){let t=this.pcState===o8.New;this.pcState=o8.Connected,t&&this.emit(oJ.Connected,e)}else t===o9.FAILED&&this.pcState===o8.Connected&&(this.pcState=o8.Disconnected,this.handleDisconnect("peerconnection failed","failed"===n?eG.RR_SUBSCRIBER_FAILED:eG.RR_PUBLISHER_FAILED));let r=this.client.isDisconnected||this.client.currentState===o1.RECONNECTING,s=[o9.FAILED,o9.CLOSING,o9.CLOSED].includes(t);r&&s&&!this._isClosed&&this.emit(oJ.Offline)}),this.pcManager.onTrack=e=>{this.emit(oJ.MediaTrackAdded,e.track,e.streams[0],e.receiver)},void 0!==(n=null===(i=e.serverInfo)||void 0===i?void 0:i.protocol)&&n>13||this.createDataChannels()})}setupSignalClientCallbacks(){this.client.onAnswer=(e,t)=>ib(this,void 0,void 0,function*(){this.pcManager&&(this.log.debug("received server answer",Object.assign(Object.assign({},this.logContext),{RTCSdpType:e.type})),yield this.pcManager.setPublisherAnswer(e,t))}),this.client.onTrickle=(e,t)=>{this.pcManager&&(this.log.debug("got ICE candidate from peer",Object.assign(Object.assign({},this.logContext),{candidate:e,target:t})),this.pcManager.addIceCandidate(e,t))},this.client.onOffer=(e,t)=>ib(this,void 0,void 0,function*(){if(this.latestRemoteOfferId=t,!this.pcManager)return;let i=yield this.pcManager.createSubscriberAnswerFromOffer(e,t);i&&this.client.sendAnswer(i,t)}),this.client.onLocalTrackPublished=e=>{var t;if(this.log.debug("received trackPublishedResponse",Object.assign(Object.assign({},this.logContext),{cid:e.cid,track:null===(t=e.track)||void 0===t?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}let{resolve:i}=this.pendingTrackResolvers[e.cid];delete this.pendingTrackResolvers[e.cid],i(e.track)},this.client.onLocalTrackUnpublished=e=>{this.emit(oJ.LocalTrackUnpublished,e)},this.client.onLocalTrackSubscribed=e=>{this.emit(oJ.LocalTrackSubscribed,e)},this.client.onTokenRefresh=e=>{this.token=e},this.client.onRemoteMuteChanged=(e,t)=>{this.emit(oJ.RemoteMute,e,t)},this.client.onSubscribedQualityUpdate=e=>{this.emit(oJ.SubscribedQualityUpdate,e)},this.client.onRoomMoved=e=>{var t;this.participantSid=null===(t=e.participant)||void 0===t?void 0:t.sid,this.latestJoinResponse&&(this.latestJoinResponse.room=e.room),this.emit(oJ.RoomMoved,e)},this.client.onClose=()=>{this.handleDisconnect("signal",eG.RR_SIGNAL_DISCONNECTED)},this.client.onLeave=e=>{switch(this.log.debug("client leave request",Object.assign(Object.assign({},this.logContext),{reason:null==e?void 0:e.reason})),e.regions&&this.regionUrlProvider&&(this.log.debug("updating regions",this.logContext),this.regionUrlProvider.setServerReportedRegions(e.regions)),e.action){case tz.DISCONNECT:this.emit(oJ.Disconnected,null==e?void 0:e.reason),this.close();break;case tz.RECONNECT:this.fullReconnectOnNext=!0,this.handleDisconnect(sf);break;case tz.RESUME:this.handleDisconnect(sf)}}}makeRTCConfiguration(e){var t;let i=Object.assign({},this.rtcConfig);if((null===(t=this.signalOpts)||void 0===t?void 0:t.e2eeEnabled)&&(this.log.debug("E2EE - setting up transports with insertable streams",this.logContext),i.encodedInsertableStreams=!0),e.iceServers&&!i.iceServers){let t=[];e.iceServers.forEach(e=>{let i={urls:e.urls};e.username&&(i.username=e.username),e.credential&&(i.credential=e.credential),t.push(i)}),i.iceServers=t}return e.clientConfiguration&&e.clientConfiguration.forceRelay===ez.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(sp,{ordered:!1,maxRetransmits:0}),this.reliableDC=this.pcManager.createPublisherDataChannel(sm,{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 ib(this,void 0,void 0,function*(){if(nW())return yield this.createTransceiverRTCRtpSender(e,t,i);if(nz())return this.log.warn("using add-track fallback",this.logContext),yield this.createRTCRtpSender(e.mediaStreamTrack);throw new nT("Required webRTC APIs not supported on this device")})}createSimulcastSender(e,t,i,n){return ib(this,void 0,void 0,function*(){if(nW())return this.createSimulcastTransceiverSender(e,t,i,n);if(nz())return this.log.debug("using add-track fallback",this.logContext),this.createRTCRtpSender(e.mediaStreamTrack);throw new nT("Cannot stream on this device")})}createTransceiverRTCRtpSender(e,t,i){return ib(this,void 0,void 0,function*(){if(!this.pcManager)throw new nT("publisher is closed");let n=[];e.mediaStream&&n.push(e.mediaStream),rd(e)&&(e.codec=t.videoCodec);let r={direction:"sendonly",streams:n};return i&&(r.sendEncodings=i),(yield this.pcManager.addPublisherTransceiver(e.mediaStreamTrack,r)).sender})}createSimulcastTransceiverSender(e,t,i,n){return ib(this,void 0,void 0,function*(){if(!this.pcManager)throw new nT("publisher is closed");let r={direction:"sendonly"};n&&(r.sendEncodings=n);let s=yield this.pcManager.addPublisherTransceiver(t.mediaStreamTrack,r);if(i.videoCodec)return e.setSimulcastTrackSender(i.videoCodec,s.sender),s.sender})}createRTCRtpSender(e){return ib(this,void 0,void 0,function*(){if(!this.pcManager)throw new nT("publisher is closed");return this.pcManager.addPublisherTrack(e)})}attemptReconnect(e){return ib(this,void 0,void 0,function*(){var t,i,n;if(!this._isClosed){if(this.attemptingReconnect){ip.warn("already attempting reconnect, returning early",this.logContext);return}((null===(t=this.clientConfiguration)||void 0===t?void 0:t.resumeConnection)===ez.DISABLED||(null!==(n=null===(i=this.pcManager)||void 0===i?void 0:i.currentState)&&void 0!==n?n:o9.NEW)===o9.NEW)&&(this.fullReconnectOnNext=!0);try{this.attemptingReconnect=!0,this.fullReconnectOnNext?yield this.restartConnection():yield this.resumeConnection(e),this.clearPendingReconnect(),this.fullReconnectOnNext=!1}catch(t){this.reconnectAttempts+=1;let e=!0;t instanceof nT?(this.log.debug("received unrecoverable error",Object.assign(Object.assign({},this.logContext),{error:t})),e=!1):t instanceof sv||(this.fullReconnectOnNext=!0),e?this.handleDisconnect("reconnect",eG.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(oJ.Disconnected),yield this.close())}finally{this.attemptingReconnect=!1}}})}getNextRetryDelay(e){try{return this.reconnectPolicy.nextRetryDelayInMs(e)}catch(e){this.log.warn("encountered error in reconnect policy",Object.assign(Object.assign({},this.logContext),{error:e}))}return null}restartConnection(e){return ib(this,void 0,void 0,function*(){var t,i,n;try{let i;if(!this.url||!this.token)throw new nT("could not reconnect, url or token not saved");this.log.info("reconnecting, attempt: ".concat(this.reconnectAttempts),this.logContext),this.emit(oJ.Restarting),this.client.isDisconnected||(yield this.client.sendLeave()),yield this.cleanupPeerConnections(),yield this.cleanupClient();try{if(!this.signalOpts)throw this.log.warn("attempted connection restart, without signal options present",this.logContext),new sv;i=yield this.join(null!=e?e:this.url,this.token,this.signalOpts)}catch(e){if(e instanceof nv&&e.reason===oz.NotAllowed)throw new nT("could not reconnect, token might be expired");throw new sv}if(this.shouldFailNext)throw this.shouldFailNext=!1,Error("simulated failure");if(this.client.setReconnected(),this.emit(oJ.SignalRestarted,i),yield this.waitForPCReconnected(),this.client.currentState!==o1.CONNECTED)throw new sv("Signal connection got severed during reconnect");null===(t=this.regionUrlProvider)||void 0===t||t.resetAttempts(),this.emit(oJ.Restarted)}catch(t){let e=yield null===(i=this.regionUrlProvider)||void 0===i?void 0:i.getNextBestRegionUrl();if(e){yield this.restartConnection(e);return}throw null===(n=this.regionUrlProvider)||void 0===n||n.resetAttempts(),t}})}resumeConnection(e){return ib(this,void 0,void 0,function*(){var t;let i;if(!this.url||!this.token)throw new nT("could not reconnect, url or token not saved");if(!this.pcManager)throw new nT("publisher and subscriber connections unset");this.log.info("resuming signal connection, attempt ".concat(this.reconnectAttempts),this.logContext),this.emit(oJ.Resuming);try{this.setupSignalClientCallbacks(),i=yield this.client.reconnect(this.url,this.token,this.participantSid,e)}catch(t){let e="";if(t instanceof Error&&(e=t.message,this.log.error(t.message,Object.assign(Object.assign({},this.logContext),{error:t}))),t instanceof nv&&t.reason===oz.NotAllowed)throw new nT("could not reconnect, token might be expired");if(t instanceof nv&&t.reason===oz.LeaveRequest)throw t;throw new sv(e)}if(this.emit(oJ.SignalResumed),i){let e=this.makeRTCConfiguration(i);this.pcManager.updateConfiguration(e),this.latestJoinResponse&&(this.latestJoinResponse.serverInfo=i.serverInfo)}else this.log.warn("Did not receive reconnect response",this.logContext);if(this.shouldFailNext)throw this.shouldFailNext=!1,Error("simulated failure");if(yield this.pcManager.triggerIceRestart(),yield this.waitForPCReconnected(),this.client.currentState!==o1.CONNECTED)throw new sv("Signal connection got severed during reconnect");this.client.setReconnected(),(null===(t=this.reliableDC)||void 0===t?void 0:t.readyState)==="open"&&null===this.reliableDC.id&&this.createDataChannels(),(null==i?void 0:i.lastMessageSeq)&&this.resendReliableMessagesForResume(i.lastMessageSeq),this.emit(oJ.Resumed)})}waitForPCInitialConnection(e,t){return ib(this,void 0,void 0,function*(){if(!this.pcManager)throw new nT("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(t,e)})}waitForPCReconnected(){return ib(this,void 0,void 0,function*(){this.pcState=o8.Reconnecting,this.log.debug("waiting for peer connection to reconnect",this.logContext);try{if(yield nq(2e3),!this.pcManager)throw new nT("PC manager is closed");yield this.pcManager.ensurePCTransportConnection(void 0,this.peerConnectionTimeout),this.pcState=o8.Connected}catch(e){throw this.pcState=o8.Disconnected,new nv("could not establish PC connection, ".concat(e.message),oz.InternalError)}})}publishRpcResponse(e,t,i,n){return ib(this,void 0,void 0,function*(){let r=new e6({destinationIdentities:[e],kind:e9.RELIABLE,value:{case:"rpcResponse",value:new ta({requestId:t,value:n?{case:"error",value:n.toProto()}:{case:"payload",value:null!=i?i:""}})}});yield this.sendDataPacket(r,e9.RELIABLE)})}publishRpcAck(e,t){return ib(this,void 0,void 0,function*(){let i=new e6({destinationIdentities:[e],kind:e9.RELIABLE,value:{case:"rpcAck",value:new to({requestId:t})}});yield this.sendDataPacket(i,e9.RELIABLE)})}sendDataPacket(e,t){return ib(this,void 0,void 0,function*(){yield this.ensurePublisherConnected(t),t===e9.RELIABLE&&(e.sequence=this.reliableDataSequence,this.reliableDataSequence+=1);let i=e.toBinary(),n=this.dataChannelForKind(t);if(n){if(t===e9.RELIABLE&&this.reliableMessageBuffer.push({data:i,sequence:e.sequence}),this.attemptingReconnect)return;n.send(i)}this.updateAndEmitDCBufferStatus(t)})}resendReliableMessagesForResume(e){return ib(this,void 0,void 0,function*(){yield this.ensurePublisherConnected(e9.RELIABLE);let t=this.dataChannelForKind(e9.RELIABLE);t&&(this.reliableMessageBuffer.popToSequence(e),this.reliableMessageBuffer.getAll().forEach(e=>{t.send(e.data)})),this.updateAndEmitDCBufferStatus(e9.RELIABLE)})}waitForBufferStatusLow(e){return new Promise((t,i)=>ib(this,void 0,void 0,function*(){if(this.isBufferStatusLow(e))t();else{let n=()=>i("Engine closed");for(this.once(oJ.Closing,n);!this.dcBufferStatus.get(e);)yield nq(10);this.off(oJ.Closing,n),t()}}))}ensureDataTransportConnected(e){return ib(this,arguments,void 0,function(e){var t=this;let i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.subscriberPrimary;return function*(){var n;if(!t.pcManager)throw new nT("PC manager is closed");let r=i?t.pcManager.subscriber:t.pcManager.publisher,s=i?"Subscriber":"Publisher";if(!r)throw new nv("".concat(s," connection not set"),oz.InternalError);let o=!1;i||t.dataChannelForKind(e,i)||(t.createDataChannels(),o=!0),o||i||t.pcManager.publisher.isICEConnected||"checking"===t.pcManager.publisher.getICEConnectionState()||(o=!0),o&&t.negotiate();let a=t.dataChannelForKind(e,i);if((null==a?void 0:a.readyState)==="open")return;let l=new Date().getTime()+t.peerConnectionTimeout;for(;new Date().getTime()<l;){if(r.isICEConnected&&(null===(n=t.dataChannelForKind(e,i))||void 0===n?void 0:n.readyState)==="open")return;yield nq(50)}throw new nv("could not establish ".concat(s," connection, state: ").concat(r.getICEConnectionState()),oz.InternalError)}()})}ensurePublisherConnected(e){return ib(this,void 0,void 0,function*(){this.publisherConnectionPromise||(this.publisherConnectionPromise=this.ensureDataTransportConnected(e,!1)),yield this.publisherConnectionPromise})}verifyTransport(){return!!this.pcManager&&this.pcManager.currentState===o9.CONNECTED&&!!this.client.ws&&this.client.ws.readyState!==WebSocket.CLOSED}negotiate(){return ib(this,void 0,void 0,function*(){return new Promise((e,t)=>ib(this,void 0,void 0,function*(){if(!this.pcManager){t(new nS("PC manager is closed"));return}this.pcManager.requirePublisher(),0!=this.pcManager.publisher.getTransceivers().length||this.lossyDC||this.reliableDC||this.createDataChannels();let i=new AbortController,n=()=>{i.abort(),this.log.debug("engine disconnected while negotiation was ongoing",this.logContext),e()};this.isClosed&&t("cannot negotiate on closed engine"),this.on(oJ.Closing,n),this.pcManager.publisher.once(rB.RTPVideoPayloadTypes,e=>{let t=new Map;e.forEach(e=>{let i=e.codec.toLowerCase();nj.includes(i)&&t.set(e.payload,i)}),this.emit(oJ.RTPVideoMapUpdate,t)});try{yield this.pcManager.negotiate(i),e()}catch(e){e instanceof nS&&(this.fullReconnectOnNext=!0),this.handleDisconnect("negotiation",eG.RR_UNKNOWN),t(e)}finally{this.off(oJ.Closing,n)}}))})}dataChannelForKind(e,t){if(t){if(e===e9.LOSSY)return this.lossyDCSub;if(e===e9.RELIABLE)return this.reliableDCSub}else{if(e===e9.LOSSY)return this.lossyDC;if(e===e9.RELIABLE)return this.reliableDC}}sendSyncState(e,t){var i,n;if(!this.pcManager){this.log.warn("sync state cannot be sent without peer connection setup",this.logContext);return}let r=this.pcManager.subscriber.getLocalDescription(),s=this.pcManager.subscriber.getRemoteDescription(),o=null===(n=null===(i=this.signalOpts)||void 0===i?void 0:i.autoSubscribe)||void 0===n||n,a=[],l=[];e.forEach(e=>{e.isDesired!==o&&a.push(e.trackSid),e.isEnabled||l.push(e.trackSid)}),this.client.sendSyncState(new t9({answer:r?rM({sdp:r.sdp,type:r.type}):void 0,offer:s?rM({sdp:s.sdp,type:s.type}):void 0,subscription:new tF({trackSids:a,subscribe:!o,participantTracks:[]}),publishTracks:function(e){let t=[];return e.forEach(e=>{void 0!==e.track&&t.push(new tN({cid:e.track.mediaStreamID,track:e.trackInfo}))}),t}(t),dataChannels:this.dataChannelsInfo(),trackSidsDisabled:l,datachannelReceiveStates:this.reliableReceivedState.map((e,t)=>new t8({publisherSid:t,lastSeq:e}))}))}failNext(){this.shouldFailNext=!0}dataChannelsInfo(){let e=[],t=(t,i)=>{(null==t?void 0:t.id)!==void 0&&null!==t.id&&e.push(new t7({label:t.label,id:t.id,target:i}))};return t(this.dataChannelForKind(e9.LOSSY),tw.PUBLISHER),t(this.dataChannelForKind(e9.RELIABLE),tw.PUBLISHER),t(this.dataChannelForKind(e9.LOSSY,!0),tw.SUBSCRIBER),t(this.dataChannelForKind(e9.RELIABLE,!0),tw.SUBSCRIBER),e}clearReconnectTimeout(){this.reconnectTimeout&&nA.clearTimeout(this.reconnectTimeout)}clearPendingReconnect(){this.clearReconnectTimeout(),this.reconnectAttempts=0}registerOnLineListener(){nY()&&window.addEventListener("online",this.handleBrowserOnLine)}deregisterOnLineListener(){nY()&&window.removeEventListener("online",this.handleBrowserOnLine)}}class sv extends Error{}class sy{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 nZ(this.serverUrl)}getServerUrl(){return this.serverUrl}getNextBestRegionUrl(e){return ib(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));let t=this.regionSettings.regions.filter(e=>!this.attemptedRegions.find(t=>t.url===e.url));if(!(t.length>0))return null;{let e=t[0];return this.attemptedRegions.push(e),ip.debug("next region: ".concat(e.region)),e.url}})}resetAttempts(){this.attemptedRegions=[]}fetchRegionSettings(e){return ib(this,void 0,void 0,function*(){var t;let i=yield fetch("".concat((t=this.serverUrl,"".concat(t.protocol.replace("ws","http"),"//").concat(t.host,"/settings")),"/regions"),{headers:{authorization:"Bearer ".concat(this.token)},signal:e});if(i.ok){let e=yield i.json();return this.lastUpdateAt=Date.now(),e}throw new nv("Could not fetch region settings: ".concat(i.statusText),401===i.status?oz.NotAllowed:oz.InternalError,i.status)})}setServerReportedRegions(e){this.regionSettings=e,this.lastUpdateAt=Date.now()}}class sb{get info(){return this._info}constructor(e,t,i){this.reader=t,this.totalByteSize=i,this._info=e,this.bytesReceived=0}}class sk extends sb{handleChunkReceived(e){var t;this.bytesReceived+=e.content.byteLength;let i=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;null===(t=this.onProgress)||void 0===t||t.call(this,i)}[Symbol.asyncIterator](){let e=this.reader.getReader();return{next:()=>ib(this,void 0,void 0,function*(){try{let{done:t,value:i}=yield e.read();if(t)return{done:!0,value:void 0};return this.handleChunkReceived(i),{done:!1,value:i.content}}catch(e){return{done:!0,value:void 0}}}),return(){return ib(this,void 0,void 0,function*(){return e.releaseLock(),{done:!0,value:void 0}})}}}readAll(){return ib(this,void 0,void 0,function*(){var e,t,i,n;let r=new Set;try{for(var s,o=!0,a=ik(this);!(e=(s=yield a.next()).done);o=!0)n=s.value,o=!1,r.add(n)}catch(e){t={error:e}}finally{try{!o&&!e&&(i=a.return)&&(yield i.call(a))}finally{if(t)throw t.error}}return Array.from(r)})}}class sT extends sb{constructor(e,t,i){super(e,t,i),this.receivedChunks=new Map}handleChunkReceived(e){var t;let i=ro(e.chunkIndex),n=this.receivedChunks.get(i);if(n&&n.version>e.version)return;this.receivedChunks.set(i,e),this.bytesReceived+=e.content.byteLength;let r=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;null===(t=this.onProgress)||void 0===t||t.call(this,r)}[Symbol.asyncIterator](){let e=this.reader.getReader(),t=new TextDecoder;return{next:()=>ib(this,void 0,void 0,function*(){try{let{done:i,value:n}=yield e.read();if(i)return{done:!0,value:void 0};return this.handleChunkReceived(n),{done:!1,value:t.decode(n.content)}}catch(e){return{done:!0,value:void 0}}}),return(){return ib(this,void 0,void 0,function*(){return e.releaseLock(),{done:!0,value:void 0}})}}}readAll(){return ib(this,void 0,void 0,function*(){var e,t,i,n;let r="";try{for(var s,o=!0,a=ik(this);!(e=(s=yield a.next()).done);o=!0)n=s.value,o=!1,r+=n}catch(e){t={error:e}}finally{try{!o&&!e&&(i=a.return)&&(yield i.call(a))}finally{if(t)throw t.error}}return r})}}class sS{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 ib(this,void 0,void 0,function*(){var e;yield this.defaultWriter.close(),this.defaultWriter.releaseLock(),null===(e=this.onClose)||void 0===e||e.call(this)})}}class sC extends sS{}class sw extends sS{}class sE extends nM{constructor(e,t,i,n,r){super(e,i,r),this.sid=t,this.receiver=n}get isLocal(){return!1}setMuted(e){this.isMuted!==e&&(this.isMuted=e,this._mediaStreamTrack.enabled=!e,this.emit(e?oX.Muted:oX.Unmuted,this))}setMediaStream(e){this.mediaStream=e;let 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(oX.Ended,this))};e.addEventListener("removetrack",t)}start(){this.startMonitor(),super.enable()}stop(){this.stopMonitor(),super.disable()}getRTCStatsReport(){return ib(this,void 0,void 0,function*(){var e;if(null===(e=this.receiver)||void 0===e?void 0:e.getStats)return yield this.receiver.getStats()})}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(),2e3)),"undefined"!=typeof RTCRtpReceiver&&"getSynchronizationSources"in RTCRtpReceiver&&this.registerTimeSyncUpdate()}registerTimeSyncUpdate(){let e=()=>{var t;this.timeSyncHandle=requestAnimationFrame(()=>e());let i=null===(t=this.receiver)||void 0===t?void 0:t.getSynchronizationSources()[0];if(i){let{timestamp:e,rtpTimestamp:t}=i;t&&this.rtpTimestamp!==t&&(this.emit(oX.TimeSyncUpdate,{timestamp:e,rtpTimestamp:t}),this.rtpTimestamp=t)}};e()}}class sP extends sE{constructor(e,t,i,n,r,s){super(e,t,nM.Kind.Audio,i,s),this.monitorReceiver=()=>ib(this,void 0,void 0,function*(){if(!this.receiver){this._currentBitrate=0;return}let e=yield this.getReceiverStats();e&&this.prevStats&&this.receiver&&(this._currentBitrate=r0(e,this.prevStats)),this.prevStats=e}),this.audioContext=n,this.webAudioPluginNodes=[],r&&(this.sinkId=r.deviceId)}setVolume(e){var t;for(let i of this.attachedElements)this.audioContext?null===(t=this.gainNode)||void 0===t||t.gain.setTargetAtTime(e,0,.1):i.volume=e;nQ()&&this._mediaStreamTrack._setVolume(e),this.elementVolume=e}getVolume(){if(this.elementVolume)return this.elementVolume;if(nQ())return 1;let e=0;return this.attachedElements.forEach(t=>{t.volume>e&&(e=t.volume)}),e}setSinkId(e){return ib(this,void 0,void 0,function*(){this.sinkId=e,yield Promise.all(this.attachedElements.map(t=>{if(nG(t))return t.setSinkId(e)}))})}attach(e){let t=0===this.attachedElements.length;return e?super.attach(e):e=super.attach(),this.sinkId&&nG(e)&&e.setSinkId(this.sinkId).catch(e=>{this.log.error("Failed to set sink id on remote audio track",e,this.logContext)}),this.audioContext&&t&&(this.log.debug("using audio context mapping",this.logContext),this.connectWebAudio(this.audioContext,e),e.volume=0,e.muted=!0),this.elementVolume&&this.setVolume(this.elementVolume),e}detach(e){let t;return e?(t=super.detach(e),this.audioContext&&(this.attachedElements.length>0?this.connectWebAudio(this.audioContext,this.attachedElements[0]):this.disconnectWebAudio())):(t=super.detach(),this.disconnectWebAudio()),t}setAudioContext(e){this.audioContext=e,e&&this.attachedElements.length>0?this.connectWebAudio(e,this.attachedElements[0]):e||this.disconnectWebAudio()}setWebAudioPlugins(e){this.webAudioPluginNodes=e,this.attachedElements.length>0&&this.audioContext&&this.connectWebAudio(this.audioContext,this.attachedElements[0])}connectWebAudio(e,t){this.disconnectWebAudio(),this.sourceNode=e.createMediaStreamSource(t.srcObject);let i=this.sourceNode;this.webAudioPluginNodes.forEach(e=>{i.connect(e),i=e}),this.gainNode=e.createGain(),i.connect(this.gainNode),this.gainNode.connect(e.destination),this.elementVolume&&this.gainNode.gain.setTargetAtTime(this.elementVolume,0,.1),"running"!==e.state&&e.resume().then(()=>{"running"!==e.state&&this.emit(oX.AudioPlaybackFailed,Error("Audio Context couldn't be started automatically"))}).catch(e=>{this.emit(oX.AudioPlaybackFailed,e)})}disconnectWebAudio(){var e,t;null===(e=this.gainNode)||void 0===e||e.disconnect(),null===(t=this.sourceNode)||void 0===t||t.disconnect(),this.gainNode=void 0,this.sourceNode=void 0}getReceiverStats(){return ib(this,void 0,void 0,function*(){let e;if(this.receiver&&this.receiver.getStats)return(yield this.receiver.getStats()).forEach(t=>{"inbound-rtp"===t.type&&(e={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})}),e})}}class sx extends sE{constructor(e,t,i,n,r){super(e,t,nM.Kind.Video,i,r),this.elementInfos=[],this.monitorReceiver=()=>ib(this,void 0,void 0,function*(){if(!this.receiver){this._currentBitrate=0;return}let e=yield this.getReceiverStats();e&&this.prevStats&&this.receiver&&(this._currentBitrate=r0(e,this.prevStats)),this.prevStats=e}),this.debouncedHandleResize=rV(()=>{this.updateDimensions()},100),this.adaptiveStreamSettings=n}get isAdaptiveStream(){return void 0!==this.adaptiveStreamSettings}get mediaStreamTrack(){return this._mediaStreamTrack}setMuted(e){super.setMuted(e),this.attachedElements.forEach(t=>{e?n_(this._mediaStreamTrack,t):nD(this._mediaStreamTrack,t)})}attach(e){if(e?super.attach(e):e=super.attach(),this.adaptiveStreamSettings&&void 0===this.elementInfos.find(t=>t.element===e)){let t=new sR(e);this.observeElementInfo(t)}return e}observeElementInfo(e){this.adaptiveStreamSettings&&void 0===this.elementInfos.find(t=>t===e)?(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}for(let t of this.elementInfos.filter(t=>t===e))t.stopObserving();this.elementInfos=this.elementInfos.filter(t=>t!==e),this.updateVisibility(),this.debouncedHandleResize()}detach(e){let t=[];if(e)return this.stopObservingElement(e),super.detach(e);for(let e of t=super.detach())this.stopObservingElement(e);return t}getDecoderImplementation(){var e;return null===(e=this.prevStats)||void 0===e?void 0:e.decoderImplementation}getReceiverStats(){return ib(this,void 0,void 0,function*(){let e;if(!this.receiver||!this.receiver.getStats)return;let t=yield this.receiver.getStats(),i="",n=new Map;return t.forEach(t=>{"inbound-rtp"===t.type?(i=t.codecId,e={type:"video",streamId:t.id,framesDecoded:t.framesDecoded,framesDropped:t.framesDropped,framesReceived:t.framesReceived,packetsReceived:t.packetsReceived,packetsLost:t.packetsLost,frameWidth:t.frameWidth,frameHeight:t.frameHeight,pliCount:t.pliCount,firCount:t.firCount,nackCount:t.nackCount,jitter:t.jitter,timestamp:t.timestamp,bytesReceived:t.bytesReceived,decoderImplementation:t.decoderImplementation}):"codec"===t.type&&n.set(t.id,t)}),e&&""!==i&&n.get(i)&&(e.mimeType=n.get(i).mimeType),e})}stopObservingElement(e){for(let t of this.elementInfos.filter(t=>t.element===e))this.stopObservingElementInfo(t)}handleAppVisibilityChanged(){let e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return ib(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),this.isAdaptiveStream&&this.updateVisibility()})}updateVisibility(){var e,t;let i=this.elementInfos.reduce((e,t)=>Math.max(e,t.visibilityChangedAt||0),0),n=(null===(t=null===(e=this.adaptiveStreamSettings)||void 0===e?void 0:e.pauseVideoInBackground)||void 0===t||!!t)&&this.isInBackground,r=this.elementInfos.some(e=>e.pictureInPicture),s=this.elementInfos.some(e=>e.visible)&&!n||r;if(this.lastVisible!==s){if(!s&&Date.now()-i<100){nA.setTimeout(()=>{this.updateVisibility()},100);return}this.lastVisible=s,this.emit(oX.VisibilityChanged,s,this)}}updateDimensions(){var e,t;let i=0,n=0,r=this.getPixelDensity();for(let e of this.elementInfos){let t=e.width()*r,s=e.height()*r;t+s>i+n&&(i=t,n=s)}((null===(e=this.lastDimensions)||void 0===e?void 0:e.width)!==i||(null===(t=this.lastDimensions)||void 0===t?void 0:t.height)!==n)&&(this.lastDimensions={width:i,height:n},this.emit(oX.VideoDimensionsChanged,this.lastDimensions,this))}getPixelDensity(){var e;let t=null===(e=this.adaptiveStreamSettings)||void 0===e?void 0:e.pixelDensity;return"screen"===t?n2():t||(n2()>2?2:1)}}class sR{get visible(){return this.isPiP||this.isIntersecting}get pictureInPicture(){return this.isPiP}constructor(e,t){this.onVisibilityChanged=e=>{var t;let{target:i,isIntersecting:n}=e;i===this.element&&(this.isIntersecting=n,this.isPiP=sO(this.element),this.visibilityChangedAt=Date.now(),null===(t=this.handleVisibilityChanged)||void 0===t||t.call(this))},this.onEnterPiP=()=>{var e,t,i;null===(t=null===(e=window.documentPictureInPicture)||void 0===e?void 0:e.window)||void 0===t||t.addEventListener("pagehide",this.onLeavePiP),this.isPiP=sO(this.element),null===(i=this.handleVisibilityChanged)||void 0===i||i.call(this)},this.onLeavePiP=()=>{var e;this.isPiP=sO(this.element),null===(e=this.handleVisibilityChanged)||void 0===e||e.call(this)},this.element=e,this.isIntersecting=null!=t?t:sA(e),this.isPiP=nY()&&sO(e),this.visibilityChangedAt=0}width(){return this.element.clientWidth}height(){return this.element.clientHeight}observe(){var e,t,i;this.isIntersecting=sA(this.element),this.isPiP=sO(this.element),this.element.handleResize=()=>{var e;null===(e=this.handleResize)||void 0===e||e.call(this)},this.element.handleVisibilityChanged=this.onVisibilityChanged,n7().observe(this.element),n9().observe(this.element),this.element.addEventListener("enterpictureinpicture",this.onEnterPiP),this.element.addEventListener("leavepictureinpicture",this.onLeavePiP),null===(e=window.documentPictureInPicture)||void 0===e||e.addEventListener("enter",this.onEnterPiP),null===(i=null===(t=window.documentPictureInPicture)||void 0===t?void 0:t.window)||void 0===i||i.addEventListener("pagehide",this.onLeavePiP)}stopObserving(){var e,t,i,n,r;null===(e=n7())||void 0===e||e.unobserve(this.element),null===(t=n9())||void 0===t||t.unobserve(this.element),this.element.removeEventListener("enterpictureinpicture",this.onEnterPiP),this.element.removeEventListener("leavepictureinpicture",this.onLeavePiP),null===(i=window.documentPictureInPicture)||void 0===i||i.removeEventListener("enter",this.onEnterPiP),null===(r=null===(n=window.documentPictureInPicture)||void 0===n?void 0:n.window)||void 0===r||r.removeEventListener("pagehide",this.onLeavePiP)}}function sO(e){var t,i;return document.pictureInPictureElement===e||null!==(t=window.documentPictureInPicture)&&void 0!==t&&!!t.window&&sA(e,null===(i=window.documentPictureInPicture)||void 0===i?void 0:i.window)}function sA(e,t){let i=t||window,n=e.offsetTop,r=e.offsetLeft,s=e.offsetWidth,o=e.offsetHeight,{hidden:a}=e,{display:l}=getComputedStyle(e);for(;e.offsetParent;)n+=(e=e.offsetParent).offsetTop,r+=e.offsetLeft;return n<i.pageYOffset+i.innerHeight&&r<i.pageXOffset+i.innerWidth&&n+o>i.pageYOffset&&r+s>i.pageXOffset&&!a&&"none"!==l}class sI extends iS.EventEmitter{constructor(e,t,i,n){var r;super(),this.metadataMuted=!1,this.encryption=e2.NONE,this.log=ip,this.handleMuted=()=>{this.emit(oX.Muted)},this.handleUnmuted=()=>{this.emit(oX.Unmuted)},this.log=im(null!==(r=null==n?void 0:n.loggerName)&&void 0!==r?r:oj.Publication),this.loggerContextCb=this.loggerContextCb,this.setMaxListeners(100),this.kind=e,this.trackSid=t,this.trackName=i,this.source=nM.Source.Unknown}setTrack(e){this.track&&(this.track.off(oX.Muted,this.handleMuted),this.track.off(oX.Unmuted,this.handleUnmuted)),this.track=e,e&&(e.on(oX.Muted,this.handleMuted),e.on(oX.Unmuted,this.handleUnmuted))}get logContext(){var e;return Object.assign(Object.assign({},null===(e=this.loggerContextCb)||void 0===e?void 0:e.call(this)),rT(this))}get isMuted(){return this.metadataMuted}get isEnabled(){return!0}get isSubscribed(){return void 0!==this.track}get isEncrypted(){return this.encryption!==e2.NONE}get audioTrack(){if(rc(this.track))return this.track}get videoTrack(){if(rd(this.track))return this.track}updateInfo(e){this.trackSid=e.sid,this.trackName=e.name,this.source=nM.sourceFromProto(e.source),this.mimeType=e.mimeType,this.kind===nM.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(e){var t,i;(t=e.SubscriptionStatus||(e.SubscriptionStatus={})).Desired="desired",t.Subscribed="subscribed",t.Unsubscribed="unsubscribed",(i=e.PermissionStatus||(e.PermissionStatus={})).Allowed="allowed",i.NotAllowed="not_allowed"}(sI||(sI={}));class sM extends sI{get isUpstreamPaused(){var e;return null===(e=this.track)||void 0===e?void 0:e.isUpstreamPaused}constructor(e,t,i,n){super(e,t.sid,t.name,n),this.track=void 0,this.handleTrackEnded=()=>{this.emit(oX.Ended)},this.handleCpuConstrained=()=>{this.track&&rd(this.track)&&this.emit(oX.CpuConstrained,this.track)},this.updateInfo(t),this.setTrack(i)}setTrack(e){this.track&&(this.track.off(oX.Ended,this.handleTrackEnded),this.track.off(oX.CpuConstrained,this.handleCpuConstrained)),super.setTrack(e),e&&(e.on(oX.Ended,this.handleTrackEnded),e.on(oX.CpuConstrained,this.handleCpuConstrained))}get isMuted(){return this.track?this.track.isMuted:super.isMuted}get audioTrack(){return super.audioTrack}get videoTrack(){return super.videoTrack}get isLocal(){return!0}mute(){return ib(this,void 0,void 0,function*(){var e;return null===(e=this.track)||void 0===e?void 0:e.mute()})}unmute(){return ib(this,void 0,void 0,function*(){var e;return null===(e=this.track)||void 0===e?void 0:e.unmute()})}pauseUpstream(){return ib(this,void 0,void 0,function*(){var e;yield null===(e=this.track)||void 0===e?void 0:e.pauseUpstream()})}resumeUpstream(){return ib(this,void 0,void 0,function*(){var e;yield null===(e=this.track)||void 0===e?void 0:e.resumeUpstream()})}getTrackFeatures(){var e;if(!rc(this.track))return[];{let t=this.track.getSourceTrackSettings(),i=new Set;return t.autoGainControl&&i.add(eK.TF_AUTO_GAIN_CONTROL),t.echoCancellation&&i.add(eK.TF_ECHO_CANCELLATION),t.noiseSuppression&&i.add(eK.TF_NOISE_SUPPRESSION),t.channelCount&&t.channelCount>1&&i.add(eK.TF_STEREO),(null===(e=this.options)||void 0===e?void 0:e.dtx)||i.add(eK.TF_NO_DTX),this.track.enhancedNoiseCancellation&&i.add(eK.TF_ENHANCED_NOISE_CANCELLATION),Array.from(i.values())}}}!function(e){e.Excellent="excellent",e.Good="good",e.Poor="poor",e.Lost="lost",e.Unknown="unknown"}(o7||(o7={}));class sD extends iS.EventEmitter{get logContext(){var e,t;return Object.assign({},null===(t=null===(e=this.loggerOptions)||void 0===e?void 0:e.loggerContextCb)||void 0===t?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(null===(e=this.permissions)||void 0===e?void 0:e.agent)||this.kind===e0.AGENT}get isActive(){var e;return(null===(e=this.participantInfo)||void 0===e?void 0:e.state)===eZ.ACTIVE}get kind(){return this._kind}get attributes(){return Object.freeze(Object.assign({},this._attributes))}constructor(e,t,i,n,r,s){var o;let a=arguments.length>6&&void 0!==arguments[6]?arguments[6]:e0.STANDARD;super(),this.audioLevel=0,this.isSpeaking=!1,this._connectionQuality=o7.Unknown,this.log=ip,this.log=im(null!==(o=null==s?void 0:s.loggerName)&&void 0!==o?o:oj.Participant),this.loggerOptions=s,this.setMaxListeners(100),this.sid=e,this.identity=t,this.name=i,this.metadata=n,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this._kind=a,this._attributes=null!=r?r:{}}getTrackPublications(){return Array.from(this.trackPublications.values())}getTrackPublication(e){for(let[,t]of this.trackPublications)if(t.source===e)return t}getTrackPublicationByName(e){for(let[,t]of this.trackPublications)if(t.trackName===e)return t}waitUntilActive(){return this.isActive?Promise.resolve():(this.activeFuture||(this.activeFuture=new ri,this.once(oK.Active,()=>{var e,t;null===(t=null===(e=this.activeFuture)||void 0===e?void 0:e.resolve)||void 0===t||t.call(e),this.activeFuture=void 0})),this.activeFuture.promise)}get connectionQuality(){return this._connectionQuality}get isCameraEnabled(){var e;let t=this.getTrackPublication(nM.Source.Camera);return!(null===(e=null==t?void 0:t.isMuted)||void 0===e||e)}get isMicrophoneEnabled(){var e;let t=this.getTrackPublication(nM.Source.Microphone);return!(null===(e=null==t?void 0:t.isMuted)||void 0===e||e)}get isScreenShareEnabled(){return!!this.getTrackPublication(nM.Source.ScreenShare)}get isLocal(){return!1}get joinedAt(){return this.participantInfo?new Date(1e3*Number.parseInt(this.participantInfo.joinedAt.toString())):new Date}updateInfo(e){var t;return(!this.participantInfo||this.participantInfo.sid!==e.sid||!(this.participantInfo.version>e.version))&&(this.identity=e.identity,this.sid=e.sid,this._setName(e.name),this._setMetadata(e.metadata),this._setAttributes(e.attributes),e.state===eZ.ACTIVE&&(null===(t=this.participantInfo)||void 0===t?void 0:t.state)!==eZ.ACTIVE&&this.emit(oK.Active),e.permission&&this.setPermissions(e.permission),this.participantInfo=e,!0)}_setMetadata(e){let t=this.metadata!==e,i=this.metadata;this.metadata=e,t&&this.emit(oK.ParticipantMetadataChanged,i)}_setName(e){let t=this.name!==e;this.name=e,t&&this.emit(oK.ParticipantNameChanged,e)}_setAttributes(e){let t=function(e,t){var i;void 0===e&&(e={}),void 0===t&&(t={});let n=[...Object.keys(t),...Object.keys(e)],r={};for(let s of n)e[s]!==t[s]&&(r[s]=null!==(i=t[s])&&void 0!==i?i:"");return r}(this.attributes,e);this._attributes=e,Object.keys(t).length>0&&this.emit(oK.AttributesChanged,t)}setPermissions(e){var t,i,n,r,s,o;let a=this.permissions,l=e.canPublish!==(null===(t=this.permissions)||void 0===t?void 0:t.canPublish)||e.canSubscribe!==(null===(i=this.permissions)||void 0===i?void 0:i.canSubscribe)||e.canPublishData!==(null===(n=this.permissions)||void 0===n?void 0:n.canPublishData)||e.hidden!==(null===(r=this.permissions)||void 0===r?void 0:r.hidden)||e.recorder!==(null===(s=this.permissions)||void 0===s?void 0:s.recorder)||e.canPublishSources.length!==this.permissions.canPublishSources.length||e.canPublishSources.some((e,t)=>{var i;return e!==(null===(i=this.permissions)||void 0===i?void 0:i.canPublishSources[t])})||e.canSubscribeMetrics!==(null===(o=this.permissions)||void 0===o?void 0:o.canSubscribeMetrics);return this.permissions=e,l&&this.emit(oK.ParticipantPermissionsChanged,a),l}setIsSpeaking(e){e!==this.isSpeaking&&(this.isSpeaking=e,e&&(this.lastSpokeAt=new Date),this.emit(oK.IsSpeakingChanged,e))}setConnectionQuality(e){let t=this._connectionQuality;this._connectionQuality=function(e){switch(e){case eW.EXCELLENT:return o7.Excellent;case eW.GOOD:return o7.Good;case eW.POOR:return o7.Poor;case eW.LOST:return o7.Lost;default:return o7.Unknown}}(e),t!==this._connectionQuality&&this.emit(oK.ConnectionQualityChanged,this._connectionQuality)}setDisconnected(){var e,t;this.activeFuture&&(null===(t=(e=this.activeFuture).reject)||void 0===t||t.call(e,Error("Participant disconnected")),this.activeFuture=void 0)}setAudioContext(e){this.audioContext=e,this.audioTrackPublications.forEach(t=>rc(t.track)&&t.track.setAudioContext(e))}addTrackPublication(e){switch(e.on(oX.Muted,()=>{this.emit(oK.TrackMuted,e)}),e.on(oX.Unmuted,()=>{this.emit(oK.TrackUnmuted,e)}),e.track&&(e.track.sid=e.trackSid),this.trackPublications.set(e.trackSid,e),e.kind){case nM.Kind.Audio:this.audioTrackPublications.set(e.trackSid,e);break;case nM.Kind.Video:this.videoTrackPublications.set(e.trackSid,e)}}}class s_ extends sD{constructor(e,t,i,n,r){super(e,t,void 0,void 0,void 0,{loggerName:n.loggerName,loggerContextCb:()=>this.engine.logContext}),this.pendingPublishing=new Set,this.pendingPublishPromises=new Map,this.participantTrackPermissions=[],this.allParticipantsAllowedToSubscribe=!0,this.encryptionType=e2.NONE,this.enabledPublishVideoCodecs=[],this.pendingAcks=new Map,this.pendingResponses=new Map,this.handleReconnecting=()=>{this.reconnectFuture||(this.reconnectFuture=new ri)},this.handleReconnected=()=>{var e,t;null===(t=null===(e=this.reconnectFuture)||void 0===e?void 0:e.resolve)||void 0===t||t.call(e),this.reconnectFuture=void 0,this.updateTrackSubscriptionPermissions()},this.handleClosing=()=>{var e,t,i,n,r,s;this.reconnectFuture&&(this.reconnectFuture.promise.catch(e=>this.log.warn(e.message,this.logContext)),null===(t=null===(e=this.reconnectFuture)||void 0===e?void 0:e.reject)||void 0===t||t.call(e,"Got disconnected during reconnection attempt"),this.reconnectFuture=void 0),this.signalConnectedFuture&&(null===(n=(i=this.signalConnectedFuture).reject)||void 0===n||n.call(i,"Got disconnected without signal connected"),this.signalConnectedFuture=void 0),null===(s=null===(r=this.activeAgentFuture)||void 0===r?void 0:r.reject)||void 0===s||s.call(r,"Got disconnected without active agent present"),this.activeAgentFuture=void 0,this.firstActiveAgent=void 0},this.handleSignalConnected=e=>{var t,i;e.participant&&this.updateInfo(e.participant),this.signalConnectedFuture||(this.signalConnectedFuture=new ri),null===(i=(t=this.signalConnectedFuture).resolve)||void 0===i||i.call(t)},this.handleSignalRequestResponse=e=>{let{requestId:t,reason:i,message:n}=e,r=this.pendingSignalRequests.get(t);r&&(i!==il.OK&&r.reject(new nw(n,i)),this.pendingSignalRequests.delete(t))},this.handleDataPacket=e=>{switch(e.value.case){case"rpcResponse":let t=e.value.value,i=null,n=null;"payload"===t.value.case?i=t.value.value:"error"===t.value.case&&(n=rY.fromProto(t.value.value)),this.handleIncomingRpcResponse(t.requestId,i,n);break;case"rpcAck":let r=e.value.value;this.handleIncomingRpcAck(r.requestId)}},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(e=>(function(e){var t,i,n;if(!e.participantSid&&!e.participantIdentity)throw Error("Invalid track permission, must provide at least one of participantIdentity and participantSid");return new t3({participantIdentity:null!==(t=e.participantIdentity)&&void 0!==t?t:"",participantSid:null!==(i=e.participantSid)&&void 0!==i?i:"",allTracks:null!==(n=e.allowAll)&&void 0!==n&&n,trackSids:e.allowedTrackSids||[]})})(e)))},this.onTrackUnmuted=e=>{this.onTrackMuted(e,e.isUpstreamPaused)},this.onTrackMuted=(e,t)=>{if(void 0===t&&(t=!0),!e.sid){this.log.error("could not update mute status for unpublished track",Object.assign(Object.assign({},this.logContext),rT(e)));return}this.engine.updateMuteStatus(e.sid,t)},this.onTrackUpstreamPaused=e=>{this.log.debug("upstream paused",Object.assign(Object.assign({},this.logContext),rT(e))),this.onTrackMuted(e,!0)},this.onTrackUpstreamResumed=e=>{this.log.debug("upstream resumed",Object.assign(Object.assign({},this.logContext),rT(e))),this.onTrackMuted(e,e.isMuted)},this.onTrackFeatureUpdate=e=>{let t=this.audioTrackPublications.get(e.sid);if(!t){this.log.warn("Could not update local audio track settings, missing publication for track ".concat(e.sid),this.logContext);return}this.engine.client.sendUpdateLocalAudioTrack(t.trackSid,t.getTrackFeatures())},this.onTrackCpuConstrained=(e,t)=>{this.log.debug("track cpu constrained",Object.assign(Object.assign({},this.logContext),rT(t))),this.emit(oK.LocalTrackCpuConstrained,e,t)},this.handleSubscribedQualityUpdate=e=>ib(this,void 0,void 0,function*(){if(!(null===(a=this.roomOptions)||void 0===a?void 0:a.dynacast))return;let t=this.videoTrackPublications.get(e.trackSid);if(!t){this.log.warn("received subscribed quality update for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:e.trackSid}));return}if(!t.videoTrack)return;let i=yield t.videoTrack.setPublishingCodecs(e.subscribedCodecs);try{for(var n,r,s,o,a,l,c=!0,d=ik(i);!(n=(l=yield d.next()).done);c=!0)o=l.value,c=!1,function(e){return!!nL.find(t=>t===e)}(o)&&(this.log.debug("publish ".concat(o," for ").concat(t.videoTrack.sid),Object.assign(Object.assign({},this.logContext),rT(t))),yield this.publishAdditionalCodecForTrack(t.videoTrack,o,t.options))}catch(e){r={error:e}}finally{try{!c&&!n&&(s=d.return)&&(yield s.call(d))}finally{if(r)throw r.error}}}),this.handleLocalTrackUnpublished=e=>{let t=this.trackPublications.get(e.trackSid);if(!t){this.log.warn("received unpublished event for unknown track",Object.assign(Object.assign({},this.logContext),{trackSid:e.trackSid}));return}this.unpublishTrack(t.track)},this.handleTrackEnded=e=>ib(this,void 0,void 0,function*(){if(e.source===nM.Source.ScreenShare||e.source===nM.Source.ScreenShareAudio)this.log.debug("unpublishing local track due to TrackEnded",Object.assign(Object.assign({},this.logContext),rT(e))),this.unpublishTrack(e);else if(e.isUserProvided)yield e.mute();else if(rh(e)||ru(e))try{if(nY())try{let t=yield null==navigator?void 0:navigator.permissions.query({name:e.source===nM.Source.Camera?"camera":"microphone"});if(t&&"denied"===t.state)throw this.log.warn("user has revoked access to ".concat(e.source),Object.assign(Object.assign({},this.logContext),rT(e))),t.onchange=()=>{"denied"!==t.state&&(e.isMuted||e.restartTrack(),t.onchange=null)},Error("GetUserMedia Permission denied")}catch(e){}e.isMuted||(this.log.debug("track ended, attempting to use a different device",Object.assign(Object.assign({},this.logContext),rT(e))),rh(e)?yield e.restartTrack({deviceId:"default"}):yield e.restartTrack())}catch(t){this.log.warn("could not restart track, muting instead",Object.assign(Object.assign({},this.logContext),rT(e))),yield e.mute()}}),this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this.engine=i,this.roomOptions=n,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!==e2.NONE}getTrackPublication(e){let t=super.getTrackPublication(e);if(t)return t}getTrackPublicationByName(e){let t=super.getTrackPublicationByName(e);if(t)return t}setupEngine(e){var t;this.engine=e,this.engine.on(oJ.RemoteMute,(e,t)=>{let i=this.trackPublications.get(e);i&&i.track&&(t?i.mute():i.unmute())}),(null===(t=this.signalConnectedFuture)||void 0===t?void 0:t.isResolved)&&(this.signalConnectedFuture=void 0),this.engine.on(oJ.Connected,this.handleReconnected).on(oJ.SignalConnected,this.handleSignalConnected).on(oJ.SignalRestarted,this.handleReconnected).on(oJ.SignalResumed,this.handleReconnected).on(oJ.Restarting,this.handleReconnecting).on(oJ.Resuming,this.handleReconnecting).on(oJ.LocalTrackUnpublished,this.handleLocalTrackUnpublished).on(oJ.SubscribedQualityUpdate,this.handleSubscribedQualityUpdate).on(oJ.Closing,this.handleClosing).on(oJ.SignalRequestResponse,this.handleSignalRequestResponse).on(oJ.DataPacketReceived,this.handleDataPacket)}setMetadata(e){return ib(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({metadata:e})})}setName(e){return ib(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({name:e})})}setAttributes(e){return ib(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({attributes:e})})}requestMetadataUpdate(e){return ib(this,arguments,void 0,function(e){var t=this;let{metadata:i,name:n,attributes:r}=e;return function*(){return new Promise((e,s)=>ib(t,void 0,void 0,function*(){var t,o;try{let a=!1,l=yield this.engine.client.sendUpdateLocalMetadata(null!==(t=null!=i?i:this.metadata)&&void 0!==t?t:"",null!==(o=null!=n?n:this.name)&&void 0!==o?o:"",r),c=performance.now();for(this.pendingSignalRequests.set(l,{resolve:e,reject:e=>{s(e),a=!0},values:{name:n,metadata:i,attributes:r}});performance.now()-c<5e3&&!a;){if((!n||this.name===n)&&(!i||this.metadata===i)&&(!r||Object.entries(r).every(e=>{let[t,i]=e;return this.attributes[t]===i||""===i&&!this.attributes[t]}))){this.pendingSignalRequests.delete(l),e();return}yield nq(50)}s(new nw("Request to update local metadata timed out","TimeoutError"))}catch(e){e instanceof Error&&s(e)}}))}()})}setCameraEnabled(e,t,i){return this.setTrackEnabled(nM.Source.Camera,e,t,i)}setMicrophoneEnabled(e,t,i){return this.setTrackEnabled(nM.Source.Microphone,e,t,i)}setScreenShareEnabled(e,t,i){return this.setTrackEnabled(nM.Source.ScreenShare,e,t,i)}setPermissions(e){let t=this.permissions,i=super.setPermissions(e);return i&&t&&this.emit(oK.ParticipantPermissionsChanged,t),i}setE2EEEnabled(e){return ib(this,void 0,void 0,function*(){this.encryptionType=e?e2.GCM:e2.NONE,yield this.republishAllTracks(void 0,!1)})}setTrackEnabled(e,t,i,n){return ib(this,void 0,void 0,function*(){this.log.debug("setTrackEnabled",Object.assign(Object.assign({},this.logContext),{source:e,enabled:t})),this.republishPromise&&(yield this.republishPromise);let r=this.getTrackPublication(e);if(t){if(r)yield r.unmute();else{let t;if(this.pendingPublishing.has(e)){let t=yield this.waitForPendingPublicationOfSource(e);return t||this.log.info("waiting for pending publication promise timed out",Object.assign(Object.assign({},this.logContext),{source:e})),yield null==t?void 0:t.unmute(),t}this.pendingPublishing.add(e);try{switch(e){case nM.Source.Camera:t=yield this.createTracks({video:null==i||i});break;case nM.Source.Microphone:t=yield this.createTracks({audio:null==i||i});break;case nM.Source.ScreenShare:t=yield this.createScreenTracks(Object.assign({},i));break;default:throw new nb(e)}}catch(i){throw null==t||t.forEach(e=>{e.stop()}),i instanceof Error&&this.emit(oK.MediaDevicesError,i,rb(e)),this.pendingPublishing.delete(e),i}for(let n of t){let t=Object.assign(Object.assign({},this.roomOptions.publishDefaults),i);e===nM.Source.Microphone&&rc(n)&&t.preConnectBuffer&&(this.log.info("starting preconnect buffer for microphone",Object.assign({},this.logContext)),n.startPreConnectBuffer())}try{let e=[];for(let i of t)this.log.info("publishing track",Object.assign(Object.assign({},this.logContext),rT(i))),e.push(this.publishTrack(i,n));let i=yield Promise.all(e);[r]=i}catch(e){throw null==t||t.forEach(e=>{e.stop()}),e}finally{this.pendingPublishing.delete(e)}}}else if(!(!(null==r?void 0:r.track)&&this.pendingPublishing.has(e))||(r=yield this.waitForPendingPublicationOfSource(e))||this.log.info("waiting for pending publication promise timed out",Object.assign(Object.assign({},this.logContext),{source:e})),r&&r.track){if(e===nM.Source.ScreenShare){r=yield this.unpublishTrack(r.track);let e=this.getTrackPublication(nM.Source.ScreenShareAudio);e&&e.track&&this.unpublishTrack(e.track)}else yield r.mute()}return r})}enableCameraAndMicrophone(){return ib(this,void 0,void 0,function*(){if(!(this.pendingPublishing.has(nM.Source.Camera)||this.pendingPublishing.has(nM.Source.Microphone))){this.pendingPublishing.add(nM.Source.Camera),this.pendingPublishing.add(nM.Source.Microphone);try{let e=yield this.createTracks({audio:!0,video:!0});yield Promise.all(e.map(e=>this.publishTrack(e)))}finally{this.pendingPublishing.delete(nM.Source.Camera),this.pendingPublishing.delete(nM.Source.Microphone)}}})}createTracks(e){return ib(this,void 0,void 0,function*(){var t,i;null!=e||(e={});let n=rf(e,null===(t=this.roomOptions)||void 0===t?void 0:t.audioCaptureDefaults,null===(i=this.roomOptions)||void 0===i?void 0:i.videoCaptureDefaults);try{return(yield function e(t,i){return ib(this,void 0,void 0,function*(){null!=t||(t={});let n=!1,{audioProcessor:r,videoProcessor:s,optionsWithoutProcessor:o}=rS(t),a=o.audio,l=o.video;if(r&&"object"==typeof o.audio&&(o.audio.processor=r),s&&"object"==typeof o.video&&(o.video.processor=s),t.audio&&"object"==typeof o.audio&&"string"==typeof o.audio.deviceId){let e=o.audio.deviceId;o.audio.deviceId={exact:e},n=!0,a=Object.assign(Object.assign({},o.audio),{deviceId:{ideal:e}})}if(o.video&&"object"==typeof o.video&&"string"==typeof o.video.deviceId){let e=o.video.deviceId;o.video.deviceId={exact:e},n=!0,l=Object.assign(Object.assign({},o.video),{deviceId:{ideal:e}})}!0!==o.audio&&("object"!=typeof o.audio||o.audio.deviceId)||(o.audio={deviceId:"default"}),!0===o.video?o.video={deviceId:"default"}:"object"!=typeof o.video||o.video.deviceId||(o.video.deviceId="default");let c=rf(o,rG,r$),d=rv(c),u=navigator.mediaDevices.getUserMedia(d);o.audio&&(rP.userMediaPromiseMap.set("audioinput",u),u.catch(()=>rP.userMediaPromiseMap.delete("audioinput"))),o.video&&(rP.userMediaPromiseMap.set("videoinput",u),u.catch(()=>rP.userMediaPromiseMap.delete("videoinput")));try{let e=yield u;return yield Promise.all(e.getTracks().map(t=>ib(this,void 0,void 0,function*(){let n;let o="audio"===t.kind,a=o?c.audio:c.video;"boolean"!=typeof a&&a||(a={});let l=o?d.audio:d.video;"boolean"!=typeof l&&(n=l);let u=t.getSettings().deviceId;(null==n?void 0:n.deviceId)&&rn(n.deviceId)!==u?n.deviceId=u:n||(n={deviceId:u});let h=function(e,t,i){switch(e.kind){case"audio":return new r6(e,t,!1,void 0,i);case"video":return new sc(e,t,!1,i);default:throw new nb("unsupported track type: ".concat(e.kind))}}(t,n,i);return h.kind===nM.Kind.Video?h.source=nM.Source.Camera:h.kind===nM.Kind.Audio&&(h.source=nM.Source.Microphone),h.mediaStream=e,rc(h)&&r?yield h.setProcessor(r):rd(h)&&s&&(yield h.setProcessor(s)),h})))}catch(r){if(!n)throw r;return e(Object.assign(Object.assign({},t),{audio:a,video:l}),i)}})}(n,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext})).map(e=>(rc(e)&&(this.microphoneError=void 0,e.setAudioContext(this.audioContext),e.source=nM.Source.Microphone,this.emit(oK.AudioStreamAcquired)),rd(e)&&(this.cameraError=void 0,e.source=nM.Source.Camera),e))}catch(t){throw t instanceof Error&&(e.audio&&(this.microphoneError=t),e.video&&(this.cameraError=t)),t}})}createScreenTracks(e){return ib(this,void 0,void 0,function*(){var t,i,n;let r;if(void 0===e&&(e={}),void 0===navigator.mediaDevices.getDisplayMedia)throw new ny("getDisplayMedia not supported");void 0===e.resolution&&!function(){let e=nP();return(null==e?void 0:e.name)==="Safari"&&e.version.startsWith("17.")||(null==e?void 0:e.os)==="iOS"&&!!(null==e?void 0:e.osVersion)&&n3(e.osVersion,"17")>=0}()&&(e.resolution=nV.h1080fps30.resolution);let s=(r=null===(i=(t=e).video)||void 0===i||i,t.resolution&&t.resolution.width>0&&t.resolution.height>0&&(r="boolean"==typeof r?{}:r,r=nK()?Object.assign(Object.assign({},r),{width:{max:t.resolution.width},height:{max:t.resolution.height},frameRate:t.resolution.frameRate}):Object.assign(Object.assign({},r),{width:{ideal:t.resolution.width},height:{ideal:t.resolution.height},frameRate:t.resolution.frameRate})),{audio:null!==(n=t.audio)&&void 0!==n&&n,video:r,controller:t.controller,selfBrowserSurface:t.selfBrowserSurface,surfaceSwitching:t.surfaceSwitching,systemAudio:t.systemAudio,preferCurrentTab:t.preferCurrentTab}),o=yield navigator.mediaDevices.getDisplayMedia(s),a=o.getVideoTracks();if(0===a.length)throw new nb("no video track found");let l=new sc(a[0],void 0,!1,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});l.source=nM.Source.ScreenShare,e.contentHint&&(l.mediaStreamTrack.contentHint=e.contentHint);let c=[l];if(o.getAudioTracks().length>0){this.emit(oK.AudioStreamAcquired);let e=new r6(o.getAudioTracks()[0],void 0,!1,this.audioContext,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});e.source=nM.Source.ScreenShareAudio,c.push(e)}return c})}publishTrack(e,t){return ib(this,void 0,void 0,function*(){return this.publishOrRepublishTrack(e,t)})}publishOrRepublishTrack(e,t){return ib(this,arguments,void 0,function(e,t){var i=this;let n=arguments.length>2&&void 0!==arguments[2]&&arguments[2];return function*(){var r,s,o,a;let l,c;if(rh(e)&&e.setAudioContext(i.audioContext),yield null===(r=i.reconnectFuture)||void 0===r?void 0:r.promise,i.republishPromise&&!n&&(yield i.republishPromise),rl(e)&&i.pendingPublishPromises.has(e)&&(yield i.pendingPublishPromises.get(e)),e instanceof MediaStreamTrack)l=e.getConstraints();else{let t;switch(l=e.constraints,e.source){case nM.Source.Microphone:t="audioinput";break;case nM.Source.Camera:t="videoinput"}t&&i.activeDeviceMap.has(t)&&(l=Object.assign(Object.assign({},l),{deviceId:i.activeDeviceMap.get(t)}))}if(e instanceof MediaStreamTrack)switch(e.kind){case"audio":e=new r6(e,l,!0,i.audioContext,{loggerName:i.roomOptions.loggerName,loggerContextCb:()=>i.logContext});break;case"video":e=new sc(e,l,!0,{loggerName:i.roomOptions.loggerName,loggerContextCb:()=>i.logContext});break;default:throw new nb("unsupported MediaStreamTrack kind ".concat(e.kind))}else e.updateLoggerOptions({loggerName:i.roomOptions.loggerName,loggerContextCb:()=>i.logContext});if(i.trackPublications.forEach(t=>{t.track&&t.track===e&&(c=t)}),c)return i.log.warn("track has already been published, skipping",Object.assign(Object.assign({},i.logContext),rT(c))),c;let d="channelCount"in e.mediaStreamTrack.getSettings()&&2===e.mediaStreamTrack.getSettings().channelCount||2===e.mediaStreamTrack.getConstraints().channelCount,u=null!==(s=null==t?void 0:t.forceStereo)&&void 0!==s?s:d;u&&(t||(t={}),void 0===t.dtx&&i.log.info("Opus DTX will be disabled for stereo tracks by default. Enable them explicitly to make it work.",Object.assign(Object.assign({},i.logContext),rT(e))),void 0===t.red&&i.log.info("Opus RED will be disabled for stereo tracks by default. Enable them explicitly to make it work."),null!==(o=t.dtx)&&void 0!==o||(t.dtx=!1),null!==(a=t.red)&&void 0!==a||(t.red=!1));let h=Object.assign(Object.assign({},i.roomOptions.publishDefaults),t);!function(){let e=nP(),t="17.2";if(e)return"Safari"!==e.name&&"iOS"!==e.os||!!("iOS"===e.os&&e.osVersion&&n3(t,e.osVersion)>=0)||!!("Safari"===e.name&&n3(t,e.version)>=0)}()&&i.roomOptions.e2ee&&(i.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({},i.logContext)),h.simulcast=!1),h.source&&(e.source=h.source);let p=new Promise((t,n)=>ib(i,void 0,void 0,function*(){try{if(this.engine.client.currentState!==o1.CONNECTED){this.log.debug("deferring track publication until signal is connected",Object.assign(Object.assign({},this.logContext),{track:rT(e)}));let i=setTimeout(()=>{n(new nC("publishing rejected as engine not connected within timeout",408))},15e3);yield this.waitUntilEngineConnected(),clearTimeout(i);let r=yield this.publish(e,h,u);t(r)}else try{let i=yield this.publish(e,h,u);t(i)}catch(e){n(e)}}catch(e){n(e)}}));i.pendingPublishPromises.set(e,p);try{return yield p}catch(e){throw e}finally{i.pendingPublishPromises.delete(e)}}()})}waitUntilEngineConnected(){return this.signalConnectedFuture||(this.signalConnectedFuture=new ri),this.signalConnectedFuture.promise}hasPermissionsToPublish(e){if(!this.permissions)return this.log.warn("no permissions present for publishing track",Object.assign(Object.assign({},this.logContext),rT(e))),!1;let{canPublish:t,canPublishSources:i}=this.permissions;return!!(t&&(0===i.length||i.map(e=>(function(e){switch(e){case eB.CAMERA:return nM.Source.Camera;case eB.MICROPHONE:return nM.Source.Microphone;case eB.SCREEN_SHARE:return nM.Source.ScreenShare;case eB.SCREEN_SHARE_AUDIO:return nM.Source.ScreenShareAudio;default:return nM.Source.Unknown}})(e)).includes(e.source)))||(this.log.warn("insufficient permissions to publish",Object.assign(Object.assign({},this.logContext),rT(e))),!1)}publish(e,t,i){return ib(this,void 0,void 0,function*(){var n,r,s,o,a,l,c,d,u,h;let p,m;if(!this.hasPermissionsToPublish(e))throw new nC("failed to publish track, insufficient permissions",403);Array.from(this.trackPublications.values()).find(t=>rl(e)&&t.source===e.source)&&e.source!==nM.Source.Unknown&&this.log.info("publishing a second track with the same source: ".concat(e.source),Object.assign(Object.assign({},this.logContext),rT(e))),t.stopMicTrackOnMute&&rc(e)&&(e.stopOnMute=!0),e.source===nM.Source.ScreenShare&&n$()&&(t.simulcast=!1),"av1"===t.videoCodec&&!function(){if(!("getCapabilities"in RTCRtpSender)||nK())return!1;let e=RTCRtpSender.getCapabilities("video"),t=!1;if(e){for(let i of e.codecs)if("video/AV1"===i.mimeType){t=!0;break}}return t}()&&(t.videoCodec=void 0),"vp9"===t.videoCodec&&!function(){if(!("getCapabilities"in RTCRtpSender)||n$())return!1;if(nK()){let e=nP();if((null==e?void 0:e.version)&&0>n3(e.version,"16")||(null==e?void 0:e.os)==="iOS"&&(null==e?void 0:e.osVersion)&&0>n3(e.osVersion,"16"))return!1}let e=RTCRtpSender.getCapabilities("video"),t=!1;if(e){for(let i of e.codecs)if("video/VP9"===i.mimeType){t=!0;break}}return t}()&&(t.videoCodec=void 0),void 0===t.videoCodec&&(t.videoCodec="vp8"),this.enabledPublishVideoCodecs.length>0&&!this.enabledPublishVideoCodecs.some(e=>t.videoCodec===rk(e.mime))&&(t.videoCodec=rk(this.enabledPublishVideoCodecs[0].mime));let f=t.videoCodec;e.on(oX.Muted,this.onTrackMuted),e.on(oX.Unmuted,this.onTrackUnmuted),e.on(oX.Ended,this.handleTrackEnded),e.on(oX.UpstreamPaused,this.onTrackUpstreamPaused),e.on(oX.UpstreamResumed,this.onTrackUpstreamResumed),e.on(oX.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate);let g=[],v=!(null===(n=t.dtx)||void 0===n||n),y=e.getSourceTrackSettings();y.autoGainControl&&g.push(eK.TF_AUTO_GAIN_CONTROL),y.echoCancellation&&g.push(eK.TF_ECHO_CANCELLATION),y.noiseSuppression&&g.push(eK.TF_NOISE_SUPPRESSION),y.channelCount&&y.channelCount>1&&g.push(eK.TF_STEREO),v&&g.push(eK.TF_NO_DTX),rh(e)&&e.hasPreConnectBuffer&&g.push(eK.TF_PRECONNECT_BUFFER);let b=new tA({cid:e.mediaStreamTrack.id,name:t.name,type:nM.kindToProto(e.kind),muted:e.isMuted,source:nM.sourceToProto(e.source),disableDtx:v,encryption:this.encryptionType,stereo:i,disableRed:this.isE2EEEnabled||!(null===(r=t.red)||void 0===r||r),stream:null==t?void 0:t.stream,backupCodecPolicy:null==t?void 0:t.backupCodecPolicy,audioFeatures:g});if(e.kind===nM.Kind.Video){let i={width:0,height:0};try{i=yield e.waitForDimensions()}catch(n){let t=null!==(o=null===(s=this.roomOptions.videoCaptureDefaults)||void 0===s?void 0:s.resolution)&&void 0!==o?o:nU.h720.resolution;i={width:t.width,height:t.height},this.log.error("could not determine track dimensions, using defaults",Object.assign(Object.assign(Object.assign({},this.logContext),rT(e)),{dims:i}))}b.width=i.width,b.height=i.height,ru(e)&&(nH(f)&&(e.source===nM.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),rT(e))))),t.scalabilityMode=null!==(a=t.scalabilityMode)&&void 0!==a?a:"L3T3_KEY"),b.simulcastCodecs=[new tO({codec:f,cid:e.mediaStreamTrack.id})],!0===t.backupCodec&&(t.backupCodec={codec:"vp8"}),t.backupCodec&&f!==t.backupCodec.codec&&b.encryption===e2.NONE&&(this.roomOptions.dynacast||(this.roomOptions.dynacast=!0),b.simulcastCodecs.push(new tO({codec:t.backupCodec.codec,cid:""})))),p=sr(e.source===nM.Source.ScreenShare,b.width,b.height,t),b.layers=sh(b.width,b.height,p,nH(t.videoCodec))}else e.kind===nM.Kind.Audio&&(p=[{maxBitrate:null===(l=t.audioPreset)||void 0===l?void 0:l.maxBitrate,priority:null!==(d=null===(c=t.audioPreset)||void 0===c?void 0:c.priority)&&void 0!==d?d:"high",networkPriority:null!==(h=null===(u=t.audioPreset)||void 0===u?void 0:u.priority)&&void 0!==h?h:"high"}]);if(!this.engine||this.engine.isClosed)throw new nT("cannot publish track when not connected");let k=()=>ib(this,void 0,void 0,function*(){var i,n,r;if(!this.engine.pcManager)throw new nT("pcManager is not ready");if(e.sender=yield this.engine.createSender(e,t,p),this.emit(oK.LocalSenderCreated,e.sender,e),ru(e)&&(null!==(i=t.degradationPreference)&&void 0!==i||(t.degradationPreference=e.source===nM.Source.ScreenShare||e.constraints.height&&rn(e.constraints.height)>=1080?"maintain-resolution":"balanced"),e.setDegradationPreference(t.degradationPreference)),p){if(n$()&&e.kind===nM.Kind.Audio){let t;for(let i of this.engine.pcManager.publisher.getTransceivers())if(i.sender===e.sender){t=i;break}t&&this.engine.pcManager.publisher.setTrackCodecBitrate({transceiver:t,codec:"opus",maxbr:(null===(n=p[0])||void 0===n?void 0:n.maxBitrate)?p[0].maxBitrate/1e3:0})}else e.codec&&nH(e.codec)&&(null===(r=p[0])||void 0===r?void 0:r.maxBitrate)&&this.engine.pcManager.publisher.setTrackCodecBitrate({cid:b.cid,codec:e.codec,maxbr:p[0].maxBitrate/1e3})}yield this.engine.negotiate()}),T=new Promise((t,i)=>ib(this,void 0,void 0,function*(){var n;try{m=yield this.engine.addTrack(b),t(m)}catch(t){e.sender&&(null===(n=this.engine.pcManager)||void 0===n?void 0:n.publisher)&&(this.engine.pcManager.publisher.removeTrack(e.sender),yield this.engine.negotiate().catch(t=>{this.log.error("failed to negotiate after removing track due to failed add track request",Object.assign(Object.assign(Object.assign({},this.logContext),rT(e)),{error:t}))})),i(t)}}));if(this.enabledPublishVideoCodecs.length>0)m=(yield Promise.all([T,k()]))[0];else{let i;if((m=yield T).codecs.forEach(e=>{void 0===i&&(i=e.mimeType)}),i&&e.kind===nM.Kind.Video){let n=rk(i);n!==f&&(this.log.debug("falling back to server selected codec",Object.assign(Object.assign(Object.assign({},this.logContext),rT(e)),{codec:n})),t.videoCodec=n,p=sr(e.source===nM.Source.ScreenShare,b.width,b.height,t))}yield k()}let S=new sM(e.kind,m,e,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});if(S.on(oX.CpuConstrained,e=>this.onTrackCpuConstrained(e,S)),S.options=t,e.sid=m.sid,this.log.debug("publishing ".concat(e.kind," with encodings"),Object.assign(Object.assign({},this.logContext),{encodings:p,trackInfo:m})),ru(e)?e.startMonitor(this.engine.client):rh(e)&&e.startMonitor(),this.addTrackPublication(S),this.emit(oK.LocalTrackPublished,S),rh(e)&&m.audioFeatures.includes(eK.TF_PRECONNECT_BUFFER)){let t=e.getPreConnectBuffer(),i=e.getPreConnectBufferMimeType();this.on(oK.LocalTrackSubscribed,t=>{if(t.trackSid===m.sid){if(!e.hasPreConnectBuffer){this.log.warn("subscribe event came to late, buffer already closed",this.logContext);return}this.log.debug("finished recording preconnect buffer",Object.assign(Object.assign({},this.logContext),rT(e))),e.stopPreConnectBuffer()}}),t&&new Promise((n,r)=>ib(this,void 0,void 0,function*(){try{this.log.debug("waiting for agent",Object.assign(Object.assign({},this.logContext),rT(e)));let m=setTimeout(()=>{r(Error("agent not active within 10 seconds"))},1e4),f=yield this.waitUntilActiveAgentPresent();clearTimeout(m),this.log.debug("sending preconnect buffer",Object.assign(Object.assign({},this.logContext),rT(e)));let g=yield this.streamBytes({name:"preconnect-buffer",mimeType:i,topic:"lk.agent.pre-connect-audio-buffer",destinationIdentities:[f.identity],attributes:{trackId:S.trackSid,sampleRate:String(null!==(c=y.sampleRate)&&void 0!==c?c:"48000"),channels:String(null!==(d=y.channelCount)&&void 0!==d?d:"1")}});try{for(var s,o,a,l,c,d,u,h=!0,p=ik(t);!(s=(u=yield p.next()).done);h=!0)l=u.value,h=!1,yield g.write(l)}catch(e){o={error:e}}finally{try{!h&&!s&&(a=p.return)&&(yield a.call(p))}finally{if(o)throw o.error}}yield g.close(),n()}catch(e){r(e)}})).then(()=>{this.log.debug("preconnect buffer sent successfully",Object.assign(Object.assign({},this.logContext),rT(e)))}).catch(t=>{this.log.error("error sending preconnect buffer",Object.assign(Object.assign(Object.assign({},this.logContext),rT(e)),{error:t}))})}return S})}get isLocal(){return!0}publishAdditionalCodecForTrack(e,t,i){return ib(this,void 0,void 0,function*(){var n;let r;if(this.encryptionType!==e2.NONE)return;if(this.trackPublications.forEach(t=>{t.track&&t.track===e&&(r=t)}),!r)throw new nb("track is not published");if(!ru(e))throw new nb("track is not a video track");let s=Object.assign(Object.assign({},null===(n=this.roomOptions)||void 0===n?void 0:n.publishDefaults),i),o=function(e,t,i){var n,r,s,o;if(!i.backupCodec||!0===i.backupCodec||i.backupCodec.codec===i.videoCodec)return;t!==i.backupCodec.codec&&ip.warn("requested a different codec than specified as backup",{serverRequested:t,backup:i.backupCodec.codec}),i.videoCodec=t,i.videoEncoding=i.backupCodec.encoding;let a=e.mediaStreamTrack.getSettings(),l=null!==(n=a.width)&&void 0!==n?n:null===(r=e.dimensions)||void 0===r?void 0:r.width,c=null!==(s=a.height)&&void 0!==s?s:null===(o=e.dimensions)||void 0===o?void 0:o.height;return e.source===nM.Source.ScreenShare&&i.simulcast&&(i.simulcast=!1),sr(e.source===nM.Source.ScreenShare,l,c,i)}(e,t,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),rT(e)));return}let a=e.addSimulcastTrack(t,o);if(!a)return;let l=new tA({cid:a.mediaStreamTrack.id,type:nM.kindToProto(e.kind),muted:e.isMuted,source:nM.sourceToProto(e.source),sid:e.sid,simulcastCodecs:[{codec:s.videoCodec,cid:a.mediaStreamTrack.id}]});if(l.layers=sh(l.width,l.height,o),!this.engine||this.engine.isClosed)throw new nT("cannot publish track when not connected");let c=(yield Promise.all([this.engine.addTrack(l),ib(this,void 0,void 0,function*(){yield this.engine.createSimulcastSender(e,a,s,o),yield this.engine.negotiate()})]))[0];this.log.debug("published ".concat(t," for track ").concat(e.sid),Object.assign(Object.assign({},this.logContext),{encodings:o,trackInfo:c}))})}unpublishTrack(e,t){return ib(this,void 0,void 0,function*(){var i,n;if(rl(e)){let t=this.pendingPublishPromises.get(e);t&&(this.log.info("awaiting publish promise before attempting to unpublish",Object.assign(Object.assign({},this.logContext),rT(e))),yield t)}let r=this.getPublicationForTrack(e),s=r?rT(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).off(oX.Muted,this.onTrackMuted),e.off(oX.Unmuted,this.onTrackUnmuted),e.off(oX.Ended,this.handleTrackEnded),e.off(oX.UpstreamPaused,this.onTrackUpstreamPaused),e.off(oX.UpstreamResumed,this.onTrackUpstreamResumed),e.off(oX.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate),void 0===t&&(t=null===(n=null===(i=this.roomOptions)||void 0===i?void 0:i.stopLocalTrackOnUnpublish)||void 0===n||n),t?e.stop():e.stopMonitor();let o=!1,a=e.sender;if(e.sender=void 0,this.engine.pcManager&&this.engine.pcManager.currentState<o9.FAILED&&a)try{for(let e of this.engine.pcManager.publisher.getTransceivers())e.sender===a&&(e.direction="inactive",o=!0);if(this.engine.removeTrack(a)&&(o=!0),ru(e)){for(let[,t]of e.simulcastCodecs)t.sender&&(this.engine.removeTrack(t.sender)&&(o=!0),t.sender=void 0);e.simulcastCodecs.clear()}}catch(e){this.log.warn("failed to unpublish track",Object.assign(Object.assign(Object.assign({},this.logContext),s),{error:e}))}switch(this.trackPublications.delete(r.trackSid),r.kind){case nM.Kind.Audio:this.audioTrackPublications.delete(r.trackSid);break;case nM.Kind.Video:this.videoTrackPublications.delete(r.trackSid)}return this.emit(oK.LocalTrackUnpublished,r),r.setTrack(void 0),o&&(yield this.engine.negotiate()),r})}unpublishTracks(e){return ib(this,void 0,void 0,function*(){return(yield Promise.all(e.map(e=>this.unpublishTrack(e)))).filter(e=>!!e)})}republishAllTracks(e){return ib(this,arguments,void 0,function(e){var t=this;let i=!(arguments.length>1)||void 0===arguments[1]||arguments[1];return function*(){t.republishPromise&&(yield t.republishPromise),t.republishPromise=new Promise((n,r)=>ib(t,void 0,void 0,function*(){try{let t=[];this.trackPublications.forEach(i=>{i.track&&(e&&(i.options=Object.assign(Object.assign({},i.options),e)),t.push(i))}),yield Promise.all(t.map(e=>ib(this,void 0,void 0,function*(){let t=e.track;yield this.unpublishTrack(t,!1),i&&!t.isMuted&&t.source!==nM.Source.ScreenShare&&t.source!==nM.Source.ScreenShareAudio&&(rh(t)||ru(t))&&!t.isUserProvided&&(this.log.debug("restarting existing track",Object.assign(Object.assign({},this.logContext),{track:e.trackSid})),yield t.restartTrack()),yield this.publishOrRepublishTrack(t,e.options,!0)}))),n()}catch(e){r(e)}finally{this.republishPromise=void 0}})),yield t.republishPromise}()})}publishData(e){return ib(this,arguments,void 0,function(e){var t=this;let i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){let n=i.reliable?e9.RELIABLE:e9.LOSSY,r=i.destinationIdentities,s=i.topic,o=new e6({kind:n,value:{case:"user",value:new te({participantIdentity:t.identity,payload:e,destinationIdentities:r,topic:s})}});yield t.engine.sendDataPacket(o,n)}()})}publishDtmf(e,t){return ib(this,void 0,void 0,function*(){let i=new e6({kind:e9.RELIABLE,value:{case:"sipDtmf",value:new tt({code:e,digit:t})}});yield this.engine.sendDataPacket(i,e9.RELIABLE)})}sendChatMessage(e,t){return ib(this,void 0,void 0,function*(){let i={id:crypto.randomUUID(),message:e,timestamp:Date.now(),attachedFiles:null==t?void 0:t.attachments},n=new e6({value:{case:"chatMessage",value:new tr(Object.assign(Object.assign({},i),{timestamp:j.parse(i.timestamp)}))}});return yield this.engine.sendDataPacket(n,e9.RELIABLE),this.emit(oK.ChatMessage,i),i})}editChatMessage(e,t){return ib(this,void 0,void 0,function*(){let i=Object.assign(Object.assign({},t),{message:e,editTimestamp:Date.now()}),n=new e6({value:{case:"chatMessage",value:new tr(Object.assign(Object.assign({},i),{timestamp:j.parse(i.timestamp),editTimestamp:j.parse(i.editTimestamp)}))}});return yield this.engine.sendDataPacket(n,e9.RELIABLE),this.emit(oK.ChatMessage,i),i})}sendText(e,t){return ib(this,void 0,void 0,function*(){var i;let n=crypto.randomUUID(),r=new TextEncoder().encode(e).byteLength,s=null===(i=null==t?void 0:t.attachments)||void 0===i?void 0:i.map(()=>crypto.randomUUID()),o=Array(s?s.length+1:1).fill(0),a=(e,i)=>{var n;o[i]=e;let r=o.reduce((e,t)=>e+t,0);null===(n=null==t?void 0:t.onProgress)||void 0===n||n.call(t,r)},l=yield this.streamText({streamId:n,totalSize:r,destinationIdentities:null==t?void 0:t.destinationIdentities,topic:null==t?void 0:t.topic,attachedStreamIds:s,attributes:null==t?void 0:t.attributes});return yield l.write(e),a(1,0),yield l.close(),(null==t?void 0:t.attachments)&&s&&(yield Promise.all(t.attachments.map((e,i)=>ib(this,void 0,void 0,function*(){return this._sendFile(s[i],e,{topic:t.topic,mimeType:e.type,onProgress:e=>{a(e,i+1)}})})))),l.info})}streamText(e){return ib(this,void 0,void 0,function*(){var t,i;let n=null!==(t=null==e?void 0:e.streamId)&&void 0!==t?t:crypto.randomUUID(),r={id:n,mimeType:"text/plain",timestamp:Date.now(),topic:null!==(i=null==e?void 0:e.topic)&&void 0!==i?i:"",size:null==e?void 0:e.totalSize,attributes:null==e?void 0:e.attributes},s=new tT({streamId:n,mimeType:r.mimeType,topic:r.topic,timestamp:ra(r.timestamp),totalLength:ra(null==e?void 0:e.totalSize),attributes:r.attributes,contentHeader:{case:"textHeader",value:new tb({version:null==e?void 0:e.version,attachedStreamIds:null==e?void 0:e.attachedStreamIds,replyToStreamId:null==e?void 0:e.replyToStreamId,operationType:(null==e?void 0:e.type)==="update"?ty.UPDATE:ty.CREATE})}}),o=null==e?void 0:e.destinationIdentities,a=new e6({destinationIdentities:o,value:{case:"streamHeader",value:s}});yield this.engine.sendDataPacket(a,e9.RELIABLE);let l=0,c=this,d=new WritableStream({write(e){return ib(this,void 0,void 0,function*(){for(let t of function(e,t){let i=[],n=new TextEncoder().encode(e);for(;n.length>15e3;){let e=15e3;for(;e>0;){let t=n[e];if(void 0!==t&&(192&t)!=128)break;e--}i.push(n.slice(0,e)),n=n.slice(e)}return n.length>0&&i.push(n),i}(e,0)){yield c.engine.waitForBufferStatusLow(e9.RELIABLE);let e=new e6({destinationIdentities:o,value:{case:"streamChunk",value:new tS({content:t,streamId:n,chunkIndex:ra(l)})}});yield c.engine.sendDataPacket(e,e9.RELIABLE),l+=1}})},close(){return ib(this,void 0,void 0,function*(){let e=new e6({destinationIdentities:o,value:{case:"streamTrailer",value:new tC({streamId:n})}});yield c.engine.sendDataPacket(e,e9.RELIABLE)})},abort(e){console.log("Sink error:",e)}}),u=()=>ib(this,void 0,void 0,function*(){yield h.close()});c.engine.once(oJ.Closing,u);let h=new sC(d,r,()=>this.engine.off(oJ.Closing,u));return h})}sendFile(e,t){return ib(this,void 0,void 0,function*(){let i=crypto.randomUUID();return yield this._sendFile(i,e,t),{id:i}})}_sendFile(e,t,i){return ib(this,void 0,void 0,function*(){var n;let r=yield this.streamBytes({streamId:e,totalSize:t.size,name:t.name,mimeType:null!==(n=null==i?void 0:i.mimeType)&&void 0!==n?n:t.type,topic:null==i?void 0:i.topic,destinationIdentities:null==i?void 0:i.destinationIdentities}),s=t.stream().getReader();for(;;){let{done:e,value:t}=yield s.read();if(e)break;yield r.write(t)}return yield r.close(),r.info})}streamBytes(e){return ib(this,void 0,void 0,function*(){var t,i,n,r,s;let o=null!==(t=null==e?void 0:e.streamId)&&void 0!==t?t:crypto.randomUUID(),a=null==e?void 0:e.destinationIdentities,l={id:o,mimeType:null!==(i=null==e?void 0:e.mimeType)&&void 0!==i?i:"application/octet-stream",topic:null!==(n=null==e?void 0:e.topic)&&void 0!==n?n:"",timestamp:Date.now(),attributes:null==e?void 0:e.attributes,size:null==e?void 0:e.totalSize,name:null!==(r=null==e?void 0:e.name)&&void 0!==r?r:"unknown"},c=new e6({destinationIdentities:a,value:{case:"streamHeader",value:new tT({totalLength:ra(null!==(s=l.size)&&void 0!==s?s:0),mimeType:l.mimeType,streamId:o,topic:l.topic,timestamp:ra(Date.now()),attributes:l.attributes,contentHeader:{case:"byteHeader",value:new tk({name:l.name})}})}});yield this.engine.sendDataPacket(c,e9.RELIABLE);let d=0,u=new y,h=this.engine,p=this.log;return new sw(new WritableStream({write(e){return ib(this,void 0,void 0,function*(){let t=yield u.lock(),i=0;try{for(;i<e.byteLength;){let t=e.slice(i,i+15e3);yield h.waitForBufferStatusLow(e9.RELIABLE);let n=new e6({destinationIdentities:a,value:{case:"streamChunk",value:new tS({content:t,streamId:o,chunkIndex:ra(d)})}});yield h.sendDataPacket(n,e9.RELIABLE),d+=1,i+=t.byteLength}}finally{t()}})},close(){return ib(this,void 0,void 0,function*(){let e=new e6({destinationIdentities:a,value:{case:"streamTrailer",value:new tC({streamId:o})}});yield h.sendDataPacket(e,e9.RELIABLE)})},abort(e){p.error("Sink error:",e)}}),l)})}performRpc(e){return ib(this,arguments,void 0,function(e){var t=this;let{destinationIdentity:i,method:n,payload:r,responseTimeout:s=1e4}=e;return function*(){return new Promise((e,o)=>ib(t,void 0,void 0,function*(){var t,a,l,c;if(rQ(r)>15360){o(rY.builtIn("REQUEST_PAYLOAD_TOO_LARGE"));return}if((null===(a=null===(t=this.engine.latestJoinResponse)||void 0===t?void 0:t.serverInfo)||void 0===a?void 0:a.version)&&0>n3(null===(c=null===(l=this.engine.latestJoinResponse)||void 0===l?void 0:l.serverInfo)||void 0===c?void 0:c.version,"1.8.0")){o(rY.builtIn("UNSUPPORTED_SERVER"));return}let d=crypto.randomUUID();yield this.publishRpcRequest(i,d,n,r,s-2e3);let u=setTimeout(()=>{this.pendingAcks.delete(d),o(rY.builtIn("CONNECTION_TIMEOUT")),this.pendingResponses.delete(d),clearTimeout(h)},2e3);this.pendingAcks.set(d,{resolve:()=>{clearTimeout(u)},participantIdentity:i});let h=setTimeout(()=>{this.pendingResponses.delete(d),o(rY.builtIn("RESPONSE_TIMEOUT"))},s);this.pendingResponses.set(d,{resolve:(t,i)=>{clearTimeout(h),this.pendingAcks.has(d)&&(console.warn("RPC response received before ack",d),this.pendingAcks.delete(d),clearTimeout(u)),i?o(i):e(null!=t?t:"")},participantIdentity:i})}))}()})}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&&void 0!==arguments[1]?arguments[1]:[];this.participantTrackPermissions=t,this.allParticipantsAllowedToSubscribe=e,this.engine.client.isDisconnected||this.updateTrackSubscriptionPermissions()}handleIncomingRpcAck(e){let 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){let n=this.pendingResponses.get(e);n?(n.resolve(t,i),this.pendingResponses.delete(e)):console.error("Response received for unexpected RPC request",e)}publishRpcRequest(e,t,i,n,r){return ib(this,void 0,void 0,function*(){let s=new e6({destinationIdentities:[e],kind:e9.RELIABLE,value:{case:"rpcRequest",value:new ts({id:t,method:i,payload:n,responseTimeoutMs:r,version:1})}});yield this.engine.sendDataPacket(s,e9.RELIABLE)})}handleParticipantDisconnected(e){for(let[t,{participantIdentity:i}]of this.pendingAcks)i===e&&this.pendingAcks.delete(t);for(let[t,{participantIdentity:i,resolve:n}]of this.pendingResponses)i===e&&(n(null,rY.builtIn("RECIPIENT_DISCONNECTED")),this.pendingResponses.delete(t))}setEnabledPublishCodecs(e){this.enabledPublishVideoCodecs=e.filter(e=>"video"===e.mime.split("/")[0].toLowerCase())}updateInfo(e){return!!super.updateInfo(e)&&(e.tracks.forEach(e=>{var t,i;let n=this.trackPublications.get(e.sid);if(n){let r=n.isMuted||null!==(i=null===(t=n.track)||void 0===t?void 0:t.isUpstreamPaused)&&void 0!==i&&i;r!==e.muted&&(this.log.debug("updating server mute state after reconcile",Object.assign(Object.assign(Object.assign({},this.logContext),rT(n)),{mutedOnServer:r})),this.engine.client.sendMuteTrack(e.sid,r))}}),!0)}setActiveAgent(e){var t,i,n,r;this.firstActiveAgent=e,e&&!this.firstActiveAgent&&(this.firstActiveAgent=e),e?null===(i=null===(t=this.activeAgentFuture)||void 0===t?void 0:t.resolve)||void 0===i||i.call(t,e):null===(r=null===(n=this.activeAgentFuture)||void 0===n?void 0:n.reject)||void 0===r||r.call(n,"Agent disconnected"),this.activeAgentFuture=void 0}waitUntilActiveAgentPresent(){return this.firstActiveAgent?Promise.resolve(this.firstActiveAgent):(this.activeAgentFuture||(this.activeAgentFuture=new ri),this.activeAgentFuture.promise)}getPublicationForTrack(e){let t;return this.trackPublications.forEach(i=>{let n=i.track;n&&(e instanceof MediaStreamTrack?(rh(n)||ru(n))&&n.mediaStreamTrack===e&&(t=i):e===n&&(t=i))}),t}waitForPendingPublicationOfSource(e){return ib(this,void 0,void 0,function*(){let t=Date.now();for(;Date.now()<t+1e4;){let t=Array.from(this.pendingPublishPromises.entries()).find(t=>{let[i]=t;return i.source===e});if(t)return t[1];yield nq(20)}})}}class sN extends sI{constructor(e,t,i,n){super(e,t.sid,t.name,n),this.track=void 0,this.allowed=!0,this.requestedDisabled=void 0,this.visible=!0,this.handleEnded=e=>{this.setTrack(void 0),this.emit(oX.Ended,e)},this.handleVisibilityChange=e=>{this.log.debug("adaptivestream video visibility ".concat(this.trackSid,", visible=").concat(e),this.logContext),this.visible=e,this.emitTrackUpdate()},this.handleVideoDimensionsChange=e=>{this.log.debug("adaptivestream video dimensions ".concat(e.width,"x").concat(e.height),this.logContext),this.videoDimensionsAdaptiveStream=e,this.emitTrackUpdate()},this.subscribed=i,this.updateInfo(t)}setSubscribed(e){let t=this.subscriptionStatus,i=this.permissionStatus;this.subscribed=e,e&&(this.allowed=!0);let n=new tF({trackSids:[this.trackSid],subscribe:this.subscribed,participantTracks:[new tc({participantSid:"",trackSids:[this.trackSid]})]});this.emit(oX.UpdateSubscription,n),this.emitSubscriptionUpdateIfChanged(t),this.emitPermissionUpdateIfChanged(i)}get subscriptionStatus(){return!1===this.subscribed?sI.SubscriptionStatus.Unsubscribed:super.isSubscribed?sI.SubscriptionStatus.Subscribed:sI.SubscriptionStatus.Desired}get permissionStatus(){return this.allowed?sI.PermissionStatus.Allowed:sI.PermissionStatus.NotAllowed}get isSubscribed(){return!1!==this.subscribed&&super.isSubscribed}get isDesired(){return!1!==this.subscribed}get isEnabled(){return void 0!==this.requestedDisabled?!this.requestedDisabled:!this.isAdaptiveStream||this.visible}get isLocal(){return!1}setEnabled(e){this.isManualOperationAllowed()&&!e!==this.requestedDisabled&&(this.requestedDisabled=!e,this.emitTrackUpdate())}setVideoQuality(e){this.isManualOperationAllowed()&&this.requestedMaxQuality!==e&&(this.requestedMaxQuality=e,this.requestedVideoDimensions=void 0,this.emitTrackUpdate())}setVideoDimensions(e){var t,i;this.isManualOperationAllowed()&&((null===(t=this.requestedVideoDimensions)||void 0===t?void 0:t.width)!==e.width||(null===(i=this.requestedVideoDimensions)||void 0===i?void 0:i.height)!==e.height)&&(rm(this.track)&&(this.requestedVideoDimensions=e),this.requestedMaxQuality=void 0,this.emitTrackUpdate())}setVideoFPS(e){this.isManualOperationAllowed()&&rm(this.track)&&this.fps!==e&&(this.fps=e,this.emitTrackUpdate())}get videoQuality(){var e;return null!==(e=this.requestedMaxQuality)&&void 0!==e?e:oY.HIGH}setTrack(e){let t=this.subscriptionStatus,i=this.permissionStatus,n=this.track;n!==e&&(n&&(n.off(oX.VideoDimensionsChanged,this.handleVideoDimensionsChange),n.off(oX.VisibilityChanged,this.handleVisibilityChange),n.off(oX.Ended,this.handleEnded),n.detach(),n.stopMonitor(),this.emit(oX.Unsubscribed,n)),super.setTrack(e),e&&(e.sid=this.trackSid,e.on(oX.VideoDimensionsChanged,this.handleVideoDimensionsChange),e.on(oX.VisibilityChanged,this.handleVisibilityChange),e.on(oX.Ended,this.handleEnded),this.emit(oX.Subscribed,e)),this.emitPermissionUpdateIfChanged(i),this.emitSubscriptionUpdateIfChanged(t))}setAllowed(e){let t=this.subscriptionStatus,i=this.permissionStatus;this.allowed=e,this.emitPermissionUpdateIfChanged(i),this.emitSubscriptionUpdateIfChanged(t)}setSubscriptionError(e){this.emit(oX.SubscriptionFailed,e)}updateInfo(e){super.updateInfo(e);let t=this.metadataMuted;this.metadataMuted=e.muted,this.track?this.track.setMuted(e.muted):t!==e.muted&&this.emit(e.muted?oX.Muted:oX.Unmuted)}emitSubscriptionUpdateIfChanged(e){let t=this.subscriptionStatus;e!==t&&this.emit(oX.SubscriptionStatusChanged,t,e)}emitPermissionUpdateIfChanged(e){this.permissionStatus!==e&&this.emit(oX.SubscriptionPermissionChanged,this.permissionStatus,e)}isManualOperationAllowed(){return!!this.isDesired||(this.log.warn("cannot update track settings when not subscribed",this.logContext),!1)}get isAdaptiveStream(){return rm(this.track)&&this.track.isAdaptiveStream}emitTrackUpdate(){let e=new tV({trackSids:[this.trackSid],disabled:!this.isEnabled,fps:this.fps});if(this.kind===nM.Kind.Video){let r=this.requestedVideoDimensions;if(void 0!==this.videoDimensionsAdaptiveStream){if(r)rC(this.videoDimensionsAdaptiveStream,r)&&(this.log.debug("using adaptive stream dimensions instead of requested",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),r=this.videoDimensionsAdaptiveStream);else if(void 0!==this.requestedMaxQuality&&this.trackInfo){var t,i,n;let e=(t=this.trackInfo,i=this.requestedMaxQuality,null===(n=t.layers)||void 0===n?void 0:n.find(e=>e.quality===i));e&&rC(this.videoDimensionsAdaptiveStream,e)&&(this.log.debug("using adaptive stream dimensions instead of max quality layer",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),r=this.videoDimensionsAdaptiveStream)}else this.log.debug("using adaptive stream dimensions",Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),r=this.videoDimensionsAdaptiveStream}r?(e.width=Math.ceil(r.width),e.height=Math.ceil(r.height)):void 0!==this.requestedMaxQuality?(this.log.debug("using requested max quality",Object.assign(Object.assign({},this.logContext),{quality:this.requestedMaxQuality})),e.quality=this.requestedMaxQuality):(this.log.debug("using default quality",Object.assign(Object.assign({},this.logContext),{quality:oY.HIGH})),e.quality=oY.HIGH)}this.emit(oX.UpdateSettings,e)}}class sL extends sD{static fromParticipantInfo(e,t,i){return new sL(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,n,r,s,o){let a=arguments.length>7&&void 0!==arguments[7]?arguments[7]:e0.STANDARD;super(t,i||"",n,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(oX.UpdateSettings,t=>{this.log.debug("send update settings",Object.assign(Object.assign(Object.assign({},this.logContext),rT(e)),{settings:t})),this.signalClient.sendUpdateTrackSettings(t)}),e.on(oX.UpdateSubscription,e=>{e.participantTracks.forEach(e=>{e.participantSid=this.sid}),this.signalClient.sendUpdateSubscription(e)}),e.on(oX.SubscriptionPermissionChanged,t=>{this.emit(oK.TrackSubscriptionPermissionChanged,e,t)}),e.on(oX.SubscriptionStatusChanged,t=>{this.emit(oK.TrackSubscriptionStatusChanged,e,t)}),e.on(oX.Subscribed,t=>{this.emit(oK.TrackSubscribed,t,e)}),e.on(oX.Unsubscribed,t=>{this.emit(oK.TrackUnsubscribed,t,e)}),e.on(oX.SubscriptionFailed,t=>{this.emit(oK.TrackSubscriptionFailed,e.trackSid,t)})}getTrackPublication(e){let t=super.getTrackPublication(e);if(t)return t}getTrackPublicationByName(e){let t=super.getTrackPublicationByName(e);if(t)return t}setVolume(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:nM.Source.Microphone;this.volumeMap.set(t,e);let i=this.getTrackPublication(t);i&&i.track&&i.track.setVolume(e)}getVolume(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:nM.Source.Microphone,t=this.getTrackPublication(e);return t&&t.track?t.track.getVolume():this.volumeMap.get(e)}addSubscribedMediaTrack(e,t,i,n,r,s){let o,a=this.getTrackPublicationBySid(t);if(a||t.startsWith("TR")||this.trackPublications.forEach(t=>{a||e.kind!==t.kind.toString()||(a=t)}),!a){if(0===s){this.log.error("could not find published track",Object.assign(Object.assign({},this.logContext),{trackSid:t})),this.emit(oK.TrackSubscriptionFailed,t);return}void 0===s&&(s=20),setTimeout(()=>{this.addSubscribedMediaTrack(e,t,i,n,r,s-1)},150);return}if("ended"===e.readyState){this.log.error("unable to subscribe because MediaStreamTrack is ended. Do not call MediaStreamTrack.stop()",Object.assign(Object.assign({},this.logContext),rT(a))),this.emit(oK.TrackSubscriptionFailed,t);return}return(o="video"===e.kind?new sx(e,t,n,r):new sP(e,t,n,this.audioContext,this.audioOutput)).source=a.source,o.isMuted=a.isMuted,o.setMediaStream(i),o.start(),a.setTrack(o),this.volumeMap.has(a.source)&&rp(o)&&rc(o)&&o.setVolume(this.volumeMap.get(a.source)),a}get hasMetadata(){return!!this.participantInfo}getTrackPublicationBySid(e){return this.trackPublications.get(e)}updateInfo(e){if(!super.updateInfo(e))return!1;let t=new Map,i=new Map;return e.tracks.forEach(e=>{var n,r;let s=this.getTrackPublicationBySid(e.sid);if(s)s.updateInfo(e);else{let t=nM.kindFromProto(e.type);if(!t)return;(s=new sN(t,e,null===(n=this.signalClient.connectOptions)||void 0===n?void 0:n.autoSubscribe,{loggerContextCb:()=>this.logContext,loggerName:null===(r=this.loggerOptions)||void 0===r?void 0:r.loggerName})).updateInfo(e),i.set(e.sid,s);let o=Array.from(this.trackPublications.values()).find(e=>e.source===(null==s?void 0:s.source));o&&s.source!==nM.Source.Unknown&&this.log.debug("received a second track publication for ".concat(this.identity," with the same source: ").concat(s.source),Object.assign(Object.assign({},this.logContext),{oldTrack:rT(o),newTrack:rT(s)})),this.addTrackPublication(s)}t.set(e.sid,s)}),this.trackPublications.forEach(e=>{t.has(e.trackSid)||(this.log.trace("detected removed track on remote participant, unpublishing",Object.assign(Object.assign({},this.logContext),rT(e))),this.unpublishTrack(e.trackSid,!0))}),i.forEach(e=>{this.emit(oK.TrackPublished,e)}),!0}unpublishTrack(e,t){let i=this.trackPublications.get(e);if(!i)return;let{track:n}=i;switch(n&&(n.stop(),i.setTrack(void 0)),this.trackPublications.delete(e),i.kind){case nM.Kind.Audio:this.audioTrackPublications.delete(e);break;case nM.Kind.Video:this.videoTrackPublications.delete(e)}t&&this.emit(oK.TrackUnpublished,i)}setAudioOutput(e){return ib(this,void 0,void 0,function*(){this.audioOutput=e;let t=[];this.audioTrackPublications.forEach(i=>{var n;rc(i.track)&&rp(i.track)&&t.push(i.track.setSinkId(null!==(n=e.deviceId)&&void 0!==n?n:"default"))}),yield Promise.all(t)})}emit(e){for(var t=arguments.length,i=Array(t>1?t-1:0),n=1;n<t;n++)i[n-1]=arguments[n];return this.log.trace("participant event",Object.assign(Object.assign({},this.logContext),{event:e,args:i})),super.emit(e,...i)}}!function(e){e.Disconnected="disconnected",e.Connecting="connecting",e.Connected="connected",e.Reconnecting="reconnecting",e.SignalReconnecting="signalReconnecting"}(ae||(ae={}));class sj extends iS.EventEmitter{constructor(e){var t,i,n,r;if(super(),t=this,this.state=ae.Disconnected,this.activeSpeakers=[],this.isE2EEEnabled=!1,this.audioEnabled=!0,this.isVideoPlaybackBlocked=!1,this.log=ip,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=(e,t,i)=>ib(this,void 0,void 0,function*(){var n;if(!("undefined"!=typeof RTCPeerConnection&&(nW()||nz()))){if(nQ())throw Error("WebRTC isn't detected, have you called registerGlobals?");throw Error("LiveKit doesn't seem to be supported on this browser. Try to update your browser and make sure no browser extensions are disabling webRTC.")}let r=yield this.disconnectLock.lock();if(this.state===ae.Connected)return this.log.info("already connected to room ".concat(this.name),this.logContext),r(),Promise.resolve();if(this.connectFuture)return r(),this.connectFuture.promise;this.setAndEmitConnectionState(ae.Connecting),(null===(n=this.regionUrlProvider)||void 0===n?void 0:n.getServerUrl().toString())!==e&&(this.regionUrl=void 0,this.regionUrlProvider=void 0),nZ(new URL(e))&&(void 0===this.regionUrlProvider?this.regionUrlProvider=new sy(e,t):this.regionUrlProvider.updateToken(t),this.regionUrlProvider.fetchRegionSettings().then(e=>{var t;null===(t=this.regionUrlProvider)||void 0===t||t.setServerReportedRegions(e)}).catch(e=>{this.log.warn("could not fetch region settings",Object.assign(Object.assign({},this.logContext),{error:e}))}));let s=(n,o,a)=>ib(this,void 0,void 0,function*(){var l,c;this.abortController&&this.abortController.abort();let d=new AbortController;this.abortController=d,null==r||r();try{yield this.attemptConnection(null!=a?a:e,t,i,d),this.abortController=void 0,n()}catch(e){if(this.regionUrlProvider&&e instanceof nv&&e.reason!==oz.Cancelled&&e.reason!==oz.NotAllowed){let t=null;try{t=yield this.regionUrlProvider.getNextBestRegionUrl(null===(l=this.abortController)||void 0===l?void 0:l.signal)}catch(e){if(e instanceof nv&&(401===e.status||e.reason===oz.Cancelled)){this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),o(e);return}}!t||(null===(c=this.abortController)||void 0===c?void 0:c.signal.aborted)?(this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,rs(e)),o(e)):(this.log.info("Initial connection failed with ConnectionError: ".concat(e.message,". Retrying with another region: ").concat(t),this.logContext),this.recreateEngine(),yield s(n,o,t))}else{let t=eH.UNKNOWN_REASON;e instanceof nv&&(t=rs(e)),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,t),o(e)}}}),o=this.regionUrl;return this.regionUrl=void 0,this.connectFuture=new ri((e,t)=>{s(e,t,o)},()=>{this.clearConnectionFutures()}),this.connectFuture.promise}),this.connectSignal=(e,t,i,n,r,s)=>ib(this,void 0,void 0,function*(){var o,a,l;let c=yield i.join(e,t,{autoSubscribe:n.autoSubscribe,adaptiveStream:"object"==typeof r.adaptiveStream||r.adaptiveStream,maxRetries:n.maxRetries,e2eeEnabled:!!this.e2eeManager,websocketTimeout:n.websocketTimeout},s.signal),d=c.serverInfo;if(d||(d={version:c.serverVersion,region:c.serverRegion}),this.serverInfo=d,this.log.debug("connected to Livekit Server ".concat(Object.entries(d).map(e=>{let[t,i]=e;return"".concat(t,": ").concat(i)}).join(", ")),{room:null===(o=c.room)||void 0===o?void 0:o.name,roomSid:null===(a=c.room)||void 0===a?void 0:a.sid,identity:null===(l=c.participant)||void 0===l?void 0:l.identity}),!d.version)throw new nk("unknown server version");return"0.15.1"===d.version&&this.options.dynacast&&(this.log.debug("disabling dynacast due to server version",this.logContext),r.dynacast=!1),c}),this.applyJoinResponse=e=>{let t=e.participant;if(this.localParticipant.sid=t.sid,this.localParticipant.identity=t.identity,this.localParticipant.setEnabledPublishCodecs(e.enabledPublishCodecs),this.options.e2ee&&this.e2eeManager)try{this.e2eeManager.setSifTrailer(e.sifTrailer)}catch(e){this.log.error(e instanceof Error?e.message:"Could not set SifTrailer",Object.assign(Object.assign({},this.logContext),{error:e}))}this.handleParticipantUpdates([t,...e.otherParticipants]),e.room&&this.handleRoomUpdate(e.room)},this.attemptConnection=(e,t,i,n)=>ib(this,void 0,void 0,function*(){var r,s;this.state===ae.Reconnecting||this.isResuming||(null===(r=this.engine)||void 0===r?void 0:r.pendingReconnect)?(this.log.info("Reconnection attempt replaced by new connection attempt",this.logContext),this.recreateEngine()):this.maybeCreateEngine(),(null===(s=this.regionUrlProvider)||void 0===s?void 0:s.isCloud())&&this.engine.setRegionUrlProvider(this.regionUrlProvider),this.acquireAudioContext(),this.connOptions=Object.assign(Object.assign({},rJ),i),this.connOptions.rtcConfig&&(this.engine.rtcConfig=this.connOptions.rtcConfig),this.connOptions.peerConnectionTimeout&&(this.engine.peerConnectionTimeout=this.connOptions.peerConnectionTimeout);try{let i=yield this.connectSignal(e,t,this.engine,this.connOptions,this.options,n);this.applyJoinResponse(i),this.setupLocalParticipantEvents(),this.emit(o$.SignalConnected)}catch(t){yield this.engine.close(),this.recreateEngine();let e=new nv("could not establish signal connection",oz.ServerUnreachable);throw t instanceof Error&&(e.message="".concat(e.message,": ").concat(t.message)),t instanceof nv&&(e.reason=t.reason,e.status=t.status),this.log.debug("error trying to establish signal connection",Object.assign(Object.assign({},this.logContext),{error:t})),e}if(n.signal.aborted)throw yield this.engine.close(),this.recreateEngine(),new nv("Connection attempt aborted",oz.Cancelled);try{yield this.engine.waitForPCInitialConnection(this.connOptions.peerConnectionTimeout,n)}catch(e){throw yield this.engine.close(),this.recreateEngine(),e}nY()&&this.options.disconnectOnPageLeave&&(window.addEventListener("pagehide",this.onPageLeave),window.addEventListener("beforeunload",this.onPageLeave)),nY()&&document.addEventListener("freeze",this.onPageLeave),this.setAndEmitConnectionState(ae.Connected),this.emit(o$.Connected),this.registerConnectionReconcile()}),this.disconnect=function(){for(var e=arguments.length,i=Array(e),n=0;n<e;n++)i[n]=arguments[n];return ib(t,[...i],void 0,function(){var e=this;let t=!(arguments.length>0)||void 0===arguments[0]||arguments[0];return function*(){var i,n,r,s;let o=yield e.disconnectLock.lock();try{if(e.state===ae.Disconnected){e.log.debug("already disconnected",e.logContext);return}e.log.info("disconnect from room",Object.assign({},e.logContext)),(e.state===ae.Connecting||e.state===ae.Reconnecting||e.isResuming)&&(e.log.warn("abort connection attempt",e.logContext),null===(i=e.abortController)||void 0===i||i.abort(),null===(r=null===(n=e.connectFuture)||void 0===n?void 0:n.reject)||void 0===r||r.call(n,new nv("Client initiated disconnect",oz.Cancelled)),e.connectFuture=void 0),(null===(s=e.engine)||void 0===s?void 0:s.client.isDisconnected)||(yield e.engine.client.sendLeave()),e.engine&&(yield e.engine.close()),e.handleDisconnect(t,eH.CLIENT_INITIATED),e.engine=void 0}finally{o()}}()})},this.onPageLeave=()=>ib(this,void 0,void 0,function*(){this.log.info("Page leave detected, disconnecting",this.logContext),yield this.disconnect()}),this.startAudio=()=>ib(this,void 0,void 0,function*(){let e=[],t=nP();if(t&&"iOS"===t.os){let t="livekit-dummy-audio-el",i=document.getElementById(t);if(!i){(i=document.createElement("audio")).id=t,i.autoplay=!0,i.hidden=!0;let e=rt();e.enabled=!0;let n=new MediaStream([e]);i.srcObject=n,document.addEventListener("visibilitychange",()=>{i&&(i.srcObject=document.hidden?null:n,document.hidden||(this.log.debug("page visible again, triggering startAudio to resume playback and update playback status",this.logContext),this.startAudio()))}),document.body.append(i),this.once(o$.Disconnected,()=>{null==i||i.remove(),i=null})}e.push(i)}this.remoteParticipants.forEach(t=>{t.audioTrackPublications.forEach(t=>{t.track&&t.track.attachedElements.forEach(t=>{e.push(t)})})});try{yield Promise.all([this.acquireAudioContext(),...e.map(e=>(e.muted=!1,e.play()))]),this.handleAudioPlaybackStarted()}catch(e){throw this.handleAudioPlaybackFailed(e),e}}),this.startVideo=()=>ib(this,void 0,void 0,function*(){let e=[];for(let t of this.remoteParticipants.values())t.videoTrackPublications.forEach(t=>{var i;null===(i=t.track)||void 0===i||i.attachedElements.forEach(t=>{e.includes(t)||e.push(t)})});yield Promise.all(e.map(e=>e.play())).then(()=>{this.handleVideoPlaybackStarted()}).catch(e=>{"NotAllowedError"===e.name?this.handleVideoPlaybackFailed():this.log.warn("Resuming video playback failed, make sure you call `startVideo` directly in a user gesture handler",this.logContext)})}),this.handleRestarting=()=>{for(let e of(this.clearConnectionReconcile(),this.isResuming=!1,this.remoteParticipants.values()))this.handleParticipantDisconnected(e.identity,e);this.setAndEmitConnectionState(ae.Reconnecting)&&this.emit(o$.Reconnecting)},this.handleSignalRestarted=e=>ib(this,void 0,void 0,function*(){this.log.debug("signal reconnected to server, region ".concat(e.serverRegion),Object.assign(Object.assign({},this.logContext),{region:e.serverRegion})),this.bufferedEvents=[],this.applyJoinResponse(e);try{yield this.localParticipant.republishAllTracks(void 0,!0)}catch(e){this.log.error("error trying to re-publish tracks after reconnection",Object.assign(Object.assign({},this.logContext),{error:e}))}try{yield this.engine.waitForRestarted(),this.log.debug("fully reconnected to server",Object.assign(Object.assign({},this.logContext),{region:e.serverRegion}))}catch(e){return}this.setAndEmitConnectionState(ae.Connected),this.emit(o$.Reconnected),this.registerConnectionReconcile(),this.emitBufferedEvents()}),this.handleParticipantUpdates=e=>{e.forEach(e=>{var t;if(e.identity===this.localParticipant.identity){this.localParticipant.updateInfo(e);return}""===e.identity&&(e.identity=null!==(t=this.sidToIdentity.get(e.sid))&&void 0!==t?t:"");let i=this.remoteParticipants.get(e.identity);e.state===eZ.DISCONNECTED?this.handleParticipantDisconnected(e.identity,i):i=this.getOrCreateParticipant(e.identity,e)})},this.handleActiveSpeakersUpdate=e=>{let t=[],i={};e.forEach(e=>{if(i[e.sid]=!0,e.sid===this.localParticipant.sid)this.localParticipant.audioLevel=e.level,this.localParticipant.setIsSpeaking(!0),t.push(this.localParticipant);else{let i=this.getRemoteParticipantBySid(e.sid);i&&(i.audioLevel=e.level,i.setIsSpeaking(!0),t.push(i))}}),i[this.localParticipant.sid]||(this.localParticipant.audioLevel=0,this.localParticipant.setIsSpeaking(!1)),this.remoteParticipants.forEach(e=>{i[e.sid]||(e.audioLevel=0,e.setIsSpeaking(!1))}),this.activeSpeakers=t,this.emitWhenConnected(o$.ActiveSpeakersChanged,t)},this.handleSpeakersChanged=e=>{let t=new Map;this.activeSpeakers.forEach(e=>{let i=this.remoteParticipants.get(e.identity);i&&i.sid!==e.sid||t.set(e.sid,e)}),e.forEach(e=>{let i=this.getRemoteParticipantBySid(e.sid);e.sid===this.localParticipant.sid&&(i=this.localParticipant),i&&(i.audioLevel=e.level,i.setIsSpeaking(e.active),e.active?t.set(e.sid,i):t.delete(e.sid))});let i=Array.from(t.values());i.sort((e,t)=>t.audioLevel-e.audioLevel),this.activeSpeakers=i,this.emitWhenConnected(o$.ActiveSpeakersChanged,i)},this.handleStreamStateUpdate=e=>{e.streamStates.forEach(e=>{let t=this.getRemoteParticipantBySid(e.participantSid);if(!t)return;let i=t.getTrackPublicationBySid(e.trackSid);if(!i||!i.track)return;let n=nM.streamStateFromProto(e.state);n!==i.track.streamState&&(i.track.streamState=n,t.emit(oK.TrackStreamStateChanged,i,i.track.streamState),this.emitWhenConnected(o$.TrackStreamStateChanged,i,i.track.streamState,t))})},this.handleSubscriptionPermissionUpdate=e=>{let t=this.getRemoteParticipantBySid(e.participantSid);if(!t)return;let i=t.getTrackPublicationBySid(e.trackSid);i&&i.setAllowed(e.allowed)},this.handleSubscriptionError=e=>{let t=Array.from(this.remoteParticipants.values()).find(t=>t.trackPublications.has(e.trackSid));if(!t)return;let i=t.getTrackPublicationBySid(e.trackSid);i&&i.setSubscriptionError(e.err)},this.handleDataPacket=e=>{let t=this.remoteParticipants.get(e.participantIdentity);if("user"===e.value.case)this.handleUserPacket(t,e.value.value,e.kind);else if("transcription"===e.value.case)this.handleTranscription(t,e.value.value);else if("sipDtmf"===e.value.case)this.handleSipDtmf(t,e.value.value);else if("chatMessage"===e.value.case)this.handleChatMessage(t,e.value.value);else if("metrics"===e.value.case)this.handleMetrics(e.value.value,t);else if("streamHeader"===e.value.case)this.handleStreamHeader(e.value.value,e.participantIdentity);else if("streamChunk"===e.value.case)this.handleStreamChunk(e.value.value);else if("streamTrailer"===e.value.case)this.handleStreamTrailer(e.value.value);else if("rpcRequest"===e.value.case){let t=e.value.value;this.handleIncomingRpcRequest(e.participantIdentity,t.id,t.method,t.payload,t.responseTimeoutMs,t.version)}},this.handleUserPacket=(e,t,i)=>{this.emit(o$.DataReceived,t.payload,e,i,t.topic),null==e||e.emit(oK.DataReceived,t.payload,i)},this.handleSipDtmf=(e,t)=>{this.emit(o$.SipDTMFReceived,t,e),null==e||e.emit(oK.SipDTMFReceived,t)},this.bufferedSegments=new Map,this.handleTranscription=(e,t)=>{let i=t.transcribedParticipantIdentity===this.localParticipant.identity?this.localParticipant:this.getParticipantByIdentity(t.transcribedParticipantIdentity),n=null==i?void 0:i.trackPublications.get(t.trackId),r=function(e,t){return e.segments.map(e=>{var i;let{id:n,text:r,language:s,startTime:o,endTime:a,final:l}=e,c=null!==(i=t.get(n))&&void 0!==i?i:Date.now(),d=Date.now();return l?t.delete(n):t.set(n,c),{id:n,text:r,startTime:Number.parseInt(o.toString()),endTime:Number.parseInt(a.toString()),final:l,language:s,firstReceivedTime:c,lastReceivedTime:d}})}(t,this.transcriptionReceivedTimes);null==n||n.emit(oX.TranscriptionReceived,r),null==i||i.emit(oK.TranscriptionReceived,r,n),this.emit(o$.TranscriptionReceived,r,i,n)},this.handleChatMessage=(e,t)=>{let i=function(e){let{id:t,timestamp:i,message:n,editTimestamp:r}=e;return{id:t,timestamp:Number.parseInt(i.toString()),editTimestamp:r?Number.parseInt(r.toString()):void 0,message:n}}(t);this.emit(o$.ChatMessage,i,e)},this.handleMetrics=(e,t)=>{this.emit(o$.MetricsReceived,e,t)},this.handleAudioPlaybackStarted=()=>{this.canPlaybackAudio||(this.audioEnabled=!0,this.emit(o$.AudioPlaybackStatusChanged,!0))},this.handleAudioPlaybackFailed=e=>{this.log.warn("could not playback audio",Object.assign(Object.assign({},this.logContext),{error:e})),this.canPlaybackAudio&&(this.audioEnabled=!1,this.emit(o$.AudioPlaybackStatusChanged,!1))},this.handleVideoPlaybackStarted=()=>{this.isVideoPlaybackBlocked&&(this.isVideoPlaybackBlocked=!1,this.emit(o$.VideoPlaybackStatusChanged,!0))},this.handleVideoPlaybackFailed=()=>{this.isVideoPlaybackBlocked||(this.isVideoPlaybackBlocked=!0,this.emit(o$.VideoPlaybackStatusChanged,!1))},this.handleDeviceChange=()=>ib(this,void 0,void 0,function*(){var e;(null===(e=nP())||void 0===e?void 0:e.os)!=="iOS"&&(yield this.selectDefaultDevices()),this.emit(o$.MediaDevicesChanged)}),this.handleRoomUpdate=e=>{let t=this.roomInfo;this.roomInfo=e,t&&t.metadata!==e.metadata&&this.emitWhenConnected(o$.RoomMetadataChanged,e.metadata),(null==t?void 0:t.activeRecording)!==e.activeRecording&&this.emitWhenConnected(o$.RecordingStatusChanged,e.activeRecording)},this.handleConnectionQualityUpdate=e=>{e.updates.forEach(e=>{if(e.participantSid===this.localParticipant.sid){this.localParticipant.setConnectionQuality(e.quality);return}let t=this.getRemoteParticipantBySid(e.participantSid);t&&t.setConnectionQuality(e.quality)})},this.onLocalParticipantMetadataChanged=e=>{this.emit(o$.ParticipantMetadataChanged,e,this.localParticipant)},this.onLocalParticipantNameChanged=e=>{this.emit(o$.ParticipantNameChanged,e,this.localParticipant)},this.onLocalAttributesChanged=e=>{this.emit(o$.ParticipantAttributesChanged,e,this.localParticipant)},this.onLocalTrackMuted=e=>{this.emit(o$.TrackMuted,e,this.localParticipant)},this.onLocalTrackUnmuted=e=>{this.emit(o$.TrackUnmuted,e,this.localParticipant)},this.onTrackProcessorUpdate=e=>{var t;null===(t=null==e?void 0:e.onPublish)||void 0===t||t.call(e,this)},this.onLocalTrackPublished=e=>ib(this,void 0,void 0,function*(){var t,i,n,r,s,o;null===(t=e.track)||void 0===t||t.on(oX.TrackProcessorUpdate,this.onTrackProcessorUpdate),null===(i=e.track)||void 0===i||i.on(oX.Restarted,this.onLocalTrackRestarted),null===(s=null===(r=null===(n=e.track)||void 0===n?void 0:n.getProcessor())||void 0===r?void 0:r.onPublish)||void 0===s||s.call(r,this),this.emit(o$.LocalTrackPublished,e,this.localParticipant),rh(e.track)&&(yield e.track.checkForSilence())&&this.emit(o$.LocalAudioSilenceDetected,e);let a=yield null===(o=e.track)||void 0===o?void 0:o.getDeviceId(!1),l=rb(e.source);l&&a&&a!==this.localParticipant.activeDeviceMap.get(l)&&(this.localParticipant.activeDeviceMap.set(l,a),this.emit(o$.ActiveDeviceChanged,l,a))}),this.onLocalTrackUnpublished=e=>{var t,i;null===(t=e.track)||void 0===t||t.off(oX.TrackProcessorUpdate,this.onTrackProcessorUpdate),null===(i=e.track)||void 0===i||i.off(oX.Restarted,this.onLocalTrackRestarted),this.emit(o$.LocalTrackUnpublished,e,this.localParticipant)},this.onLocalTrackRestarted=e=>ib(this,void 0,void 0,function*(){let t=yield e.getDeviceId(!1),i=rb(e.source);i&&t&&t!==this.localParticipant.activeDeviceMap.get(i)&&(this.log.debug("local track restarted, setting ".concat(i," ").concat(t," active"),this.logContext),this.localParticipant.activeDeviceMap.set(i,t),this.emit(o$.ActiveDeviceChanged,i,t))}),this.onLocalConnectionQualityChanged=e=>{this.emit(o$.ConnectionQualityChanged,e,this.localParticipant)},this.onMediaDevicesError=(e,t)=>{this.emit(o$.MediaDevicesError,e,t)},this.onLocalParticipantPermissionsChanged=e=>{this.emit(o$.ParticipantPermissionsChanged,e,this.localParticipant)},this.onLocalChatMessageSent=e=>{this.emit(o$.ChatMessage,e,this.localParticipant)},this.setMaxListeners(100),this.remoteParticipants=new Map,this.sidToIdentity=new Map,this.options=Object.assign(Object.assign({},rK),e),this.log=im(null!==(i=this.options.loggerName)&&void 0!==i?i:oj.Room),this.transcriptionReceivedTimes=new Map,this.options.audioCaptureDefaults=Object.assign(Object.assign({},rG),null==e?void 0:e.audioCaptureDefaults),this.options.videoCaptureDefaults=Object.assign(Object.assign({},r$),null==e?void 0:e.videoCaptureDefaults),this.options.publishDefaults=Object.assign(Object.assign({},rH),null==e?void 0:e.publishDefaults),this.maybeCreateEngine(),this.disconnectLock=new y,this.localParticipant=new s_("","",this.engine,this.options,this.rpcHandlers),this.options.videoCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("videoinput",rn(this.options.videoCaptureDefaults.deviceId)),this.options.audioCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set("audioinput",rn(this.options.audioCaptureDefaults.deviceId)),(null===(n=this.options.audioOutput)||void 0===n?void 0:n.deviceId)&&this.switchActiveDevice("audiooutput",rn(this.options.audioOutput.deviceId)).catch(e=>this.log.warn("Could not set audio output: ".concat(e.message),this.logContext)),this.options.e2ee&&this.setupE2EE(),nY()){let e=new AbortController;null===(r=navigator.mediaDevices)||void 0===r||r.addEventListener("devicechange",this.handleDeviceChange,{signal:e.signal}),sj.cleanupRegistry&&sj.cleanupRegistry.register(this,()=>{e.abort()})}}registerTextStreamHandler(e,t){if(this.textStreamHandlers.has(e))throw 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 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,n,r,s){return ib(this,void 0,void 0,function*(){if(yield this.engine.publishRpcAck(e,t),1!==s){yield this.engine.publishRpcResponse(e,t,null,rY.builtIn("UNSUPPORTED_VERSION"));return}let o=this.rpcHandlers.get(i);if(!o){yield this.engine.publishRpcResponse(e,t,null,rY.builtIn("UNSUPPORTED_METHOD"));return}let a=null,l=null;try{let s=yield o({requestId:t,callerIdentity:e,payload:n,responseTimeout:r});rQ(s)>15360?(a=rY.builtIn("RESPONSE_PAYLOAD_TOO_LARGE"),console.warn("RPC Response payload too large for ".concat(i))):l=s}catch(e){e instanceof rY?a=e:(console.warn("Uncaught error returned by RPC handler for ".concat(i,". Returning APPLICATION_ERROR instead."),e),a=rY.builtIn("APPLICATION_ERROR"))}yield this.engine.publishRpcResponse(e,t,l,a)})}setE2EEEnabled(e){return ib(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 rw(this.options.e2ee),this.e2eeManager.on(oq.ParticipantEncryptionStatusChanged,(e,t)=>{t.isLocal&&(this.isE2EEEnabled=e),this.emit(o$.ParticipantEncryptionStatusChanged,e,t)}),this.e2eeManager.on(oq.EncryptionError,e=>this.emit(o$.EncryptionError,e)),null===(e=this.e2eeManager)||void 0===e||e.setup(this))}get logContext(){var e;return{room:this.name,roomID:null===(e=this.roomInfo)||void 0===e?void 0:e.sid,participant:this.localParticipant.identity,pID:this.localParticipant.sid}}get isRecording(){var e,t;return null!==(t=null===(e=this.roomInfo)||void 0===e?void 0:e.activeRecording)&&void 0!==t&&t}getSid(){return ib(this,void 0,void 0,function*(){return this.state===ae.Disconnected?"":this.roomInfo&&""!==this.roomInfo.sid?this.roomInfo.sid:new Promise((e,t)=>{let i=t=>{""!==t.sid&&(this.engine.off(oJ.RoomUpdate,i),e(t.sid))};this.engine.on(oJ.RoomUpdate,i),this.once(o$.Disconnected,()=>{this.engine.off(oJ.RoomUpdate,i),t("Room disconnected before room server id was available")})})})}get name(){var e,t;return null!==(t=null===(e=this.roomInfo)||void 0===e?void 0:e.name)&&void 0!==t?t:""}get metadata(){var e;return null===(e=this.roomInfo)||void 0===e?void 0:e.metadata}get numParticipants(){var e,t;return null!==(t=null===(e=this.roomInfo)||void 0===e?void 0:e.numParticipants)&&void 0!==t?t:0}get numPublishers(){var e,t;return null!==(t=null===(e=this.roomInfo)||void 0===e?void 0:e.numPublishers)&&void 0!==t?t:0}maybeCreateEngine(){(!this.engine||this.engine.isClosed)&&(this.engine=new sg(this.options),this.engine.on(oJ.ParticipantUpdate,this.handleParticipantUpdates).on(oJ.RoomUpdate,this.handleRoomUpdate).on(oJ.SpeakersChanged,this.handleSpeakersChanged).on(oJ.StreamStateChanged,this.handleStreamStateUpdate).on(oJ.ConnectionQualityUpdate,this.handleConnectionQualityUpdate).on(oJ.SubscriptionError,this.handleSubscriptionError).on(oJ.SubscriptionPermissionUpdate,this.handleSubscriptionPermissionUpdate).on(oJ.MediaTrackAdded,(e,t,i)=>{this.onTrackAdded(e,t,i)}).on(oJ.Disconnected,e=>{this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e)}).on(oJ.ActiveSpeakersUpdate,this.handleActiveSpeakersUpdate).on(oJ.DataPacketReceived,this.handleDataPacket).on(oJ.Resuming,()=>{this.clearConnectionReconcile(),this.isResuming=!0,this.log.info("Resuming signal connection",this.logContext),this.setAndEmitConnectionState(ae.SignalReconnecting)&&this.emit(o$.SignalReconnecting)}).on(oJ.Resumed,()=>{this.registerConnectionReconcile(),this.isResuming=!1,this.log.info("Resumed signal connection",this.logContext),this.updateSubscriptions(),this.emitBufferedEvents(),this.setAndEmitConnectionState(ae.Connected)&&this.emit(o$.Reconnected)}).on(oJ.SignalResumed,()=>{this.bufferedEvents=[],(this.state===ae.Reconnecting||this.isResuming)&&this.sendSyncState()}).on(oJ.Restarting,this.handleRestarting).on(oJ.SignalRestarted,this.handleSignalRestarted).on(oJ.Offline,()=>{this.setAndEmitConnectionState(ae.Reconnecting)&&this.emit(o$.Reconnecting)}).on(oJ.DCBufferStatusChanged,(e,t)=>{this.emit(o$.DCBufferStatusChanged,e,t)}).on(oJ.LocalTrackSubscribed,e=>{let t=this.localParticipant.getTrackPublications().find(t=>{let{trackSid:i}=t;return i===e});if(!t){this.log.warn("could not find local track subscription for subscribed event",this.logContext);return}this.localParticipant.emit(oK.LocalTrackSubscribed,t),this.emitWhenConnected(o$.LocalTrackSubscribed,t,this.localParticipant)}).on(oJ.RoomMoved,e=>{this.log.debug("room moved",e),e.room&&this.handleRoomUpdate(e.room),this.remoteParticipants.forEach((e,t)=>{this.handleParticipantDisconnected(t,e)}),this.emit(o$.Moved,e.room.name),e.participant?this.handleParticipantUpdates([e.participant,...e.otherParticipants]):this.handleParticipantUpdates(e.otherParticipants)}),this.localParticipant&&this.localParticipant.setupEngine(this.engine),this.e2eeManager&&this.e2eeManager.setupEngine(this.engine))}static getLocalDevices(e){let t=!(arguments.length>1)||void 0===arguments[1]||arguments[1];return rP.getInstance().getDevices(e,t)}prepareConnection(e,t){return ib(this,void 0,void 0,function*(){if(this.state===ae.Disconnected){this.log.debug("prepareConnection to ".concat(e),this.logContext);try{if(nZ(new URL(e))&&t){this.regionUrlProvider=new sy(e,t);let i=yield this.regionUrlProvider.getNextBestRegionUrl();i&&this.state===ae.Disconnected&&(this.regionUrl=i,yield fetch(rr(i),{method:"HEAD"}),this.log.debug("prepared connection to ".concat(i),this.logContext))}else yield fetch(rr(e),{method:"HEAD"})}catch(e){this.log.warn("could not prepare connection",Object.assign(Object.assign({},this.logContext),{error:e}))}}})}getParticipantByIdentity(e){return this.localParticipant.identity===e?this.localParticipant:this.remoteParticipants.get(e)}clearConnectionFutures(){this.connectFuture=void 0}simulateScenario(e,t){return ib(this,void 0,void 0,function*(){let i,n=()=>{};switch(e){case"signal-reconnect":yield this.engine.client.handleOnClose("simulate disconnect");break;case"speaker":i=new ie({scenario:{case:"speakerUpdate",value:3}});break;case"node-failure":i=new ie({scenario:{case:"nodeFailure",value:!0}});break;case"server-leave":i=new ie({scenario:{case:"serverLeave",value:!0}});break;case"migration":i=new ie({scenario:{case:"migration",value:!0}});break;case"resume-reconnect":this.engine.failNext(),yield this.engine.client.handleOnClose("simulate resume-disconnect");break;case"disconnect-signal-on-resume":n=()=>ib(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),i=new ie({scenario:{case:"disconnectSignalOnResume",value:!0}});break;case"disconnect-signal-on-resume-no-messages":n=()=>ib(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose("simulate resume-disconnect")}),i=new ie({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 ie({scenario:{case:"switchCandidateProtocol",value:"force-tls"===e?2:1}}),n=()=>ib(this,void 0,void 0,function*(){let e=this.engine.client.onLeave;e&&e(new tW({reason:eH.CLIENT_INITIATED,action:tz.RECONNECT}))});break;case"subscriber-bandwidth":if(void 0===t||"number"!=typeof t)throw Error("subscriber-bandwidth requires a number as argument");i=new ie({scenario:{case:"subscriberBandwidth",value:ra(t)}});break;case"leave-full-reconnect":i=new ie({scenario:{case:"leaveRequestFullReconnect",value:!0}})}i&&(yield this.engine.client.sendSimulateScenario(i),yield n())})}get canPlaybackAudio(){return this.audioEnabled}get canPlaybackVideo(){return!this.isVideoPlaybackBlocked}getActiveDevice(e){return this.localParticipant.activeDeviceMap.get(e)}switchActiveDevice(e,t){return ib(this,arguments,void 0,function(e,t){var i=this;let n=!(arguments.length>2)||void 0===arguments[2]||arguments[2];return function*(){var r,s,o,a,l,c,d;let u=!0,h=!1,p=n?{exact:t}:t;if("audioinput"===e){h=0===i.localParticipant.audioTrackPublications.size;let t=null!==(r=i.getActiveDevice(e))&&void 0!==r?r:i.options.audioCaptureDefaults.deviceId;i.options.audioCaptureDefaults.deviceId=p;let n=Array.from(i.localParticipant.audioTrackPublications.values()).filter(e=>e.source===nM.Source.Microphone);try{u=(yield Promise.all(n.map(e=>{var t;return null===(t=e.audioTrack)||void 0===t?void 0:t.setDeviceId(p)}))).every(e=>!0===e)}catch(e){throw i.options.audioCaptureDefaults.deviceId=t,e}let s=n.some(e=>{var t,i;return null!==(i=null===(t=e.track)||void 0===t?void 0:t.isMuted)&&void 0!==i&&i});u&&s&&(h=!0)}else if("videoinput"===e){h=0===i.localParticipant.videoTrackPublications.size;let t=null!==(s=i.getActiveDevice(e))&&void 0!==s?s:i.options.videoCaptureDefaults.deviceId;i.options.videoCaptureDefaults.deviceId=p;let n=Array.from(i.localParticipant.videoTrackPublications.values()).filter(e=>e.source===nM.Source.Camera);try{u=(yield Promise.all(n.map(e=>{var t;return null===(t=e.videoTrack)||void 0===t?void 0:t.setDeviceId(p)}))).every(e=>!0===e)}catch(e){throw i.options.videoCaptureDefaults.deviceId=t,e}let r=n.some(e=>{var t,i;return null!==(i=null===(t=e.track)||void 0===t?void 0:t.isMuted)&&void 0!==i&&i});u&&r&&(h=!0)}else if("audiooutput"===e){if(h=!0,!nG()&&!i.options.webAudioMix||i.options.webAudioMix&&i.audioContext&&!("setSinkId"in i.audioContext))throw Error("cannot switch audio output, the current browser does not support it");i.options.webAudioMix&&(t=null!==(o=yield rP.getInstance().normalizeDeviceId("audiooutput",t))&&void 0!==o?o:""),null!==(a=(d=i.options).audioOutput)&&void 0!==a||(d.audioOutput={});let n=null!==(l=i.getActiveDevice(e))&&void 0!==l?l:i.options.audioOutput.deviceId;i.options.audioOutput.deviceId=t;try{i.options.webAudioMix&&(null===(c=i.audioContext)||void 0===c||c.setSinkId(t)),yield Promise.all(Array.from(i.remoteParticipants.values()).map(e=>e.setAudioOutput({deviceId:t})))}catch(e){throw i.options.audioOutput.deviceId=n,e}}return h&&(i.localParticipant.activeDeviceMap.set(e,t),i.emit(o$.ActiveDeviceChanged,e,t)),u}()})}setupLocalParticipantEvents(){this.localParticipant.on(oK.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).on(oK.ParticipantNameChanged,this.onLocalParticipantNameChanged).on(oK.AttributesChanged,this.onLocalAttributesChanged).on(oK.TrackMuted,this.onLocalTrackMuted).on(oK.TrackUnmuted,this.onLocalTrackUnmuted).on(oK.LocalTrackPublished,this.onLocalTrackPublished).on(oK.LocalTrackUnpublished,this.onLocalTrackUnpublished).on(oK.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).on(oK.MediaDevicesError,this.onMediaDevicesError).on(oK.AudioStreamAcquired,this.startAudio).on(oK.ChatMessage,this.onLocalChatMessageSent).on(oK.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged)}recreateEngine(){var e;null===(e=this.engine)||void 0===e||e.close(),this.engine=void 0,this.isResuming=!1,this.remoteParticipants.clear(),this.sidToIdentity.clear(),this.bufferedEvents=[],this.maybeCreateEngine()}onTrackAdded(e,t,i){let n;if(this.state===ae.Connecting||this.state===ae.Reconnecting){let n=()=>{this.onTrackAdded(e,t,i),r()},r=()=>{this.off(o$.Reconnected,n),this.off(o$.Connected,n),this.off(o$.Disconnected,r)};this.once(o$.Reconnected,n),this.once(o$.Connected,n),this.once(o$.Disconnected,r);return}if(this.state===ae.Disconnected){this.log.warn("skipping incoming track after Room disconnected",this.logContext);return}if("ended"===e.readyState){this.log.info("skipping incoming track as it already ended",this.logContext);return}let r=function(e){let t=e.split("|");return t.length>1?[t[0],e.substr(t[0].length+1)]:[e,""]}(t.id),s=r[0],o=r[1],a=e.id;if(o&&o.startsWith("TR")&&(a=o),s===this.localParticipant.sid){this.log.warn("tried to create RemoteParticipant for local participant",this.logContext);return}let l=Array.from(this.remoteParticipants.values()).find(e=>e.sid===s);if(!l){this.log.error("Tried to add a track for a participant, that's not present. Sid: ".concat(s),this.logContext);return}this.options.adaptiveStream&&(n="object"==typeof this.options.adaptiveStream?this.options.adaptiveStream:{}),l.addSubscribedMediaTrack(e,a,t,i,n)}handleDisconnect(){var e;let t=!(arguments.length>0)||void 0===arguments[0]||arguments[0],i=arguments.length>1?arguments[1]:void 0;if(this.clearConnectionReconcile(),this.isResuming=!1,this.bufferedEvents=[],this.transcriptionReceivedTimes.clear(),this.state!==ae.Disconnected){this.regionUrl=void 0;try{this.remoteParticipants.forEach(e=>{e.trackPublications.forEach(t=>{e.unpublishTrack(t.trackSid)})}),this.localParticipant.trackPublications.forEach(e=>{var i,n,r;e.track&&this.localParticipant.unpublishTrack(e.track,t),t?(null===(i=e.track)||void 0===i||i.detach(),null===(n=e.track)||void 0===n||n.stop()):null===(r=e.track)||void 0===r||r.stopMonitor()}),this.localParticipant.off(oK.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).off(oK.ParticipantNameChanged,this.onLocalParticipantNameChanged).off(oK.AttributesChanged,this.onLocalAttributesChanged).off(oK.TrackMuted,this.onLocalTrackMuted).off(oK.TrackUnmuted,this.onLocalTrackUnmuted).off(oK.LocalTrackPublished,this.onLocalTrackPublished).off(oK.LocalTrackUnpublished,this.onLocalTrackUnpublished).off(oK.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).off(oK.MediaDevicesError,this.onMediaDevicesError).off(oK.AudioStreamAcquired,this.startAudio).off(oK.ChatMessage,this.onLocalChatMessageSent).off(oK.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&&"boolean"==typeof this.options.webAudioMix&&(this.audioContext.close(),this.audioContext=void 0),nY()&&(window.removeEventListener("beforeunload",this.onPageLeave),window.removeEventListener("pagehide",this.onPageLeave),window.removeEventListener("freeze",this.onPageLeave),null===(e=navigator.mediaDevices)||void 0===e||e.removeEventListener("devicechange",this.handleDeviceChange))}finally{this.setAndEmitConnectionState(ae.Disconnected),this.emit(o$.Disconnected,i)}}}handleParticipantDisconnected(e,t){var i;this.remoteParticipants.delete(e),t&&(t.trackPublications.forEach(e=>{t.unpublishTrack(e.trackSid,!0)}),this.emit(o$.ParticipantDisconnected,t),t.setDisconnected(),null===(i=this.localParticipant)||void 0===i||i.handleParticipantDisconnected(t.identity))}handleStreamHeader(e,t){return ib(this,void 0,void 0,function*(){var i;if("byteHeader"===e.contentHeader.case){let n;let r=this.byteStreamHandlers.get(e.topic);if(!r){this.log.debug("ignoring incoming byte stream due to no handler for topic",e.topic);return}let s={id:e.streamId,name:null!==(i=e.contentHeader.value.name)&&void 0!==i?i:"unknown",mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:ro(e.timestamp),attributes:e.attributes},o=new ReadableStream({start:t=>{n=t,this.byteStreamControllers.set(e.streamId,{info:s,controller:n,startTime:Date.now()})}});r(new sk(s,o,ro(e.totalLength)),{identity:t})}else if("textHeader"===e.contentHeader.case){let i;let n=this.textStreamHandlers.get(e.topic);if(!n){this.log.debug("ignoring incoming text stream due to no handler for topic",e.topic);return}let r={id:e.streamId,mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:Number(e.timestamp),attributes:e.attributes},s=new ReadableStream({start:t=>{i=t,this.textStreamControllers.set(e.streamId,{info:r,controller:i,startTime:Date.now()})}});n(new sT(r,s,ro(e.totalLength)),{identity:t})}})}handleStreamChunk(e){let t=this.byteStreamControllers.get(e.streamId);t&&e.content.length>0&&t.controller.enqueue(e);let i=this.textStreamControllers.get(e.streamId);i&&e.content.length>0&&i.controller.enqueue(e)}handleStreamTrailer(e){let 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));let 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))}selectDefaultDevices(){return ib(this,void 0,void 0,function*(){var e,t,i;let n=rP.getInstance().previousDevices,r=yield rP.getInstance().getDevices(void 0,!1),s=nP();if((null==s?void 0:s.name)==="Chrome"&&"iOS"!==s.os)for(let e of r){let t=n.find(t=>t.deviceId===e.deviceId);t&&""!==t.label&&t.kind===e.kind&&t.label!==e.label&&"default"===this.getActiveDevice(e.kind)&&this.emit(o$.ActiveDeviceChanged,e.kind,e.deviceId)}for(let s of["audiooutput","audioinput","videoinput"]){let o="audioinput"===s?nM.Source.Microphone:"videoinput"===s?nM.Source.Camera:nM.Source.Unknown,a=this.localParticipant.getTrackPublication(o);if(a&&(null===(e=a.track)||void 0===e?void 0:e.isUserProvided))continue;let l=r.filter(e=>e.kind===s),c=this.getActiveDevice(s);if(c===(null===(t=n.filter(e=>e.kind===s)[0])||void 0===t?void 0:t.deviceId)&&l.length>0&&(null===(i=l[0])||void 0===i?void 0:i.deviceId)!==c){yield this.switchActiveDevice(s,l[0].deviceId);continue}("audioinput"!==s||nJ())&&"videoinput"!==s&&(!(l.length>0)||l.find(e=>e.deviceId===this.getActiveDevice(s))||"audiooutput"===s&&nJ()||(yield this.switchActiveDevice(s,l[0].deviceId)))}})}acquireAudioContext(){return ib(this,void 0,void 0,function*(){var e,t;if("boolean"!=typeof this.options.webAudioMix&&this.options.webAudioMix.audioContext?this.audioContext=this.options.webAudioMix.audioContext:this.audioContext&&"closed"!==this.audioContext.state||(this.audioContext=null!==(e=ry())&&void 0!==e?e:void 0),this.options.webAudioMix&&this.remoteParticipants.forEach(e=>e.setAudioContext(this.audioContext)),this.localParticipant.setAudioContext(this.audioContext),this.audioContext&&"suspended"===this.audioContext.state)try{yield Promise.race([this.audioContext.resume(),nq(200)])}catch(e){this.log.warn("Could not resume audio context",Object.assign(Object.assign({},this.logContext),{error:e}))}let i=(null===(t=this.audioContext)||void 0===t?void 0:t.state)==="running";i!==this.canPlaybackAudio&&(this.audioEnabled=i,this.emit(o$.AudioPlaybackStatusChanged,i))})}createParticipant(e,t){var i;let n;return n=t?sL.fromParticipantInfo(this.engine.client,t,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}):new sL(this.engine.client,"",e,void 0,void 0,void 0,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}),this.options.webAudioMix&&n.setAudioContext(this.audioContext),(null===(i=this.options.audioOutput)||void 0===i?void 0:i.deviceId)&&n.setAudioOutput(this.options.audioOutput).catch(e=>this.log.warn("Could not set audio output: ".concat(e.message),this.logContext)),n}getOrCreateParticipant(e,t){if(this.remoteParticipants.has(e)){let i=this.remoteParticipants.get(e);return t&&i.updateInfo(t)&&this.sidToIdentity.set(t.sid,t.identity),i}let i=this.createParticipant(e,t);return this.remoteParticipants.set(e,i),this.sidToIdentity.set(t.sid,t.identity),this.emitWhenConnected(o$.ParticipantConnected,i),i.on(oK.TrackPublished,e=>{this.emitWhenConnected(o$.TrackPublished,e,i)}).on(oK.TrackSubscribed,(e,t)=>{e.kind===nM.Kind.Audio?(e.on(oX.AudioPlaybackStarted,this.handleAudioPlaybackStarted),e.on(oX.AudioPlaybackFailed,this.handleAudioPlaybackFailed)):e.kind===nM.Kind.Video&&(e.on(oX.VideoPlaybackFailed,this.handleVideoPlaybackFailed),e.on(oX.VideoPlaybackStarted,this.handleVideoPlaybackStarted)),this.emit(o$.TrackSubscribed,e,t,i)}).on(oK.TrackUnpublished,e=>{this.emit(o$.TrackUnpublished,e,i)}).on(oK.TrackUnsubscribed,(e,t)=>{this.emit(o$.TrackUnsubscribed,e,t,i)}).on(oK.TrackMuted,e=>{this.emitWhenConnected(o$.TrackMuted,e,i)}).on(oK.TrackUnmuted,e=>{this.emitWhenConnected(o$.TrackUnmuted,e,i)}).on(oK.ParticipantMetadataChanged,e=>{this.emitWhenConnected(o$.ParticipantMetadataChanged,e,i)}).on(oK.ParticipantNameChanged,e=>{this.emitWhenConnected(o$.ParticipantNameChanged,e,i)}).on(oK.AttributesChanged,e=>{this.emitWhenConnected(o$.ParticipantAttributesChanged,e,i)}).on(oK.ConnectionQualityChanged,e=>{this.emitWhenConnected(o$.ConnectionQualityChanged,e,i)}).on(oK.ParticipantPermissionsChanged,e=>{this.emitWhenConnected(o$.ParticipantPermissionsChanged,e,i)}).on(oK.TrackSubscriptionStatusChanged,(e,t)=>{this.emitWhenConnected(o$.TrackSubscriptionStatusChanged,e,t,i)}).on(oK.TrackSubscriptionFailed,(e,t)=>{this.emit(o$.TrackSubscriptionFailed,e,i,t)}).on(oK.TrackSubscriptionPermissionChanged,(e,t)=>{this.emitWhenConnected(o$.TrackSubscriptionPermissionChanged,e,t,i)}).on(oK.Active,()=>{this.emitWhenConnected(o$.ParticipantActive,i),i.kind===e0.AGENT&&this.localParticipant.setActiveAgent(i)}),t&&i.updateInfo(t),i}sendSyncState(){let e=Array.from(this.remoteParticipants.values()).reduce((e,t)=>(e.push(...t.getTrackPublications()),e),[]),t=this.localParticipant.getTrackPublications();this.engine.sendSyncState(e,t)}updateSubscriptions(){for(let t of this.remoteParticipants.values())for(let i of t.videoTrackPublications.values()){var e;i.isSubscribed&&(e=i)&&!e.isLocal&&i.emitTrackUpdate()}}getRemoteParticipantBySid(e){let t=this.sidToIdentity.get(e);if(t)return this.remoteParticipants.get(t)}registerConnectionReconcile(){this.clearConnectionReconcile();let e=0;this.connectionReconcileInterval=nA.setInterval(()=>{this.engine&&!this.engine.isClosed&&this.engine.verifyTransport()?e=0:(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,eH.STATE_MISMATCH)))},4e3)}clearConnectionReconcile(){this.connectionReconcileInterval&&nA.clearInterval(this.connectionReconcileInterval)}setAndEmitConnectionState(e){return e!==this.state&&(this.state=e,this.emit(o$.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=Array(t>1?t-1:0),n=1;n<t;n++)i[n-1]=arguments[n];if(this.state===ae.Reconnecting||this.isResuming||!this.engine||this.engine.pendingReconnect)this.bufferedEvents.push([e,i]);else if(this.state===ae.Connected)return this.emit(e,...i);return!1}simulateParticipants(e){return ib(this,void 0,void 0,function*(){var t,i;let n=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 eJ({sid:"RM_SIMULATED",name:"simulated-room",emptyTimeout:0,maxParticipants:0,creationTime:j.parse(new Date().getTime()),metadata:"",numParticipants:1,numPublishers:1,turnPassword:"",enabledCodecs:[],activeRecording:!1}),this.localParticipant.updateInfo(new eQ({identity:"simulated-local",name:"local-name"})),this.setupLocalParticipantEvents(),this.emit(o$.SignalConnected),this.emit(o$.Connected),this.setAndEmitConnectionState(ae.Connected),n.video){let e=new sM(nM.Kind.Video,new e5({source:eB.CAMERA,sid:Math.floor(1e4*Math.random()).toString(),type:eV.AUDIO,name:"video-dummy"}),new sc(n.useRealTracks?(yield window.navigator.mediaDevices.getUserMedia({video:!0})).getVideoTracks()[0]:re(160*(null!==(t=r.aspectRatios[0])&&void 0!==t?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(e),this.localParticipant.emit(oK.LocalTrackPublished,e)}if(n.audio){let e=new sM(nM.Kind.Audio,new e5({source:eB.MICROPHONE,sid:Math.floor(1e4*Math.random()).toString(),type:eV.AUDIO}),new r6(n.useRealTracks?(yield navigator.mediaDevices.getUserMedia({audio:!0})).getAudioTracks()[0]:rt(),void 0,!1,this.audioContext,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(e),this.localParticipant.emit(oK.LocalTrackPublished,e)}for(let e=0;e<r.count-1;e+=1){let t=new eQ({sid:Math.floor(1e4*Math.random()).toString(),identity:"simulated-".concat(e),state:eZ.ACTIVE,tracks:[],joinedAt:j.parse(Date.now())}),n=this.getOrCreateParticipant(t.identity,t);if(r.video){let s=re(160*(null!==(i=r.aspectRatios[e%r.aspectRatios.length])&&void 0!==i?i:1),160,!1,!0),o=new e5({source:eB.CAMERA,sid:Math.floor(1e4*Math.random()).toString(),type:eV.AUDIO});n.addSubscribedMediaTrack(s,o.sid,new MediaStream([s]),new RTCRtpReceiver),t.tracks=[...t.tracks,o]}if(r.audio){let e=rt(),i=new e5({source:eB.MICROPHONE,sid:Math.floor(1e4*Math.random()).toString(),type:eV.AUDIO});n.addSubscribedMediaTrack(e,i.sid,new MediaStream([e]),new RTCRtpReceiver),t.tracks=[...t.tracks,i]}n.updateInfo(t)}})}emit(e){for(var t=arguments.length,i=Array(t>1?t-1:0),n=1;n<t;n++)i[n-1]=arguments[n];if(e!==o$.ActiveSpeakersChanged&&e!==o$.TranscriptionReceived){let t=(function e(t){return t.map(t=>t?Array.isArray(t)?e(t):"object"==typeof t?"logContext"in t?t.logContext:void 0:t:void 0)})(i).filter(e=>void 0!==e);this.log.debug("room event ".concat(e),Object.assign(Object.assign({},this.logContext),{event:e,args:t}))}return super.emit(e,...i)}}sj.cleanupRegistry="undefined"!=typeof FinalizationRegistry&&new FinalizationRegistry(e=>{e()}),!function(e){e[e.IDLE=0]="IDLE",e[e.RUNNING=1]="RUNNING",e[e.SKIPPED=2]="SKIPPED",e[e.SUCCESS=3]="SUCCESS",e[e.FAILED=4]="FAILED"}(at||(at={}));let sU=Math.min,sF=Math.max,sV=Math.round,sB=Math.floor,sq=e=>({x:e,y:e}),sW={left:"right",right:"left",bottom:"top",top:"bottom"},sz={start:"end",end:"start"};function sH(e,t){return"function"==typeof e?e(t):e}function sG(e){return e.split("-")[0]}function s$(e){return e.split("-")[1]}function sK(e){return"x"===e?"y":"x"}function sJ(e){return"y"===e?"height":"width"}function sX(e){return["top","bottom"].includes(sG(e))?"y":"x"}function sY(e){return e.replace(/start|end/g,e=>sz[e])}function sQ(e){return e.replace(/left|right|bottom|top/g,e=>sW[e])}function sZ(e){let{x:t,y:i,width:n,height:r}=e;return{width:n,height:r,top:i,left:t,right:t+n,bottom:i+r,x:t,y:i}}function s0(e,t,i){let n,{reference:r,floating:s}=e,o=sX(t),a=sK(sX(t)),l=sJ(a),c=sG(t),d="y"===o,u=r.x+r.width/2-s.width/2,h=r.y+r.height/2-s.height/2,p=r[l]/2-s[l]/2;switch(c){case"top":n={x:u,y:r.y-s.height};break;case"bottom":n={x:u,y:r.y+r.height};break;case"right":n={x:r.x+r.width,y:h};break;case"left":n={x:r.x-s.width,y:h};break;default:n={x:r.x,y:r.y}}switch(s$(t)){case"start":n[a]-=p*(i&&d?-1:1);break;case"end":n[a]+=p*(i&&d?-1:1)}return n}let s1=async(e,t,i)=>{let{placement:n="bottom",strategy:r="absolute",middleware:s=[],platform:o}=i,a=s.filter(Boolean),l=await (null==o.isRTL?void 0:o.isRTL(t)),c=await o.getElementRects({reference:e,floating:t,strategy:r}),{x:d,y:u}=s0(c,n,l),h=n,p={},m=0;for(let i=0;i<a.length;i++){let{name:s,fn:f}=a[i],{x:g,y:v,data:y,reset:b}=await f({x:d,y:u,initialPlacement:n,placement:h,strategy:r,middlewareData:p,rects:c,platform:o,elements:{reference:e,floating:t}});d=g??d,u=v??u,p={...p,[s]:{...p[s],...y}},b&&m<=50&&(m++,"object"==typeof b&&(b.placement&&(h=b.placement),b.rects&&(c=!0===b.rects?await o.getElementRects({reference:e,floating:t,strategy:r}):b.rects),{x:d,y:u}=s0(c,h,l)),i=-1)}return{x:d,y:u,placement:h,strategy:r,middlewareData:p}};async function s2(e,t){var i;void 0===t&&(t={});let{x:n,y:r,platform:s,rects:o,elements:a,strategy:l}=e,{boundary:c="clippingAncestors",rootBoundary:d="viewport",elementContext:u="floating",altBoundary:h=!1,padding:p=0}=sH(t,e),m="number"!=typeof p?{top:0,right:0,bottom:0,left:0,...p}:{top:p,right:p,bottom:p,left:p},f=a[h?"floating"===u?"reference":"floating":u],g=sZ(await s.getClippingRect({element:null==(i=await (null==s.isElement?void 0:s.isElement(f)))||i?f:f.contextElement||await (null==s.getDocumentElement?void 0:s.getDocumentElement(a.floating)),boundary:c,rootBoundary:d,strategy:l})),v="floating"===u?{x:n,y:r,width:o.floating.width,height:o.floating.height}:o.reference,y=await (null==s.getOffsetParent?void 0:s.getOffsetParent(a.floating)),b=await (null==s.isElement?void 0:s.isElement(y))&&await (null==s.getScale?void 0:s.getScale(y))||{x:1,y:1},k=sZ(s.convertOffsetParentRelativeRectToViewportRelativeRect?await s.convertOffsetParentRelativeRectToViewportRelativeRect({elements:a,rect:v,offsetParent:y,strategy:l}):v);return{top:(g.top-k.top+m.top)/b.y,bottom:(k.bottom-g.bottom+m.bottom)/b.y,left:(g.left-k.left+m.left)/b.x,right:(k.right-g.right+m.right)/b.x}}async function s3(e,t){let{placement:i,platform:n,elements:r}=e,s=await (null==n.isRTL?void 0:n.isRTL(r.floating)),o=sG(i),a=s$(i),l="y"===sX(i),c=["left","top"].includes(o)?-1:1,d=s&&l?-1:1,u=sH(t,e),{mainAxis:h,crossAxis:p,alignmentAxis:m}="number"==typeof u?{mainAxis:u,crossAxis:0,alignmentAxis:null}:{mainAxis:u.mainAxis||0,crossAxis:u.crossAxis||0,alignmentAxis:u.alignmentAxis};return a&&"number"==typeof m&&(p="end"===a?-1*m:m),l?{x:p*d,y:h*c}:{x:h*c,y:p*d}}function s5(){return"u">typeof window}function s4(e){return s8(e)?(e.nodeName||"").toLowerCase():"#document"}function s6(e){var t;return(null==e||null==(t=e.ownerDocument)?void 0:t.defaultView)||window}function s9(e){var t;return null==(t=(s8(e)?e.ownerDocument:e.document)||window.document)?void 0:t.documentElement}function s8(e){return!!s5()&&(e instanceof Node||e instanceof s6(e).Node)}function s7(e){return!!s5()&&(e instanceof Element||e instanceof s6(e).Element)}function oe(e){return!!s5()&&(e instanceof HTMLElement||e instanceof s6(e).HTMLElement)}function ot(e){return!(!s5()||typeof ShadowRoot>"u")&&(e instanceof ShadowRoot||e instanceof s6(e).ShadowRoot)}function oi(e){let{overflow:t,overflowX:i,overflowY:n,display:r}=oa(e);return/auto|scroll|overlay|hidden|clip/.test(t+n+i)&&!["inline","contents"].includes(r)}function on(e){return[":popover-open",":modal"].some(t=>{try{return e.matches(t)}catch{return!1}})}function or(e){let t=os(),i=s7(e)?oa(e):e;return["transform","translate","scale","rotate","perspective"].some(e=>!!i[e]&&"none"!==i[e])||!!i.containerType&&"normal"!==i.containerType||!t&&!!i.backdropFilter&&"none"!==i.backdropFilter||!t&&!!i.filter&&"none"!==i.filter||["transform","translate","scale","rotate","perspective","filter"].some(e=>(i.willChange||"").includes(e))||["paint","layout","strict","content"].some(e=>(i.contain||"").includes(e))}function os(){return!(typeof CSS>"u")&&!!CSS.supports&&CSS.supports("-webkit-backdrop-filter","none")}function oo(e){return["html","body","#document"].includes(s4(e))}function oa(e){return s6(e).getComputedStyle(e)}function ol(e){return s7(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function oc(e){if("html"===s4(e))return e;let t=e.assignedSlot||e.parentNode||ot(e)&&e.host||s9(e);return ot(t)?t.host:t}function od(e,t,i){var n;void 0===t&&(t=[]),void 0===i&&(i=!0);let r=function e(t){let i=oc(t);return oo(i)?t.ownerDocument?t.ownerDocument.body:t.body:oe(i)&&oi(i)?i:e(i)}(e),s=r===(null==(n=e.ownerDocument)?void 0:n.body),o=s6(r);if(s){let e=ou(o);return t.concat(o,o.visualViewport||[],oi(r)?r:[],e&&i?od(e):[])}return t.concat(r,od(r,[],i))}function ou(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}function oh(e){let t=oa(e),i=parseFloat(t.width)||0,n=parseFloat(t.height)||0,r=oe(e),s=r?e.offsetWidth:i,o=r?e.offsetHeight:n,a=sV(i)!==s||sV(n)!==o;return a&&(i=s,n=o),{width:i,height:n,$:a}}function op(e){return s7(e)?e:e.contextElement}function om(e){let t=op(e);if(!oe(t))return sq(1);let i=t.getBoundingClientRect(),{width:n,height:r,$:s}=oh(t),o=(s?sV(i.width):i.width)/n,a=(s?sV(i.height):i.height)/r;return o&&Number.isFinite(o)||(o=1),a&&Number.isFinite(a)||(a=1),{x:o,y:a}}let of=sq(0);function og(e){let t=s6(e);return os()&&t.visualViewport?{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}:of}function ov(e,t,i,n){var r;void 0===t&&(t=!1),void 0===i&&(i=!1);let s=e.getBoundingClientRect(),o=op(e),a=sq(1);t&&(n?s7(n)&&(a=om(n)):a=om(e));let l=(void 0===(r=i)&&(r=!1),n&&(!r||n===s6(o))&&r)?og(o):sq(0),c=(s.left+l.x)/a.x,d=(s.top+l.y)/a.y,u=s.width/a.x,h=s.height/a.y;if(o){let e=s6(o),t=n&&s7(n)?s6(n):n,i=e,r=ou(i);for(;r&&n&&t!==i;){let e=om(r),t=r.getBoundingClientRect(),n=oa(r),s=t.left+(r.clientLeft+parseFloat(n.paddingLeft))*e.x,o=t.top+(r.clientTop+parseFloat(n.paddingTop))*e.y;c*=e.x,d*=e.y,u*=e.x,h*=e.y,c+=s,d+=o,r=ou(i=s6(r))}}return sZ({width:u,height:h,x:c,y:d})}function oy(e,t){let i=ol(e).scrollLeft;return t?t.left+i:ov(s9(e)).left+i}function ob(e,t,i){void 0===i&&(i=!1);let n=e.getBoundingClientRect();return{x:n.left+t.scrollLeft-(i?0:oy(e,n)),y:n.top+t.scrollTop}}function ok(e,t,i){let n;if("viewport"===t)n=function(e,t){let i=s6(e),n=s9(e),r=i.visualViewport,s=n.clientWidth,o=n.clientHeight,a=0,l=0;if(r){s=r.width,o=r.height;let e=os();(!e||e&&"fixed"===t)&&(a=r.offsetLeft,l=r.offsetTop)}return{width:s,height:o,x:a,y:l}}(e,i);else if("document"===t)n=function(e){let t=s9(e),i=ol(e),n=e.ownerDocument.body,r=sF(t.scrollWidth,t.clientWidth,n.scrollWidth,n.clientWidth),s=sF(t.scrollHeight,t.clientHeight,n.scrollHeight,n.clientHeight),o=-i.scrollLeft+oy(e),a=-i.scrollTop;return"rtl"===oa(n).direction&&(o+=sF(t.clientWidth,n.clientWidth)-r),{width:r,height:s,x:o,y:a}}(s9(e));else if(s7(t))n=function(e,t){let i=ov(e,!0,"fixed"===t),n=i.top+e.clientTop,r=i.left+e.clientLeft,s=oe(e)?om(e):sq(1),o=e.clientWidth*s.x;return{width:o,height:e.clientHeight*s.y,x:r*s.x,y:n*s.y}}(t,i);else{let i=og(e);n={x:t.x-i.x,y:t.y-i.y,width:t.width,height:t.height}}return sZ(n)}function oT(e){return"static"===oa(e).position}function oS(e,t){if(!oe(e)||"fixed"===oa(e).position)return null;if(t)return t(e);let i=e.offsetParent;return s9(e)===i&&(i=i.ownerDocument.body),i}function oC(e,t){let i=s6(e);if(on(e))return i;if(!oe(e)){let t=oc(e);for(;t&&!oo(t);){if(s7(t)&&!oT(t))return t;t=oc(t)}return i}let n=oS(e,t);for(;n&&["table","td","th"].includes(s4(n))&&oT(n);)n=oS(n,t);return n&&oo(n)&&oT(n)&&!or(n)?i:n||function(e){let t=oc(e);for(;oe(t)&&!oo(t);){if(or(t))return t;if(on(t))break;t=oc(t)}return null}(e)||i}let ow=async function(e){let t=this.getOffsetParent||oC,i=this.getDimensions,n=await i(e.floating);return{reference:function(e,t,i){let n=oe(t),r=s9(t),s="fixed"===i,o=ov(e,!0,s,t),a={scrollLeft:0,scrollTop:0},l=sq(0);if(n||!n&&!s){if(("body"!==s4(t)||oi(r))&&(a=ol(t)),n){let e=ov(t,!0,s,t);l.x=e.x+t.clientLeft,l.y=e.y+t.clientTop}else r&&(l.x=oy(r))}let c=!r||n||s?sq(0):ob(r,a);return{x:o.left+a.scrollLeft-l.x-c.x,y:o.top+a.scrollTop-l.y-c.y,width:o.width,height:o.height}}(e.reference,await t(e.floating),e.strategy),floating:{x:0,y:0,width:n.width,height:n.height}}},oE={convertOffsetParentRelativeRectToViewportRelativeRect:function(e){let{elements:t,rect:i,offsetParent:n,strategy:r}=e,s="fixed"===r,o=s9(n),a=!!t&&on(t.floating);if(n===o||a&&s)return i;let l={scrollLeft:0,scrollTop:0},c=sq(1),d=sq(0),u=oe(n);if((u||!u&&!s)&&(("body"!==s4(n)||oi(o))&&(l=ol(n)),oe(n))){let e=ov(n);c=om(n),d.x=e.x+n.clientLeft,d.y=e.y+n.clientTop}let h=!o||u||s?sq(0):ob(o,l,!0);return{width:i.width*c.x,height:i.height*c.y,x:i.x*c.x-l.scrollLeft*c.x+d.x+h.x,y:i.y*c.y-l.scrollTop*c.y+d.y+h.y}},getDocumentElement:s9,getClippingRect:function(e){let{element:t,boundary:i,rootBoundary:n,strategy:r}=e,s=[..."clippingAncestors"===i?on(t)?[]:function(e,t){let i=t.get(e);if(i)return i;let n=od(e,[],!1).filter(e=>s7(e)&&"body"!==s4(e)),r=null,s="fixed"===oa(e).position,o=s?oc(e):e;for(;s7(o)&&!oo(o);){let t=oa(o),i=or(o);i||"fixed"!==t.position||(r=null),(s?!i&&!r:!i&&"static"===t.position&&!!r&&["absolute","fixed"].includes(r.position)||oi(o)&&!i&&function e(t,i){let n=oc(t);return!(n===i||!s7(n)||oo(n))&&("fixed"===oa(n).position||e(n,i))}(e,o))?n=n.filter(e=>e!==o):r=t,o=oc(o)}return t.set(e,n),n}(t,this._c):[].concat(i),n],o=s[0],a=s.reduce((e,i)=>{let n=ok(t,i,r);return e.top=sF(n.top,e.top),e.right=sU(n.right,e.right),e.bottom=sU(n.bottom,e.bottom),e.left=sF(n.left,e.left),e},ok(t,o,r));return{width:a.right-a.left,height:a.bottom-a.top,x:a.left,y:a.top}},getOffsetParent:oC,getElementRects:ow,getClientRects:function(e){return Array.from(e.getClientRects())},getDimensions:function(e){let{width:t,height:i}=oh(e);return{width:t,height:i}},getScale:om,isElement:s7,isRTL:function(e){return"rtl"===oa(e).direction}};function oP(e,t){return e.x===t.x&&e.y===t.y&&e.width===t.width&&e.height===t.height}let ox=(e,t,i)=>{let n=new Map,r={platform:oE,...i},s={...r.platform,_c:n};return s1(e,t,{...r,platform:s})};var oR="u">typeof globalThis?globalThis:"u">typeof window?window:"u">typeof global?global:"u">typeof self?self:{};function oO(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var oA,oI,oM,oD,o_,oN,oL,oj,oU,oF,oV,oB,oq,oW,oz,oH,oG,o$,oK,oJ,oX,oY,oQ,oZ,o0,o1,o2,o3,o5,o4,o6,o9,o8,o7,ae,at,ai,an={exports:{}},ar=an.exports;let as=oO(function(){var e;return ai||(ai=1,e=function(){var e=function(){},t="undefined",i=typeof window!==t&&typeof window.navigator!==t&&/Trident\/|MSIE /.test(window.navigator.userAgent),n=["trace","debug","info","warn","error"],r={},s=null;function o(e,t){var i=e[t];if("function"==typeof i.bind)return i.bind(e);try{return Function.prototype.bind.call(i,e)}catch{return function(){return Function.prototype.apply.apply(i,[e,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 l(){for(var i=this.getLevel(),r=0;r<n.length;r++){var s=n[r];this[s]=r<i?e:this.methodFactory(s,i,this.name)}if(this.log=this.debug,typeof console===t&&i<this.levels.SILENT)return"No console available for logging"}function c(e){return function(){typeof console!==t&&(l.call(this),this[e].apply(this,arguments))}}function d(n,r,s){var l;return"debug"===(l=n)&&(l="log"),typeof console!==t&&("trace"===l&&i?a:void 0!==console[l]?o(console,l):void 0!==console.log?o(console,"log"):e)||c.apply(this,arguments)}function u(e,i){var o,a,c,u=this,h="loglevel";function p(){var e;if(!(typeof window===t||!h)){try{e=window.localStorage[h]}catch{}if(typeof e===t)try{var i=window.document.cookie,n=encodeURIComponent(h),r=i.indexOf(n+"=");-1!==r&&(e=/^([^;]+)/.exec(i.slice(r+n.length+1))[1])}catch{}return void 0===u.levels[e]&&(e=void 0),e}}function m(e){var t=e;if("string"==typeof t&&void 0!==u.levels[t.toUpperCase()]&&(t=u.levels[t.toUpperCase()]),"number"==typeof t&&t>=0&&t<=u.levels.SILENT)return t;throw TypeError("log.setLevel() called with invalid level: "+e)}"string"==typeof e?h+=":"+e:"symbol"==typeof e&&(h=void 0),u.name=e,u.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},u.methodFactory=i||d,u.getLevel=function(){return c??a??o},u.setLevel=function(e,i){return c=m(e),!1!==i&&function(e){var i=(n[e]||"silent").toUpperCase();if(!(typeof window===t||!h)){try{window.localStorage[h]=i;return}catch{}try{window.document.cookie=encodeURIComponent(h)+"="+i+";"}catch{}}}(c),l.call(u)},u.setDefaultLevel=function(e){a=m(e),p()||u.setLevel(e,!1)},u.resetLevel=function(){c=null,function(){if(!(typeof window===t||!h)){try{window.localStorage.removeItem(h)}catch{}try{window.document.cookie=encodeURIComponent(h)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}(),l.call(u)},u.enableAll=function(e){u.setLevel(u.levels.TRACE,e)},u.disableAll=function(e){u.setLevel(u.levels.SILENT,e)},u.rebuild=function(){if(s!==u&&(o=m(s.getLevel())),l.call(u),s===u)for(var e in r)r[e].rebuild()},o=m(s?s.getLevel():"WARN");var f=p();null!=f&&(c=m(f)),l.call(u)}(s=new u).getLogger=function(e){if("symbol"!=typeof e&&"string"!=typeof e||""===e)throw TypeError("You must supply a name when creating a logger.");var t=r[e];return t||(t=r[e]=new u(e,s.methodFactory)),t};var h=typeof window!==t?window.log:void 0;return s.noConflict=function(){return typeof window!==t&&window.log===s&&(window.log=h),s},s.getLoggers=function(){return r},s.default=s,s},an.exports?an.exports=e():ar.log=e()),an.exports}());var ao=function(e,t){return(ao=Object.setPrototypeOf||({__proto__:[]})instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i])})(e,t)};function aa(e,t){if("function"!=typeof t&&null!==t)throw TypeError("Class extends value "+String(t)+" is not a constructor or null");function i(){this.constructor=e}ao(e,t),e.prototype=null===t?Object.create(t):(i.prototype=t.prototype,new i)}function al(e,t){var i,n,r,s={label:0,sent:function(){if(1&r[0])throw r[1];return r[1]},trys:[],ops:[]},o=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return o.next=a(0),o.throw=a(1),o.return=a(2),"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function a(a){return function(l){return function(a){if(i)throw TypeError("Generator is already executing.");for(;o&&(o=0,a[0]&&(s=0)),s;)try{if(i=1,n&&(r=2&a[0]?n.return:a[0]?n.throw||((r=n.return)&&r.call(n),0):n.next)&&!(r=r.call(n,a[1])).done)return r;switch(n=0,r&&(a=[2&a[0],r.value]),a[0]){case 0:case 1:r=a;break;case 4:return s.label++,{value:a[1],done:!1};case 5:s.label++,n=a[1],a=[0];continue;case 7:a=s.ops.pop(),s.trys.pop();continue;default:if(!(r=(r=s.trys).length>0&&r[r.length-1])&&(6===a[0]||2===a[0])){s=0;continue}if(3===a[0]&&(!r||a[1]>r[0]&&a[1]<r[3])){s.label=a[1];break}if(6===a[0]&&s.label<r[1]){s.label=r[1],r=a;break}if(r&&s.label<r[2]){s.label=r[2],s.ops.push(a);break}r[2]&&s.ops.pop(),s.trys.pop();continue}a=t.call(e,s)}catch(e){a=[6,e],n=0}finally{i=r=0}if(5&a[0])throw a[1];return{value:a[0]?a[1]:void 0,done:!0}}([a,l])}}}function ac(e){var t="function"==typeof Symbol&&Symbol.iterator,i=t&&e[t],n=0;if(i)return i.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function ad(e,t){var i="function"==typeof Symbol&&e[Symbol.iterator];if(!i)return e;var n,r,s=i.call(e),o=[];try{for(;(void 0===t||t-- >0)&&!(n=s.next()).done;)o.push(n.value)}catch(e){r={error:e}}finally{try{n&&!n.done&&(i=s.return)&&i.call(s)}finally{if(r)throw r.error}}return o}function au(e,t,i){if(i||2==arguments.length)for(var n,r=0,s=t.length;r<s;r++)!n&&r in t||(n||(n=Array.prototype.slice.call(t,0,r)),n[r]=t[r]);return e.concat(n||Array.prototype.slice.call(t))}function ah(e){return this instanceof ah?(this.v=e,this):new ah(e)}function ap(e){return"function"==typeof e}function am(e){var t=e(function(e){Error.call(e),e.stack=Error().stack});return t.prototype=Object.create(Error.prototype),t.prototype.constructor=t,t}var af=am(function(e){return function(t){e(this),this.message=t?t.length+` errors occurred during unsubscription:
2
2
  `+t.map(function(e,t){return t+1+") "+e.toString()}).join(`
3
- `):"",this.name="UnsubscriptionError",this.errors=t}});function ag(e,t){if(e){var i=e.indexOf(t);0<=i&&e.splice(i,1)}}var av=function(){var e;function t(e){this.initialTeardown=e,this.closed=!1,this._parentage=null,this._finalizers=null}return t.prototype.unsubscribe=function(){var e,t,i,n,r;if(!this.closed){this.closed=!0;var s=this._parentage;if(s){if(this._parentage=null,Array.isArray(s))try{for(var o=ac(s),a=o.next();!a.done;a=o.next())a.value.remove(this)}catch(t){e={error:t}}finally{try{a&&!a.done&&(t=o.return)&&t.call(o)}finally{if(e)throw e.error}}else s.remove(this)}var l=this.initialTeardown;if(ap(l))try{l()}catch(e){r=e instanceof af?e.errors:[e]}var c=this._finalizers;if(c){this._finalizers=null;try{for(var d=ac(c),u=d.next();!u.done;u=d.next()){var h=u.value;try{ak(h)}catch(e){r=r??[],e instanceof af?r=au(au([],ad(r)),ad(e.errors)):r.push(e)}}}catch(e){i={error:e}}finally{try{u&&!u.done&&(n=d.return)&&n.call(d)}finally{if(i)throw i.error}}}if(r)throw new af(r)}},t.prototype.add=function(e){var i;if(e&&e!==this){if(this.closed)ak(e);else{if(e instanceof t){if(e.closed||e._hasParent(this))return;e._addParent(this)}(this._finalizers=null!==(i=this._finalizers)&&void 0!==i?i:[]).push(e)}}},t.prototype._hasParent=function(e){var t=this._parentage;return t===e||Array.isArray(t)&&t.includes(e)},t.prototype._addParent=function(e){var t=this._parentage;this._parentage=Array.isArray(t)?(t.push(e),t):t?[t,e]:e},t.prototype._removeParent=function(e){var t=this._parentage;t===e?this._parentage=null:Array.isArray(t)&&ag(t,e)},t.prototype.remove=function(e){var i=this._finalizers;i&&ag(i,e),e instanceof t&&e._removeParent(this)},t.EMPTY=((e=new t).closed=!0,e),t}(),ay=av.EMPTY;function ab(e){return e instanceof av||e&&"closed"in e&&ap(e.remove)&&ap(e.add)&&ap(e.unsubscribe)}function ak(e){ap(e)?e():e.unsubscribe()}var aT={Promise:void 0},aS={setTimeout:function(e,t){for(var i=[],n=2;n<arguments.length;n++)i[n-2]=arguments[n];return setTimeout.apply(void 0,au([e,t],ad(i)))}};function aC(e){aS.setTimeout(function(){throw e})}function aw(){}var aE=function(e){function t(t){var i=e.call(this)||this;return i.isStopped=!1,t?(i.destination=t,ab(t)&&t.add(i)):i.destination=aR,i}return aa(t,e),t.create=function(e,t,i){return new ax(e,t,i)},t.prototype.next=function(e){this.isStopped||this._next(e)},t.prototype.error=function(e){this.isStopped||(this.isStopped=!0,this._error(e))},t.prototype.complete=function(){this.isStopped||(this.isStopped=!0,this._complete())},t.prototype.unsubscribe=function(){this.closed||(this.isStopped=!0,e.prototype.unsubscribe.call(this),this.destination=null)},t.prototype._next=function(e){this.destination.next(e)},t.prototype._error=function(e){try{this.destination.error(e)}finally{this.unsubscribe()}},t.prototype._complete=function(){try{this.destination.complete()}finally{this.unsubscribe()}},t}(av),aP=function(){function e(e){this.partialObserver=e}return e.prototype.next=function(e){var t=this.partialObserver;if(t.next)try{t.next(e)}catch(e){aC(e)}},e.prototype.error=function(e){var t=this.partialObserver;if(t.error)try{t.error(e)}catch(e){aC(e)}else aC(e)},e.prototype.complete=function(){var e=this.partialObserver;if(e.complete)try{e.complete()}catch(e){aC(e)}},e}(),ax=function(e){function t(t,i,n){var r,s=e.call(this)||this;return r=ap(t)||!t?{next:t??void 0,error:i??void 0,complete:n??void 0}:t,s.destination=new aP(r),s}return aa(t,e),t}(aE),aR={closed:!0,next:aw,error:function(e){throw e},complete:aw},aO="function"==typeof Symbol&&Symbol.observable||"@@observable";function aA(e){return e}var aI=function(){function e(e){e&&(this._subscribe=e)}return e.prototype.lift=function(t){var i=new e;return i.source=this,i.operator=t,i},e.prototype.subscribe=function(e,t,i){var n,r,s,o=(n=e)&&n instanceof aE||n&&ap(n.next)&&ap(n.error)&&ap(n.complete)&&ab(n)?e:new ax(e,t,i);return r=this.operator,s=this.source,o.add(r?r.call(o,s):s?this._subscribe(o):this._trySubscribe(o)),o},e.prototype._trySubscribe=function(e){try{return this._subscribe(e)}catch(t){e.error(t)}},e.prototype.forEach=function(e,t){var i=this;return new(t=aM(t))(function(t,n){var r=new ax({next:function(t){try{e(t)}catch(e){n(e),r.unsubscribe()}},error:n,complete:t});i.subscribe(r)})},e.prototype._subscribe=function(e){var t;return null===(t=this.source)||void 0===t?void 0:t.subscribe(e)},e.prototype[aO]=function(){return this},e.prototype.pipe=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return(0===e.length?aA:1===e.length?e[0]:function(t){return e.reduce(function(e,t){return t(e)},t)})(this)},e.prototype.toPromise=function(e){var t=this;return new(e=aM(e))(function(e,i){var n;t.subscribe(function(e){return n=e},function(e){return i(e)},function(){return e(n)})})},e.create=function(t){return new e(t)},e}();function aM(e){var t;return null!==(t=e??aT.Promise)&&void 0!==t?t:Promise}function aD(e){return function(t){if(ap(null==t?void 0:t.lift))return t.lift(function(t){try{return e(t,this)}catch(e){this.error(e)}});throw TypeError("Unable to lift unknown Observable type")}}function a_(e,t,i,n,r){return new aN(e,t,i,n,r)}var aN=function(e){function t(t,i,n,r,s,o){var a=e.call(this,t)||this;return a.onFinalize=s,a.shouldUnsubscribe=o,a._next=i?function(e){try{i(e)}catch(e){t.error(e)}}:e.prototype._next,a._error=r?function(e){try{r(e)}catch(e){t.error(e)}finally{this.unsubscribe()}}:e.prototype._error,a._complete=n?function(){try{n()}catch(e){t.error(e)}finally{this.unsubscribe()}}:e.prototype._complete,a}return aa(t,e),t.prototype.unsubscribe=function(){var t;if(!this.shouldUnsubscribe||this.shouldUnsubscribe()){var i=this.closed;e.prototype.unsubscribe.call(this),i||null===(t=this.onFinalize)||void 0===t||t.call(this)}},t}(aE),aL=am(function(e){return function(){e(this),this.name="ObjectUnsubscribedError",this.message="object unsubscribed"}}),aj=function(e){function t(){var t=e.call(this)||this;return t.closed=!1,t.currentObservers=null,t.observers=[],t.isStopped=!1,t.hasError=!1,t.thrownError=null,t}return aa(t,e),t.prototype.lift=function(e){var t=new aU(this,this);return t.operator=e,t},t.prototype._throwIfClosed=function(){if(this.closed)throw new aL},t.prototype.next=function(e){var t=this;(function(){var i,n;if(t._throwIfClosed(),!t.isStopped){t.currentObservers||(t.currentObservers=Array.from(t.observers));try{for(var r=ac(t.currentObservers),s=r.next();!s.done;s=r.next())s.value.next(e)}catch(e){i={error:e}}finally{try{s&&!s.done&&(n=r.return)&&n.call(r)}finally{if(i)throw i.error}}}})()},t.prototype.error=function(e){var t=this;(function(){if(t._throwIfClosed(),!t.isStopped){t.hasError=t.isStopped=!0,t.thrownError=e;for(var i=t.observers;i.length;)i.shift().error(e)}})()},t.prototype.complete=function(){var e=this;(function(){if(e._throwIfClosed(),!e.isStopped){e.isStopped=!0;for(var t=e.observers;t.length;)t.shift().complete()}})()},t.prototype.unsubscribe=function(){this.isStopped=this.closed=!0,this.observers=this.currentObservers=null},Object.defineProperty(t.prototype,"observed",{get:function(){var e;return(null===(e=this.observers)||void 0===e?void 0:e.length)>0},enumerable:!1,configurable:!0}),t.prototype._trySubscribe=function(t){return this._throwIfClosed(),e.prototype._trySubscribe.call(this,t)},t.prototype._subscribe=function(e){return this._throwIfClosed(),this._checkFinalizedStatuses(e),this._innerSubscribe(e)},t.prototype._innerSubscribe=function(e){var t=this,i=this.hasError,n=this.isStopped,r=this.observers;return i||n?ay:(this.currentObservers=null,r.push(e),new av(function(){t.currentObservers=null,ag(r,e)}))},t.prototype._checkFinalizedStatuses=function(e){var t=this.hasError,i=this.thrownError,n=this.isStopped;t?e.error(i):n&&e.complete()},t.prototype.asObservable=function(){var e=new aI;return e.source=this,e},t.create=function(e,t){return new aU(e,t)},t}(aI),aU=function(e){function t(t,i){var n=e.call(this)||this;return n.destination=t,n.source=i,n}return aa(t,e),t.prototype.next=function(e){var t,i;null===(i=null===(t=this.destination)||void 0===t?void 0:t.next)||void 0===i||i.call(t,e)},t.prototype.error=function(e){var t,i;null===(i=null===(t=this.destination)||void 0===t?void 0:t.error)||void 0===i||i.call(t,e)},t.prototype.complete=function(){var e,t;null===(t=null===(e=this.destination)||void 0===e?void 0:e.complete)||void 0===t||t.call(e)},t.prototype._subscribe=function(e){var t,i;return null!==(i=null===(t=this.source)||void 0===t?void 0:t.subscribe(e))&&void 0!==i?i:ay},t}(aj),aF=function(e){function t(t){var i=e.call(this)||this;return i._value=t,i}return aa(t,e),Object.defineProperty(t.prototype,"value",{get:function(){return this.getValue()},enumerable:!1,configurable:!0}),t.prototype._subscribe=function(t){var i=e.prototype._subscribe.call(this,t);return i.closed||t.next(this._value),i},t.prototype.getValue=function(){var e=this.hasError,t=this.thrownError,i=this._value;if(e)throw t;return this._throwIfClosed(),i},t.prototype.next=function(t){e.prototype.next.call(this,this._value=t)},t}(aj),aV={now:function(){return Date.now()}},aB=function(e){function t(t,i){return e.call(this)||this}return aa(t,e),t.prototype.schedule=function(e,t){return this},t}(av),aq={setInterval:function(e,t){for(var i=[],n=2;n<arguments.length;n++)i[n-2]=arguments[n];return setInterval.apply(void 0,au([e,t],ad(i)))},clearInterval:function(e){return clearInterval(e)}},az=function(e){function t(t,i){var n=e.call(this,t,i)||this;return n.scheduler=t,n.work=i,n.pending=!1,n}return aa(t,e),t.prototype.schedule=function(e,t){if(void 0===t&&(t=0),this.closed)return this;this.state=e;var i,n=this.id,r=this.scheduler;return null!=n&&(this.id=this.recycleAsyncId(r,n,t)),this.pending=!0,this.delay=t,this.id=null!==(i=this.id)&&void 0!==i?i:this.requestAsyncId(r,this.id,t),this},t.prototype.requestAsyncId=function(e,t,i){return void 0===i&&(i=0),aq.setInterval(e.flush.bind(e,this),i)},t.prototype.recycleAsyncId=function(e,t,i){if(void 0===i&&(i=0),null!=i&&this.delay===i&&!1===this.pending)return t;null!=t&&aq.clearInterval(t)},t.prototype.execute=function(e,t){if(this.closed)return Error("executing a cancelled action");this.pending=!1;var i=this._execute(e,t);if(i)return i;!1===this.pending&&null!=this.id&&(this.id=this.recycleAsyncId(this.scheduler,this.id,null))},t.prototype._execute=function(e,t){var i,n=!1;try{this.work(e)}catch(e){n=!0,i=e||Error("Scheduled action threw falsy error")}if(n)return this.unsubscribe(),i},t.prototype.unsubscribe=function(){if(!this.closed){var t=this.id,i=this.scheduler,n=i.actions;this.work=this.state=this.scheduler=null,this.pending=!1,ag(n,this),null!=t&&(this.id=this.recycleAsyncId(i,t,null)),this.delay=null,e.prototype.unsubscribe.call(this)}},t}(aB),aW=function(){function e(t,i){void 0===i&&(i=e.now),this.schedulerActionCtor=t,this.now=i}return e.prototype.schedule=function(e,t,i){return void 0===t&&(t=0),new this.schedulerActionCtor(this,e).schedule(i,t)},e.now=aV.now,e}();function aH(e){var t;return(t=e[e.length-1])&&ap(t.schedule)?e.pop():void 0}new(function(e){function t(t,i){void 0===i&&(i=aW.now);var n=e.call(this,t,i)||this;return n.actions=[],n._active=!1,n}return aa(t,e),t.prototype.flush=function(e){var t,i=this.actions;if(this._active){i.push(e);return}this._active=!0;do if(t=e.execute(e.state,e.delay))break;while(e=i.shift());if(this._active=!1,t){for(;e=i.shift();)e.unsubscribe();throw t}},t}(aW))(az);var aG=function(e){return e&&"number"==typeof e.length&&"function"!=typeof e};function a$(e){return ap(null==e?void 0:e.then)}function aK(e){return Symbol.asyncIterator&&ap(null==e?void 0:e[Symbol.asyncIterator])}function aJ(e){return TypeError("You provided "+(null!==e&&"object"==typeof e?"an invalid object":"'"+e+"'")+" where a stream was expected. You can provide an Observable, Promise, ReadableStream, Array, AsyncIterable, or Iterable.")}var aX="function"==typeof Symbol&&Symbol.iterator?Symbol.iterator:"@@iterator";function aY(e){return ap(null==e?void 0:e[aX])}function aQ(e){return function(e,t,i){if(!Symbol.asyncIterator)throw TypeError("Symbol.asyncIterator is not defined.");var n,r=i.apply(e,t||[]),s=[];return n=Object.create(("function"==typeof AsyncIterator?AsyncIterator:Object).prototype),o("next"),o("throw"),o("return",function(e){return function(t){return Promise.resolve(t).then(e,c)}}),n[Symbol.asyncIterator]=function(){return this},n;function o(e,t){r[e]&&(n[e]=function(t){return new Promise(function(i,n){s.push([e,t,i,n])>1||a(e,t)})},t&&(n[e]=t(n[e])))}function a(e,t){try{var i;(i=r[e](t)).value instanceof ah?Promise.resolve(i.value.v).then(l,c):d(s[0][2],i)}catch(e){d(s[0][3],e)}}function l(e){a("next",e)}function c(e){a("throw",e)}function d(e,t){e(t),s.shift(),s.length&&a(s[0][0],s[0][1])}}(this,arguments,function(){var t,i,n;return al(this,function(r){switch(r.label){case 0:t=e.getReader(),r.label=1;case 1:r.trys.push([1,,9,10]),r.label=2;case 2:return[4,ah(t.read())];case 3:return n=(i=r.sent()).value,i.done?[4,ah(void 0)]:[3,5];case 4:return[2,r.sent()];case 5:return[4,ah(n)];case 6:return[4,r.sent()];case 7:return r.sent(),[3,2];case 8:return[3,10];case 9:return t.releaseLock(),[7];case 10:return[2]}})})}function aZ(e){return ap(null==e?void 0:e.getReader)}function a0(e){if(e instanceof aI)return e;if(null!=e){if(ap(e[aO]))return new aI(function(t){var i=e[aO]();if(ap(i.subscribe))return i.subscribe(t);throw TypeError("Provided object does not correctly implement Symbol.observable")});if(aG(e))return new aI(function(t){for(var i=0;i<e.length&&!t.closed;i++)t.next(e[i]);t.complete()});if(a$(e))return new aI(function(t){e.then(function(e){t.closed||(t.next(e),t.complete())},function(e){return t.error(e)}).then(null,aC)});if(aK(e))return a1(e);if(aY(e))return new aI(function(t){var i,n;try{for(var r=ac(e),s=r.next();!s.done;s=r.next()){var o=s.value;if(t.next(o),t.closed)return}}catch(e){i={error:e}}finally{try{s&&!s.done&&(n=r.return)&&n.call(r)}finally{if(i)throw i.error}}t.complete()});if(aZ(e))return a1(aQ(e))}throw aJ(e)}function a1(e){return new aI(function(t){(function(e,t){var i,n,r,s,o,a,l,c;return o=this,a=void 0,l=void 0,c=function(){var o;return al(this,function(a){switch(a.label){case 0:a.trys.push([0,5,6,11]),i=function(e){if(!Symbol.asyncIterator)throw TypeError("Symbol.asyncIterator is not defined.");var t,i=e[Symbol.asyncIterator];return i?i.call(e):(e=ac(e),t={},n("next"),n("throw"),n("return"),t[Symbol.asyncIterator]=function(){return this},t);function n(i){t[i]=e[i]&&function(t){return new Promise(function(n,r){(function(e,t,i,n){Promise.resolve(n).then(function(t){e({value:t,done:i})},t)})(n,r,(t=e[i](t)).done,t.value)})}}}(e),a.label=1;case 1:return[4,i.next()];case 2:if((n=a.sent()).done)return[3,4];if(o=n.value,t.next(o),t.closed)return[2];a.label=3;case 3:return[3,1];case 4:return[3,11];case 5:return r={error:a.sent()},[3,11];case 6:return a.trys.push([6,,9,10]),n&&!n.done&&(s=i.return)?[4,s.call(i)]:[3,8];case 7:a.sent(),a.label=8;case 8:return[3,10];case 9:if(r)throw r.error;return[7];case 10:return[7];case 11:return t.complete(),[2]}})},new(l||(l=Promise))(function(e,t){function i(e){try{r(c.next(e))}catch(e){t(e)}}function n(e){try{r(c.throw(e))}catch(e){t(e)}}function r(t){var r;t.done?e(t.value):((r=t.value)instanceof l?r:new l(function(e){e(r)})).then(i,n)}r((c=c.apply(o,a||[])).next())})})(e,t).catch(function(e){return t.error(e)})})}function a2(e,t,i,n,r){void 0===n&&(n=0),void 0===r&&(r=!1);var s=t.schedule(function(){i(),r?e.add(this.schedule(null,n)):this.unsubscribe()},n);if(e.add(s),!r)return s}function a3(e,t){return void 0===t&&(t=0),aD(function(i,n){i.subscribe(a_(n,function(i){return a2(n,e,function(){return n.next(i)},t)},function(){return a2(n,e,function(){return n.complete()},t)},function(i){return a2(n,e,function(){return n.error(i)},t)}))})}function a5(e,t){return void 0===t&&(t=0),aD(function(i,n){n.add(e.schedule(function(){return i.subscribe(n)},t))})}function a4(e,t){if(!e)throw Error("Iterable cannot be null");return new aI(function(i){a2(i,t,function(){var n=e[Symbol.asyncIterator]();a2(i,t,function(){n.next().then(function(e){e.done?i.complete():i.next(e.value)})},0,!0)})})}function a6(e,t){return aD(function(i,n){var r=0;i.subscribe(a_(n,function(i){n.next(e.call(t,i,r++))}))})}function a9(){for(var e,t,i=[],n=0;n<arguments.length;n++)i[n]=arguments[n];return(function e(t,i,n){return void 0===n&&(n=1/0),ap(i)?e(function(e,n){return a6(function(t,r){return i(e,t,n,r)})(a0(t(e,n)))},n):("number"==typeof i&&(n=i),aD(function(e,i){var r,s,o,a,l,c,d;return r=n,s=[],o=0,a=0,l=!1,c=function(){!l||s.length||o||i.complete()},d=function(e){o++;var n=!1;a0(t(e,a++)).subscribe(a_(i,function(e){i.next(e)},function(){n=!0},void 0,function(){if(n)try{for(o--;s.length&&o<r;)!function(){var e=s.shift();d(e)}();c()}catch(e){i.error(e)}}))},e.subscribe(a_(i,function(e){return o<r?d(e):s.push(e)},function(){l=!0,c()})),function(){}}))})(aA,1)((e=i,(t=aH(i))?function(e,t){if(null!=e){if(ap(e[aO]))return a0(e).pipe(a5(t),a3(t));if(aG(e))return new aI(function(i){var n=0;return t.schedule(function(){n===e.length?i.complete():(i.next(e[n++]),i.closed||this.schedule())})});if(a$(e))return a0(e).pipe(a5(t),a3(t));if(aK(e))return a4(e,t);if(aY(e))return new aI(function(i){var n;return a2(i,t,function(){n=e[aX](),a2(i,t,function(){var e,t,r;try{t=(e=n.next()).value,r=e.done}catch(e){i.error(e);return}r?i.complete():i.next(t)},0,!0)}),function(){return ap(null==n?void 0:n.return)&&n.return()}});if(aZ(e))return a4(aQ(e),t)}throw aJ(e)}(e,t):a0(e)))}function a8(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var i=aH(e);return aD(function(t,n){(i?a9(e,t,i):a9(e,t)).subscribe(n)})}am(function(e){return function(t){void 0===t&&(t=null),e(this),this.message="Timeout has occurred",this.name="TimeoutError",this.info=t}});var a7=Object.defineProperty,le=Object.defineProperties,lt=Object.getOwnPropertyDescriptors,li=Object.getOwnPropertySymbols,ln=Object.prototype.hasOwnProperty,lr=Object.prototype.propertyIsEnumerable,ls=(e,t,i)=>t in e?a7(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i,lo=(e,t)=>{for(var i in t||(t={}))ln.call(t,i)&&ls(e,i,t[i]);if(li)for(var i of li(t))lr.call(t,i)&&ls(e,i,t[i]);return e},la=(e,t)=>le(e,lt(t)),ll=(e,t,i)=>new Promise((n,r)=>{var s=e=>{try{a(i.next(e))}catch(e){r(e)}},o=e=>{try{a(i.throw(e))}catch(e){r(e)}},a=e=>e.done?n(e.value):Promise.resolve(e.value).then(s,o);a((i=i.apply(e,t)).next())});function lc(e){var t;return!(typeof e>"u")&&(!!e&&e.hasOwnProperty("participant")&&e.hasOwnProperty("source")&&e.hasOwnProperty("track")&&"u">typeof(null==(t=e.publication)?void 0:t.track)||!!e&&e.hasOwnProperty("participant")&&e.hasOwnProperty("source")&&e.hasOwnProperty("publication")&&"u">typeof e.publication)}function ld(e){if("string"==typeof e||"number"==typeof e)return`${e}`;if(e&&e.hasOwnProperty("participant")&&e.hasOwnProperty("source")&&typeof e.publication>"u")return`${e.participant.identity}_${e.source}_placeholder`;if(lc(e))return`${e.participant.identity}_${e.publication.source}_${e.publication.trackSid}`;throw Error(`Can't generate a id for the given track reference: ${e}`)}var lu=[o$.ConnectionStateChanged,o$.RoomMetadataChanged,o$.ActiveSpeakersChanged,o$.ConnectionQualityChanged,o$.ParticipantConnected,o$.ParticipantDisconnected,o$.ParticipantPermissionsChanged,o$.ParticipantMetadataChanged,o$.ParticipantNameChanged,o$.ParticipantAttributesChanged,o$.TrackMuted,o$.TrackUnmuted,o$.TrackPublished,o$.TrackUnpublished,o$.TrackStreamStateChanged,o$.TrackSubscriptionFailed,o$.TrackSubscriptionPermissionChanged,o$.TrackSubscriptionStatusChanged,o$.LocalTrackPublished,o$.LocalTrackUnpublished],lh=[oK.TrackPublished,oK.TrackUnpublished,oK.TrackMuted,oK.TrackUnmuted,oK.TrackStreamStateChanged,oK.TrackSubscribed,oK.TrackUnsubscribed,oK.TrackSubscriptionPermissionChanged,oK.TrackSubscriptionFailed,oK.LocalTrackPublished,oK.LocalTrackUnpublished],lp=(oK.ConnectionQualityChanged,oK.IsSpeakingChanged,oK.ParticipantMetadataChanged,oK.ParticipantPermissionsChanged,oK.TrackMuted,oK.TrackUnmuted,oK.TrackPublished,oK.TrackUnpublished,oK.TrackStreamStateChanged,oK.TrackSubscriptionFailed,oK.TrackSubscriptionPermissionChanged,oK.TrackSubscriptionStatusChanged,oK.LocalTrackPublished,oK.LocalTrackUnpublished,as.getLogger("lk-components-js"));function lm(e){return"object"==typeof e}function lf(e){return Array.isArray(e)&&e.filter(lm).length>0}function lg(e){return`lk-${e}`}function lv(e){if(lc(e))return e.publication;{let{source:t,name:i,participant:n}=e;if(t&&i)return n.getTrackPublications().find(e=>e.source===t&&e.trackName===i);if(i)return n.getTrackPublicationByName(i);if(t)return n.getTrackPublication(t);throw Error("At least one of source and name needs to be defined")}}function ly(e,...t){return new aI(i=>{let n=()=>{i.next(e)};return t.forEach(t=>{e.on(t,n)}),()=>{t.forEach(t=>{e.off(t,n)})}}).pipe(a8(e))}function lb(e,t){return new aI(i=>{let n=(...e)=>{i.next(e)};return e.on(t,n),()=>{e.off(t,n)}})}function lk(e){return ly(e,o$.AudioPlaybackStatusChanged).pipe(a6(e=>({canPlayAudio:e.canPlaybackAudio})))}function lT(e){return ly(e,o$.VideoPlaybackStatusChanged).pipe(a6(e=>({canPlayVideo:e.canPlaybackVideo})))}function lS(e,...t){return new aI(i=>{let n=()=>{i.next(e)};return t.forEach(t=>{e.on(t,n)}),()=>{t.forEach(t=>{e.off(t,n)})}}).pipe(a8(e))}function lC(e){return lS(e,oK.TrackMuted,oK.TrackUnmuted,oK.ParticipantPermissionsChanged,oK.TrackPublished,oK.TrackUnpublished,oK.LocalTrackPublished,oK.LocalTrackUnpublished,oK.MediaDevicesError,oK.TrackSubscriptionStatusChanged).pipe(a6(e=>{let{isMicrophoneEnabled:t,isCameraEnabled:i,isScreenShareEnabled:n}=e,r=e.getTrackPublication(nM.Source.Microphone);return{isCameraEnabled:i,isMicrophoneEnabled:t,isScreenShareEnabled:n,cameraTrack:e.getTrackPublication(nM.Source.Camera),microphoneTrack:r,participant:e}}))}function lw(e,t){return new aI(i=>{let n=(...e)=>{i.next(e)};return e.on(t,n),()=>{e.off(t,n)}})}function lE(e,t,i=!0){let n=[e.localParticipant,...Array.from(e.remoteParticipants.values())],r=[];return n.forEach(e=>{t.forEach(t=>{let n=Array.from(e.trackPublications.values()).filter(e=>e.source===t&&(!i||e.track)).map(t=>({participant:e,publication:t,source:t.source}));r.push(...n)})}),{trackReferences:r,participants:n}}function lP(e,t,i=!1){let{sources:n,kind:r,name:s}=t;return Array.from(e.trackPublications.values()).filter(e=>(!n||n.includes(e.source))&&(!r||e.kind===r)&&(!s||e.trackName===s)&&(!i||e.track)).map(t=>({participant:e,publication:t,source:t.source}))}function lx(e,t){return new aI(i=>{let n=(...e)=>{i.next(e)};return e.on(t,n),()=>{e.off(t,n)}})}lp.setDefaultLevel("WARN");var lR={videoEnabled:!0,audioEnabled:!0,videoDeviceId:"default",audioDeviceId:"default",username:""},{load:lO,save:lA}=function(e){return{load:()=>(function(e){if(typeof localStorage>"u"){lp.error("Local storage is not available.");return}try{let t=localStorage.getItem(e);if(!t){lp.warn(`Item with key ${e} does not exist in local storage.`);return}return JSON.parse(t)}catch(e){lp.error(`Error getting item from local storage: ${e}`);return}})(e),save:t=>(function(e,t){if(typeof localStorage>"u"){lp.error("Local storage is not available.");return}try{if(t){let i=Object.fromEntries(Object.entries(t).filter(([,e])=>""!==e));localStorage.setItem(e,JSON.stringify(i))}}catch(e){lp.error(`Error setting item to local storage: ${e}`)}})(e,t)}}("lk-user-choices");p.createContext(void 0);let lI=p.createContext(void 0);function lM(){return p.useContext(lI)}function lD(e){let t=lM(),i=e??t;if(!i)throw Error("No TrackRef, make sure you are inside a TrackRefContext or pass the TrackRef explicitly");return i}let l_=p.createContext(void 0);function lN(){return p.useContext(l_)}let lL=p.createContext(void 0);function lj(){let e=p.useContext(lL);if(!e)throw Error("tried to access room context outside of livekit room component");return e}function lU(){return p.useContext(lL)}function lF(e){let t=lU(),i=e??t;if(!i)throw Error("No room provided, make sure you are inside a Room context or pass the room explicitly");return i}function lV(){for(var e,t,i=0,n="",r=arguments.length;i<r;i++)(e=arguments[i])&&(t=function e(t){var i,n,r="";if("string"==typeof t||"number"==typeof t)r+=t;else if("object"==typeof t){if(Array.isArray(t)){var s=t.length;for(i=0;i<s;i++)t[i]&&(n=e(t[i]))&&(r&&(r+=" "),r+=n)}else for(n in t)t[n]&&(r&&(r+=" "),r+=n)}return r}(e))&&(n&&(n+=" "),n+=t);return n}function lB(...e){let t={...e[0]};for(let i=1;i<e.length;i++){let n=e[i];for(let e in n){let i=t[e],r=n[e];"function"==typeof i&&"function"==typeof r&&"o"===e[0]&&"n"===e[1]&&e.charCodeAt(2)>=65&&90>=e.charCodeAt(2)?t[e]=function(...e){return(...t)=>{for(let i of e)if("function"==typeof i)try{i(...t)}catch(e){console.error(e)}}}(i,r):("className"===e||"UNSAFE_className"===e)&&"string"==typeof i&&"string"==typeof r?t[e]=lV(i,r):t[e]=void 0!==r?r:i}}return t}function lq(e){return void 0!==e}function lz(...e){return lB(...e.filter(lq))}p.createContext(void 0);function lW(e,t,i=!0){let[n,r]=p.useState(t);return p.useEffect(()=>{if(i&&r(t),typeof window>"u"||!e)return;let n=e.subscribe(r);return()=>n.unsubscribe()},[e,i]),n}function lH(e){let t=lF(e);return lW(p.useMemo(()=>lb(t,o$.ConnectionStateChanged).pipe(a6(([e])=>e),a8(t.state)),[t]),t.state)}function lG(e={}){let t=lF(e.room),[i,n]=p.useState(t.localParticipant),[r,s]=p.useState(i.isMicrophoneEnabled),[o,a]=p.useState(i.isCameraEnabled),[l,c]=p.useState(i.isScreenShareEnabled),[d,u]=p.useState(i.lastMicrophoneError),[h,m]=p.useState(i.lastCameraError),[f,g]=p.useState(void 0),[v,y]=p.useState(void 0),b=e=>{a(e.isCameraEnabled),s(e.isMicrophoneEnabled),c(e.isScreenShareEnabled),y(e.cameraTrack),g(e.microphoneTrack),u(e.participant.lastMicrophoneError),m(e.participant.lastCameraError),n(e.participant)};return p.useEffect(()=>{let e=lC(t.localParticipant).subscribe(b);return()=>e.unsubscribe()},[t]),{isMicrophoneEnabled:r,isScreenShareEnabled:l,isCameraEnabled:o,microphoneTrack:f,cameraTrack:v,lastMicrophoneError:d,lastCameraError:h,localParticipant:i}}function l$(e={}){let t=lF(e.room),[i,n]=p.useState([]);return p.useEffect(()=>{let i=(function(e,t={}){var i;let n;let r=new aI(e=>(n=e,()=>o.unsubscribe())).pipe(a8(Array.from(e.remoteParticipants.values()))),s=null!=(i=t.additionalRoomEvents)?i:lu,o=ly(e,...Array.from(new Set([o$.ParticipantConnected,o$.ParticipantDisconnected,o$.ConnectionStateChanged,...s]))).subscribe(e=>null==n?void 0:n.next(Array.from(e.remoteParticipants.values())));return e.remoteParticipants.size>0&&(null==n||n.next(Array.from(e.remoteParticipants.values()))),r})(t,{additionalRoomEvents:e.updateOnlyOn}).subscribe(n);return()=>i.unsubscribe()},[t,JSON.stringify(e.updateOnlyOn)]),i}let lK=e=>{let t=e=>Math.sqrt(1- -1*Math.max(-100,Math.min(-10,e))/100);return e.map(e=>e===-1/0?0:t(e))},lJ={bands:5,loPass:100,hiPass:600,updateInterval:32,analyserOptions:{fftSize:2048}};function lX(e,t){let i=lN(),n=l$({updateOnlyOn:[]}),r=p.useMemo(()=>t?n.find(e=>e.identity===t):i,[t,n,i]);return lW(p.useMemo(()=>{if(r){var t;return t={sources:e},lS(r,...lh).pipe(a6(e=>{let i=lP(e,t);return lp.debug(`TrackReference[] was updated. (length ${i.length})`,i),i}),a8(lP(r,t)))}},[r,JSON.stringify(e)]),[])}let lY={bufferSize:100};function lQ(e,t){var i,n,r;let s={...lY,...t},[o,a]=p.useState([]),l=lW(p.useMemo(()=>{var t;return null!=(t=null==e?void 0:e.publication)&&t.track?lx(null==e?void 0:e.publication.track,oX.TimeSyncUpdate).pipe(a6(([e])=>e)):void 0},[null==(i=null==e?void 0:e.publication)?void 0:i.track]),{timestamp:Date.now(),rtpTimestamp:null==(r=null==(n=null==e?void 0:e.publication)?void 0:n.track)?void 0:r.rtpTimestamp}),c=e=>{var t;null==(t=s.onTranscription)||t.call(s,e),a(t=>{var i,n;return i=e.map(e=>{var t;return la(lo({},e),{receivedAtMediaTimestamp:null!=(t=l.rtpTimestamp)?t:0,receivedAt:l.timestamp})}),n=s.bufferSize,[...t,...i].reduceRight((e,t)=>(e.find(e=>e.id===t.id)||e.unshift(t),e),[]).slice(0-n)})};return p.useEffect(()=>{if(!(null!=e&&e.publication))return;let t=lx(e.publication,oX.TranscriptionReceived).subscribe(e=>{c(...e)});return()=>{t.unsubscribe()}},[e&&ld(e),c]),{segments:o}}let lZ="lk.agent.state";function l0(){let e=l$(),t=e.find(e=>e.kind===e0.AGENT&&!("lk.publish_on_behalf"in e.attributes)),i=e.find(e=>e.kind===e0.AGENT&&e.attributes["lk.publish_on_behalf"]===(null==t?void 0:t.identity)),n=lX([nM.Source.Microphone,nM.Source.Camera],null==t?void 0:t.identity),r=lX([nM.Source.Microphone,nM.Source.Camera],null==i?void 0:i.identity),s=n.find(e=>e.source===nM.Source.Microphone)??r.find(e=>e.source===nM.Source.Microphone),o=n.find(e=>e.source===nM.Source.Camera)??r.find(e=>e.source===nM.Source.Camera),{segments:a}=lQ(s),l=lH(),{attributes:c}=function(e={}){let t=lN(),i=e.participant??t;return lW(p.useMemo(()=>typeof i>"u"?new aI:lw(i,oK.AttributesChanged).pipe(a6(([e])=>({changed:e,attributes:i.attributes})),a8({changed:i.attributes,attributes:i.attributes})),[i]),{attributes:null==i?void 0:i.attributes})}({participant:t}),d=p.useMemo(()=>l===ae.Disconnected?"disconnected":l!==ae.Connecting&&t&&null!=c&&c[lZ]?c[lZ]:"connecting",[c,t,l]);return{agent:t,state:d,audioTrack:s,videoTrack:o,agentTranscriptions:a,agentAttributes:c}}function l1(){let e=function(){let{agentTranscriptions:e}=l0(),{segments:t}=lQ(function(){let{microphoneTrack:e,localParticipant:t}=lG();return(0,p.useMemo)(()=>({participant:t,source:nM.Source.Microphone,publication:e}),[t,e])}());return(0,p.useMemo)(()=>[...e.map(e=>({...e,role:"assistant"})),...t.map(e=>({...e,role:"user"}))].sort((e,t)=>e.firstReceivedTime-t.firstReceivedTime),[e,t])}(),t=p.useRef(null);return p.useEffect(()=>{t.current&&(t.current.scrollTop=t.current.scrollHeight)},[e]),(0,u.jsxs)("div",{className:"relative h-[200px] w-[512px] max-w-[90vw] mx-auto",children:[u.jsx("div",{className:"absolute top-0 left-0 right-0 h-8 bg-gradient-to-b from-[var(--lk-bg)] to-transparent z-10 pointer-events-none"}),u.jsx("div",{className:"absolute bottom-0 left-0 right-0 h-8 bg-gradient-to-t from-[var(--lk-bg)] to-transparent z-10 pointer-events-none"}),u.jsx("div",{ref:t,className:"h-full flex flex-col gap-2 overflow-y-auto px-4 py-8",children:e.map(e=>u.jsx("div",{id:e.id,className:"assistant"===e.role?"p-2 self-start fit-content":"bg-gray-800 rounded-md p-2 self-end fit-content",children:e.text},e.id))})]})}let l2=p.forwardRef(function(e,t){let{buttonProps:i}=function(e){let t=lj(),i=lH(t);return{buttonProps:p.useMemo(()=>{let{className:n,disconnect:r}={className:lg("disconnect-button"),disconnect:e=>{t.disconnect(e)}};return lB(e,{className:n,onClick:()=>r(e.stopTracks??!0),disabled:i===ae.Disconnected})},[t,e,i])}}(e);return p.createElement("button",{ref:t,...i},e.children)}),l3=e=>p.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:16,height:16,fill:"currentColor",...e},p.createElement("path",{d:"M1.354.646a.5.5 0 1 0-.708.708l14 14a.5.5 0 0 0 .708-.708L11 10.293V4.5A1.5 1.5 0 0 0 9.5 3H3.707zM0 4.5a1.5 1.5 0 0 1 .943-1.393l9.532 9.533c-.262.224-.603.36-.975.36h-8A1.5 1.5 0 0 1 0 11.5z"}),p.createElement("path",{d:"m15.2 3.6-2.8 2.1a1 1 0 0 0-.4.8v3a1 1 0 0 0 .4.8l2.8 2.1a.5.5 0 0 0 .8-.4V4a.5.5 0 0 0-.8-.4z"})),l5=e=>p.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:16,height:16,fill:"currentColor",...e},p.createElement("path",{d:"M0 4.5A1.5 1.5 0 0 1 1.5 3h8A1.5 1.5 0 0 1 11 4.5v7A1.5 1.5 0 0 1 9.5 13h-8A1.5 1.5 0 0 1 0 11.5zM15.2 3.6l-2.8 2.1a1 1 0 0 0-.4.8v3a1 1 0 0 0 .4.8l2.8 2.1a.5.5 0 0 0 .8-.4V4a.5.5 0 0 0-.8-.4z"})),l4=e=>p.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:16,height:16,fill:"currentColor",...e},p.createElement("path",{d:"M12.227 11.52a5.477 5.477 0 0 0 1.246-2.97.5.5 0 0 0-.995-.1 4.478 4.478 0 0 1-.962 2.359l-1.07-1.07C10.794 9.247 11 8.647 11 8V3a3 3 0 0 0-6 0v1.293L1.354.646a.5.5 0 1 0-.708.708l14 14a.5.5 0 0 0 .708-.708zM8 12.5c.683 0 1.33-.152 1.911-.425l.743.743c-.649.359-1.378.59-2.154.66V15h2a.5.5 0 0 1 0 1h-5a.5.5 0 0 1 0-1h2v-1.522a5.502 5.502 0 0 1-4.973-4.929.5.5 0 0 1 .995-.098A4.5 4.5 0 0 0 8 12.5z"}),p.createElement("path",{d:"M8.743 10.907 5 7.164V8a3 3 0 0 0 3.743 2.907z"})),l6=e=>p.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:16,height:16,fill:"currentColor",...e},p.createElement("path",{fillRule:"evenodd",d:"M2.975 8.002a.5.5 0 0 1 .547.449 4.5 4.5 0 0 0 8.956 0 .5.5 0 1 1 .995.098A5.502 5.502 0 0 1 8.5 13.478V15h2a.5.5 0 0 1 0 1h-5a.5.5 0 0 1 0-1h2v-1.522a5.502 5.502 0 0 1-4.973-4.929.5.5 0 0 1 .448-.547z",clipRule:"evenodd"}),p.createElement("path",{d:"M5 3a3 3 0 1 1 6 0v5a3 3 0 0 1-6 0z"})),l9=e=>p.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:20,height:16,fill:"none",...e},p.createElement("path",{fill:"currentColor",fillRule:"evenodd",d:"M0 2.75A2.75 2.75 0 0 1 2.75 0h14.5A2.75 2.75 0 0 1 20 2.75v10.5A2.75 2.75 0 0 1 17.25 16H2.75A2.75 2.75 0 0 1 0 13.25V2.75ZM2.75 1.5c-.69 0-1.25.56-1.25 1.25v10.5c0 .69.56 1.25 1.25 1.25h14.5c.69 0 1.25-.56 1.25-1.25V2.75c0-.69-.56-1.25-1.25-1.25H2.75Z",clipRule:"evenodd"}),p.createElement("path",{fill:"currentColor",fillRule:"evenodd",d:"M9.47 4.22a.75.75 0 0 1 1.06 0l2.25 2.25a.75.75 0 0 1-1.06 1.06l-.97-.97v4.69a.75.75 0 0 1-1.5 0V6.56l-.97.97a.75.75 0 0 1-1.06-1.06l2.25-2.25Z",clipRule:"evenodd"})),l8=e=>p.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:20,height:16,fill:"none",...e},p.createElement("g",{fill:"currentColor"},p.createElement("path",{d:"M7.28 4.22a.75.75 0 0 0-1.06 1.06L8.94 8l-2.72 2.72a.75.75 0 1 0 1.06 1.06L10 9.06l2.72 2.72a.75.75 0 1 0 1.06-1.06L11.06 8l2.72-2.72a.75.75 0 0 0-1.06-1.06L10 6.94z"}),p.createElement("path",{fillRule:"evenodd",d:"M2.75 0A2.75 2.75 0 0 0 0 2.75v10.5A2.75 2.75 0 0 0 2.75 16h14.5A2.75 2.75 0 0 0 20 13.25V2.75A2.75 2.75 0 0 0 17.25 0zM1.5 2.75c0-.69.56-1.25 1.25-1.25h14.5c.69 0 1.25.56 1.25 1.25v10.5c0 .69-.56 1.25-1.25 1.25H2.75c-.69 0-1.25-.56-1.25-1.25z",clipRule:"evenodd"}))),l7=p.forwardRef(function({kind:e,initialSelection:t,onActiveDeviceChange:i,onDeviceListChange:n,onDeviceSelectError:r,exactMatch:s,track:o,requestPermissions:a,onError:l,...c},d){let u=lU(),h=p.useRef("default"),m=p.useCallback(e=>{u&&u.emit(o$.MediaDevicesError,e),null==l||l(e)},[u,l]),{devices:f,activeDeviceId:g,setActiveMediaDevice:v,className:y}=function({kind:e,room:t,track:i,requestPermissions:n,onError:r}){let s=lU(),o=p.useMemo(()=>t??s??new sj,[t,s]),a=lW(p.useMemo(()=>(function(e,t,i=!0){return a9(new aI(n=>{sj.getLocalDevices(e,i).then(e=>{n.next(e),n.complete()}).catch(e=>{null==t||t(e),n.next([]),n.complete()})}),new aI(n=>{var r;let s=()=>ll(this,null,function*(){try{let t=yield sj.getLocalDevices(e,i);n.next(t)}catch(e){null==t||t(e)}});if("u">typeof window){if(!window.isSecureContext)throw Error("Accessing media devices is available only in secure contexts (HTTPS and localhost), in some or all supporting browsers. See: https://developer.mozilla.org/en-US/docs/Web/API/Navigator/mediaDevices");null==(r=null==navigator?void 0:navigator.mediaDevices)||r.addEventListener("devicechange",s)}return()=>{var e;null==(e=null==navigator?void 0:navigator.mediaDevices)||e.removeEventListener("devicechange",s)}}))})(e,r,n),[e,n,r]),[]),[l,c]=p.useState((null==o?void 0:o.getActiveDevice(e))??"default"),{className:d,activeDeviceObservable:u,setActiveMediaDevice:h}=p.useMemo(()=>(function(e,t,i){var n;let r=new aF(void 0),s=lb(t,o$.ActiveDeviceChanged).pipe((n=([t])=>t===e,aD(function(e,t){var i=0;e.subscribe(a_(t,function(e){return n.call(void 0,e,i++)&&t.next(e)}))})),a6(([e,t])=>(lp.debug("activeDeviceObservable | RoomEvent.ActiveDeviceChanged",{kind:e,deviceId:t}),t)));return{className:lg("media-device-select"),activeDeviceObservable:s,setActiveMediaDevice:(i,...n)=>ll(this,[i,...n],function*(i,n={}){var s,o,a;if(t){let l;lp.debug(`Switching active device of kind "${e}" with id ${i}.`),yield t.switchActiveDevice(e,i,n.exact);let c=null!=(s=t.getActiveDevice(e))?s:i;c!==i&&"default"!==i&&lp.info(`We tried to select the device with id (${i}), but the browser decided to select the device with id (${c}) instead.`),"audioinput"===e?l=null==(o=t.localParticipant.getTrackPublication(nM.Source.Microphone))?void 0:o.track:"videoinput"===e&&(l=null==(a=t.localParticipant.getTrackPublication(nM.Source.Camera))?void 0:a.track);let d="default"===i&&!l||"default"===i&&(null==l?void 0:l.mediaStreamTrack.label.startsWith("Default"));r.next(d?i:c)}})}})(e,o),[e,o,i]);return p.useEffect(()=>{let e=u.subscribe(e=>{e&&(lp.info("setCurrentDeviceId",e),c(e))});return()=>{null==e||e.unsubscribe()}},[u]),{devices:a,className:d,activeDeviceId:l,setActiveMediaDevice:h}}({kind:e,room:u,track:o,requestPermissions:a,onError:m});p.useEffect(()=>{void 0!==t&&v(t)},[v]),p.useEffect(()=>{"function"==typeof n&&n(f)},[n,f]),p.useEffect(()=>{g!==h.current&&(null==i||i(g)),h.current=g},[g]);let b=async e=>{try{await v(e,{exact:s??!0})}catch(e){if(e instanceof Error)null==r||r(e);else throw e}},k=p.useMemo(()=>lz(c,{className:y},{className:"lk-list"}),[y,c]),T=!!f.find(e=>e.label.toLowerCase().startsWith("default"));function S(e,t,i){return e===t||!T&&0===i&&"default"===t}return p.createElement("ul",{ref:d,...k},f.map((e,t)=>p.createElement("li",{key:e.deviceId,id:e.deviceId,"data-lk-active":S(e.deviceId,g,t),"aria-selected":S(e.deviceId,g,t),role:"option"},p.createElement("button",{className:"lk-button",onClick:()=>b(e.deviceId)},e.label))))}),ce=p.forwardRef(function({label:e,...t},i){let n=lj(),{mergedProps:r,canPlayAudio:s}=function({room:e,props:t}){let i=lF(e),{className:n,roomAudioPlaybackAllowedObservable:r,handleStartAudioPlayback:s}=p.useMemo(()=>(function(){return{className:lg("start-audio-button"),roomAudioPlaybackAllowedObservable:lk,handleStartAudioPlayback:e=>ll(this,null,function*(){lp.info("Start Audio for room: ",e),yield e.startAudio()})}})(),[]),{canPlayAudio:o}=lW(p.useMemo(()=>r(i),[i,r]),{canPlayAudio:i.canPlaybackAudio});return{mergedProps:p.useMemo(()=>lB(t,{className:n,onClick:()=>{s(i)},style:{display:o?"none":"block"}}),[t,n,o,s,i]),canPlayAudio:o}}({room:n,props:t}),{mergedProps:o,canPlayVideo:a}=function({room:e,props:t}){let i=lF(e),{className:n,roomVideoPlaybackAllowedObservable:r,handleStartVideoPlayback:s}=p.useMemo(()=>(function(){return{className:lg("start-audio-button"),roomVideoPlaybackAllowedObservable:lT,handleStartVideoPlayback:e=>ll(this,null,function*(){lp.info("Start Video for room: ",e),yield e.startVideo()})}})(),[]),{canPlayVideo:o}=lW(p.useMemo(()=>r(i),[i,r]),{canPlayVideo:i.canPlaybackVideo});return{mergedProps:p.useMemo(()=>lB(t,{className:n,onClick:()=>{s(i)},style:{display:o?"none":"block"}}),[t,n,o,s,i]),canPlayVideo:o}}({room:n,props:r}),{style:l,...c}=o;return l.display=s&&a?"none":"block",p.createElement("button",{ref:i,style:l,...c},e??`Start ${s?"Video":"Audio"}`)}),ct=p.forwardRef(function({showIcon:e,...t},i){let{buttonProps:n,enabled:r}=function({source:e,onChange:t,initialState:i,captureOptions:n,publishOptions:r,onDeviceError:s,...o}){var a;let l=lU(),c=null==(a=null==l?void 0:l.localParticipant)?void 0:a.getTrackPublication(e),d=p.useRef(!1),{toggle:u,className:h,pendingObserver:m,enabledObserver:f}=p.useMemo(()=>l?function(e,t,i,n,r){let{localParticipant:s}=t,o=(e,t)=>{let i=!1;switch(e){case nM.Source.Camera:i=t.isCameraEnabled;break;case nM.Source.Microphone:i=t.isMicrophoneEnabled;break;case nM.Source.ScreenShare:i=t.isScreenShareEnabled}return i},a=lC(s).pipe(a6(t=>o(e,t.participant)),a8(o(e,s))),l=new aj;return{className:lg("button"),toggle:(t,o)=>ll(this,null,function*(){try{switch(o??(o=i),l.next(!0),e){case nM.Source.Camera:return yield s.setCameraEnabled(t??!s.isCameraEnabled,o,n),s.isCameraEnabled;case nM.Source.Microphone:return yield s.setMicrophoneEnabled(t??!s.isMicrophoneEnabled,o,n),s.isMicrophoneEnabled;case nM.Source.ScreenShare:return yield s.setScreenShareEnabled(t??!s.isScreenShareEnabled,o,n),s.isScreenShareEnabled;default:throw TypeError("Tried to toggle unsupported source")}}catch(e){if(r&&e instanceof Error){null==r||r(e);return}throw e}finally{l.next(!1)}}),enabledObserver:a,pendingObserver:l.asObservable()}}(e,l,n,r,s):function(){let e=!1,t=new aj,i=new aj;return{className:lg("button"),toggle:n=>ll(this,null,function*(){i.next(!0),e=n??!e,t.next(e),i.next(!1)}),enabledObserver:t.asObservable(),pendingObserver:i.asObservable()}}(),[l,e,JSON.stringify(n),r]),g=lW(m,!1),v=lW(f,i??!!(null!=c&&c.isEnabled));p.useEffect(()=>{null==t||t(v,d.current),d.current=!1},[v,t]),p.useEffect(()=>{void 0!==i&&(lp.debug("forcing initial toggle state",e,i),u(i))},[]);let y=p.useMemo(()=>lB(o,{className:h}),[o,h]),b=p.useCallback(e=>{var t;d.current=!0,u().catch(()=>d.current=!1),null==(t=o.onClick)||t.call(o,e)},[o,u]);return{toggle:u,enabled:v,pending:g,track:c,buttonProps:{...y,"aria-pressed":v,"data-lk-source":e,"data-lk-enabled":v,disabled:g,onClick:b}}}(t),[s,o]=p.useState(!1);return p.useEffect(()=>{o(!0)},[]),s&&p.createElement("button",{ref:i,...n},(e??!0)&&function(e,t){switch(e){case nM.Source.Microphone:return t?p.createElement(l6,null):p.createElement(l4,null);case nM.Source.Camera:return t?p.createElement(l5,null):p.createElement(l3,null);case nM.Source.ScreenShare:return t?p.createElement(l8,null):p.createElement(l9,null);default:return}}(t.source,r),t.children)});function ci(e,t={}){let[i,n]=p.useState(lv(e)),[r,s]=p.useState(null==i?void 0:i.isMuted),[o,a]=p.useState(null==i?void 0:i.isSubscribed),[l,c]=p.useState(null==i?void 0:i.track),[d,u]=p.useState("landscape"),h=p.useRef(),{className:m,trackObserver:f}=p.useMemo(()=>(function(e){let t=lv(e),i=lC(e.participant).pipe(a6(()=>lv(e)),a8(t));return{className:lg(e.source===nM.Source.Camera||e.source===nM.Source.ScreenShare?"participant-media-video":"participant-media-audio"),trackObserver:i}})(e),[e.participant.sid??e.participant.identity,e.source,lc(e)&&e.publication.trackSid]);return p.useEffect(()=>{let e=f.subscribe(e=>{lp.debug("update track",e),n(e),s(null==e?void 0:e.isMuted),a(null==e?void 0:e.isSubscribed),c(null==e?void 0:e.track)});return()=>null==e?void 0:e.unsubscribe()},[f]),p.useEffect(()=>{var i,n;return l&&(h.current&&l.detach(h.current),null!=(i=t.element)&&i.current&&!(e.participant.isLocal&&(null==l?void 0:l.kind)==="audio")&&l.attach(t.element.current)),h.current=null==(n=t.element)?void 0:n.current,()=>{h.current&&(null==l||l.detach(h.current))}},[l,t.element]),p.useEffect(()=>{var e,t;"number"==typeof(null==(e=null==i?void 0:i.dimensions)?void 0:e.width)&&"number"==typeof(null==(t=null==i?void 0:i.dimensions)?void 0:t.height)&&u(i.dimensions.width>i.dimensions.height?"landscape":"portrait")},[i]),{publication:i,isMuted:r,isSubscribed:o,track:l,elementProps:lz(t.props,{className:m,"data-lk-local-participant":e.participant.isLocal,"data-lk-source":null==i?void 0:i.source,...(null==i?void 0:i.kind)==="video"&&{"data-lk-orientation":d}})}}let cn=oO(function(){if(d)return c;d=1;var e=NaN,t=/^\s+|\s+$/g,i=/^[-+]0x[0-9a-f]+$/i,n=/^0b[01]+$/i,r=/^0o[0-7]+$/i,s=parseInt,o="object"==typeof oR&&oR&&oR.Object===Object&&oR,a="object"==typeof self&&self&&self.Object===Object&&self,l=o||a||Function("return this")(),u=Object.prototype.toString,h=Math.max,p=Math.min,m=function(){return l.Date.now()};function f(e){var t=typeof e;return!!e&&("object"==t||"function"==t)}function g(o){if("number"==typeof o)return o;if("symbol"==typeof(a=o)||a&&"object"==typeof a&&"[object Symbol]"==u.call(a))return e;if(f(o)){var a,l="function"==typeof o.valueOf?o.valueOf():o;o=f(l)?l+"":l}if("string"!=typeof o)return 0===o?o:+o;o=o.replace(t,"");var c=n.test(o);return c||r.test(o)?s(o.slice(2),c?2:8):i.test(o)?e:+o}return c=function(e,t,i){var n,r,s,o,a,l,c=0,d=!1,u=!1,v=!0;if("function"!=typeof e)throw TypeError("Expected a function");function y(t){var i=n,s=r;return n=r=void 0,c=t,o=e.apply(s,i)}function b(e){var i=e-l,n=e-c;return void 0===l||i>=t||i<0||u&&n>=s}function k(){var e,i,n,r=m();if(b(r))return T(r);a=setTimeout(k,(e=r-l,i=r-c,n=t-e,u?p(n,s-i):n))}function T(e){return a=void 0,v&&n?y(e):(n=r=void 0,o)}function S(){var e,i=m(),s=b(i);if(n=arguments,r=this,l=i,s){if(void 0===a)return c=e=l,a=setTimeout(k,t),d?y(e):o;if(u)return a=setTimeout(k,t),y(l)}return void 0===a&&(a=setTimeout(k,t)),o}return t=g(t)||0,f(i)&&(d=!!i.leading,s=(u="maxWait"in i)?h(g(i.maxWait)||0,t):s,v="trailing"in i?!!i.trailing:v),S.cancel=function(){void 0!==a&&clearTimeout(a),c=0,n=l=r=a=void 0},S.flush=function(){return void 0===a?o:T(m())},S}}()),cr=p.forwardRef(function({onTrackClick:e,onClick:t,onSubscriptionStatusChanged:i,trackRef:n,manageSubscription:r,...s},o){let a=lD(n),l=p.useRef(null);p.useImperativeHandle(o,()=>l.current);let c=function({threshold:e=0,root:t=null,rootMargin:i="0%",freezeOnceVisible:n=!1,initialIsIntersecting:r=!1,onChange:s}={}){var o;let[a,l]=(0,p.useState)(null),[c,d]=(0,p.useState)(()=>({isIntersecting:r,entry:void 0})),u=(0,p.useRef)();u.current=s;let h=(null==(o=c.entry)?void 0:o.isIntersecting)&&n;(0,p.useEffect)(()=>{if(!a||!("IntersectionObserver"in window)||h)return;let n=new IntersectionObserver(e=>{let t=Array.isArray(n.thresholds)?n.thresholds:[n.thresholds];e.forEach(e=>{let i=e.isIntersecting&&t.some(t=>e.intersectionRatio>=t);d({isIntersecting:i,entry:e}),u.current&&u.current(i,e)})},{threshold:e,root:t,rootMargin:i});return n.observe(a),()=>{n.disconnect()}},[a,JSON.stringify(e),t,i,h,n]);let m=(0,p.useRef)(null);(0,p.useEffect)(()=>{var e;a||null==(e=c.entry)||!e.target||n||h||m.current===c.entry.target||(m.current=c.entry.target,d({isIntersecting:r,entry:void 0}))},[a,c.entry,n,h,r]);let f=[l,!!c.isIntersecting,c.entry];return f.ref=f[0],f.isIntersecting=f[1],f.entry=f[2],f}({root:l.current}),[d]=function(e,t,i){let n=e instanceof Function?e():e,[r,s]=(0,p.useState)(n),o=(0,p.useRef)(n),a=function(e,t=500,i){let n=(0,p.useRef)();!function(e){let t=(0,p.useRef)(e);t.current=e,(0,p.useEffect)(()=>()=>{t.current()},[])}(()=>{n.current&&n.current.cancel()});let r=(0,p.useMemo)(()=>{let r=cn(e,t,i),s=(...e)=>r(...e);return s.cancel=()=>{r.cancel()},s.isPending=()=>!!n.current,s.flush=()=>r.flush(),s},[e,t,i]);return(0,p.useEffect)(()=>{n.current=cn(e,t,i)},[e,t,i]),r}(s,3e3,void 0);return o.current===n||(a(n),o.current=n),[r,a]}(c,0);p.useEffect(()=>{r&&a.publication instanceof sN&&(null==d?void 0:d.isIntersecting)===!1&&(null==c?void 0:c.isIntersecting)===!1&&a.publication.setSubscribed(!1)},[d,a,r]),p.useEffect(()=>{r&&a.publication instanceof sN&&(null==c?void 0:c.isIntersecting)===!0&&a.publication.setSubscribed(!0)},[c,a,r]);let{elementProps:u,publication:h,isSubscribed:m}=ci(a,{element:l,props:s});return p.useEffect(()=>{null==i||i(!!m)},[m,i]),p.createElement("video",{ref:l,...u,muted:!0,onClick:i=>{null==t||t(i),null==e||e({participant:null==a?void 0:a.participant,track:h})}})}),cs=p.forwardRef(function({trackRef:e,onSubscriptionStatusChanged:t,volume:i,...n},r){let s=lD(e),o=p.useRef(null);p.useImperativeHandle(r,()=>o.current);let{elementProps:a,isSubscribed:l,track:c,publication:d}=ci(s,{element:o,props:n});return p.useEffect(()=>{null==t||t(!!l)},[l,t]),p.useEffect(()=>{void 0===c||void 0===i||(c instanceof sP?c.setVolume(i):lp.warn("Volume can only be set on remote audio tracks."))},[i,c]),p.useEffect(()=>{void 0===d||void 0===n.muted||(d instanceof sN?d.setEnabled(!n.muted):lp.warn("Can only call setEnabled on remote track publications."))},[n.muted,d,c]),p.createElement("audio",{ref:o,...a})});function co({volume:e,muted:t}){let i=(function(e=[nM.Source.Camera,nM.Source.Microphone,nM.Source.ScreenShare,nM.Source.ScreenShareAudio,nM.Source.Unknown],t={}){let i=lF(t.room),[n,r]=p.useState([]),[s,o]=p.useState([]),a=p.useMemo(()=>e.map(e=>lm(e)?e.source:e),[JSON.stringify(e)]);return p.useEffect(()=>{let e=(function(e,t,i){var n,r;let s=null!=(n=i.additionalRoomEvents)?n:lu,o=null==(r=i.onlySubscribed)||r;return ly(e,...Array.from(new Set([o$.ParticipantConnected,o$.ParticipantDisconnected,o$.ConnectionStateChanged,o$.LocalTrackPublished,o$.LocalTrackUnpublished,o$.TrackPublished,o$.TrackUnpublished,o$.TrackSubscriptionStatusChanged,...s]).values())).pipe(a6(e=>{let i=lE(e,t,o);return lp.debug(`TrackReference[] was updated. (length ${i.trackReferences.length})`,i),i}),a8(lE(e,t,o)))})(i,a,{additionalRoomEvents:t.updateOnlyOn,onlySubscribed:t.onlySubscribed}).subscribe(({trackReferences:e,participants:t})=>{lp.debug("setting track bundles",e,t),r(e),o(t)});return()=>e.unsubscribe()},[i,JSON.stringify(t.onlySubscribed),JSON.stringify(t.updateOnlyOn),JSON.stringify(e)]),p.useMemo(()=>{if(!lf(e))return n;{let t=function(e,t){let i=new Map;if(lf(e)){let n=e.filter(e=>e.withPlaceholder).map(e=>e.source);t.forEach(e=>{let t=e.getTrackPublications().map(e=>{var t;return null==(t=e.track)?void 0:t.source}).filter(e=>void 0!==e),r=Array.from(function(e,t){let i=new Set(e);for(let e of t)i.delete(e);return i}(new Set(n),new Set(t)));r.length>0&&i.set(e.identity,r)})}return i}(e,s),i=Array.from(n);return s.forEach(e=>{t.has(e.identity)&&(t.get(e.identity)??[]).forEach(t=>{n.find(({participant:i,publication:n})=>e.identity===i.identity&&n.source===t)||(lp.debug(`Add ${t} placeholder for participant ${e.identity}.`),i.push({participant:e,source:t}))})}),i}},[n,s,e])})([nM.Source.Microphone,nM.Source.ScreenShareAudio,nM.Source.Unknown],{updateOnlyOn:[],onlySubscribed:!0}).filter(e=>!e.participant.isLocal&&e.publication.kind===nM.Kind.Audio);return p.createElement("div",{style:{display:"none"}},i.map(i=>p.createElement(cs,{key:ld(i),trackRef:i,volume:e,muted:t})))}let ca=e=>{let t=[];for(let i=0;i<e;i++)t.push([i,e-1-i]);return t},cl=e=>[[Math.floor(e/2)],[-1]],cc=(e,t,i)=>{let[n,r]=(0,p.useState)(0),[s,o]=(0,p.useState)([[]]);(0,p.useEffect)(()=>{"thinking"===e?o(cl(t)):"connecting"===e||"initializing"===e?o([...ca(t)]):o("listening"===e?cl(t):void 0===e||"speaking"===e?[Array(t).fill(0).map((e,t)=>t)]:[[]]),r(0)},[e,t]);let a=(0,p.useRef)(null);return(0,p.useEffect)(()=>{let e=performance.now(),t=n=>{n-e>=i&&(r(e=>e+1),e=n),a.current=requestAnimationFrame(t)};return a.current=requestAnimationFrame(t),()=>{null!==a.current&&cancelAnimationFrame(a.current)}},[i,t,e,s.length]),s[n%s.length]},cd=new Map([["connecting",2e3],["initializing",2e3],["listening",500],["thinking",150]]),cu=(e,t)=>{if(void 0===e)return 1e3;let i=cd.get(e);return i&&"connecting"===e&&(i/=t),i},ch=p.forwardRef(function({state:e,options:t,barCount:i=15,trackRef:n,children:r,...s},o){let a=lz(s,{className:"lk-audio-bar-visualizer"}),l=lM();n&&(l=n);let c=function(e,t={}){var i;let n=e instanceof nM?e:null==(i=null==e?void 0:e.publication)?void 0:i.track,r={...lJ,...t},[s,o]=p.useState(Array(r.bands).fill(0));return p.useEffect(()=>{if(!n||!(null!=n&&n.mediaStream))return;let{analyser:e,cleanup:i}=function(e,t){let i=Object.assign({cloneTrack:!1,fftSize:2048,smoothingTimeConstant:.8,minDecibels:-100,maxDecibels:-80},t),n=ry();if(!n)throw Error("Audio Context not supported on this browser");let r=i.cloneTrack?e.mediaStreamTrack.clone():e.mediaStreamTrack,s=n.createMediaStreamSource(new MediaStream([r])),o=n.createAnalyser();o.minDecibels=i.minDecibels,o.maxDecibels=i.maxDecibels,o.fftSize=i.fftSize,o.smoothingTimeConstant=i.smoothingTimeConstant,s.connect(o);let a=new Uint8Array(o.frequencyBinCount);return{calculateVolume:()=>{o.getByteFrequencyData(a);let e=0;for(let t of a)e+=Math.pow(t/255,2);return Math.sqrt(e/a.length)},analyser:o,cleanup:()=>ib(this,void 0,void 0,function*(){yield n.close(),i.cloneTrack&&r.stop()})}}(n,r.analyserOptions),s=new Float32Array(e.frequencyBinCount),a=setInterval(()=>{e.getFloatFrequencyData(s);let i=new Float32Array(s.length);for(let e=0;e<s.length;e++)i[e]=s[e];let n=lK(i=i.slice(t.loPass,t.hiPass)),a=Math.ceil(n.length/r.bands),l=[];for(let e=0;e<r.bands;e++){let t=n.slice(e*a,(e+1)*a).reduce((e,t)=>e+=t,0);l.push(t/a)}o(l)},r.updateInterval);return()=>{i(),clearInterval(a)}},[n,null==n?void 0:n.mediaStream,JSON.stringify(t)]),s}(l,{bands:i,loPass:100,hiPass:200}),d=(null==t?void 0:t.minHeight)??20,u=(null==t?void 0:t.maxHeight)??100,h=cc(e,i,cu(e,i)??100);return p.createElement("div",{ref:o,...a,"data-lk-va-state":e},c.map((e,t)=>{var i;return r?(i={"data-lk-highlighted":h.includes(t),"data-lk-bar-index":t,className:"lk-audio-bar",style:{height:`${Math.min(u,Math.max(d,100*e+5))}%`}},p.Children.map(r,e=>p.isValidElement(e)&&p.Children.only(r)?(e.props.className&&(i??(i={}),i.className=lV(e.props.className,i.className),i.style={...e.props.style,...i.style}),p.cloneElement(e,{...i,key:void 0})):e)):p.createElement("span",{key:t,"data-lk-highlighted":h.includes(t),"data-lk-bar-index":t,className:`lk-audio-bar ${h.includes(t)&&"lk-highlighted"}`,style:{height:`${Math.min(u,Math.max(d,100*e+5))}%`}})}))});function cp({kind:e,initialSelection:t,onActiveDeviceChange:i,tracks:n,requestPermissions:r=!1,...s}){let[o,a]=p.useState(!1),[l,c]=p.useState([]),[d,u]=p.useState(!0),[h,m]=p.useState(r),f=(e,t)=>{lp.debug("handle device change"),a(!1),null==i||i(e,t)},g=p.useRef(null),v=p.useRef(null);p.useLayoutEffect(()=>{o&&m(!0)},[o]),p.useLayoutEffect(()=>{let e;return g.current&&v.current&&(l||d)&&(e=function(e,t,i){return function(e,t,i,n){void 0===n&&(n={});let{ancestorScroll:r=!0,ancestorResize:s=!0,elementResize:o="function"==typeof ResizeObserver,layoutShift:a="function"==typeof IntersectionObserver,animationFrame:l=!1}=n,c=op(e),d=r||s?[...c?od(c):[],...od(t)]:[];d.forEach(e=>{r&&e.addEventListener("scroll",i,{passive:!0}),s&&e.addEventListener("resize",i)});let u=c&&a?function(e,t){let i=null,n,r=s9(e);function s(){var e;clearTimeout(n),null==(e=i)||e.disconnect(),i=null}return function o(a,l){void 0===a&&(a=!1),void 0===l&&(l=1),s();let c=e.getBoundingClientRect(),{left:d,top:u,width:h,height:p}=c;if(a||t(),!h||!p)return;let m=sB(u),f={rootMargin:-m+"px "+-sB(r.clientWidth-(d+h))+"px "+-sB(r.clientHeight-(u+p))+"px "+-sB(d)+"px",threshold:sF(0,sU(1,l))||1},g=!0;function v(t){let i=t[0].intersectionRatio;if(i!==l){if(!g)return o();i?o(!1,i):n=setTimeout(()=>{o(!1,1e-7)},1e3)}1!==i||oP(c,e.getBoundingClientRect())||o(),g=!1}try{i=new IntersectionObserver(v,{...f,root:r.ownerDocument})}catch{i=new IntersectionObserver(v,f)}i.observe(e)}(!0),s}(c,i):null,h=-1,p=null;o&&(p=new ResizeObserver(e=>{let[n]=e;n&&n.target===c&&p&&(p.unobserve(t),cancelAnimationFrame(h),h=requestAnimationFrame(()=>{var e;null==(e=p)||e.observe(t)})),i()}),c&&!l&&p.observe(c),p.observe(t));let m,f=l?ov(e):null;return l&&function t(){let n=ov(e);f&&!oP(f,n)&&i(),f=n,m=requestAnimationFrame(t)}(),i(),()=>{var e;d.forEach(e=>{r&&e.removeEventListener("scroll",i),s&&e.removeEventListener("resize",i)}),null==u||u(),null==(e=p)||e.disconnect(),p=null,l&&cancelAnimationFrame(m)}}(e,t,()=>ll(this,null,function*(){var n,r;let{x:s,y:o}=yield ox(e,t,{placement:"top",middleware:[{name:"offset",options:6,async fn(e){var t,i;let{x:n,y:r,placement:s,middlewareData:o}=e,a=await s3(e,6);return s===(null==(t=o.offset)?void 0:t.placement)&&null!=(i=o.arrow)&&i.alignmentOffset?{}:{x:n+a.x,y:r+a.y,data:{...a,placement:s}}}},(void 0===n&&(n={}),{name:"flip",options:n,async fn(e){var t,i,r,s,o;let{placement:a,middlewareData:l,rects:c,initialPlacement:d,platform:u,elements:h}=e,{mainAxis:p=!0,crossAxis:m=!0,fallbackPlacements:f,fallbackStrategy:g="bestFit",fallbackAxisSideDirection:v="none",flipAlignment:y=!0,...b}=sH(n,e);if(null!=(t=l.arrow)&&t.alignmentOffset)return{};let k=sG(a),T=sX(d),S=sG(d)===d,C=await (null==u.isRTL?void 0:u.isRTL(h.floating)),w=f||(S||!y?[sQ(d)]:function(e){let t=sQ(e);return[sY(e),t,sY(t)]}(d)),E="none"!==v;!f&&E&&w.push(...function(e,t,i,n){let r=s$(e),s=function(e,t,i){let n=["left","right"],r=["right","left"];switch(e){case"top":case"bottom":return i?t?r:n:t?n:r;case"left":case"right":return t?["top","bottom"]:["bottom","top"];default:return[]}}(sG(e),"start"===i,n);return r&&(s=s.map(e=>e+"-"+r),t&&(s=s.concat(s.map(sY)))),s}(d,y,v,C));let P=[d,...w],x=await s2(e,b),R=[],O=(null==(i=l.flip)?void 0:i.overflows)||[];if(p&&R.push(x[k]),m){let e=function(e,t,i){void 0===i&&(i=!1);let n=s$(e),r=sK(sX(e)),s=sJ(r),o="x"===r?n===(i?"end":"start")?"right":"left":"start"===n?"bottom":"top";return t.reference[s]>t.floating[s]&&(o=sQ(o)),[o,sQ(o)]}(a,c,C);R.push(x[e[0]],x[e[1]])}if(O=[...O,{placement:a,overflows:R}],!R.every(e=>e<=0)){let e=((null==(r=l.flip)?void 0:r.index)||0)+1,t=P[e];if(t)return{data:{index:e,overflows:O},reset:{placement:t}};let i=null==(s=O.filter(e=>e.overflows[0]<=0).sort((e,t)=>e.overflows[1]-t.overflows[1])[0])?void 0:s.placement;if(!i)switch(g){case"bestFit":{let e=null==(o=O.filter(e=>{if(E){let t=sX(e.placement);return t===T||"y"===t}return!0}).map(e=>[e.placement,e.overflows.filter(e=>e>0).reduce((e,t)=>e+t,0)]).sort((e,t)=>e[1]-t[1])[0])?void 0:o[0];e&&(i=e);break}case"initialPlacement":i=d}if(a!==i)return{reset:{placement:i}}}return{}}}),{name:"shift",options:r={padding:5},async fn(e){let{x:t,y:i,placement:n}=e,{mainAxis:s=!0,crossAxis:o=!1,limiter:a={fn:e=>{let{x:t,y:i}=e;return{x:t,y:i}}},...l}=sH(r,e),c={x:t,y:i},d=await s2(e,l),u=sX(sG(n)),h=sK(u),p=c[h],m=c[u];if(s){let e="y"===h?"top":"left",t="y"===h?"bottom":"right",i=p+d[e],n=p-d[t];p=sF(i,sU(p,n))}if(o){let e="y"===u?"top":"left",t="y"===u?"bottom":"right",i=m+d[e],n=m-d[t];m=sF(i,sU(m,n))}let f=a.fn({...e,[h]:p,[u]:m});return{...f,data:{x:f.x-t,y:f.y-i,enabled:{[h]:s,[u]:o}}}}}]});null==i||i(s,o)}))}(g.current,v.current,(e,t)=>{v.current&&Object.assign(v.current.style,{left:`${e}px`,top:`${t}px`})})),u(!1),()=>{null==e||e()}},[g,v,l,d]);let y=p.useCallback(e=>{v.current&&e.target!==g.current&&o&&!v.current.contains(e.target)&&a(!1)},[o,v,g]);return p.useEffect(()=>(document.addEventListener("click",y),()=>{document.removeEventListener("click",y)}),[y]),p.createElement(p.Fragment,null,p.createElement("button",{className:"lk-button lk-button-menu","aria-pressed":o,...s,onClick:()=>a(!o),ref:g},s.children),!s.disabled&&p.createElement("div",{className:"lk-device-menu",ref:v,style:{visibility:o?"visible":"hidden"}},e?p.createElement(l7,{initialSelection:t,onActiveDeviceChange:t=>f(e,t),onDeviceListChange:c,kind:e,track:null==n?void 0:n[e],requestPermissions:h}):p.createElement(p.Fragment,null,p.createElement("div",{className:"lk-device-menu-heading"},"Audio inputs"),p.createElement(l7,{kind:"audioinput",onActiveDeviceChange:e=>f("audioinput",e),onDeviceListChange:c,track:null==n?void 0:n.audioinput,requestPermissions:h}),p.createElement("div",{className:"lk-device-menu-heading"},"Video inputs"),p.createElement(l7,{kind:"videoinput",onActiveDeviceChange:e=>f("videoinput",e),onDeviceListChange:c,track:null==n?void 0:n.videoinput,requestPermissions:h}))))}function cm({controls:e,saveUserChoices:t=!0,onDeviceError:i,...n}){let r={leave:!0,microphone:!0,...e},s=function(){let e=lj();return lW(p.useMemo(()=>{var t;return lw(t=e.localParticipant,oK.ParticipantPermissionsChanged).pipe(a6(()=>t.permissions),a8(t.permissions))},[e]),e.localParticipant.permissions)}(),{microphoneTrack:o,localParticipant:a}=lG(),l=p.useMemo(()=>({participant:a,source:nM.Source.Microphone,publication:o}),[a,o]);s?r.microphone??(r.microphone=s.canPublish):r.microphone=!1;let c=lz({className:"lk-agent-control-bar"},n),{saveAudioInputEnabled:d,saveAudioInputDeviceId:u}=function(e={}){let[t,i]=p.useState(function(e,t=!1){var i,n,r,s,o;let a={videoEnabled:null!=(i=null==e?void 0:e.videoEnabled)?i:lR.videoEnabled,audioEnabled:null!=(n=null==e?void 0:e.audioEnabled)?n:lR.audioEnabled,videoDeviceId:null!=(r=null==e?void 0:e.videoDeviceId)?r:lR.videoDeviceId,audioDeviceId:null!=(s=null==e?void 0:e.audioDeviceId)?s:lR.audioDeviceId,username:null!=(o=null==e?void 0:e.username)?o:lR.username};if(t)return a;{let e=lO();return lo(lo({},a),e??{})}}(e.defaults,e.preventLoad??!1)),n=p.useCallback(e=>{i(t=>({...t,audioEnabled:e}))},[]),r=p.useCallback(e=>{i(t=>({...t,videoEnabled:e}))},[]),s=p.useCallback(e=>{i(t=>({...t,audioDeviceId:e}))},[]),o=p.useCallback(e=>{i(t=>({...t,videoDeviceId:e}))},[]),a=p.useCallback(e=>{i(t=>({...t,username:e}))},[]);return p.useEffect(()=>{(function(e,t=!1){!0!==t&&lA(e)})(t,e.preventSave??!1)},[t,e.preventSave]),{userChoices:t,saveAudioInputEnabled:n,saveVideoInputEnabled:r,saveAudioInputDeviceId:s,saveVideoInputDeviceId:o,saveUsername:a}}({preventSave:!t}),h=p.useCallback((e,t)=>{t&&d(e)},[d]);return p.createElement("div",{...c},r.microphone&&p.createElement("div",{className:"lk-button-group"},p.createElement(ct,{source:nM.Source.Microphone,showIcon:!0,onChange:h,onDeviceError:e=>null==i?void 0:i({source:nM.Source.Microphone,error:e})},p.createElement(ch,{trackRef:l,barCount:7,options:{minHeight:5}})),p.createElement("div",{className:"lk-button-group-menu"},p.createElement(cp,{kind:"audioinput",onActiveDeviceChange:(e,t)=>u(t??"default")}))),r.leave&&p.createElement(l2,null,"Disconnect"),p.createElement(ce,null))}let cf=(0,p.createContext)({});function cg(e){let t=(0,p.useRef)(null);return null===t.current&&(t.current=e()),t.current}let cv=(0,p.createContext)(null),cy=(0,p.createContext)({transformPagePoint:e=>e,isStatic:!1,reducedMotion:"never"});class cb extends p.Component{getSnapshotBeforeUpdate(e){let t=this.props.childRef.current;if(t&&e.isPresent&&!this.props.isPresent){let e=this.props.sizeRef.current;e.height=t.offsetHeight||0,e.width=t.offsetWidth||0,e.top=t.offsetTop,e.left=t.offsetLeft}return null}componentDidUpdate(){}render(){return this.props.children}}function ck({children:e,isPresent:t}){let i=(0,p.useId)(),n=(0,p.useRef)(null),r=(0,p.useRef)({width:0,height:0,top:0,left:0}),{nonce:s}=(0,p.useContext)(cy);return(0,p.useInsertionEffect)(()=>{let{width:e,height:o,top:a,left:l}=r.current;if(t||!n.current||!e||!o)return;n.current.dataset.motionPopId=i;let c=document.createElement("style");return s&&(c.nonce=s),document.head.appendChild(c),c.sheet&&c.sheet.insertRule(`
3
+ `):"",this.name="UnsubscriptionError",this.errors=t}});function ag(e,t){if(e){var i=e.indexOf(t);0<=i&&e.splice(i,1)}}var av=function(){var e;function t(e){this.initialTeardown=e,this.closed=!1,this._parentage=null,this._finalizers=null}return t.prototype.unsubscribe=function(){var e,t,i,n,r;if(!this.closed){this.closed=!0;var s=this._parentage;if(s){if(this._parentage=null,Array.isArray(s))try{for(var o=ac(s),a=o.next();!a.done;a=o.next())a.value.remove(this)}catch(t){e={error:t}}finally{try{a&&!a.done&&(t=o.return)&&t.call(o)}finally{if(e)throw e.error}}else s.remove(this)}var l=this.initialTeardown;if(ap(l))try{l()}catch(e){r=e instanceof af?e.errors:[e]}var c=this._finalizers;if(c){this._finalizers=null;try{for(var d=ac(c),u=d.next();!u.done;u=d.next()){var h=u.value;try{ak(h)}catch(e){r=r??[],e instanceof af?r=au(au([],ad(r)),ad(e.errors)):r.push(e)}}}catch(e){i={error:e}}finally{try{u&&!u.done&&(n=d.return)&&n.call(d)}finally{if(i)throw i.error}}}if(r)throw new af(r)}},t.prototype.add=function(e){var i;if(e&&e!==this){if(this.closed)ak(e);else{if(e instanceof t){if(e.closed||e._hasParent(this))return;e._addParent(this)}(this._finalizers=null!==(i=this._finalizers)&&void 0!==i?i:[]).push(e)}}},t.prototype._hasParent=function(e){var t=this._parentage;return t===e||Array.isArray(t)&&t.includes(e)},t.prototype._addParent=function(e){var t=this._parentage;this._parentage=Array.isArray(t)?(t.push(e),t):t?[t,e]:e},t.prototype._removeParent=function(e){var t=this._parentage;t===e?this._parentage=null:Array.isArray(t)&&ag(t,e)},t.prototype.remove=function(e){var i=this._finalizers;i&&ag(i,e),e instanceof t&&e._removeParent(this)},t.EMPTY=((e=new t).closed=!0,e),t}(),ay=av.EMPTY;function ab(e){return e instanceof av||e&&"closed"in e&&ap(e.remove)&&ap(e.add)&&ap(e.unsubscribe)}function ak(e){ap(e)?e():e.unsubscribe()}var aT={Promise:void 0},aS={setTimeout:function(e,t){for(var i=[],n=2;n<arguments.length;n++)i[n-2]=arguments[n];return setTimeout.apply(void 0,au([e,t],ad(i)))}};function aC(e){aS.setTimeout(function(){throw e})}function aw(){}var aE=function(e){function t(t){var i=e.call(this)||this;return i.isStopped=!1,t?(i.destination=t,ab(t)&&t.add(i)):i.destination=aR,i}return aa(t,e),t.create=function(e,t,i){return new ax(e,t,i)},t.prototype.next=function(e){this.isStopped||this._next(e)},t.prototype.error=function(e){this.isStopped||(this.isStopped=!0,this._error(e))},t.prototype.complete=function(){this.isStopped||(this.isStopped=!0,this._complete())},t.prototype.unsubscribe=function(){this.closed||(this.isStopped=!0,e.prototype.unsubscribe.call(this),this.destination=null)},t.prototype._next=function(e){this.destination.next(e)},t.prototype._error=function(e){try{this.destination.error(e)}finally{this.unsubscribe()}},t.prototype._complete=function(){try{this.destination.complete()}finally{this.unsubscribe()}},t}(av),aP=function(){function e(e){this.partialObserver=e}return e.prototype.next=function(e){var t=this.partialObserver;if(t.next)try{t.next(e)}catch(e){aC(e)}},e.prototype.error=function(e){var t=this.partialObserver;if(t.error)try{t.error(e)}catch(e){aC(e)}else aC(e)},e.prototype.complete=function(){var e=this.partialObserver;if(e.complete)try{e.complete()}catch(e){aC(e)}},e}(),ax=function(e){function t(t,i,n){var r,s=e.call(this)||this;return r=ap(t)||!t?{next:t??void 0,error:i??void 0,complete:n??void 0}:t,s.destination=new aP(r),s}return aa(t,e),t}(aE),aR={closed:!0,next:aw,error:function(e){throw e},complete:aw},aO="function"==typeof Symbol&&Symbol.observable||"@@observable";function aA(e){return e}var aI=function(){function e(e){e&&(this._subscribe=e)}return e.prototype.lift=function(t){var i=new e;return i.source=this,i.operator=t,i},e.prototype.subscribe=function(e,t,i){var n,r,s,o=(n=e)&&n instanceof aE||n&&ap(n.next)&&ap(n.error)&&ap(n.complete)&&ab(n)?e:new ax(e,t,i);return r=this.operator,s=this.source,o.add(r?r.call(o,s):s?this._subscribe(o):this._trySubscribe(o)),o},e.prototype._trySubscribe=function(e){try{return this._subscribe(e)}catch(t){e.error(t)}},e.prototype.forEach=function(e,t){var i=this;return new(t=aM(t))(function(t,n){var r=new ax({next:function(t){try{e(t)}catch(e){n(e),r.unsubscribe()}},error:n,complete:t});i.subscribe(r)})},e.prototype._subscribe=function(e){var t;return null===(t=this.source)||void 0===t?void 0:t.subscribe(e)},e.prototype[aO]=function(){return this},e.prototype.pipe=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return(0===e.length?aA:1===e.length?e[0]:function(t){return e.reduce(function(e,t){return t(e)},t)})(this)},e.prototype.toPromise=function(e){var t=this;return new(e=aM(e))(function(e,i){var n;t.subscribe(function(e){return n=e},function(e){return i(e)},function(){return e(n)})})},e.create=function(t){return new e(t)},e}();function aM(e){var t;return null!==(t=e??aT.Promise)&&void 0!==t?t:Promise}function aD(e){return function(t){if(ap(null==t?void 0:t.lift))return t.lift(function(t){try{return e(t,this)}catch(e){this.error(e)}});throw TypeError("Unable to lift unknown Observable type")}}function a_(e,t,i,n,r){return new aN(e,t,i,n,r)}var aN=function(e){function t(t,i,n,r,s,o){var a=e.call(this,t)||this;return a.onFinalize=s,a.shouldUnsubscribe=o,a._next=i?function(e){try{i(e)}catch(e){t.error(e)}}:e.prototype._next,a._error=r?function(e){try{r(e)}catch(e){t.error(e)}finally{this.unsubscribe()}}:e.prototype._error,a._complete=n?function(){try{n()}catch(e){t.error(e)}finally{this.unsubscribe()}}:e.prototype._complete,a}return aa(t,e),t.prototype.unsubscribe=function(){var t;if(!this.shouldUnsubscribe||this.shouldUnsubscribe()){var i=this.closed;e.prototype.unsubscribe.call(this),i||null===(t=this.onFinalize)||void 0===t||t.call(this)}},t}(aE),aL=am(function(e){return function(){e(this),this.name="ObjectUnsubscribedError",this.message="object unsubscribed"}}),aj=function(e){function t(){var t=e.call(this)||this;return t.closed=!1,t.currentObservers=null,t.observers=[],t.isStopped=!1,t.hasError=!1,t.thrownError=null,t}return aa(t,e),t.prototype.lift=function(e){var t=new aU(this,this);return t.operator=e,t},t.prototype._throwIfClosed=function(){if(this.closed)throw new aL},t.prototype.next=function(e){var t=this;(function(){var i,n;if(t._throwIfClosed(),!t.isStopped){t.currentObservers||(t.currentObservers=Array.from(t.observers));try{for(var r=ac(t.currentObservers),s=r.next();!s.done;s=r.next())s.value.next(e)}catch(e){i={error:e}}finally{try{s&&!s.done&&(n=r.return)&&n.call(r)}finally{if(i)throw i.error}}}})()},t.prototype.error=function(e){var t=this;(function(){if(t._throwIfClosed(),!t.isStopped){t.hasError=t.isStopped=!0,t.thrownError=e;for(var i=t.observers;i.length;)i.shift().error(e)}})()},t.prototype.complete=function(){var e=this;(function(){if(e._throwIfClosed(),!e.isStopped){e.isStopped=!0;for(var t=e.observers;t.length;)t.shift().complete()}})()},t.prototype.unsubscribe=function(){this.isStopped=this.closed=!0,this.observers=this.currentObservers=null},Object.defineProperty(t.prototype,"observed",{get:function(){var e;return(null===(e=this.observers)||void 0===e?void 0:e.length)>0},enumerable:!1,configurable:!0}),t.prototype._trySubscribe=function(t){return this._throwIfClosed(),e.prototype._trySubscribe.call(this,t)},t.prototype._subscribe=function(e){return this._throwIfClosed(),this._checkFinalizedStatuses(e),this._innerSubscribe(e)},t.prototype._innerSubscribe=function(e){var t=this,i=this.hasError,n=this.isStopped,r=this.observers;return i||n?ay:(this.currentObservers=null,r.push(e),new av(function(){t.currentObservers=null,ag(r,e)}))},t.prototype._checkFinalizedStatuses=function(e){var t=this.hasError,i=this.thrownError,n=this.isStopped;t?e.error(i):n&&e.complete()},t.prototype.asObservable=function(){var e=new aI;return e.source=this,e},t.create=function(e,t){return new aU(e,t)},t}(aI),aU=function(e){function t(t,i){var n=e.call(this)||this;return n.destination=t,n.source=i,n}return aa(t,e),t.prototype.next=function(e){var t,i;null===(i=null===(t=this.destination)||void 0===t?void 0:t.next)||void 0===i||i.call(t,e)},t.prototype.error=function(e){var t,i;null===(i=null===(t=this.destination)||void 0===t?void 0:t.error)||void 0===i||i.call(t,e)},t.prototype.complete=function(){var e,t;null===(t=null===(e=this.destination)||void 0===e?void 0:e.complete)||void 0===t||t.call(e)},t.prototype._subscribe=function(e){var t,i;return null!==(i=null===(t=this.source)||void 0===t?void 0:t.subscribe(e))&&void 0!==i?i:ay},t}(aj),aF=function(e){function t(t){var i=e.call(this)||this;return i._value=t,i}return aa(t,e),Object.defineProperty(t.prototype,"value",{get:function(){return this.getValue()},enumerable:!1,configurable:!0}),t.prototype._subscribe=function(t){var i=e.prototype._subscribe.call(this,t);return i.closed||t.next(this._value),i},t.prototype.getValue=function(){var e=this.hasError,t=this.thrownError,i=this._value;if(e)throw t;return this._throwIfClosed(),i},t.prototype.next=function(t){e.prototype.next.call(this,this._value=t)},t}(aj),aV={now:function(){return Date.now()}},aB=function(e){function t(t,i){return e.call(this)||this}return aa(t,e),t.prototype.schedule=function(e,t){return this},t}(av),aq={setInterval:function(e,t){for(var i=[],n=2;n<arguments.length;n++)i[n-2]=arguments[n];return setInterval.apply(void 0,au([e,t],ad(i)))},clearInterval:function(e){return clearInterval(e)}},aW=function(e){function t(t,i){var n=e.call(this,t,i)||this;return n.scheduler=t,n.work=i,n.pending=!1,n}return aa(t,e),t.prototype.schedule=function(e,t){if(void 0===t&&(t=0),this.closed)return this;this.state=e;var i,n=this.id,r=this.scheduler;return null!=n&&(this.id=this.recycleAsyncId(r,n,t)),this.pending=!0,this.delay=t,this.id=null!==(i=this.id)&&void 0!==i?i:this.requestAsyncId(r,this.id,t),this},t.prototype.requestAsyncId=function(e,t,i){return void 0===i&&(i=0),aq.setInterval(e.flush.bind(e,this),i)},t.prototype.recycleAsyncId=function(e,t,i){if(void 0===i&&(i=0),null!=i&&this.delay===i&&!1===this.pending)return t;null!=t&&aq.clearInterval(t)},t.prototype.execute=function(e,t){if(this.closed)return Error("executing a cancelled action");this.pending=!1;var i=this._execute(e,t);if(i)return i;!1===this.pending&&null!=this.id&&(this.id=this.recycleAsyncId(this.scheduler,this.id,null))},t.prototype._execute=function(e,t){var i,n=!1;try{this.work(e)}catch(e){n=!0,i=e||Error("Scheduled action threw falsy error")}if(n)return this.unsubscribe(),i},t.prototype.unsubscribe=function(){if(!this.closed){var t=this.id,i=this.scheduler,n=i.actions;this.work=this.state=this.scheduler=null,this.pending=!1,ag(n,this),null!=t&&(this.id=this.recycleAsyncId(i,t,null)),this.delay=null,e.prototype.unsubscribe.call(this)}},t}(aB),az=function(){function e(t,i){void 0===i&&(i=e.now),this.schedulerActionCtor=t,this.now=i}return e.prototype.schedule=function(e,t,i){return void 0===t&&(t=0),new this.schedulerActionCtor(this,e).schedule(i,t)},e.now=aV.now,e}();function aH(e){var t;return(t=e[e.length-1])&&ap(t.schedule)?e.pop():void 0}new(function(e){function t(t,i){void 0===i&&(i=az.now);var n=e.call(this,t,i)||this;return n.actions=[],n._active=!1,n}return aa(t,e),t.prototype.flush=function(e){var t,i=this.actions;if(this._active){i.push(e);return}this._active=!0;do if(t=e.execute(e.state,e.delay))break;while(e=i.shift());if(this._active=!1,t){for(;e=i.shift();)e.unsubscribe();throw t}},t}(az))(aW);var aG=function(e){return e&&"number"==typeof e.length&&"function"!=typeof e};function a$(e){return ap(null==e?void 0:e.then)}function aK(e){return Symbol.asyncIterator&&ap(null==e?void 0:e[Symbol.asyncIterator])}function aJ(e){return TypeError("You provided "+(null!==e&&"object"==typeof e?"an invalid object":"'"+e+"'")+" where a stream was expected. You can provide an Observable, Promise, ReadableStream, Array, AsyncIterable, or Iterable.")}var aX="function"==typeof Symbol&&Symbol.iterator?Symbol.iterator:"@@iterator";function aY(e){return ap(null==e?void 0:e[aX])}function aQ(e){return function(e,t,i){if(!Symbol.asyncIterator)throw TypeError("Symbol.asyncIterator is not defined.");var n,r=i.apply(e,t||[]),s=[];return n=Object.create(("function"==typeof AsyncIterator?AsyncIterator:Object).prototype),o("next"),o("throw"),o("return",function(e){return function(t){return Promise.resolve(t).then(e,c)}}),n[Symbol.asyncIterator]=function(){return this},n;function o(e,t){r[e]&&(n[e]=function(t){return new Promise(function(i,n){s.push([e,t,i,n])>1||a(e,t)})},t&&(n[e]=t(n[e])))}function a(e,t){try{var i;(i=r[e](t)).value instanceof ah?Promise.resolve(i.value.v).then(l,c):d(s[0][2],i)}catch(e){d(s[0][3],e)}}function l(e){a("next",e)}function c(e){a("throw",e)}function d(e,t){e(t),s.shift(),s.length&&a(s[0][0],s[0][1])}}(this,arguments,function(){var t,i,n;return al(this,function(r){switch(r.label){case 0:t=e.getReader(),r.label=1;case 1:r.trys.push([1,,9,10]),r.label=2;case 2:return[4,ah(t.read())];case 3:return n=(i=r.sent()).value,i.done?[4,ah(void 0)]:[3,5];case 4:return[2,r.sent()];case 5:return[4,ah(n)];case 6:return[4,r.sent()];case 7:return r.sent(),[3,2];case 8:return[3,10];case 9:return t.releaseLock(),[7];case 10:return[2]}})})}function aZ(e){return ap(null==e?void 0:e.getReader)}function a0(e){if(e instanceof aI)return e;if(null!=e){if(ap(e[aO]))return new aI(function(t){var i=e[aO]();if(ap(i.subscribe))return i.subscribe(t);throw TypeError("Provided object does not correctly implement Symbol.observable")});if(aG(e))return new aI(function(t){for(var i=0;i<e.length&&!t.closed;i++)t.next(e[i]);t.complete()});if(a$(e))return new aI(function(t){e.then(function(e){t.closed||(t.next(e),t.complete())},function(e){return t.error(e)}).then(null,aC)});if(aK(e))return a1(e);if(aY(e))return new aI(function(t){var i,n;try{for(var r=ac(e),s=r.next();!s.done;s=r.next()){var o=s.value;if(t.next(o),t.closed)return}}catch(e){i={error:e}}finally{try{s&&!s.done&&(n=r.return)&&n.call(r)}finally{if(i)throw i.error}}t.complete()});if(aZ(e))return a1(aQ(e))}throw aJ(e)}function a1(e){return new aI(function(t){(function(e,t){var i,n,r,s,o,a,l,c;return o=this,a=void 0,l=void 0,c=function(){var o;return al(this,function(a){switch(a.label){case 0:a.trys.push([0,5,6,11]),i=function(e){if(!Symbol.asyncIterator)throw TypeError("Symbol.asyncIterator is not defined.");var t,i=e[Symbol.asyncIterator];return i?i.call(e):(e=ac(e),t={},n("next"),n("throw"),n("return"),t[Symbol.asyncIterator]=function(){return this},t);function n(i){t[i]=e[i]&&function(t){return new Promise(function(n,r){(function(e,t,i,n){Promise.resolve(n).then(function(t){e({value:t,done:i})},t)})(n,r,(t=e[i](t)).done,t.value)})}}}(e),a.label=1;case 1:return[4,i.next()];case 2:if((n=a.sent()).done)return[3,4];if(o=n.value,t.next(o),t.closed)return[2];a.label=3;case 3:return[3,1];case 4:return[3,11];case 5:return r={error:a.sent()},[3,11];case 6:return a.trys.push([6,,9,10]),n&&!n.done&&(s=i.return)?[4,s.call(i)]:[3,8];case 7:a.sent(),a.label=8;case 8:return[3,10];case 9:if(r)throw r.error;return[7];case 10:return[7];case 11:return t.complete(),[2]}})},new(l||(l=Promise))(function(e,t){function i(e){try{r(c.next(e))}catch(e){t(e)}}function n(e){try{r(c.throw(e))}catch(e){t(e)}}function r(t){var r;t.done?e(t.value):((r=t.value)instanceof l?r:new l(function(e){e(r)})).then(i,n)}r((c=c.apply(o,a||[])).next())})})(e,t).catch(function(e){return t.error(e)})})}function a2(e,t,i,n,r){void 0===n&&(n=0),void 0===r&&(r=!1);var s=t.schedule(function(){i(),r?e.add(this.schedule(null,n)):this.unsubscribe()},n);if(e.add(s),!r)return s}function a3(e,t){return void 0===t&&(t=0),aD(function(i,n){i.subscribe(a_(n,function(i){return a2(n,e,function(){return n.next(i)},t)},function(){return a2(n,e,function(){return n.complete()},t)},function(i){return a2(n,e,function(){return n.error(i)},t)}))})}function a5(e,t){return void 0===t&&(t=0),aD(function(i,n){n.add(e.schedule(function(){return i.subscribe(n)},t))})}function a4(e,t){if(!e)throw Error("Iterable cannot be null");return new aI(function(i){a2(i,t,function(){var n=e[Symbol.asyncIterator]();a2(i,t,function(){n.next().then(function(e){e.done?i.complete():i.next(e.value)})},0,!0)})})}function a6(e,t){return aD(function(i,n){var r=0;i.subscribe(a_(n,function(i){n.next(e.call(t,i,r++))}))})}function a9(){for(var e,t,i=[],n=0;n<arguments.length;n++)i[n]=arguments[n];return(function e(t,i,n){return void 0===n&&(n=1/0),ap(i)?e(function(e,n){return a6(function(t,r){return i(e,t,n,r)})(a0(t(e,n)))},n):("number"==typeof i&&(n=i),aD(function(e,i){var r,s,o,a,l,c,d;return r=n,s=[],o=0,a=0,l=!1,c=function(){!l||s.length||o||i.complete()},d=function(e){o++;var n=!1;a0(t(e,a++)).subscribe(a_(i,function(e){i.next(e)},function(){n=!0},void 0,function(){if(n)try{for(o--;s.length&&o<r;)!function(){var e=s.shift();d(e)}();c()}catch(e){i.error(e)}}))},e.subscribe(a_(i,function(e){return o<r?d(e):s.push(e)},function(){l=!0,c()})),function(){}}))})(aA,1)((e=i,(t=aH(i))?function(e,t){if(null!=e){if(ap(e[aO]))return a0(e).pipe(a5(t),a3(t));if(aG(e))return new aI(function(i){var n=0;return t.schedule(function(){n===e.length?i.complete():(i.next(e[n++]),i.closed||this.schedule())})});if(a$(e))return a0(e).pipe(a5(t),a3(t));if(aK(e))return a4(e,t);if(aY(e))return new aI(function(i){var n;return a2(i,t,function(){n=e[aX](),a2(i,t,function(){var e,t,r;try{t=(e=n.next()).value,r=e.done}catch(e){i.error(e);return}r?i.complete():i.next(t)},0,!0)}),function(){return ap(null==n?void 0:n.return)&&n.return()}});if(aZ(e))return a4(aQ(e),t)}throw aJ(e)}(e,t):a0(e)))}function a8(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var i=aH(e);return aD(function(t,n){(i?a9(e,t,i):a9(e,t)).subscribe(n)})}am(function(e){return function(t){void 0===t&&(t=null),e(this),this.message="Timeout has occurred",this.name="TimeoutError",this.info=t}});var a7=Object.defineProperty,le=Object.defineProperties,lt=Object.getOwnPropertyDescriptors,li=Object.getOwnPropertySymbols,ln=Object.prototype.hasOwnProperty,lr=Object.prototype.propertyIsEnumerable,ls=(e,t,i)=>t in e?a7(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i,lo=(e,t)=>{for(var i in t||(t={}))ln.call(t,i)&&ls(e,i,t[i]);if(li)for(var i of li(t))lr.call(t,i)&&ls(e,i,t[i]);return e},la=(e,t)=>le(e,lt(t)),ll=(e,t,i)=>new Promise((n,r)=>{var s=e=>{try{a(i.next(e))}catch(e){r(e)}},o=e=>{try{a(i.throw(e))}catch(e){r(e)}},a=e=>e.done?n(e.value):Promise.resolve(e.value).then(s,o);a((i=i.apply(e,t)).next())});function lc(e){var t;return!(typeof e>"u")&&(!!e&&e.hasOwnProperty("participant")&&e.hasOwnProperty("source")&&e.hasOwnProperty("track")&&"u">typeof(null==(t=e.publication)?void 0:t.track)||!!e&&e.hasOwnProperty("participant")&&e.hasOwnProperty("source")&&e.hasOwnProperty("publication")&&"u">typeof e.publication)}function ld(e){if("string"==typeof e||"number"==typeof e)return`${e}`;if(e&&e.hasOwnProperty("participant")&&e.hasOwnProperty("source")&&typeof e.publication>"u")return`${e.participant.identity}_${e.source}_placeholder`;if(lc(e))return`${e.participant.identity}_${e.publication.source}_${e.publication.trackSid}`;throw Error(`Can't generate a id for the given track reference: ${e}`)}var lu=[o$.ConnectionStateChanged,o$.RoomMetadataChanged,o$.ActiveSpeakersChanged,o$.ConnectionQualityChanged,o$.ParticipantConnected,o$.ParticipantDisconnected,o$.ParticipantPermissionsChanged,o$.ParticipantMetadataChanged,o$.ParticipantNameChanged,o$.ParticipantAttributesChanged,o$.TrackMuted,o$.TrackUnmuted,o$.TrackPublished,o$.TrackUnpublished,o$.TrackStreamStateChanged,o$.TrackSubscriptionFailed,o$.TrackSubscriptionPermissionChanged,o$.TrackSubscriptionStatusChanged,o$.LocalTrackPublished,o$.LocalTrackUnpublished],lh=[oK.TrackPublished,oK.TrackUnpublished,oK.TrackMuted,oK.TrackUnmuted,oK.TrackStreamStateChanged,oK.TrackSubscribed,oK.TrackUnsubscribed,oK.TrackSubscriptionPermissionChanged,oK.TrackSubscriptionFailed,oK.LocalTrackPublished,oK.LocalTrackUnpublished],lp=(oK.ConnectionQualityChanged,oK.IsSpeakingChanged,oK.ParticipantMetadataChanged,oK.ParticipantPermissionsChanged,oK.TrackMuted,oK.TrackUnmuted,oK.TrackPublished,oK.TrackUnpublished,oK.TrackStreamStateChanged,oK.TrackSubscriptionFailed,oK.TrackSubscriptionPermissionChanged,oK.TrackSubscriptionStatusChanged,oK.LocalTrackPublished,oK.LocalTrackUnpublished,as.getLogger("lk-components-js"));function lm(e){return"object"==typeof e}function lf(e){return Array.isArray(e)&&e.filter(lm).length>0}function lg(e){return`lk-${e}`}function lv(e){if(lc(e))return e.publication;{let{source:t,name:i,participant:n}=e;if(t&&i)return n.getTrackPublications().find(e=>e.source===t&&e.trackName===i);if(i)return n.getTrackPublicationByName(i);if(t)return n.getTrackPublication(t);throw Error("At least one of source and name needs to be defined")}}function ly(e,...t){return new aI(i=>{let n=()=>{i.next(e)};return t.forEach(t=>{e.on(t,n)}),()=>{t.forEach(t=>{e.off(t,n)})}}).pipe(a8(e))}function lb(e,t){return new aI(i=>{let n=(...e)=>{i.next(e)};return e.on(t,n),()=>{e.off(t,n)}})}function lk(e){return ly(e,o$.AudioPlaybackStatusChanged).pipe(a6(e=>({canPlayAudio:e.canPlaybackAudio})))}function lT(e){return ly(e,o$.VideoPlaybackStatusChanged).pipe(a6(e=>({canPlayVideo:e.canPlaybackVideo})))}function lS(e,...t){return new aI(i=>{let n=()=>{i.next(e)};return t.forEach(t=>{e.on(t,n)}),()=>{t.forEach(t=>{e.off(t,n)})}}).pipe(a8(e))}function lC(e){return lS(e,oK.TrackMuted,oK.TrackUnmuted,oK.ParticipantPermissionsChanged,oK.TrackPublished,oK.TrackUnpublished,oK.LocalTrackPublished,oK.LocalTrackUnpublished,oK.MediaDevicesError,oK.TrackSubscriptionStatusChanged).pipe(a6(e=>{let{isMicrophoneEnabled:t,isCameraEnabled:i,isScreenShareEnabled:n}=e,r=e.getTrackPublication(nM.Source.Microphone);return{isCameraEnabled:i,isMicrophoneEnabled:t,isScreenShareEnabled:n,cameraTrack:e.getTrackPublication(nM.Source.Camera),microphoneTrack:r,participant:e}}))}function lw(e,t){return new aI(i=>{let n=(...e)=>{i.next(e)};return e.on(t,n),()=>{e.off(t,n)}})}function lE(e,t,i=!0){let n=[e.localParticipant,...Array.from(e.remoteParticipants.values())],r=[];return n.forEach(e=>{t.forEach(t=>{let n=Array.from(e.trackPublications.values()).filter(e=>e.source===t&&(!i||e.track)).map(t=>({participant:e,publication:t,source:t.source}));r.push(...n)})}),{trackReferences:r,participants:n}}function lP(e,t,i=!1){let{sources:n,kind:r,name:s}=t;return Array.from(e.trackPublications.values()).filter(e=>(!n||n.includes(e.source))&&(!r||e.kind===r)&&(!s||e.trackName===s)&&(!i||e.track)).map(t=>({participant:e,publication:t,source:t.source}))}function lx(e,t){return new aI(i=>{let n=(...e)=>{i.next(e)};return e.on(t,n),()=>{e.off(t,n)}})}lp.setDefaultLevel("WARN");var lR={videoEnabled:!0,audioEnabled:!0,videoDeviceId:"default",audioDeviceId:"default",username:""},{load:lO,save:lA}=function(e){return{load:()=>(function(e){if(typeof localStorage>"u"){lp.error("Local storage is not available.");return}try{let t=localStorage.getItem(e);if(!t){lp.warn(`Item with key ${e} does not exist in local storage.`);return}return JSON.parse(t)}catch(e){lp.error(`Error getting item from local storage: ${e}`);return}})(e),save:t=>(function(e,t){if(typeof localStorage>"u"){lp.error("Local storage is not available.");return}try{if(t){let i=Object.fromEntries(Object.entries(t).filter(([,e])=>""!==e));localStorage.setItem(e,JSON.stringify(i))}}catch(e){lp.error(`Error setting item to local storage: ${e}`)}})(e,t)}}("lk-user-choices");p.createContext(void 0);let lI=p.createContext(void 0);function lM(){return p.useContext(lI)}function lD(e){let t=lM(),i=e??t;if(!i)throw Error("No TrackRef, make sure you are inside a TrackRefContext or pass the TrackRef explicitly");return i}let l_=p.createContext(void 0);function lN(){return p.useContext(l_)}let lL=p.createContext(void 0);function lj(){let e=p.useContext(lL);if(!e)throw Error("tried to access room context outside of livekit room component");return e}function lU(){return p.useContext(lL)}function lF(e){let t=lU(),i=e??t;if(!i)throw Error("No room provided, make sure you are inside a Room context or pass the room explicitly");return i}function lV(){for(var e,t,i=0,n="",r=arguments.length;i<r;i++)(e=arguments[i])&&(t=function e(t){var i,n,r="";if("string"==typeof t||"number"==typeof t)r+=t;else if("object"==typeof t){if(Array.isArray(t)){var s=t.length;for(i=0;i<s;i++)t[i]&&(n=e(t[i]))&&(r&&(r+=" "),r+=n)}else for(n in t)t[n]&&(r&&(r+=" "),r+=n)}return r}(e))&&(n&&(n+=" "),n+=t);return n}function lB(...e){let t={...e[0]};for(let i=1;i<e.length;i++){let n=e[i];for(let e in n){let i=t[e],r=n[e];"function"==typeof i&&"function"==typeof r&&"o"===e[0]&&"n"===e[1]&&e.charCodeAt(2)>=65&&90>=e.charCodeAt(2)?t[e]=function(...e){return(...t)=>{for(let i of e)if("function"==typeof i)try{i(...t)}catch(e){console.error(e)}}}(i,r):("className"===e||"UNSAFE_className"===e)&&"string"==typeof i&&"string"==typeof r?t[e]=lV(i,r):t[e]=void 0!==r?r:i}}return t}function lq(e){return void 0!==e}function lW(...e){return lB(...e.filter(lq))}p.createContext(void 0);function lz(e,t,i=!0){let[n,r]=p.useState(t);return p.useEffect(()=>{if(i&&r(t),typeof window>"u"||!e)return;let n=e.subscribe(r);return()=>n.unsubscribe()},[e,i]),n}function lH(e){let t=lF(e);return lz(p.useMemo(()=>lb(t,o$.ConnectionStateChanged).pipe(a6(([e])=>e),a8(t.state)),[t]),t.state)}function lG(e={}){let t=lF(e.room),[i,n]=p.useState(t.localParticipant),[r,s]=p.useState(i.isMicrophoneEnabled),[o,a]=p.useState(i.isCameraEnabled),[l,c]=p.useState(i.isScreenShareEnabled),[d,u]=p.useState(i.lastMicrophoneError),[h,m]=p.useState(i.lastCameraError),[f,g]=p.useState(void 0),[v,y]=p.useState(void 0),b=e=>{a(e.isCameraEnabled),s(e.isMicrophoneEnabled),c(e.isScreenShareEnabled),y(e.cameraTrack),g(e.microphoneTrack),u(e.participant.lastMicrophoneError),m(e.participant.lastCameraError),n(e.participant)};return p.useEffect(()=>{let e=lC(t.localParticipant).subscribe(b);return()=>e.unsubscribe()},[t]),{isMicrophoneEnabled:r,isScreenShareEnabled:l,isCameraEnabled:o,microphoneTrack:f,cameraTrack:v,lastMicrophoneError:d,lastCameraError:h,localParticipant:i}}function l$(e={}){let t=lF(e.room),[i,n]=p.useState([]);return p.useEffect(()=>{let i=(function(e,t={}){var i;let n;let r=new aI(e=>(n=e,()=>o.unsubscribe())).pipe(a8(Array.from(e.remoteParticipants.values()))),s=null!=(i=t.additionalRoomEvents)?i:lu,o=ly(e,...Array.from(new Set([o$.ParticipantConnected,o$.ParticipantDisconnected,o$.ConnectionStateChanged,...s]))).subscribe(e=>null==n?void 0:n.next(Array.from(e.remoteParticipants.values())));return e.remoteParticipants.size>0&&(null==n||n.next(Array.from(e.remoteParticipants.values()))),r})(t,{additionalRoomEvents:e.updateOnlyOn}).subscribe(n);return()=>i.unsubscribe()},[t,JSON.stringify(e.updateOnlyOn)]),i}let lK=e=>{let t=e=>Math.sqrt(1- -1*Math.max(-100,Math.min(-10,e))/100);return e.map(e=>e===-1/0?0:t(e))},lJ={bands:5,loPass:100,hiPass:600,updateInterval:32,analyserOptions:{fftSize:2048}};function lX(e,t){let i=lN(),n=l$({updateOnlyOn:[]}),r=p.useMemo(()=>t?n.find(e=>e.identity===t):i,[t,n,i]);return lz(p.useMemo(()=>{if(r){var t;return t={sources:e},lS(r,...lh).pipe(a6(e=>{let i=lP(e,t);return lp.debug(`TrackReference[] was updated. (length ${i.length})`,i),i}),a8(lP(r,t)))}},[r,JSON.stringify(e)]),[])}let lY={bufferSize:100};function lQ(e,t){var i,n,r;let s={...lY,...t},[o,a]=p.useState([]),l=lz(p.useMemo(()=>{var t;return null!=(t=null==e?void 0:e.publication)&&t.track?lx(null==e?void 0:e.publication.track,oX.TimeSyncUpdate).pipe(a6(([e])=>e)):void 0},[null==(i=null==e?void 0:e.publication)?void 0:i.track]),{timestamp:Date.now(),rtpTimestamp:null==(r=null==(n=null==e?void 0:e.publication)?void 0:n.track)?void 0:r.rtpTimestamp}),c=e=>{var t;null==(t=s.onTranscription)||t.call(s,e),a(t=>{var i,n;return i=e.map(e=>{var t;return la(lo({},e),{receivedAtMediaTimestamp:null!=(t=l.rtpTimestamp)?t:0,receivedAt:l.timestamp})}),n=s.bufferSize,[...t,...i].reduceRight((e,t)=>(e.find(e=>e.id===t.id)||e.unshift(t),e),[]).slice(0-n)})};return p.useEffect(()=>{if(!(null!=e&&e.publication))return;let t=lx(e.publication,oX.TranscriptionReceived).subscribe(e=>{c(...e)});return()=>{t.unsubscribe()}},[e&&ld(e),c]),{segments:o}}let lZ="lk.agent.state";function l0(){let e=l$(),t=e.find(e=>e.kind===e0.AGENT&&!("lk.publish_on_behalf"in e.attributes)),i=e.find(e=>e.kind===e0.AGENT&&e.attributes["lk.publish_on_behalf"]===(null==t?void 0:t.identity)),n=lX([nM.Source.Microphone,nM.Source.Camera],null==t?void 0:t.identity),r=lX([nM.Source.Microphone,nM.Source.Camera],null==i?void 0:i.identity),s=n.find(e=>e.source===nM.Source.Microphone)??r.find(e=>e.source===nM.Source.Microphone),o=n.find(e=>e.source===nM.Source.Camera)??r.find(e=>e.source===nM.Source.Camera),{segments:a}=lQ(s),l=lH(),{attributes:c}=function(e={}){let t=lN(),i=e.participant??t;return lz(p.useMemo(()=>typeof i>"u"?new aI:lw(i,oK.AttributesChanged).pipe(a6(([e])=>({changed:e,attributes:i.attributes})),a8({changed:i.attributes,attributes:i.attributes})),[i]),{attributes:null==i?void 0:i.attributes})}({participant:t}),d=p.useMemo(()=>l===ae.Disconnected?"disconnected":l!==ae.Connecting&&t&&null!=c&&c[lZ]?c[lZ]:"connecting",[c,t,l]);return{agent:t,state:d,audioTrack:s,videoTrack:o,agentTranscriptions:a,agentAttributes:c}}function l1(){let e=function(){let{agentTranscriptions:e}=l0(),{segments:t}=lQ(function(){let{microphoneTrack:e,localParticipant:t}=lG();return(0,p.useMemo)(()=>({participant:t,source:nM.Source.Microphone,publication:e}),[t,e])}());return(0,p.useMemo)(()=>[...e.map(e=>({...e,role:"assistant"})),...t.map(e=>({...e,role:"user"}))].sort((e,t)=>e.firstReceivedTime-t.firstReceivedTime),[e,t])}(),t=p.useRef(null);return p.useEffect(()=>{t.current&&(t.current.scrollTop=t.current.scrollHeight)},[e]),(0,u.jsxs)("div",{className:"relative h-[200px] w-[512px] max-w-[90vw] mx-auto",children:[u.jsx("div",{className:"absolute top-0 left-0 right-0 h-8 bg-gradient-to-b from-[var(--lk-bg)] to-transparent z-10 pointer-events-none"}),u.jsx("div",{className:"absolute bottom-0 left-0 right-0 h-8 bg-gradient-to-t from-[var(--lk-bg)] to-transparent z-10 pointer-events-none"}),u.jsx("div",{ref:t,className:"h-full flex flex-col gap-2 overflow-y-auto px-4 py-8",children:e.map(e=>u.jsx("div",{id:e.id,className:"assistant"===e.role?"p-2 self-start fit-content":"bg-gray-800 rounded-md p-2 self-end fit-content",children:e.text},e.id))})]})}let l2=p.forwardRef(function(e,t){let{buttonProps:i}=function(e){let t=lj(),i=lH(t);return{buttonProps:p.useMemo(()=>{let{className:n,disconnect:r}={className:lg("disconnect-button"),disconnect:e=>{t.disconnect(e)}};return lB(e,{className:n,onClick:()=>r(e.stopTracks??!0),disabled:i===ae.Disconnected})},[t,e,i])}}(e);return p.createElement("button",{ref:t,...i},e.children)}),l3=e=>p.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:16,height:16,fill:"currentColor",...e},p.createElement("path",{d:"M1.354.646a.5.5 0 1 0-.708.708l14 14a.5.5 0 0 0 .708-.708L11 10.293V4.5A1.5 1.5 0 0 0 9.5 3H3.707zM0 4.5a1.5 1.5 0 0 1 .943-1.393l9.532 9.533c-.262.224-.603.36-.975.36h-8A1.5 1.5 0 0 1 0 11.5z"}),p.createElement("path",{d:"m15.2 3.6-2.8 2.1a1 1 0 0 0-.4.8v3a1 1 0 0 0 .4.8l2.8 2.1a.5.5 0 0 0 .8-.4V4a.5.5 0 0 0-.8-.4z"})),l5=e=>p.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:16,height:16,fill:"currentColor",...e},p.createElement("path",{d:"M0 4.5A1.5 1.5 0 0 1 1.5 3h8A1.5 1.5 0 0 1 11 4.5v7A1.5 1.5 0 0 1 9.5 13h-8A1.5 1.5 0 0 1 0 11.5zM15.2 3.6l-2.8 2.1a1 1 0 0 0-.4.8v3a1 1 0 0 0 .4.8l2.8 2.1a.5.5 0 0 0 .8-.4V4a.5.5 0 0 0-.8-.4z"})),l4=e=>p.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:16,height:16,fill:"currentColor",...e},p.createElement("path",{d:"M12.227 11.52a5.477 5.477 0 0 0 1.246-2.97.5.5 0 0 0-.995-.1 4.478 4.478 0 0 1-.962 2.359l-1.07-1.07C10.794 9.247 11 8.647 11 8V3a3 3 0 0 0-6 0v1.293L1.354.646a.5.5 0 1 0-.708.708l14 14a.5.5 0 0 0 .708-.708zM8 12.5c.683 0 1.33-.152 1.911-.425l.743.743c-.649.359-1.378.59-2.154.66V15h2a.5.5 0 0 1 0 1h-5a.5.5 0 0 1 0-1h2v-1.522a5.502 5.502 0 0 1-4.973-4.929.5.5 0 0 1 .995-.098A4.5 4.5 0 0 0 8 12.5z"}),p.createElement("path",{d:"M8.743 10.907 5 7.164V8a3 3 0 0 0 3.743 2.907z"})),l6=e=>p.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:16,height:16,fill:"currentColor",...e},p.createElement("path",{fillRule:"evenodd",d:"M2.975 8.002a.5.5 0 0 1 .547.449 4.5 4.5 0 0 0 8.956 0 .5.5 0 1 1 .995.098A5.502 5.502 0 0 1 8.5 13.478V15h2a.5.5 0 0 1 0 1h-5a.5.5 0 0 1 0-1h2v-1.522a5.502 5.502 0 0 1-4.973-4.929.5.5 0 0 1 .448-.547z",clipRule:"evenodd"}),p.createElement("path",{d:"M5 3a3 3 0 1 1 6 0v5a3 3 0 0 1-6 0z"})),l9=e=>p.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:20,height:16,fill:"none",...e},p.createElement("path",{fill:"currentColor",fillRule:"evenodd",d:"M0 2.75A2.75 2.75 0 0 1 2.75 0h14.5A2.75 2.75 0 0 1 20 2.75v10.5A2.75 2.75 0 0 1 17.25 16H2.75A2.75 2.75 0 0 1 0 13.25V2.75ZM2.75 1.5c-.69 0-1.25.56-1.25 1.25v10.5c0 .69.56 1.25 1.25 1.25h14.5c.69 0 1.25-.56 1.25-1.25V2.75c0-.69-.56-1.25-1.25-1.25H2.75Z",clipRule:"evenodd"}),p.createElement("path",{fill:"currentColor",fillRule:"evenodd",d:"M9.47 4.22a.75.75 0 0 1 1.06 0l2.25 2.25a.75.75 0 0 1-1.06 1.06l-.97-.97v4.69a.75.75 0 0 1-1.5 0V6.56l-.97.97a.75.75 0 0 1-1.06-1.06l2.25-2.25Z",clipRule:"evenodd"})),l8=e=>p.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:20,height:16,fill:"none",...e},p.createElement("g",{fill:"currentColor"},p.createElement("path",{d:"M7.28 4.22a.75.75 0 0 0-1.06 1.06L8.94 8l-2.72 2.72a.75.75 0 1 0 1.06 1.06L10 9.06l2.72 2.72a.75.75 0 1 0 1.06-1.06L11.06 8l2.72-2.72a.75.75 0 0 0-1.06-1.06L10 6.94z"}),p.createElement("path",{fillRule:"evenodd",d:"M2.75 0A2.75 2.75 0 0 0 0 2.75v10.5A2.75 2.75 0 0 0 2.75 16h14.5A2.75 2.75 0 0 0 20 13.25V2.75A2.75 2.75 0 0 0 17.25 0zM1.5 2.75c0-.69.56-1.25 1.25-1.25h14.5c.69 0 1.25.56 1.25 1.25v10.5c0 .69-.56 1.25-1.25 1.25H2.75c-.69 0-1.25-.56-1.25-1.25z",clipRule:"evenodd"}))),l7=p.forwardRef(function({kind:e,initialSelection:t,onActiveDeviceChange:i,onDeviceListChange:n,onDeviceSelectError:r,exactMatch:s,track:o,requestPermissions:a,onError:l,...c},d){let u=lU(),h=p.useRef("default"),m=p.useCallback(e=>{u&&u.emit(o$.MediaDevicesError,e),null==l||l(e)},[u,l]),{devices:f,activeDeviceId:g,setActiveMediaDevice:v,className:y}=function({kind:e,room:t,track:i,requestPermissions:n,onError:r}){let s=lU(),o=p.useMemo(()=>t??s??new sj,[t,s]),a=lz(p.useMemo(()=>(function(e,t,i=!0){return a9(new aI(n=>{sj.getLocalDevices(e,i).then(e=>{n.next(e),n.complete()}).catch(e=>{null==t||t(e),n.next([]),n.complete()})}),new aI(n=>{var r;let s=()=>ll(this,null,function*(){try{let t=yield sj.getLocalDevices(e,i);n.next(t)}catch(e){null==t||t(e)}});if("u">typeof window){if(!window.isSecureContext)throw Error("Accessing media devices is available only in secure contexts (HTTPS and localhost), in some or all supporting browsers. See: https://developer.mozilla.org/en-US/docs/Web/API/Navigator/mediaDevices");null==(r=null==navigator?void 0:navigator.mediaDevices)||r.addEventListener("devicechange",s)}return()=>{var e;null==(e=null==navigator?void 0:navigator.mediaDevices)||e.removeEventListener("devicechange",s)}}))})(e,r,n),[e,n,r]),[]),[l,c]=p.useState((null==o?void 0:o.getActiveDevice(e))??"default"),{className:d,activeDeviceObservable:u,setActiveMediaDevice:h}=p.useMemo(()=>(function(e,t,i){var n;let r=new aF(void 0),s=lb(t,o$.ActiveDeviceChanged).pipe((n=([t])=>t===e,aD(function(e,t){var i=0;e.subscribe(a_(t,function(e){return n.call(void 0,e,i++)&&t.next(e)}))})),a6(([e,t])=>(lp.debug("activeDeviceObservable | RoomEvent.ActiveDeviceChanged",{kind:e,deviceId:t}),t)));return{className:lg("media-device-select"),activeDeviceObservable:s,setActiveMediaDevice:(i,...n)=>ll(this,[i,...n],function*(i,n={}){var s,o,a;if(t){let l;lp.debug(`Switching active device of kind "${e}" with id ${i}.`),yield t.switchActiveDevice(e,i,n.exact);let c=null!=(s=t.getActiveDevice(e))?s:i;c!==i&&"default"!==i&&lp.info(`We tried to select the device with id (${i}), but the browser decided to select the device with id (${c}) instead.`),"audioinput"===e?l=null==(o=t.localParticipant.getTrackPublication(nM.Source.Microphone))?void 0:o.track:"videoinput"===e&&(l=null==(a=t.localParticipant.getTrackPublication(nM.Source.Camera))?void 0:a.track);let d="default"===i&&!l||"default"===i&&(null==l?void 0:l.mediaStreamTrack.label.startsWith("Default"));r.next(d?i:c)}})}})(e,o),[e,o,i]);return p.useEffect(()=>{let e=u.subscribe(e=>{e&&(lp.info("setCurrentDeviceId",e),c(e))});return()=>{null==e||e.unsubscribe()}},[u]),{devices:a,className:d,activeDeviceId:l,setActiveMediaDevice:h}}({kind:e,room:u,track:o,requestPermissions:a,onError:m});p.useEffect(()=>{void 0!==t&&v(t)},[v]),p.useEffect(()=>{"function"==typeof n&&n(f)},[n,f]),p.useEffect(()=>{g!==h.current&&(null==i||i(g)),h.current=g},[g]);let b=async e=>{try{await v(e,{exact:s??!0})}catch(e){if(e instanceof Error)null==r||r(e);else throw e}},k=p.useMemo(()=>lW(c,{className:y},{className:"lk-list"}),[y,c]),T=!!f.find(e=>e.label.toLowerCase().startsWith("default"));function S(e,t,i){return e===t||!T&&0===i&&"default"===t}return p.createElement("ul",{ref:d,...k},f.map((e,t)=>p.createElement("li",{key:e.deviceId,id:e.deviceId,"data-lk-active":S(e.deviceId,g,t),"aria-selected":S(e.deviceId,g,t),role:"option"},p.createElement("button",{className:"lk-button",onClick:()=>b(e.deviceId)},e.label))))}),ce=p.forwardRef(function({label:e,...t},i){let n=lj(),{mergedProps:r,canPlayAudio:s}=function({room:e,props:t}){let i=lF(e),{className:n,roomAudioPlaybackAllowedObservable:r,handleStartAudioPlayback:s}=p.useMemo(()=>(function(){return{className:lg("start-audio-button"),roomAudioPlaybackAllowedObservable:lk,handleStartAudioPlayback:e=>ll(this,null,function*(){lp.info("Start Audio for room: ",e),yield e.startAudio()})}})(),[]),{canPlayAudio:o}=lz(p.useMemo(()=>r(i),[i,r]),{canPlayAudio:i.canPlaybackAudio});return{mergedProps:p.useMemo(()=>lB(t,{className:n,onClick:()=>{s(i)},style:{display:o?"none":"block"}}),[t,n,o,s,i]),canPlayAudio:o}}({room:n,props:t}),{mergedProps:o,canPlayVideo:a}=function({room:e,props:t}){let i=lF(e),{className:n,roomVideoPlaybackAllowedObservable:r,handleStartVideoPlayback:s}=p.useMemo(()=>(function(){return{className:lg("start-audio-button"),roomVideoPlaybackAllowedObservable:lT,handleStartVideoPlayback:e=>ll(this,null,function*(){lp.info("Start Video for room: ",e),yield e.startVideo()})}})(),[]),{canPlayVideo:o}=lz(p.useMemo(()=>r(i),[i,r]),{canPlayVideo:i.canPlaybackVideo});return{mergedProps:p.useMemo(()=>lB(t,{className:n,onClick:()=>{s(i)},style:{display:o?"none":"block"}}),[t,n,o,s,i]),canPlayVideo:o}}({room:n,props:r}),{style:l,...c}=o;return l.display=s&&a?"none":"block",p.createElement("button",{ref:i,style:l,...c},e??`Start ${s?"Video":"Audio"}`)}),ct=p.forwardRef(function({showIcon:e,...t},i){let{buttonProps:n,enabled:r}=function({source:e,onChange:t,initialState:i,captureOptions:n,publishOptions:r,onDeviceError:s,...o}){var a;let l=lU(),c=null==(a=null==l?void 0:l.localParticipant)?void 0:a.getTrackPublication(e),d=p.useRef(!1),{toggle:u,className:h,pendingObserver:m,enabledObserver:f}=p.useMemo(()=>l?function(e,t,i,n,r){let{localParticipant:s}=t,o=(e,t)=>{let i=!1;switch(e){case nM.Source.Camera:i=t.isCameraEnabled;break;case nM.Source.Microphone:i=t.isMicrophoneEnabled;break;case nM.Source.ScreenShare:i=t.isScreenShareEnabled}return i},a=lC(s).pipe(a6(t=>o(e,t.participant)),a8(o(e,s))),l=new aj;return{className:lg("button"),toggle:(t,o)=>ll(this,null,function*(){try{switch(o??(o=i),l.next(!0),e){case nM.Source.Camera:return yield s.setCameraEnabled(t??!s.isCameraEnabled,o,n),s.isCameraEnabled;case nM.Source.Microphone:return yield s.setMicrophoneEnabled(t??!s.isMicrophoneEnabled,o,n),s.isMicrophoneEnabled;case nM.Source.ScreenShare:return yield s.setScreenShareEnabled(t??!s.isScreenShareEnabled,o,n),s.isScreenShareEnabled;default:throw TypeError("Tried to toggle unsupported source")}}catch(e){if(r&&e instanceof Error){null==r||r(e);return}throw e}finally{l.next(!1)}}),enabledObserver:a,pendingObserver:l.asObservable()}}(e,l,n,r,s):function(){let e=!1,t=new aj,i=new aj;return{className:lg("button"),toggle:n=>ll(this,null,function*(){i.next(!0),e=n??!e,t.next(e),i.next(!1)}),enabledObserver:t.asObservable(),pendingObserver:i.asObservable()}}(),[l,e,JSON.stringify(n),r]),g=lz(m,!1),v=lz(f,i??!!(null!=c&&c.isEnabled));p.useEffect(()=>{null==t||t(v,d.current),d.current=!1},[v,t]),p.useEffect(()=>{void 0!==i&&(lp.debug("forcing initial toggle state",e,i),u(i))},[]);let y=p.useMemo(()=>lB(o,{className:h}),[o,h]),b=p.useCallback(e=>{var t;d.current=!0,u().catch(()=>d.current=!1),null==(t=o.onClick)||t.call(o,e)},[o,u]);return{toggle:u,enabled:v,pending:g,track:c,buttonProps:{...y,"aria-pressed":v,"data-lk-source":e,"data-lk-enabled":v,disabled:g,onClick:b}}}(t),[s,o]=p.useState(!1);return p.useEffect(()=>{o(!0)},[]),s&&p.createElement("button",{ref:i,...n},(e??!0)&&function(e,t){switch(e){case nM.Source.Microphone:return t?p.createElement(l6,null):p.createElement(l4,null);case nM.Source.Camera:return t?p.createElement(l5,null):p.createElement(l3,null);case nM.Source.ScreenShare:return t?p.createElement(l8,null):p.createElement(l9,null);default:return}}(t.source,r),t.children)});function ci(e,t={}){let[i,n]=p.useState(lv(e)),[r,s]=p.useState(null==i?void 0:i.isMuted),[o,a]=p.useState(null==i?void 0:i.isSubscribed),[l,c]=p.useState(null==i?void 0:i.track),[d,u]=p.useState("landscape"),h=p.useRef(),{className:m,trackObserver:f}=p.useMemo(()=>(function(e){let t=lv(e),i=lC(e.participant).pipe(a6(()=>lv(e)),a8(t));return{className:lg(e.source===nM.Source.Camera||e.source===nM.Source.ScreenShare?"participant-media-video":"participant-media-audio"),trackObserver:i}})(e),[e.participant.sid??e.participant.identity,e.source,lc(e)&&e.publication.trackSid]);return p.useEffect(()=>{let e=f.subscribe(e=>{lp.debug("update track",e),n(e),s(null==e?void 0:e.isMuted),a(null==e?void 0:e.isSubscribed),c(null==e?void 0:e.track)});return()=>null==e?void 0:e.unsubscribe()},[f]),p.useEffect(()=>{var i,n;return l&&(h.current&&l.detach(h.current),null!=(i=t.element)&&i.current&&!(e.participant.isLocal&&(null==l?void 0:l.kind)==="audio")&&l.attach(t.element.current)),h.current=null==(n=t.element)?void 0:n.current,()=>{h.current&&(null==l||l.detach(h.current))}},[l,t.element]),p.useEffect(()=>{var e,t;"number"==typeof(null==(e=null==i?void 0:i.dimensions)?void 0:e.width)&&"number"==typeof(null==(t=null==i?void 0:i.dimensions)?void 0:t.height)&&u(i.dimensions.width>i.dimensions.height?"landscape":"portrait")},[i]),{publication:i,isMuted:r,isSubscribed:o,track:l,elementProps:lW(t.props,{className:m,"data-lk-local-participant":e.participant.isLocal,"data-lk-source":null==i?void 0:i.source,...(null==i?void 0:i.kind)==="video"&&{"data-lk-orientation":d}})}}let cn=oO(function(){if(d)return c;d=1;var e=NaN,t=/^\s+|\s+$/g,i=/^[-+]0x[0-9a-f]+$/i,n=/^0b[01]+$/i,r=/^0o[0-7]+$/i,s=parseInt,o="object"==typeof oR&&oR&&oR.Object===Object&&oR,a="object"==typeof self&&self&&self.Object===Object&&self,l=o||a||Function("return this")(),u=Object.prototype.toString,h=Math.max,p=Math.min,m=function(){return l.Date.now()};function f(e){var t=typeof e;return!!e&&("object"==t||"function"==t)}function g(o){if("number"==typeof o)return o;if("symbol"==typeof(a=o)||a&&"object"==typeof a&&"[object Symbol]"==u.call(a))return e;if(f(o)){var a,l="function"==typeof o.valueOf?o.valueOf():o;o=f(l)?l+"":l}if("string"!=typeof o)return 0===o?o:+o;o=o.replace(t,"");var c=n.test(o);return c||r.test(o)?s(o.slice(2),c?2:8):i.test(o)?e:+o}return c=function(e,t,i){var n,r,s,o,a,l,c=0,d=!1,u=!1,v=!0;if("function"!=typeof e)throw TypeError("Expected a function");function y(t){var i=n,s=r;return n=r=void 0,c=t,o=e.apply(s,i)}function b(e){var i=e-l,n=e-c;return void 0===l||i>=t||i<0||u&&n>=s}function k(){var e,i,n,r=m();if(b(r))return T(r);a=setTimeout(k,(e=r-l,i=r-c,n=t-e,u?p(n,s-i):n))}function T(e){return a=void 0,v&&n?y(e):(n=r=void 0,o)}function S(){var e,i=m(),s=b(i);if(n=arguments,r=this,l=i,s){if(void 0===a)return c=e=l,a=setTimeout(k,t),d?y(e):o;if(u)return a=setTimeout(k,t),y(l)}return void 0===a&&(a=setTimeout(k,t)),o}return t=g(t)||0,f(i)&&(d=!!i.leading,s=(u="maxWait"in i)?h(g(i.maxWait)||0,t):s,v="trailing"in i?!!i.trailing:v),S.cancel=function(){void 0!==a&&clearTimeout(a),c=0,n=l=r=a=void 0},S.flush=function(){return void 0===a?o:T(m())},S}}()),cr=p.forwardRef(function({onTrackClick:e,onClick:t,onSubscriptionStatusChanged:i,trackRef:n,manageSubscription:r,...s},o){let a=lD(n),l=p.useRef(null);p.useImperativeHandle(o,()=>l.current);let c=function({threshold:e=0,root:t=null,rootMargin:i="0%",freezeOnceVisible:n=!1,initialIsIntersecting:r=!1,onChange:s}={}){var o;let[a,l]=(0,p.useState)(null),[c,d]=(0,p.useState)(()=>({isIntersecting:r,entry:void 0})),u=(0,p.useRef)();u.current=s;let h=(null==(o=c.entry)?void 0:o.isIntersecting)&&n;(0,p.useEffect)(()=>{if(!a||!("IntersectionObserver"in window)||h)return;let n=new IntersectionObserver(e=>{let t=Array.isArray(n.thresholds)?n.thresholds:[n.thresholds];e.forEach(e=>{let i=e.isIntersecting&&t.some(t=>e.intersectionRatio>=t);d({isIntersecting:i,entry:e}),u.current&&u.current(i,e)})},{threshold:e,root:t,rootMargin:i});return n.observe(a),()=>{n.disconnect()}},[a,JSON.stringify(e),t,i,h,n]);let m=(0,p.useRef)(null);(0,p.useEffect)(()=>{var e;a||null==(e=c.entry)||!e.target||n||h||m.current===c.entry.target||(m.current=c.entry.target,d({isIntersecting:r,entry:void 0}))},[a,c.entry,n,h,r]);let f=[l,!!c.isIntersecting,c.entry];return f.ref=f[0],f.isIntersecting=f[1],f.entry=f[2],f}({root:l.current}),[d]=function(e,t,i){let n=e instanceof Function?e():e,[r,s]=(0,p.useState)(n),o=(0,p.useRef)(n),a=function(e,t=500,i){let n=(0,p.useRef)();!function(e){let t=(0,p.useRef)(e);t.current=e,(0,p.useEffect)(()=>()=>{t.current()},[])}(()=>{n.current&&n.current.cancel()});let r=(0,p.useMemo)(()=>{let r=cn(e,t,i),s=(...e)=>r(...e);return s.cancel=()=>{r.cancel()},s.isPending=()=>!!n.current,s.flush=()=>r.flush(),s},[e,t,i]);return(0,p.useEffect)(()=>{n.current=cn(e,t,i)},[e,t,i]),r}(s,3e3,void 0);return o.current===n||(a(n),o.current=n),[r,a]}(c,0);p.useEffect(()=>{r&&a.publication instanceof sN&&(null==d?void 0:d.isIntersecting)===!1&&(null==c?void 0:c.isIntersecting)===!1&&a.publication.setSubscribed(!1)},[d,a,r]),p.useEffect(()=>{r&&a.publication instanceof sN&&(null==c?void 0:c.isIntersecting)===!0&&a.publication.setSubscribed(!0)},[c,a,r]);let{elementProps:u,publication:h,isSubscribed:m}=ci(a,{element:l,props:s});return p.useEffect(()=>{null==i||i(!!m)},[m,i]),p.createElement("video",{ref:l,...u,muted:!0,onClick:i=>{null==t||t(i),null==e||e({participant:null==a?void 0:a.participant,track:h})}})}),cs=p.forwardRef(function({trackRef:e,onSubscriptionStatusChanged:t,volume:i,...n},r){let s=lD(e),o=p.useRef(null);p.useImperativeHandle(r,()=>o.current);let{elementProps:a,isSubscribed:l,track:c,publication:d}=ci(s,{element:o,props:n});return p.useEffect(()=>{null==t||t(!!l)},[l,t]),p.useEffect(()=>{void 0===c||void 0===i||(c instanceof sP?c.setVolume(i):lp.warn("Volume can only be set on remote audio tracks."))},[i,c]),p.useEffect(()=>{void 0===d||void 0===n.muted||(d instanceof sN?d.setEnabled(!n.muted):lp.warn("Can only call setEnabled on remote track publications."))},[n.muted,d,c]),p.createElement("audio",{ref:o,...a})});function co({volume:e,muted:t}){let i=(function(e=[nM.Source.Camera,nM.Source.Microphone,nM.Source.ScreenShare,nM.Source.ScreenShareAudio,nM.Source.Unknown],t={}){let i=lF(t.room),[n,r]=p.useState([]),[s,o]=p.useState([]),a=p.useMemo(()=>e.map(e=>lm(e)?e.source:e),[JSON.stringify(e)]);return p.useEffect(()=>{let e=(function(e,t,i){var n,r;let s=null!=(n=i.additionalRoomEvents)?n:lu,o=null==(r=i.onlySubscribed)||r;return ly(e,...Array.from(new Set([o$.ParticipantConnected,o$.ParticipantDisconnected,o$.ConnectionStateChanged,o$.LocalTrackPublished,o$.LocalTrackUnpublished,o$.TrackPublished,o$.TrackUnpublished,o$.TrackSubscriptionStatusChanged,...s]).values())).pipe(a6(e=>{let i=lE(e,t,o);return lp.debug(`TrackReference[] was updated. (length ${i.trackReferences.length})`,i),i}),a8(lE(e,t,o)))})(i,a,{additionalRoomEvents:t.updateOnlyOn,onlySubscribed:t.onlySubscribed}).subscribe(({trackReferences:e,participants:t})=>{lp.debug("setting track bundles",e,t),r(e),o(t)});return()=>e.unsubscribe()},[i,JSON.stringify(t.onlySubscribed),JSON.stringify(t.updateOnlyOn),JSON.stringify(e)]),p.useMemo(()=>{if(!lf(e))return n;{let t=function(e,t){let i=new Map;if(lf(e)){let n=e.filter(e=>e.withPlaceholder).map(e=>e.source);t.forEach(e=>{let t=e.getTrackPublications().map(e=>{var t;return null==(t=e.track)?void 0:t.source}).filter(e=>void 0!==e),r=Array.from(function(e,t){let i=new Set(e);for(let e of t)i.delete(e);return i}(new Set(n),new Set(t)));r.length>0&&i.set(e.identity,r)})}return i}(e,s),i=Array.from(n);return s.forEach(e=>{t.has(e.identity)&&(t.get(e.identity)??[]).forEach(t=>{n.find(({participant:i,publication:n})=>e.identity===i.identity&&n.source===t)||(lp.debug(`Add ${t} placeholder for participant ${e.identity}.`),i.push({participant:e,source:t}))})}),i}},[n,s,e])})([nM.Source.Microphone,nM.Source.ScreenShareAudio,nM.Source.Unknown],{updateOnlyOn:[],onlySubscribed:!0}).filter(e=>!e.participant.isLocal&&e.publication.kind===nM.Kind.Audio);return p.createElement("div",{style:{display:"none"}},i.map(i=>p.createElement(cs,{key:ld(i),trackRef:i,volume:e,muted:t})))}let ca=e=>{let t=[];for(let i=0;i<e;i++)t.push([i,e-1-i]);return t},cl=e=>[[Math.floor(e/2)],[-1]],cc=(e,t,i)=>{let[n,r]=(0,p.useState)(0),[s,o]=(0,p.useState)([[]]);(0,p.useEffect)(()=>{"thinking"===e?o(cl(t)):"connecting"===e||"initializing"===e?o([...ca(t)]):o("listening"===e?cl(t):void 0===e||"speaking"===e?[Array(t).fill(0).map((e,t)=>t)]:[[]]),r(0)},[e,t]);let a=(0,p.useRef)(null);return(0,p.useEffect)(()=>{let e=performance.now(),t=n=>{n-e>=i&&(r(e=>e+1),e=n),a.current=requestAnimationFrame(t)};return a.current=requestAnimationFrame(t),()=>{null!==a.current&&cancelAnimationFrame(a.current)}},[i,t,e,s.length]),s[n%s.length]},cd=new Map([["connecting",2e3],["initializing",2e3],["listening",500],["thinking",150]]),cu=(e,t)=>{if(void 0===e)return 1e3;let i=cd.get(e);return i&&"connecting"===e&&(i/=t),i},ch=p.forwardRef(function({state:e,options:t,barCount:i=15,trackRef:n,children:r,...s},o){let a=lW(s,{className:"lk-audio-bar-visualizer"}),l=lM();n&&(l=n);let c=function(e,t={}){var i;let n=e instanceof nM?e:null==(i=null==e?void 0:e.publication)?void 0:i.track,r={...lJ,...t},[s,o]=p.useState(Array(r.bands).fill(0));return p.useEffect(()=>{if(!n||!(null!=n&&n.mediaStream))return;let{analyser:e,cleanup:i}=function(e,t){let i=Object.assign({cloneTrack:!1,fftSize:2048,smoothingTimeConstant:.8,minDecibels:-100,maxDecibels:-80},t),n=ry();if(!n)throw Error("Audio Context not supported on this browser");let r=i.cloneTrack?e.mediaStreamTrack.clone():e.mediaStreamTrack,s=n.createMediaStreamSource(new MediaStream([r])),o=n.createAnalyser();o.minDecibels=i.minDecibels,o.maxDecibels=i.maxDecibels,o.fftSize=i.fftSize,o.smoothingTimeConstant=i.smoothingTimeConstant,s.connect(o);let a=new Uint8Array(o.frequencyBinCount);return{calculateVolume:()=>{o.getByteFrequencyData(a);let e=0;for(let t of a)e+=Math.pow(t/255,2);return Math.sqrt(e/a.length)},analyser:o,cleanup:()=>ib(this,void 0,void 0,function*(){yield n.close(),i.cloneTrack&&r.stop()})}}(n,r.analyserOptions),s=new Float32Array(e.frequencyBinCount),a=setInterval(()=>{e.getFloatFrequencyData(s);let i=new Float32Array(s.length);for(let e=0;e<s.length;e++)i[e]=s[e];let n=lK(i=i.slice(t.loPass,t.hiPass)),a=Math.ceil(n.length/r.bands),l=[];for(let e=0;e<r.bands;e++){let t=n.slice(e*a,(e+1)*a).reduce((e,t)=>e+=t,0);l.push(t/a)}o(l)},r.updateInterval);return()=>{i(),clearInterval(a)}},[n,null==n?void 0:n.mediaStream,JSON.stringify(t)]),s}(l,{bands:i,loPass:100,hiPass:200}),d=(null==t?void 0:t.minHeight)??20,u=(null==t?void 0:t.maxHeight)??100,h=cc(e,i,cu(e,i)??100);return p.createElement("div",{ref:o,...a,"data-lk-va-state":e},c.map((e,t)=>{var i;return r?(i={"data-lk-highlighted":h.includes(t),"data-lk-bar-index":t,className:"lk-audio-bar",style:{height:`${Math.min(u,Math.max(d,100*e+5))}%`}},p.Children.map(r,e=>p.isValidElement(e)&&p.Children.only(r)?(e.props.className&&(i??(i={}),i.className=lV(e.props.className,i.className),i.style={...e.props.style,...i.style}),p.cloneElement(e,{...i,key:void 0})):e)):p.createElement("span",{key:t,"data-lk-highlighted":h.includes(t),"data-lk-bar-index":t,className:`lk-audio-bar ${h.includes(t)&&"lk-highlighted"}`,style:{height:`${Math.min(u,Math.max(d,100*e+5))}%`}})}))});function cp({kind:e,initialSelection:t,onActiveDeviceChange:i,tracks:n,requestPermissions:r=!1,...s}){let[o,a]=p.useState(!1),[l,c]=p.useState([]),[d,u]=p.useState(!0),[h,m]=p.useState(r),f=(e,t)=>{lp.debug("handle device change"),a(!1),null==i||i(e,t)},g=p.useRef(null),v=p.useRef(null);p.useLayoutEffect(()=>{o&&m(!0)},[o]),p.useLayoutEffect(()=>{let e;return g.current&&v.current&&(l||d)&&(e=function(e,t,i){return function(e,t,i,n){void 0===n&&(n={});let{ancestorScroll:r=!0,ancestorResize:s=!0,elementResize:o="function"==typeof ResizeObserver,layoutShift:a="function"==typeof IntersectionObserver,animationFrame:l=!1}=n,c=op(e),d=r||s?[...c?od(c):[],...od(t)]:[];d.forEach(e=>{r&&e.addEventListener("scroll",i,{passive:!0}),s&&e.addEventListener("resize",i)});let u=c&&a?function(e,t){let i=null,n,r=s9(e);function s(){var e;clearTimeout(n),null==(e=i)||e.disconnect(),i=null}return function o(a,l){void 0===a&&(a=!1),void 0===l&&(l=1),s();let c=e.getBoundingClientRect(),{left:d,top:u,width:h,height:p}=c;if(a||t(),!h||!p)return;let m=sB(u),f={rootMargin:-m+"px "+-sB(r.clientWidth-(d+h))+"px "+-sB(r.clientHeight-(u+p))+"px "+-sB(d)+"px",threshold:sF(0,sU(1,l))||1},g=!0;function v(t){let i=t[0].intersectionRatio;if(i!==l){if(!g)return o();i?o(!1,i):n=setTimeout(()=>{o(!1,1e-7)},1e3)}1!==i||oP(c,e.getBoundingClientRect())||o(),g=!1}try{i=new IntersectionObserver(v,{...f,root:r.ownerDocument})}catch{i=new IntersectionObserver(v,f)}i.observe(e)}(!0),s}(c,i):null,h=-1,p=null;o&&(p=new ResizeObserver(e=>{let[n]=e;n&&n.target===c&&p&&(p.unobserve(t),cancelAnimationFrame(h),h=requestAnimationFrame(()=>{var e;null==(e=p)||e.observe(t)})),i()}),c&&!l&&p.observe(c),p.observe(t));let m,f=l?ov(e):null;return l&&function t(){let n=ov(e);f&&!oP(f,n)&&i(),f=n,m=requestAnimationFrame(t)}(),i(),()=>{var e;d.forEach(e=>{r&&e.removeEventListener("scroll",i),s&&e.removeEventListener("resize",i)}),null==u||u(),null==(e=p)||e.disconnect(),p=null,l&&cancelAnimationFrame(m)}}(e,t,()=>ll(this,null,function*(){var n,r;let{x:s,y:o}=yield ox(e,t,{placement:"top",middleware:[{name:"offset",options:6,async fn(e){var t,i;let{x:n,y:r,placement:s,middlewareData:o}=e,a=await s3(e,6);return s===(null==(t=o.offset)?void 0:t.placement)&&null!=(i=o.arrow)&&i.alignmentOffset?{}:{x:n+a.x,y:r+a.y,data:{...a,placement:s}}}},(void 0===n&&(n={}),{name:"flip",options:n,async fn(e){var t,i,r,s,o;let{placement:a,middlewareData:l,rects:c,initialPlacement:d,platform:u,elements:h}=e,{mainAxis:p=!0,crossAxis:m=!0,fallbackPlacements:f,fallbackStrategy:g="bestFit",fallbackAxisSideDirection:v="none",flipAlignment:y=!0,...b}=sH(n,e);if(null!=(t=l.arrow)&&t.alignmentOffset)return{};let k=sG(a),T=sX(d),S=sG(d)===d,C=await (null==u.isRTL?void 0:u.isRTL(h.floating)),w=f||(S||!y?[sQ(d)]:function(e){let t=sQ(e);return[sY(e),t,sY(t)]}(d)),E="none"!==v;!f&&E&&w.push(...function(e,t,i,n){let r=s$(e),s=function(e,t,i){let n=["left","right"],r=["right","left"];switch(e){case"top":case"bottom":return i?t?r:n:t?n:r;case"left":case"right":return t?["top","bottom"]:["bottom","top"];default:return[]}}(sG(e),"start"===i,n);return r&&(s=s.map(e=>e+"-"+r),t&&(s=s.concat(s.map(sY)))),s}(d,y,v,C));let P=[d,...w],x=await s2(e,b),R=[],O=(null==(i=l.flip)?void 0:i.overflows)||[];if(p&&R.push(x[k]),m){let e=function(e,t,i){void 0===i&&(i=!1);let n=s$(e),r=sK(sX(e)),s=sJ(r),o="x"===r?n===(i?"end":"start")?"right":"left":"start"===n?"bottom":"top";return t.reference[s]>t.floating[s]&&(o=sQ(o)),[o,sQ(o)]}(a,c,C);R.push(x[e[0]],x[e[1]])}if(O=[...O,{placement:a,overflows:R}],!R.every(e=>e<=0)){let e=((null==(r=l.flip)?void 0:r.index)||0)+1,t=P[e];if(t)return{data:{index:e,overflows:O},reset:{placement:t}};let i=null==(s=O.filter(e=>e.overflows[0]<=0).sort((e,t)=>e.overflows[1]-t.overflows[1])[0])?void 0:s.placement;if(!i)switch(g){case"bestFit":{let e=null==(o=O.filter(e=>{if(E){let t=sX(e.placement);return t===T||"y"===t}return!0}).map(e=>[e.placement,e.overflows.filter(e=>e>0).reduce((e,t)=>e+t,0)]).sort((e,t)=>e[1]-t[1])[0])?void 0:o[0];e&&(i=e);break}case"initialPlacement":i=d}if(a!==i)return{reset:{placement:i}}}return{}}}),{name:"shift",options:r={padding:5},async fn(e){let{x:t,y:i,placement:n}=e,{mainAxis:s=!0,crossAxis:o=!1,limiter:a={fn:e=>{let{x:t,y:i}=e;return{x:t,y:i}}},...l}=sH(r,e),c={x:t,y:i},d=await s2(e,l),u=sX(sG(n)),h=sK(u),p=c[h],m=c[u];if(s){let e="y"===h?"top":"left",t="y"===h?"bottom":"right",i=p+d[e],n=p-d[t];p=sF(i,sU(p,n))}if(o){let e="y"===u?"top":"left",t="y"===u?"bottom":"right",i=m+d[e],n=m-d[t];m=sF(i,sU(m,n))}let f=a.fn({...e,[h]:p,[u]:m});return{...f,data:{x:f.x-t,y:f.y-i,enabled:{[h]:s,[u]:o}}}}}]});null==i||i(s,o)}))}(g.current,v.current,(e,t)=>{v.current&&Object.assign(v.current.style,{left:`${e}px`,top:`${t}px`})})),u(!1),()=>{null==e||e()}},[g,v,l,d]);let y=p.useCallback(e=>{v.current&&e.target!==g.current&&o&&!v.current.contains(e.target)&&a(!1)},[o,v,g]);return p.useEffect(()=>(document.addEventListener("click",y),()=>{document.removeEventListener("click",y)}),[y]),p.createElement(p.Fragment,null,p.createElement("button",{className:"lk-button lk-button-menu","aria-pressed":o,...s,onClick:()=>a(!o),ref:g},s.children),!s.disabled&&p.createElement("div",{className:"lk-device-menu",ref:v,style:{visibility:o?"visible":"hidden"}},e?p.createElement(l7,{initialSelection:t,onActiveDeviceChange:t=>f(e,t),onDeviceListChange:c,kind:e,track:null==n?void 0:n[e],requestPermissions:h}):p.createElement(p.Fragment,null,p.createElement("div",{className:"lk-device-menu-heading"},"Audio inputs"),p.createElement(l7,{kind:"audioinput",onActiveDeviceChange:e=>f("audioinput",e),onDeviceListChange:c,track:null==n?void 0:n.audioinput,requestPermissions:h}),p.createElement("div",{className:"lk-device-menu-heading"},"Video inputs"),p.createElement(l7,{kind:"videoinput",onActiveDeviceChange:e=>f("videoinput",e),onDeviceListChange:c,track:null==n?void 0:n.videoinput,requestPermissions:h}))))}function cm({controls:e,saveUserChoices:t=!0,onDeviceError:i,...n}){let r={leave:!0,microphone:!0,...e},s=function(){let e=lj();return lz(p.useMemo(()=>{var t;return lw(t=e.localParticipant,oK.ParticipantPermissionsChanged).pipe(a6(()=>t.permissions),a8(t.permissions))},[e]),e.localParticipant.permissions)}(),{microphoneTrack:o,localParticipant:a}=lG(),l=p.useMemo(()=>({participant:a,source:nM.Source.Microphone,publication:o}),[a,o]);s?r.microphone??(r.microphone=s.canPublish):r.microphone=!1;let c=lW({className:"lk-agent-control-bar"},n),{saveAudioInputEnabled:d,saveAudioInputDeviceId:u}=function(e={}){let[t,i]=p.useState(function(e,t=!1){var i,n,r,s,o;let a={videoEnabled:null!=(i=null==e?void 0:e.videoEnabled)?i:lR.videoEnabled,audioEnabled:null!=(n=null==e?void 0:e.audioEnabled)?n:lR.audioEnabled,videoDeviceId:null!=(r=null==e?void 0:e.videoDeviceId)?r:lR.videoDeviceId,audioDeviceId:null!=(s=null==e?void 0:e.audioDeviceId)?s:lR.audioDeviceId,username:null!=(o=null==e?void 0:e.username)?o:lR.username};if(t)return a;{let e=lO();return lo(lo({},a),e??{})}}(e.defaults,e.preventLoad??!1)),n=p.useCallback(e=>{i(t=>({...t,audioEnabled:e}))},[]),r=p.useCallback(e=>{i(t=>({...t,videoEnabled:e}))},[]),s=p.useCallback(e=>{i(t=>({...t,audioDeviceId:e}))},[]),o=p.useCallback(e=>{i(t=>({...t,videoDeviceId:e}))},[]),a=p.useCallback(e=>{i(t=>({...t,username:e}))},[]);return p.useEffect(()=>{(function(e,t=!1){!0!==t&&lA(e)})(t,e.preventSave??!1)},[t,e.preventSave]),{userChoices:t,saveAudioInputEnabled:n,saveVideoInputEnabled:r,saveAudioInputDeviceId:s,saveVideoInputDeviceId:o,saveUsername:a}}({preventSave:!t}),h=p.useCallback((e,t)=>{t&&d(e)},[d]);return p.createElement("div",{...c},r.microphone&&p.createElement("div",{className:"lk-button-group"},p.createElement(ct,{source:nM.Source.Microphone,showIcon:!0,onChange:h,onDeviceError:e=>null==i?void 0:i({source:nM.Source.Microphone,error:e})},p.createElement(ch,{trackRef:l,barCount:7,options:{minHeight:5}})),p.createElement("div",{className:"lk-button-group-menu"},p.createElement(cp,{kind:"audioinput",onActiveDeviceChange:(e,t)=>u(t??"default")}))),r.leave&&p.createElement(l2,null,"Disconnect"),p.createElement(ce,null))}let cf=(0,p.createContext)({});function cg(e){let t=(0,p.useRef)(null);return null===t.current&&(t.current=e()),t.current}let cv=(0,p.createContext)(null),cy=(0,p.createContext)({transformPagePoint:e=>e,isStatic:!1,reducedMotion:"never"});class cb extends p.Component{getSnapshotBeforeUpdate(e){let t=this.props.childRef.current;if(t&&e.isPresent&&!this.props.isPresent){let e=this.props.sizeRef.current;e.height=t.offsetHeight||0,e.width=t.offsetWidth||0,e.top=t.offsetTop,e.left=t.offsetLeft}return null}componentDidUpdate(){}render(){return this.props.children}}function ck({children:e,isPresent:t}){let i=(0,p.useId)(),n=(0,p.useRef)(null),r=(0,p.useRef)({width:0,height:0,top:0,left:0}),{nonce:s}=(0,p.useContext)(cy);return(0,p.useInsertionEffect)(()=>{let{width:e,height:o,top:a,left:l}=r.current;if(t||!n.current||!e||!o)return;n.current.dataset.motionPopId=i;let c=document.createElement("style");return s&&(c.nonce=s),document.head.appendChild(c),c.sheet&&c.sheet.insertRule(`
4
4
  [data-motion-pop-id="${i}"] {
5
5
  position: absolute !important;
6
6
  width: ${e}px !important;
@@ -8,4 +8,4 @@
8
8
  top: ${a}px !important;
9
9
  left: ${l}px !important;
10
10
  }
11
- `),()=>{document.head.removeChild(c)}},[t]),(0,u.jsx)(cb,{isPresent:t,childRef:n,sizeRef:r,children:p.cloneElement(e,{ref:n})})}let cT=({children:e,initial:t,isPresent:i,onExitComplete:n,custom:r,presenceAffectsLayout:s,mode:o})=>{let a=cg(cS),l=(0,p.useId)(),c=(0,p.useCallback)(e=>{for(let t of(a.set(e,!0),a.values()))if(!t)return;n&&n()},[a,n]),d=(0,p.useMemo)(()=>({id:l,initial:t,isPresent:i,custom:r,onExitComplete:c,register:e=>(a.set(e,!1),()=>a.delete(e))}),s?[Math.random(),c]:[i,c]);return(0,p.useMemo)(()=>{a.forEach((e,t)=>a.set(t,!1))},[i]),p.useEffect(()=>{i||a.size||!n||n()},[i]),"popLayout"===o&&(e=(0,u.jsx)(ck,{isPresent:i,children:e})),(0,u.jsx)(cv.Provider,{value:d,children:e})};function cS(){return new Map}function cC(e=!0){let t=(0,p.useContext)(cv);if(null===t)return[!0,null];let{isPresent:i,onExitComplete:n,register:r}=t,s=(0,p.useId)();(0,p.useEffect)(()=>{e&&r(s)},[e]);let o=(0,p.useCallback)(()=>e&&n&&n(s),[s,n,e]);return!i&&n?[!1,o]:[!0]}let cw=e=>e.key||"";function cE(e){let t=[];return p.Children.forEach(e,e=>{(0,p.isValidElement)(e)&&t.push(e)}),t}let cP="undefined"!=typeof window,cx=cP?p.useLayoutEffect:p.useEffect,cR=({children:e,custom:t,initial:i=!0,onExitComplete:n,presenceAffectsLayout:r=!0,mode:s="sync",propagate:o=!1})=>{let[a,l]=cC(o),c=(0,p.useMemo)(()=>cE(e),[e]),d=o&&!a?[]:c.map(cw),h=(0,p.useRef)(!0),m=(0,p.useRef)(c),f=cg(()=>new Map),[g,v]=(0,p.useState)(c),[y,b]=(0,p.useState)(c);cx(()=>{h.current=!1,m.current=c;for(let e=0;e<y.length;e++){let t=cw(y[e]);d.includes(t)?f.delete(t):!0!==f.get(t)&&f.set(t,!1)}},[y,d.length,d.join("-")]);let k=[];if(c!==g){let e=[...c];for(let t=0;t<y.length;t++){let i=y[t],n=cw(i);d.includes(n)||(e.splice(t,0,i),k.push(i))}"wait"===s&&k.length&&(e=k),b(cE(e)),v(c);return}let{forceRender:T}=(0,p.useContext)(cf);return(0,u.jsx)(u.Fragment,{children:y.map(e=>{let p=cw(e),g=(!o||!!a)&&(c===y||d.includes(p));return(0,u.jsx)(cT,{isPresent:g,initial:(!h.current||!!i)&&void 0,custom:g?void 0:t,presenceAffectsLayout:r,mode:s,onExitComplete:g?void 0:()=>{if(!f.has(p))return;f.set(p,!0);let e=!0;f.forEach(t=>{t||(e=!1)}),e&&(null==T||T(),b(m.current),o&&(null==l||l()),n&&n())},children:e},p)})})};function cO(e){return null!==e&&"object"==typeof e&&"function"==typeof e.start}let cA=e=>Array.isArray(e);function cI(e,t){if(!Array.isArray(t))return!1;let i=t.length;if(i!==e.length)return!1;for(let n=0;n<i;n++)if(t[n]!==e[n])return!1;return!0}function cM(e){return"string"==typeof e||Array.isArray(e)}function cD(e){let t=[{},{}];return null==e||e.values.forEach((e,i)=>{t[0][i]=e.get(),t[1][i]=e.getVelocity()}),t}function c_(e,t,i,n){if("function"==typeof t){let[r,s]=cD(n);t=t(void 0!==i?i:e.custom,r,s)}if("string"==typeof t&&(t=e.variants&&e.variants[t]),"function"==typeof t){let[r,s]=cD(n);t=t(void 0!==i?i:e.custom,r,s)}return t}function cN(e,t,i){let n=e.getProps();return c_(n,t,void 0!==i?i:n.custom,e)}let cL=["animate","whileInView","whileFocus","whileHover","whileTap","whileDrag","exit"],cj=["initial",...cL];function cU(e){let t;return()=>(void 0===t&&(t=e()),t)}let cF=cU(()=>void 0!==window.ScrollTimeline);class cV{constructor(e){this.stop=()=>this.runAll("stop"),this.animations=e.filter(Boolean)}get finished(){return Promise.all(this.animations.map(e=>"finished"in e?e.finished:e))}getAll(e){return this.animations[0][e]}setAll(e,t){for(let i=0;i<this.animations.length;i++)this.animations[i][e]=t}attachTimeline(e,t){let i=this.animations.map(i=>cF()&&i.attachTimeline?i.attachTimeline(e):"function"==typeof t?t(i):void 0);return()=>{i.forEach((e,t)=>{e&&e(),this.animations[t].stop()})}}get time(){return this.getAll("time")}set time(e){this.setAll("time",e)}get speed(){return this.getAll("speed")}set speed(e){this.setAll("speed",e)}get startTime(){return this.getAll("startTime")}get duration(){let e=0;for(let t=0;t<this.animations.length;t++)e=Math.max(e,this.animations[t].duration);return e}runAll(e){this.animations.forEach(t=>t[e]())}flatten(){this.runAll("flatten")}play(){this.runAll("play")}pause(){this.runAll("pause")}cancel(){this.runAll("cancel")}complete(){this.runAll("complete")}}class cB extends cV{then(e,t){return Promise.all(this.animations).then(e).catch(t)}}function cq(e,t){return e?e[t]||e.default||e:void 0}function cz(e){let t=0,i=e.next(t);for(;!i.done&&t<2e4;)t+=50,i=e.next(t);return t>=2e4?1/0:t}function cW(e){return"function"==typeof e}function cH(e,t){e.timeline=t,e.onfinish=null}let cG=e=>Array.isArray(e)&&"number"==typeof e[0],c$={linearEasing:void 0},cK=function(e,t){let i=cU(e);return()=>{var e;return null!==(e=c$[t])&&void 0!==e?e:i()}}(()=>{try{document.createElement("div").animate({opacity:0},{easing:"linear(0, 1)"})}catch(e){return!1}return!0},"linearEasing"),cJ=(e,t,i)=>{let n=t-e;return 0===n?1:(i-e)/n},cX=(e,t,i=10)=>{let n="",r=Math.max(Math.round(t/i),2);for(let t=0;t<r;t++)n+=e(cJ(0,r-1,t))+", ";return`linear(${n.substring(0,n.length-2)})`},cY=([e,t,i,n])=>`cubic-bezier(${e}, ${t}, ${i}, ${n})`,cQ={linear:"linear",ease:"ease",easeIn:"ease-in",easeOut:"ease-out",easeInOut:"ease-in-out",circIn:cY([0,.65,.55,1]),circOut:cY([.55,0,1,.45]),backIn:cY([.31,.01,.66,-.59]),backOut:cY([.33,1.53,.69,.99])},cZ={x:!1,y:!1};function c0(e,t){let i=function(e,t,i){if(e instanceof Element)return[e];if("string"==typeof e){let t=document.querySelectorAll(e);return t?Array.from(t):[]}return Array.from(e)}(e),n=new AbortController;return[i,{passive:!0,...t,signal:n.signal},()=>n.abort()]}function c1(e){return t=>{"touch"===t.pointerType||cZ.x||cZ.y||e(t)}}let c2=(e,t)=>!!t&&(e===t||c2(e,t.parentElement)),c3=e=>"mouse"===e.pointerType?"number"!=typeof e.button||e.button<=0:!1!==e.isPrimary,c5=new Set(["BUTTON","INPUT","SELECT","TEXTAREA","A"]),c4=new WeakSet;function c6(e){return t=>{"Enter"===t.key&&e(t)}}function c9(e,t){e.dispatchEvent(new PointerEvent("pointer"+t,{isPrimary:!0,bubbles:!0}))}let c8=(e,t)=>{let i=e.currentTarget;if(!i)return;let n=c6(()=>{if(c4.has(i))return;c9(i,"down");let e=c6(()=>{c9(i,"up")});i.addEventListener("keyup",e,t),i.addEventListener("blur",()=>c9(i,"cancel"),t)});i.addEventListener("keydown",n,t),i.addEventListener("blur",()=>i.removeEventListener("keydown",n),t)};function c7(e){return c3(e)&&!(cZ.x||cZ.y)}let de=e=>1e3*e,dt=e=>e/1e3,di=e=>e,dn=["transformPerspective","x","y","z","translateX","translateY","translateZ","scale","scaleX","scaleY","rotate","rotateX","rotateY","rotateZ","skew","skewX","skewY"],dr=new Set(dn),ds=new Set(["width","height","top","left","right","bottom",...dn]),da=e=>!!(e&&"object"==typeof e&&e.mix&&e.toValue),dl=e=>cA(e)?e[e.length-1]||0:e,dc={skipAnimations:!1,useManualTiming:!1},dd=["read","resolveKeyframes","update","preRender","render","postRender"];function du(e,t){let i=!1,n=!0,r={delta:0,timestamp:0,isProcessing:!1},s=()=>i=!0,o=dd.reduce((e,t)=>(e[t]=function(e){let t=new Set,i=new Set,n=!1,r=!1,s=new WeakSet,o={delta:0,timestamp:0,isProcessing:!1};function a(t){s.has(t)&&(l.schedule(t),e()),t(o)}let l={schedule:(e,r=!1,o=!1)=>{let a=o&&n?t:i;return r&&s.add(e),a.has(e)||a.add(e),e},cancel:e=>{i.delete(e),s.delete(e)},process:e=>{if(o=e,n){r=!0;return}n=!0,[t,i]=[i,t],t.forEach(a),t.clear(),n=!1,r&&(r=!1,l.process(e))}};return l}(s),e),{}),{read:a,resolveKeyframes:l,update:c,preRender:d,render:u,postRender:h}=o,p=()=>{let s=dc.useManualTiming?r.timestamp:performance.now();i=!1,r.delta=n?1e3/60:Math.max(Math.min(s-r.timestamp,40),1),r.timestamp=s,r.isProcessing=!0,a.process(r),l.process(r),c.process(r),d.process(r),u.process(r),h.process(r),r.isProcessing=!1,i&&t&&(n=!1,e(p))},m=()=>{i=!0,n=!0,r.isProcessing||e(p)};return{schedule:dd.reduce((e,t)=>{let n=o[t];return e[t]=(e,t=!1,r=!1)=>(i||m(),n.schedule(e,t,r)),e},{}),cancel:e=>{for(let t=0;t<dd.length;t++)o[dd[t]].cancel(e)},state:r,steps:o}}let{schedule:dh,cancel:dp,state:dm,steps:df}=du("undefined"!=typeof requestAnimationFrame?requestAnimationFrame:di,!0);function dg(){o=void 0}let dv={now:()=>(void 0===o&&dv.set(dm.isProcessing||dc.useManualTiming?dm.timestamp:performance.now()),o),set:e=>{o=e,queueMicrotask(dg)}};function dy(e,t){-1===e.indexOf(t)&&e.push(t)}function db(e,t){let i=e.indexOf(t);i>-1&&e.splice(i,1)}class dk{constructor(){this.subscriptions=[]}add(e){return dy(this.subscriptions,e),()=>db(this.subscriptions,e)}notify(e,t,i){let n=this.subscriptions.length;if(n){if(1===n)this.subscriptions[0](e,t,i);else for(let r=0;r<n;r++){let n=this.subscriptions[r];n&&n(e,t,i)}}}getSize(){return this.subscriptions.length}clear(){this.subscriptions.length=0}}let dT=e=>!isNaN(parseFloat(e)),dS={current:void 0};class dC{constructor(e,t={}){this.version="11.18.2",this.canTrackVelocity=null,this.events={},this.updateAndNotify=(e,t=!0)=>{let i=dv.now();this.updatedAt!==i&&this.setPrevFrameValue(),this.prev=this.current,this.setCurrent(e),this.current!==this.prev&&this.events.change&&this.events.change.notify(this.current),t&&this.events.renderRequest&&this.events.renderRequest.notify(this.current)},this.hasAnimated=!1,this.setCurrent(e),this.owner=t.owner}setCurrent(e){this.current=e,this.updatedAt=dv.now(),null===this.canTrackVelocity&&void 0!==e&&(this.canTrackVelocity=dT(this.current))}setPrevFrameValue(e=this.current){this.prevFrameValue=e,this.prevUpdatedAt=this.updatedAt}onChange(e){return this.on("change",e)}on(e,t){this.events[e]||(this.events[e]=new dk);let i=this.events[e].add(t);return"change"===e?()=>{i(),dh.read(()=>{this.events.change.getSize()||this.stop()})}:i}clearListeners(){for(let e in this.events)this.events[e].clear()}attach(e,t){this.passiveEffect=e,this.stopPassiveEffect=t}set(e,t=!0){t&&this.passiveEffect?this.passiveEffect(e,this.updateAndNotify):this.updateAndNotify(e,t)}setWithVelocity(e,t,i){this.set(t),this.prev=void 0,this.prevFrameValue=e,this.prevUpdatedAt=this.updatedAt-i}jump(e,t=!0){this.updateAndNotify(e),this.prev=e,this.prevUpdatedAt=this.prevFrameValue=void 0,t&&this.stop(),this.stopPassiveEffect&&this.stopPassiveEffect()}get(){return dS.current&&dS.current.push(this),this.current}getPrevious(){return this.prev}getVelocity(){var e;let t=dv.now();if(!this.canTrackVelocity||void 0===this.prevFrameValue||t-this.updatedAt>30)return 0;let i=Math.min(this.updatedAt-this.prevUpdatedAt,30);return e=parseFloat(this.current)-parseFloat(this.prevFrameValue),i?1e3/i*e:0}start(e){return this.stop(),new Promise(t=>{this.hasAnimated=!0,this.animation=e(t),this.events.animationStart&&this.events.animationStart.notify()}).then(()=>{this.events.animationComplete&&this.events.animationComplete.notify(),this.clearAnimation()})}stop(){this.animation&&(this.animation.stop(),this.events.animationCancel&&this.events.animationCancel.notify()),this.clearAnimation()}isAnimating(){return!!this.animation}clearAnimation(){delete this.animation}destroy(){this.clearListeners(),this.stop(),this.stopPassiveEffect&&this.stopPassiveEffect()}}function dw(e,t){return new dC(e,t)}let dE=e=>!!(e&&e.getVelocity);function dP(e,t){let i=e.getValue("willChange");if(dE(i)&&i.add)return i.add(t)}let dx=e=>e.replace(/([a-z])([A-Z])/gu,"$1-$2").toLowerCase(),dR="data-"+dx("framerAppearId"),dO={current:!1},dA=(e,t,i)=>(((1-3*i+3*t)*e+(3*i-6*t))*e+3*t)*e;function dI(e,t,i,n){if(e===t&&i===n)return di;let r=t=>(function(e,t,i,n,r){let s,o;let a=0;do(s=dA(o=t+(i-t)/2,n,r)-e)>0?i=o:t=o;while(Math.abs(s)>1e-7&&++a<12);return o})(t,0,1,e,i);return e=>0===e||1===e?e:dA(r(e),t,n)}let dM=e=>t=>t<=.5?e(2*t)/2:(2-e(2*(1-t)))/2,dD=e=>t=>1-e(1-t),d_=dI(.33,1.53,.69,.99),dN=dD(d_),dL=dM(dN),dj=e=>(e*=2)<1?.5*dN(e):.5*(2-Math.pow(2,-10*(e-1))),dU=e=>1-Math.sin(Math.acos(e)),dF=dD(dU),dV=dM(dU),dB=e=>/^0[^.\s]+$/u.test(e),dq=(e,t,i)=>i>t?t:i<e?e:i,dz={test:e=>"number"==typeof e,parse:parseFloat,transform:e=>e},dW={...dz,transform:e=>dq(0,1,e)},dH={...dz,default:1},dG=e=>Math.round(1e5*e)/1e5,d$=/-?(?:\d+(?:\.\d+)?|\.\d+)/gu,dK=/^(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))$/iu,dJ=(e,t)=>i=>!!("string"==typeof i&&dK.test(i)&&i.startsWith(e)||t&&null!=i&&Object.prototype.hasOwnProperty.call(i,t)),dX=(e,t,i)=>n=>{if("string"!=typeof n)return n;let[r,s,o,a]=n.match(d$);return{[e]:parseFloat(r),[t]:parseFloat(s),[i]:parseFloat(o),alpha:void 0!==a?parseFloat(a):1}},dY=e=>dq(0,255,e),dQ={...dz,transform:e=>Math.round(dY(e))},dZ={test:dJ("rgb","red"),parse:dX("red","green","blue"),transform:({red:e,green:t,blue:i,alpha:n=1})=>"rgba("+dQ.transform(e)+", "+dQ.transform(t)+", "+dQ.transform(i)+", "+dG(dW.transform(n))+")"},d0={test:dJ("#"),parse:function(e){let t="",i="",n="",r="";return e.length>5?(t=e.substring(1,3),i=e.substring(3,5),n=e.substring(5,7),r=e.substring(7,9)):(t=e.substring(1,2),i=e.substring(2,3),n=e.substring(3,4),r=e.substring(4,5),t+=t,i+=i,n+=n,r+=r),{red:parseInt(t,16),green:parseInt(i,16),blue:parseInt(n,16),alpha:r?parseInt(r,16)/255:1}},transform:dZ.transform},d1=e=>({test:t=>"string"==typeof t&&t.endsWith(e)&&1===t.split(" ").length,parse:parseFloat,transform:t=>`${t}${e}`}),d2=d1("deg"),d3=d1("%"),d5=d1("px"),d4=d1("vh"),d6=d1("vw"),d9={...d3,parse:e=>d3.parse(e)/100,transform:e=>d3.transform(100*e)},d8={test:dJ("hsl","hue"),parse:dX("hue","saturation","lightness"),transform:({hue:e,saturation:t,lightness:i,alpha:n=1})=>"hsla("+Math.round(e)+", "+d3.transform(dG(t))+", "+d3.transform(dG(i))+", "+dG(dW.transform(n))+")"},d7={test:e=>dZ.test(e)||d0.test(e)||d8.test(e),parse:e=>dZ.test(e)?dZ.parse(e):d8.test(e)?d8.parse(e):d0.parse(e),transform:e=>"string"==typeof e?e:e.hasOwnProperty("red")?dZ.transform(e):d8.transform(e)},ue=/(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))/giu,ut="number",ui="color",un=/var\s*\(\s*--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)|#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\)|-?(?:\d+(?:\.\d+)?|\.\d+)/giu;function ur(e){let t=e.toString(),i=[],n={color:[],number:[],var:[]},r=[],s=0,o=t.replace(un,e=>(d7.test(e)?(n.color.push(s),r.push(ui),i.push(d7.parse(e))):e.startsWith("var(")?(n.var.push(s),r.push("var"),i.push(e)):(n.number.push(s),r.push(ut),i.push(parseFloat(e))),++s,"${}")).split("${}");return{values:i,split:o,indexes:n,types:r}}function us(e){return ur(e).values}function uo(e){let{split:t,types:i}=ur(e),n=t.length;return e=>{let r="";for(let s=0;s<n;s++)if(r+=t[s],void 0!==e[s]){let t=i[s];t===ut?r+=dG(e[s]):t===ui?r+=d7.transform(e[s]):r+=e[s]}return r}}let ua=e=>"number"==typeof e?0:e,ul={test:function(e){var t,i;return isNaN(e)&&"string"==typeof e&&((null===(t=e.match(d$))||void 0===t?void 0:t.length)||0)+((null===(i=e.match(ue))||void 0===i?void 0:i.length)||0)>0},parse:us,createTransformer:uo,getAnimatableNone:function(e){let t=us(e);return uo(e)(t.map(ua))}},uc=new Set(["brightness","contrast","saturate","opacity"]);function ud(e){let[t,i]=e.slice(0,-1).split("(");if("drop-shadow"===t)return e;let[n]=i.match(d$)||[];if(!n)return e;let r=i.replace(n,""),s=uc.has(t)?1:0;return n!==i&&(s*=100),t+"("+s+r+")"}let uu=/\b([a-z-]*)\(.*?\)/gu,uh={...ul,getAnimatableNone:e=>{let t=e.match(uu);return t?t.map(ud).join(" "):e}},up={...dz,transform:Math.round},um={borderWidth:d5,borderTopWidth:d5,borderRightWidth:d5,borderBottomWidth:d5,borderLeftWidth:d5,borderRadius:d5,radius:d5,borderTopLeftRadius:d5,borderTopRightRadius:d5,borderBottomRightRadius:d5,borderBottomLeftRadius:d5,width:d5,maxWidth:d5,height:d5,maxHeight:d5,top:d5,right:d5,bottom:d5,left:d5,padding:d5,paddingTop:d5,paddingRight:d5,paddingBottom:d5,paddingLeft:d5,margin:d5,marginTop:d5,marginRight:d5,marginBottom:d5,marginLeft:d5,backgroundPositionX:d5,backgroundPositionY:d5,rotate:d2,rotateX:d2,rotateY:d2,rotateZ:d2,scale:dH,scaleX:dH,scaleY:dH,scaleZ:dH,skew:d2,skewX:d2,skewY:d2,distance:d5,translateX:d5,translateY:d5,translateZ:d5,x:d5,y:d5,z:d5,perspective:d5,transformPerspective:d5,opacity:dW,originX:d9,originY:d9,originZ:d5,zIndex:up,size:d5,fillOpacity:dW,strokeOpacity:dW,numOctaves:up},uf={...um,color:d7,backgroundColor:d7,outlineColor:d7,fill:d7,stroke:d7,borderColor:d7,borderTopColor:d7,borderRightColor:d7,borderBottomColor:d7,borderLeftColor:d7,filter:uh,WebkitFilter:uh},ug=e=>uf[e];function uv(e,t){let i=ug(e);return i!==uh&&(i=ul),i.getAnimatableNone?i.getAnimatableNone(t):void 0}let uy=new Set(["auto","none","0"]),ub=e=>e===dz||e===d5,uk=(e,t)=>parseFloat(e.split(", ")[t]),uT=(e,t)=>(i,{transform:n})=>{if("none"===n||!n)return 0;let r=n.match(/^matrix3d\((.+)\)$/u);if(r)return uk(r[1],t);{let t=n.match(/^matrix\((.+)\)$/u);return t?uk(t[1],e):0}},uS=new Set(["x","y","z"]),uC=dn.filter(e=>!uS.has(e)),uw={width:({x:e},{paddingLeft:t="0",paddingRight:i="0"})=>e.max-e.min-parseFloat(t)-parseFloat(i),height:({y:e},{paddingTop:t="0",paddingBottom:i="0"})=>e.max-e.min-parseFloat(t)-parseFloat(i),top:(e,{top:t})=>parseFloat(t),left:(e,{left:t})=>parseFloat(t),bottom:({y:e},{top:t})=>parseFloat(t)+(e.max-e.min),right:({x:e},{left:t})=>parseFloat(t)+(e.max-e.min),x:uT(4,13),y:uT(5,14)};uw.translateX=uw.x,uw.translateY=uw.y;let uE=new Set,uP=!1,ux=!1;function uR(){if(ux){let e=Array.from(uE).filter(e=>e.needsMeasurement),t=new Set(e.map(e=>e.element)),i=new Map;t.forEach(e=>{let t=function(e){let t=[];return uC.forEach(i=>{let n=e.getValue(i);void 0!==n&&(t.push([i,n.get()]),n.set(i.startsWith("scale")?1:0))}),t}(e);t.length&&(i.set(e,t),e.render())}),e.forEach(e=>e.measureInitialState()),t.forEach(e=>{e.render();let t=i.get(e);t&&t.forEach(([t,i])=>{var n;null===(n=e.getValue(t))||void 0===n||n.set(i)})}),e.forEach(e=>e.measureEndState()),e.forEach(e=>{void 0!==e.suspendedScrollY&&window.scrollTo(0,e.suspendedScrollY)})}ux=!1,uP=!1,uE.forEach(e=>e.complete()),uE.clear()}function uO(){uE.forEach(e=>{e.readKeyframes(),e.needsMeasurement&&(ux=!0)})}class uA{constructor(e,t,i,n,r,s=!1){this.isComplete=!1,this.isAsync=!1,this.needsMeasurement=!1,this.isScheduled=!1,this.unresolvedKeyframes=[...e],this.onComplete=t,this.name=i,this.motionValue=n,this.element=r,this.isAsync=s}scheduleResolve(){this.isScheduled=!0,this.isAsync?(uE.add(this),uP||(uP=!0,dh.read(uO),dh.resolveKeyframes(uR))):(this.readKeyframes(),this.complete())}readKeyframes(){let{unresolvedKeyframes:e,name:t,element:i,motionValue:n}=this;for(let r=0;r<e.length;r++)if(null===e[r]){if(0===r){let r=null==n?void 0:n.get(),s=e[e.length-1];if(void 0!==r)e[0]=r;else if(i&&t){let n=i.readValue(t,s);null!=n&&(e[0]=n)}void 0===e[0]&&(e[0]=s),n&&void 0===r&&n.set(e[0])}else e[r]=e[r-1]}}setFinalKeyframe(){}measureInitialState(){}renderEndStyles(){}measureEndState(){}complete(){this.isComplete=!0,this.onComplete(this.unresolvedKeyframes,this.finalKeyframe),uE.delete(this)}cancel(){this.isComplete||(this.isScheduled=!1,uE.delete(this))}resume(){this.isComplete||this.scheduleResolve()}}let uI=e=>/^-?(?:\d+(?:\.\d+)?|\.\d+)$/u.test(e),uM=e=>t=>"string"==typeof t&&t.startsWith(e),uD=uM("--"),u_=uM("var(--"),uN=e=>!!u_(e)&&uL.test(e.split("/*")[0].trim()),uL=/var\(--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)$/iu,uj=/^var\(--(?:([\w-]+)|([\w-]+), ?([a-zA-Z\d ()%#.,-]+))\)/u,uU=e=>t=>t.test(e),uF=[dz,d5,d3,d2,d6,d4,{test:e=>"auto"===e,parse:e=>e}],uV=e=>uF.find(uU(e));class uB extends uA{constructor(e,t,i,n,r){super(e,t,i,n,r,!0)}readKeyframes(){let{unresolvedKeyframes:e,element:t,name:i}=this;if(!t||!t.current)return;super.readKeyframes();for(let i=0;i<e.length;i++){let n=e[i];if("string"==typeof n&&uN(n=n.trim())){let r=function e(t,i,n=1){di(n<=4,`Max CSS variable fallback depth detected in property "${t}". This may indicate a circular fallback dependency.`);let[r,s]=function(e){let t=uj.exec(e);if(!t)return[,];let[,i,n,r]=t;return[`--${null!=i?i:n}`,r]}(t);if(!r)return;let o=window.getComputedStyle(i).getPropertyValue(r);if(o){let e=o.trim();return uI(e)?parseFloat(e):e}return uN(s)?e(s,i,n+1):s}(n,t.current);void 0!==r&&(e[i]=r),i===e.length-1&&(this.finalKeyframe=n)}}if(this.resolveNoneKeyframes(),!ds.has(i)||2!==e.length)return;let[n,r]=e,s=uV(n),o=uV(r);if(s!==o){if(ub(s)&&ub(o))for(let t=0;t<e.length;t++){let i=e[t];"string"==typeof i&&(e[t]=parseFloat(i))}else this.needsMeasurement=!0}}resolveNoneKeyframes(){let{unresolvedKeyframes:e,name:t}=this,i=[];for(let t=0;t<e.length;t++){var n;("number"==typeof(n=e[t])?0===n:null===n||"none"===n||"0"===n||dB(n))&&i.push(t)}i.length&&function(e,t,i){let n,r=0;for(;r<e.length&&!n;){let t=e[r];"string"==typeof t&&!uy.has(t)&&ur(t).values.length&&(n=e[r]),r++}if(n&&i)for(let r of t)e[r]=uv(i,n)}(e,i,t)}measureInitialState(){let{element:e,unresolvedKeyframes:t,name:i}=this;if(!e||!e.current)return;"height"===i&&(this.suspendedScrollY=window.pageYOffset),this.measuredOrigin=uw[i](e.measureViewportBox(),window.getComputedStyle(e.current)),t[0]=this.measuredOrigin;let n=t[t.length-1];void 0!==n&&e.getValue(i,n).jump(n,!1)}measureEndState(){var e;let{element:t,name:i,unresolvedKeyframes:n}=this;if(!t||!t.current)return;let r=t.getValue(i);r&&r.jump(this.measuredOrigin,!1);let s=n.length-1,o=n[s];n[s]=uw[i](t.measureViewportBox(),window.getComputedStyle(t.current)),null!==o&&void 0===this.finalKeyframe&&(this.finalKeyframe=o),(null===(e=this.removedTransforms)||void 0===e?void 0:e.length)&&this.removedTransforms.forEach(([e,i])=>{t.getValue(e).set(i)}),this.resolveNoneKeyframes()}}let uq=(e,t)=>"zIndex"!==t&&!!("number"==typeof e||Array.isArray(e)||"string"==typeof e&&(ul.test(e)||"0"===e)&&!e.startsWith("url(")),uz=e=>null!==e;function uW(e,{repeat:t,repeatType:i="loop"},n){let r=e.filter(uz),s=t&&"loop"!==i&&t%2==1?0:r.length-1;return s&&void 0!==n?n:r[s]}class uH{constructor({autoplay:e=!0,delay:t=0,type:i="keyframes",repeat:n=0,repeatDelay:r=0,repeatType:s="loop",...o}){this.isStopped=!1,this.hasAttemptedResolve=!1,this.createdAt=dv.now(),this.options={autoplay:e,delay:t,type:i,repeat:n,repeatDelay:r,repeatType:s,...o},this.updateFinishedPromise()}calcStartTime(){return this.resolvedAt&&this.resolvedAt-this.createdAt>40?this.resolvedAt:this.createdAt}get resolved(){return this._resolved||this.hasAttemptedResolve||(uO(),uR()),this._resolved}onKeyframesResolved(e,t){this.resolvedAt=dv.now(),this.hasAttemptedResolve=!0;let{name:i,type:n,velocity:r,delay:s,onComplete:o,onUpdate:a,isGenerator:l}=this.options;if(!l&&!function(e,t,i,n){let r=e[0];if(null===r)return!1;if("display"===t||"visibility"===t)return!0;let s=e[e.length-1],o=uq(r,t),a=uq(s,t);return di(o===a,`You are trying to animate ${t} from "${r}" to "${s}". ${r} is not an animatable value - to enable this animation set ${r} to a value animatable to ${s} via the \`style\` property.`),!!o&&!!a&&(function(e){let t=e[0];if(1===e.length)return!0;for(let i=0;i<e.length;i++)if(e[i]!==t)return!0}(e)||("spring"===i||cW(i))&&n)}(e,i,n,r)){if(dO.current||!s){a&&a(uW(e,this.options,t)),o&&o(),this.resolveFinishedPromise();return}this.options.duration=0}let c=this.initPlayback(e,t);!1!==c&&(this._resolved={keyframes:e,finalKeyframe:t,...c},this.onPostResolved())}onPostResolved(){}then(e,t){return this.currentFinishedPromise.then(e,t)}flatten(){this.options.type="keyframes",this.options.ease="linear"}updateFinishedPromise(){this.currentFinishedPromise=new Promise(e=>{this.resolveFinishedPromise=e})}}let uG=(e,t,i)=>e+(t-e)*i;function u$(e,t,i){return(i<0&&(i+=1),i>1&&(i-=1),i<1/6)?e+(t-e)*6*i:i<.5?t:i<2/3?e+(t-e)*(2/3-i)*6:e}function uK(e,t){return i=>i>0?t:e}let uJ=(e,t,i)=>{let n=e*e,r=i*(t*t-n)+n;return r<0?0:Math.sqrt(r)},uX=[d0,dZ,d8],uY=e=>uX.find(t=>t.test(e));function uQ(e){let t=uY(e);if(di(!!t,`'${e}' is not an animatable color. Use the equivalent color code instead.`),!t)return!1;let i=t.parse(e);return t===d8&&(i=function({hue:e,saturation:t,lightness:i,alpha:n}){e/=360,i/=100;let r=0,s=0,o=0;if(t/=100){let n=i<.5?i*(1+t):i+t-i*t,a=2*i-n;r=u$(a,n,e+1/3),s=u$(a,n,e),o=u$(a,n,e-1/3)}else r=s=o=i;return{red:Math.round(255*r),green:Math.round(255*s),blue:Math.round(255*o),alpha:n}}(i)),i}let uZ=(e,t)=>{let i=uQ(e),n=uQ(t);if(!i||!n)return uK(e,t);let r={...i};return e=>(r.red=uJ(i.red,n.red,e),r.green=uJ(i.green,n.green,e),r.blue=uJ(i.blue,n.blue,e),r.alpha=uG(i.alpha,n.alpha,e),dZ.transform(r))},u0=(e,t)=>i=>t(e(i)),u1=(...e)=>e.reduce(u0),u2=new Set(["none","hidden"]);function u3(e,t){return i=>uG(e,t,i)}function u5(e){return"number"==typeof e?u3:"string"==typeof e?uN(e)?uK:d7.test(e)?uZ:u9:Array.isArray(e)?u4:"object"==typeof e?d7.test(e)?uZ:u6:uK}function u4(e,t){let i=[...e],n=i.length,r=e.map((e,i)=>u5(e)(e,t[i]));return e=>{for(let t=0;t<n;t++)i[t]=r[t](e);return i}}function u6(e,t){let i={...e,...t},n={};for(let r in i)void 0!==e[r]&&void 0!==t[r]&&(n[r]=u5(e[r])(e[r],t[r]));return e=>{for(let t in n)i[t]=n[t](e);return i}}let u9=(e,t)=>{let i=ul.createTransformer(t),n=ur(e),r=ur(t);return n.indexes.var.length===r.indexes.var.length&&n.indexes.color.length===r.indexes.color.length&&n.indexes.number.length>=r.indexes.number.length?u2.has(e)&&!r.values.length||u2.has(t)&&!n.values.length?function(e,t){return u2.has(e)?i=>i<=0?e:t:i=>i>=1?t:e}(e,t):u1(u4(function(e,t){var i;let n=[],r={color:0,var:0,number:0};for(let s=0;s<t.values.length;s++){let o=t.types[s],a=e.indexes[o][r[o]],l=null!==(i=e.values[a])&&void 0!==i?i:0;n[s]=l,r[o]++}return n}(n,r),r.values),i):(di(!0,`Complex values '${e}' and '${t}' too different to mix. Ensure all colors are of the same type, and that each contains the same quantity of number and color values. Falling back to instant transition.`),uK(e,t))};function u8(e,t,i){return"number"==typeof e&&"number"==typeof t&&"number"==typeof i?uG(e,t,i):u5(e)(e,t)}function u7(e,t,i){var n,r;let s=Math.max(t-5,0);return n=i-e(s),(r=t-s)?1e3/r*n:0}let he={stiffness:100,damping:10,mass:1,velocity:0,duration:800,bounce:.3,visualDuration:.3,restSpeed:{granular:.01,default:2},restDelta:{granular:.005,default:.5},minDuration:.01,maxDuration:10,minDamping:.05,maxDamping:1};function ht(e,t){return e*Math.sqrt(1-t*t)}let hi=["duration","bounce"],hn=["stiffness","damping","mass"];function hr(e,t){return t.some(t=>void 0!==e[t])}function hs(e=he.visualDuration,t=he.bounce){let i;let n="object"!=typeof e?{visualDuration:e,keyframes:[0,1],bounce:t}:e,{restSpeed:r,restDelta:s}=n,o=n.keyframes[0],a=n.keyframes[n.keyframes.length-1],l={done:!1,value:o},{stiffness:c,damping:d,mass:u,duration:h,velocity:p,isResolvedFromDuration:m}=function(e){let t={velocity:he.velocity,stiffness:he.stiffness,damping:he.damping,mass:he.mass,isResolvedFromDuration:!1,...e};if(!hr(e,hn)&&hr(e,hi)){if(e.visualDuration){let i=2*Math.PI/(1.2*e.visualDuration),n=i*i,r=2*dq(.05,1,1-(e.bounce||0))*Math.sqrt(n);t={...t,mass:he.mass,stiffness:n,damping:r}}else{let i=function({duration:e=he.duration,bounce:t=he.bounce,velocity:i=he.velocity,mass:n=he.mass}){let r,s;di(e<=de(he.maxDuration),"Spring duration must be 10 seconds or less");let o=1-t;o=dq(he.minDamping,he.maxDamping,o),e=dq(he.minDuration,he.maxDuration,dt(e)),o<1?(r=t=>{let n=t*o,r=n*e;return .001-(n-i)/ht(t,o)*Math.exp(-r)},s=t=>{let n=t*o*e,s=Math.pow(o,2)*Math.pow(t,2)*e,a=ht(Math.pow(t,2),o);return(n*i+i-s)*Math.exp(-n)*(-r(t)+.001>0?-1:1)/a}):(r=t=>-.001+Math.exp(-t*e)*((t-i)*e+1),s=t=>e*e*(i-t)*Math.exp(-t*e));let a=function(e,t,i){let n=i;for(let i=1;i<12;i++)n-=e(n)/t(n);return n}(r,s,5/e);if(e=de(e),isNaN(a))return{stiffness:he.stiffness,damping:he.damping,duration:e};{let t=Math.pow(a,2)*n;return{stiffness:t,damping:2*o*Math.sqrt(n*t),duration:e}}}(e);(t={...t,...i,mass:he.mass}).isResolvedFromDuration=!0}}return t}({...n,velocity:-dt(n.velocity||0)}),f=p||0,g=d/(2*Math.sqrt(c*u)),v=a-o,y=dt(Math.sqrt(c/u)),b=5>Math.abs(v);if(r||(r=b?he.restSpeed.granular:he.restSpeed.default),s||(s=b?he.restDelta.granular:he.restDelta.default),g<1){let e=ht(y,g);i=t=>a-Math.exp(-g*y*t)*((f+g*y*v)/e*Math.sin(e*t)+v*Math.cos(e*t))}else if(1===g)i=e=>a-Math.exp(-y*e)*(v+(f+y*v)*e);else{let e=y*Math.sqrt(g*g-1);i=t=>{let i=Math.exp(-g*y*t),n=Math.min(e*t,300);return a-i*((f+g*y*v)*Math.sinh(n)+e*v*Math.cosh(n))/e}}let k={calculatedDuration:m&&h||null,next:e=>{let t=i(e);if(m)l.done=e>=h;else{let n=0;g<1&&(n=0===e?de(f):u7(i,e,t));let o=Math.abs(n)<=r,c=Math.abs(a-t)<=s;l.done=o&&c}return l.value=l.done?a:t,l},toString:()=>{let e=Math.min(cz(k),2e4),t=cX(t=>k.next(e*t).value,e,30);return e+"ms "+t}};return k}function ho({keyframes:e,velocity:t=0,power:i=.8,timeConstant:n=325,bounceDamping:r=10,bounceStiffness:s=500,modifyTarget:o,min:a,max:l,restDelta:c=.5,restSpeed:d}){let u,h;let p=e[0],m={done:!1,value:p},f=e=>void 0!==a&&e<a||void 0!==l&&e>l,g=e=>void 0===a?l:void 0===l?a:Math.abs(a-e)<Math.abs(l-e)?a:l,v=i*t,y=p+v,b=void 0===o?y:o(y);b!==y&&(v=b-p);let k=e=>-v*Math.exp(-e/n),T=e=>b+k(e),S=e=>{let t=k(e),i=T(e);m.done=Math.abs(t)<=c,m.value=m.done?b:i},C=e=>{f(m.value)&&(u=e,h=hs({keyframes:[m.value,g(m.value)],velocity:u7(T,e,m.value),damping:r,stiffness:s,restDelta:c,restSpeed:d}))};return C(0),{calculatedDuration:null,next:e=>{let t=!1;return(h||void 0!==u||(t=!0,S(e),C(e)),void 0!==u&&e>=u)?h.next(e-u):(t||S(e),m)}}}let ha=dI(.42,0,1,1),hl=dI(0,0,.58,1),hc=dI(.42,0,.58,1),hd=e=>Array.isArray(e)&&"number"!=typeof e[0],hu={linear:di,easeIn:ha,easeInOut:hc,easeOut:hl,circIn:dU,circInOut:dV,circOut:dF,backIn:dN,backInOut:dL,backOut:d_,anticipate:dj},hh=e=>{if(cG(e)){di(4===e.length,"Cubic bezier arrays must contain four numerical values.");let[t,i,n,r]=e;return dI(t,i,n,r)}return"string"==typeof e?(di(void 0!==hu[e],`Invalid easing type '${e}'`),hu[e]):e};function hp({duration:e=300,keyframes:t,times:i,ease:n="easeInOut"}){let r=hd(n)?n.map(hh):hh(n),s={done:!1,value:t[0]},o=function(e,t,{clamp:i=!0,ease:n,mixer:r}={}){let s=e.length;if(di(s===t.length,"Both input and output ranges must be the same length"),1===s)return()=>t[0];if(2===s&&t[0]===t[1])return()=>t[1];let o=e[0]===e[1];e[0]>e[s-1]&&(e=[...e].reverse(),t=[...t].reverse());let a=function(e,t,i){let n=[],r=i||u8,s=e.length-1;for(let i=0;i<s;i++){let s=r(e[i],e[i+1]);t&&(s=u1(Array.isArray(t)?t[i]||di:t,s)),n.push(s)}return n}(t,n,r),l=a.length,c=i=>{if(o&&i<e[0])return t[0];let n=0;if(l>1)for(;n<e.length-2&&!(i<e[n+1]);n++);let r=cJ(e[n],e[n+1],i);return a[n](r)};return i?t=>c(dq(e[0],e[s-1],t)):c}((i&&i.length===t.length?i:function(e){let t=[0];return function(e,t){let i=e[e.length-1];for(let n=1;n<=t;n++){let r=cJ(0,t,n);e.push(uG(i,1,r))}}(t,e.length-1),t}(t)).map(t=>t*e),t,{ease:Array.isArray(r)?r:t.map(()=>r||hc).splice(0,t.length-1)});return{calculatedDuration:e,next:t=>(s.value=o(t),s.done=t>=e,s)}}let hm=e=>{let t=({timestamp:t})=>e(t);return{start:()=>dh.update(t,!0),stop:()=>dp(t),now:()=>dm.isProcessing?dm.timestamp:dv.now()}},hf={decay:ho,inertia:ho,tween:hp,keyframes:hp,spring:hs},hg=e=>e/100;class hv extends uH{constructor(e){super(e),this.holdTime=null,this.cancelTime=null,this.currentTime=0,this.playbackSpeed=1,this.pendingPlayState="running",this.startTime=null,this.state="idle",this.stop=()=>{if(this.resolver.cancel(),this.isStopped=!0,"idle"===this.state)return;this.teardown();let{onStop:e}=this.options;e&&e()};let{name:t,motionValue:i,element:n,keyframes:r}=this.options,s=(null==n?void 0:n.KeyframeResolver)||uA;this.resolver=new s(r,(e,t)=>this.onKeyframesResolved(e,t),t,i,n),this.resolver.scheduleResolve()}flatten(){super.flatten(),this._resolved&&Object.assign(this._resolved,this.initPlayback(this._resolved.keyframes))}initPlayback(e){let t,i;let{type:n="keyframes",repeat:r=0,repeatDelay:s=0,repeatType:o,velocity:a=0}=this.options,l=cW(n)?n:hf[n]||hp;l!==hp&&"number"!=typeof e[0]&&(t=u1(hg,u8(e[0],e[1])),e=[0,100]);let c=l({...this.options,keyframes:e});"mirror"===o&&(i=l({...this.options,keyframes:[...e].reverse(),velocity:-a})),null===c.calculatedDuration&&(c.calculatedDuration=cz(c));let{calculatedDuration:d}=c,u=d+s;return{generator:c,mirroredGenerator:i,mapPercentToKeyframes:t,calculatedDuration:d,resolvedDuration:u,totalDuration:u*(r+1)-s}}onPostResolved(){let{autoplay:e=!0}=this.options;this.play(),"paused"!==this.pendingPlayState&&e?this.state=this.pendingPlayState:this.pause()}tick(e,t=!1){let{resolved:i}=this;if(!i){let{keyframes:e}=this.options;return{done:!0,value:e[e.length-1]}}let{finalKeyframe:n,generator:r,mirroredGenerator:s,mapPercentToKeyframes:o,keyframes:a,calculatedDuration:l,totalDuration:c,resolvedDuration:d}=i;if(null===this.startTime)return r.next(0);let{delay:u,repeat:h,repeatType:p,repeatDelay:m,onUpdate:f}=this.options;this.speed>0?this.startTime=Math.min(this.startTime,e):this.speed<0&&(this.startTime=Math.min(e-c/this.speed,this.startTime)),t?this.currentTime=e:null!==this.holdTime?this.currentTime=this.holdTime:this.currentTime=Math.round(e-this.startTime)*this.speed;let g=this.currentTime-u*(this.speed>=0?1:-1),v=this.speed>=0?g<0:g>c;this.currentTime=Math.max(g,0),"finished"===this.state&&null===this.holdTime&&(this.currentTime=c);let y=this.currentTime,b=r;if(h){let e=Math.min(this.currentTime,c)/d,t=Math.floor(e),i=e%1;!i&&e>=1&&(i=1),1===i&&t--,(t=Math.min(t,h+1))%2&&("reverse"===p?(i=1-i,m&&(i-=m/d)):"mirror"===p&&(b=s)),y=dq(0,1,i)*d}let k=v?{done:!1,value:a[0]}:b.next(y);o&&(k.value=o(k.value));let{done:T}=k;v||null===l||(T=this.speed>=0?this.currentTime>=c:this.currentTime<=0);let S=null===this.holdTime&&("finished"===this.state||"running"===this.state&&T);return S&&void 0!==n&&(k.value=uW(a,this.options,n)),f&&f(k.value),S&&this.finish(),k}get duration(){let{resolved:e}=this;return e?dt(e.calculatedDuration):0}get time(){return dt(this.currentTime)}set time(e){e=de(e),this.currentTime=e,null!==this.holdTime||0===this.speed?this.holdTime=e:this.driver&&(this.startTime=this.driver.now()-e/this.speed)}get speed(){return this.playbackSpeed}set speed(e){let t=this.playbackSpeed!==e;this.playbackSpeed=e,t&&(this.time=dt(this.currentTime))}play(){if(this.resolver.isScheduled||this.resolver.resume(),!this._resolved){this.pendingPlayState="running";return}if(this.isStopped)return;let{driver:e=hm,onPlay:t,startTime:i}=this.options;this.driver||(this.driver=e(e=>this.tick(e))),t&&t();let n=this.driver.now();null!==this.holdTime?this.startTime=n-this.holdTime:this.startTime?"finished"===this.state&&(this.startTime=n):this.startTime=null!=i?i:this.calcStartTime(),"finished"===this.state&&this.updateFinishedPromise(),this.cancelTime=this.startTime,this.holdTime=null,this.state="running",this.driver.start()}pause(){var e;if(!this._resolved){this.pendingPlayState="paused";return}this.state="paused",this.holdTime=null!==(e=this.currentTime)&&void 0!==e?e:0}complete(){"running"!==this.state&&this.play(),this.pendingPlayState=this.state="finished",this.holdTime=null}finish(){this.teardown(),this.state="finished";let{onComplete:e}=this.options;e&&e()}cancel(){null!==this.cancelTime&&this.tick(this.cancelTime),this.teardown(),this.updateFinishedPromise()}teardown(){this.state="idle",this.stopDriver(),this.resolveFinishedPromise(),this.updateFinishedPromise(),this.startTime=this.cancelTime=null,this.resolver.cancel()}stopDriver(){this.driver&&(this.driver.stop(),this.driver=void 0)}sample(e){return this.startTime=0,this.tick(e,!0)}}let hy=new Set(["opacity","clipPath","filter","transform"]),hb=cU(()=>Object.hasOwnProperty.call(Element.prototype,"animate")),hk={anticipate:dj,backInOut:dL,circInOut:dV};class hT extends uH{constructor(e){super(e);let{name:t,motionValue:i,element:n,keyframes:r}=this.options;this.resolver=new uB(r,(e,t)=>this.onKeyframesResolved(e,t),t,i,n),this.resolver.scheduleResolve()}initPlayback(e,t){var i;let{duration:n=300,times:r,ease:s,type:o,motionValue:a,name:l,startTime:c}=this.options;if(!a.owner||!a.owner.current)return!1;if("string"==typeof s&&cK()&&s in hk&&(s=hk[s]),cW((i=this.options).type)||"spring"===i.type||!function e(t){return!!("function"==typeof t&&cK()||!t||"string"==typeof t&&(t in cQ||cK())||cG(t)||Array.isArray(t)&&t.every(e))}(i.ease)){let{onComplete:t,onUpdate:i,motionValue:a,element:l,...c}=this.options,d=function(e,t){let i=new hv({...t,keyframes:e,repeat:0,delay:0,isGenerator:!0}),n={done:!1,value:e[0]},r=[],s=0;for(;!n.done&&s<2e4;)r.push((n=i.sample(s)).value),s+=10;return{times:void 0,keyframes:r,duration:s-10,ease:"linear"}}(e,c);1===(e=d.keyframes).length&&(e[1]=e[0]),n=d.duration,r=d.times,s=d.ease,o="keyframes"}let d=function(e,t,i,{delay:n=0,duration:r=300,repeat:s=0,repeatType:o="loop",ease:a="easeInOut",times:l}={}){let c={[t]:i};l&&(c.offset=l);let d=function e(t,i){if(t)return"function"==typeof t&&cK()?cX(t,i):cG(t)?cY(t):Array.isArray(t)?t.map(t=>e(t,i)||cQ.easeOut):cQ[t]}(a,r);return Array.isArray(d)&&(c.easing=d),e.animate(c,{delay:n,duration:r,easing:Array.isArray(d)?"linear":d,fill:"both",iterations:s+1,direction:"reverse"===o?"alternate":"normal"})}(a.owner.current,l,e,{...this.options,duration:n,times:r,ease:s});return d.startTime=null!=c?c:this.calcStartTime(),this.pendingTimeline?(cH(d,this.pendingTimeline),this.pendingTimeline=void 0):d.onfinish=()=>{let{onComplete:i}=this.options;a.set(uW(e,this.options,t)),i&&i(),this.cancel(),this.resolveFinishedPromise()},{animation:d,duration:n,times:r,type:o,ease:s,keyframes:e}}get duration(){let{resolved:e}=this;if(!e)return 0;let{duration:t}=e;return dt(t)}get time(){let{resolved:e}=this;if(!e)return 0;let{animation:t}=e;return dt(t.currentTime||0)}set time(e){let{resolved:t}=this;if(!t)return;let{animation:i}=t;i.currentTime=de(e)}get speed(){let{resolved:e}=this;if(!e)return 1;let{animation:t}=e;return t.playbackRate}set speed(e){let{resolved:t}=this;if(!t)return;let{animation:i}=t;i.playbackRate=e}get state(){let{resolved:e}=this;if(!e)return"idle";let{animation:t}=e;return t.playState}get startTime(){let{resolved:e}=this;if(!e)return null;let{animation:t}=e;return t.startTime}attachTimeline(e){if(this._resolved){let{resolved:t}=this;if(!t)return di;let{animation:i}=t;cH(i,e)}else this.pendingTimeline=e;return di}play(){if(this.isStopped)return;let{resolved:e}=this;if(!e)return;let{animation:t}=e;"finished"===t.playState&&this.updateFinishedPromise(),t.play()}pause(){let{resolved:e}=this;if(!e)return;let{animation:t}=e;t.pause()}stop(){if(this.resolver.cancel(),this.isStopped=!0,"idle"===this.state)return;this.resolveFinishedPromise(),this.updateFinishedPromise();let{resolved:e}=this;if(!e)return;let{animation:t,keyframes:i,duration:n,type:r,ease:s,times:o}=e;if("idle"===t.playState||"finished"===t.playState)return;if(this.time){let{motionValue:e,onUpdate:t,onComplete:a,element:l,...c}=this.options,d=new hv({...c,keyframes:i,duration:n,type:r,ease:s,times:o,isGenerator:!0}),u=de(this.time);e.setWithVelocity(d.sample(u-10).value,d.sample(u).value,10)}let{onStop:a}=this.options;a&&a(),this.cancel()}complete(){let{resolved:e}=this;e&&e.animation.finish()}cancel(){let{resolved:e}=this;e&&e.animation.cancel()}static supports(e){let{motionValue:t,name:i,repeatDelay:n,repeatType:r,damping:s,type:o}=e;if(!t||!t.owner||!(t.owner.current instanceof HTMLElement))return!1;let{onUpdate:a,transformTemplate:l}=t.owner.getProps();return hb()&&i&&hy.has(i)&&!a&&!l&&!n&&"mirror"!==r&&0!==s&&"inertia"!==o}}let hS={type:"spring",stiffness:500,damping:25,restSpeed:10},hC=e=>({type:"spring",stiffness:550,damping:0===e?2*Math.sqrt(550):30,restSpeed:10}),hw={type:"keyframes",duration:.8},hE={type:"keyframes",ease:[.25,.1,.35,1],duration:.3},hP=(e,{keyframes:t})=>t.length>2?hw:dr.has(e)?e.startsWith("scale")?hC(t[1]):hS:hE,hx=(e,t,i,n={},r,s)=>o=>{let a=cq(n,e)||{},l=a.delay||n.delay||0,{elapsed:c=0}=n;c-=de(l);let d={keyframes:Array.isArray(i)?i:[null,i],ease:"easeOut",velocity:t.getVelocity(),...a,delay:-c,onUpdate:e=>{t.set(e),a.onUpdate&&a.onUpdate(e)},onComplete:()=>{o(),a.onComplete&&a.onComplete()},name:e,motionValue:t,element:s?void 0:r};!function({when:e,delay:t,delayChildren:i,staggerChildren:n,staggerDirection:r,repeat:s,repeatType:o,repeatDelay:a,from:l,elapsed:c,...d}){return!!Object.keys(d).length}(a)&&(d={...d,...hP(e,d)}),d.duration&&(d.duration=de(d.duration)),d.repeatDelay&&(d.repeatDelay=de(d.repeatDelay)),void 0!==d.from&&(d.keyframes[0]=d.from);let u=!1;if(!1!==d.type&&(0!==d.duration||d.repeatDelay)||(d.duration=0,0!==d.delay||(u=!0)),(dO.current||dc.skipAnimations)&&(u=!0,d.duration=0,d.delay=0),u&&!s&&void 0!==t.get()){let e=uW(d.keyframes,a);if(void 0!==e)return dh.update(()=>{d.onUpdate(e),d.onComplete()}),new cB([])}return!s&&hT.supports(d)?new hT(d):new hv(d)};function hR(e,t,{delay:i=0,transitionOverride:n,type:r}={}){var s;let{transition:o=e.getDefaultTransition(),transitionEnd:a,...l}=t;n&&(o=n);let c=[],d=r&&e.animationState&&e.animationState.getState()[r];for(let t in l){let n=e.getValue(t,null!==(s=e.latestValues[t])&&void 0!==s?s:null),r=l[t];if(void 0===r||d&&function({protectedKeys:e,needsAnimating:t},i){let n=e.hasOwnProperty(i)&&!0!==t[i];return t[i]=!1,n}(d,t))continue;let a={delay:i,...cq(o||{},t)},u=!1;if(window.MotionHandoffAnimation){let i=e.props[dR];if(i){let e=window.MotionHandoffAnimation(i,t,dh);null!==e&&(a.startTime=e,u=!0)}}dP(e,t),n.start(hx(t,n,r,e.shouldReduceMotion&&ds.has(t)?{type:!1}:a,e,u));let h=n.animation;h&&c.push(h)}return a&&Promise.all(c).then(()=>{dh.update(()=>{a&&function(e,t){let{transitionEnd:i={},transition:n={},...r}=cN(e,t)||{};for(let t in r={...r,...i}){let i=dl(r[t]);e.hasValue(t)?e.getValue(t).set(i):e.addValue(t,dw(i))}}(e,a)})}),c}function hO(e,t,i={}){var n;let r=cN(e,t,"exit"===i.type?null===(n=e.presenceContext)||void 0===n?void 0:n.custom:void 0),{transition:s=e.getDefaultTransition()||{}}=r||{};i.transitionOverride&&(s=i.transitionOverride);let o=r?()=>Promise.all(hR(e,r,i)):()=>Promise.resolve(),a=e.variantChildren&&e.variantChildren.size?(n=0)=>{let{delayChildren:r=0,staggerChildren:o,staggerDirection:a}=s;return function(e,t,i=0,n=0,r=1,s){let o=[],a=(e.variantChildren.size-1)*n,l=1===r?(e=0)=>e*n:(e=0)=>a-e*n;return Array.from(e.variantChildren).sort(hA).forEach((e,n)=>{e.notify("AnimationStart",t),o.push(hO(e,t,{...s,delay:i+l(n)}).then(()=>e.notify("AnimationComplete",t)))}),Promise.all(o)}(e,t,r+n,o,a,i)}:()=>Promise.resolve(),{when:l}=s;if(!l)return Promise.all([o(),a(i.delay)]);{let[e,t]="beforeChildren"===l?[o,a]:[a,o];return e().then(()=>t())}}function hA(e,t){return e.sortNodePosition(t)}let hI=cj.length,hM=[...cL].reverse(),hD=cL.length;function h_(e=!1){return{isActive:e,protectedKeys:{},needsAnimating:{},prevResolvedValues:{}}}function hN(){return{animate:h_(!0),whileInView:h_(),whileHover:h_(),whileTap:h_(),whileDrag:h_(),whileFocus:h_(),exit:h_()}}class hL{constructor(e){this.isMounted=!1,this.node=e}update(){}}class hj extends hL{constructor(e){super(e),e.animationState||(e.animationState=function(e){let t=t=>Promise.all(t.map(({animation:t,options:i})=>(function(e,t,i={}){let n;if(e.notify("AnimationStart",t),Array.isArray(t))n=Promise.all(t.map(t=>hO(e,t,i)));else if("string"==typeof t)n=hO(e,t,i);else{let r="function"==typeof t?cN(e,t,i.custom):t;n=Promise.all(hR(e,r,i))}return n.then(()=>{e.notify("AnimationComplete",t)})})(e,t,i))),i=hN(),n=!0,r=t=>(i,n)=>{var r;let s=cN(e,n,"exit"===t?null===(r=e.presenceContext)||void 0===r?void 0:r.custom:void 0);if(s){let{transition:e,transitionEnd:t,...n}=s;i={...i,...n,...t}}return i};function s(s){let{props:o}=e,a=function e(t){if(!t)return;if(!t.isControllingVariants){let i=t.parent&&e(t.parent)||{};return void 0!==t.props.initial&&(i.initial=t.props.initial),i}let i={};for(let e=0;e<hI;e++){let n=cj[e],r=t.props[n];(cM(r)||!1===r)&&(i[n]=r)}return i}(e.parent)||{},l=[],c=new Set,d={},u=1/0;for(let t=0;t<hD;t++){var h;let p=hM[t],m=i[p],f=void 0!==o[p]?o[p]:a[p],g=cM(f),v=p===s?m.isActive:null;!1===v&&(u=t);let y=f===a[p]&&f!==o[p]&&g;if(y&&n&&e.manuallyAnimateOnMount&&(y=!1),m.protectedKeys={...d},!m.isActive&&null===v||!f&&!m.prevProp||cO(f)||"boolean"==typeof f)continue;let b=(h=m.prevProp,"string"==typeof f?f!==h:!!Array.isArray(f)&&!cI(f,h)),k=b||p===s&&m.isActive&&!y&&g||t>u&&g,T=!1,S=Array.isArray(f)?f:[f],C=S.reduce(r(p),{});!1===v&&(C={});let{prevResolvedValues:w={}}=m,E={...w,...C},P=t=>{k=!0,c.has(t)&&(T=!0,c.delete(t)),m.needsAnimating[t]=!0;let i=e.getValue(t);i&&(i.liveStyle=!1)};for(let e in E){let t=C[e],i=w[e];if(!d.hasOwnProperty(e))(cA(t)&&cA(i)?cI(t,i):t===i)?void 0!==t&&c.has(e)?P(e):m.protectedKeys[e]=!0:null!=t?P(e):c.add(e)}m.prevProp=f,m.prevResolvedValues=C,m.isActive&&(d={...d,...C}),n&&e.blockInitialAnimation&&(k=!1);let x=!(y&&b)||T;k&&x&&l.push(...S.map(e=>({animation:e,options:{type:p}})))}if(c.size){let t={};c.forEach(i=>{let n=e.getBaseTarget(i),r=e.getValue(i);r&&(r.liveStyle=!0),t[i]=null!=n?n:null}),l.push({animation:t})}let p=!!l.length;return n&&(!1===o.initial||o.initial===o.animate)&&!e.manuallyAnimateOnMount&&(p=!1),n=!1,p?t(l):Promise.resolve()}return{animateChanges:s,setActive:function(t,n){var r;if(i[t].isActive===n)return Promise.resolve();null===(r=e.variantChildren)||void 0===r||r.forEach(e=>{var i;return null===(i=e.animationState)||void 0===i?void 0:i.setActive(t,n)}),i[t].isActive=n;let o=s(t);for(let e in i)i[e].protectedKeys={};return o},setAnimateFunction:function(i){t=i(e)},getState:()=>i,reset:()=>{i=hN(),n=!0}}}(e))}updateAnimationControlsSubscription(){let{animate:e}=this.node.getProps();cO(e)&&(this.unmountControls=e.subscribe(this.node))}mount(){this.updateAnimationControlsSubscription()}update(){let{animate:e}=this.node.getProps(),{animate:t}=this.node.prevProps||{};e!==t&&this.updateAnimationControlsSubscription()}unmount(){var e;this.node.animationState.reset(),null===(e=this.unmountControls)||void 0===e||e.call(this)}}let hU=0;class hF extends hL{constructor(){super(...arguments),this.id=hU++}update(){if(!this.node.presenceContext)return;let{isPresent:e,onExitComplete:t}=this.node.presenceContext,{isPresent:i}=this.node.prevPresenceContext||{};if(!this.node.animationState||e===i)return;let n=this.node.animationState.setActive("exit",!e);t&&!e&&n.then(()=>t(this.id))}mount(){let{register:e}=this.node.presenceContext||{};e&&(this.unmount=e(this.id))}unmount(){}}function hV(e,t,i,n={passive:!0}){return e.addEventListener(t,i,n),()=>e.removeEventListener(t,i)}function hB(e){return{point:{x:e.pageX,y:e.pageY}}}let hq=e=>t=>c3(t)&&e(t,hB(t));function hz(e,t,i,n){return hV(e,t,hq(i),n)}let hW=(e,t)=>Math.abs(e-t);class hH{constructor(e,t,{transformPagePoint:i,contextWindow:n,dragSnapToOrigin:r=!1}={}){if(this.startEvent=null,this.lastMoveEvent=null,this.lastMoveEventInfo=null,this.handlers={},this.contextWindow=window,this.updatePoint=()=>{if(!(this.lastMoveEvent&&this.lastMoveEventInfo))return;let e=hK(this.lastMoveEventInfo,this.history),t=null!==this.startEvent,i=function(e,t){return Math.sqrt(hW(e.x,t.x)**2+hW(e.y,t.y)**2)}(e.offset,{x:0,y:0})>=3;if(!t&&!i)return;let{point:n}=e,{timestamp:r}=dm;this.history.push({...n,timestamp:r});let{onStart:s,onMove:o}=this.handlers;t||(s&&s(this.lastMoveEvent,e),this.startEvent=this.lastMoveEvent),o&&o(this.lastMoveEvent,e)},this.handlePointerMove=(e,t)=>{this.lastMoveEvent=e,this.lastMoveEventInfo=hG(t,this.transformPagePoint),dh.update(this.updatePoint,!0)},this.handlePointerUp=(e,t)=>{this.end();let{onEnd:i,onSessionEnd:n,resumeAnimation:r}=this.handlers;if(this.dragSnapToOrigin&&r&&r(),!(this.lastMoveEvent&&this.lastMoveEventInfo))return;let s=hK("pointercancel"===e.type?this.lastMoveEventInfo:hG(t,this.transformPagePoint),this.history);this.startEvent&&i&&i(e,s),n&&n(e,s)},!c3(e))return;this.dragSnapToOrigin=r,this.handlers=t,this.transformPagePoint=i,this.contextWindow=n||window;let s=hG(hB(e),this.transformPagePoint),{point:o}=s,{timestamp:a}=dm;this.history=[{...o,timestamp:a}];let{onSessionStart:l}=t;l&&l(e,hK(s,this.history)),this.removeListeners=u1(hz(this.contextWindow,"pointermove",this.handlePointerMove),hz(this.contextWindow,"pointerup",this.handlePointerUp),hz(this.contextWindow,"pointercancel",this.handlePointerUp))}updateHandlers(e){this.handlers=e}end(){this.removeListeners&&this.removeListeners(),dp(this.updatePoint)}}function hG(e,t){return t?{point:t(e.point)}:e}function h$(e,t){return{x:e.x-t.x,y:e.y-t.y}}function hK({point:e},t){return{point:e,delta:h$(e,hJ(t)),offset:h$(e,t[0]),velocity:function(e,t){if(e.length<2)return{x:0,y:0};let i=e.length-1,n=null,r=hJ(e);for(;i>=0&&(n=e[i],!(r.timestamp-n.timestamp>de(.1)));)i--;if(!n)return{x:0,y:0};let s=dt(r.timestamp-n.timestamp);if(0===s)return{x:0,y:0};let o={x:(r.x-n.x)/s,y:(r.y-n.y)/s};return o.x===1/0&&(o.x=0),o.y===1/0&&(o.y=0),o}(t,0)}}function hJ(e){return e[e.length-1]}function hX(e){return e&&"object"==typeof e&&Object.prototype.hasOwnProperty.call(e,"current")}function hY(e){return e.max-e.min}function hQ(e,t,i,n=.5){e.origin=n,e.originPoint=uG(t.min,t.max,e.origin),e.scale=hY(i)/hY(t),e.translate=uG(i.min,i.max,e.origin)-e.originPoint,(e.scale>=.9999&&e.scale<=1.0001||isNaN(e.scale))&&(e.scale=1),(e.translate>=-.01&&e.translate<=.01||isNaN(e.translate))&&(e.translate=0)}function hZ(e,t,i,n){hQ(e.x,t.x,i.x,n?n.originX:void 0),hQ(e.y,t.y,i.y,n?n.originY:void 0)}function h0(e,t,i){e.min=i.min+t.min,e.max=e.min+hY(t)}function h1(e,t,i){e.min=t.min-i.min,e.max=e.min+hY(t)}function h2(e,t,i){h1(e.x,t.x,i.x),h1(e.y,t.y,i.y)}function h3(e,t,i){return{min:void 0!==t?e.min+t:void 0,max:void 0!==i?e.max+i-(e.max-e.min):void 0}}function h5(e,t){let i=t.min-e.min,n=t.max-e.max;return t.max-t.min<e.max-e.min&&([i,n]=[n,i]),{min:i,max:n}}function h4(e,t,i){return{min:h6(e,t),max:h6(e,i)}}function h6(e,t){return"number"==typeof e?e:e[t]||0}let h9=()=>({translate:0,scale:1,origin:0,originPoint:0}),h8=()=>({x:h9(),y:h9()}),h7=()=>({min:0,max:0}),pe=()=>({x:h7(),y:h7()});function pt(e){return[e("x"),e("y")]}function pi({top:e,left:t,right:i,bottom:n}){return{x:{min:t,max:i},y:{min:e,max:n}}}function pn(e){return void 0===e||1===e}function pr({scale:e,scaleX:t,scaleY:i}){return!pn(e)||!pn(t)||!pn(i)}function ps(e){return pr(e)||po(e)||e.z||e.rotate||e.rotateX||e.rotateY||e.skewX||e.skewY}function po(e){var t,i;return(t=e.x)&&"0%"!==t||(i=e.y)&&"0%"!==i}function pa(e,t,i,n,r){return void 0!==r&&(e=n+r*(e-n)),n+i*(e-n)+t}function pl(e,t=0,i=1,n,r){e.min=pa(e.min,t,i,n,r),e.max=pa(e.max,t,i,n,r)}function pc(e,{x:t,y:i}){pl(e.x,t.translate,t.scale,t.originPoint),pl(e.y,i.translate,i.scale,i.originPoint)}function pd(e,t){e.min=e.min+t,e.max=e.max+t}function pu(e,t,i,n,r=.5){let s=uG(e.min,e.max,r);pl(e,t,i,s,n)}function ph(e,t){pu(e.x,t.x,t.scaleX,t.scale,t.originX),pu(e.y,t.y,t.scaleY,t.scale,t.originY)}function pp(e,t){return pi(function(e,t){if(!t)return e;let i=t({x:e.left,y:e.top}),n=t({x:e.right,y:e.bottom});return{top:i.y,left:i.x,bottom:n.y,right:n.x}}(e.getBoundingClientRect(),t))}let pm=({current:e})=>e?e.ownerDocument.defaultView:null,pf=new WeakMap;class pg{constructor(e){this.openDragLock=null,this.isDragging=!1,this.currentDirection=null,this.originPoint={x:0,y:0},this.constraints=!1,this.hasMutatedConstraints=!1,this.elastic=pe(),this.visualElement=e}start(e,{snapToCursor:t=!1}={}){let{presenceContext:i}=this.visualElement;if(i&&!1===i.isPresent)return;let{dragSnapToOrigin:n}=this.getProps();this.panSession=new hH(e,{onSessionStart:e=>{let{dragSnapToOrigin:i}=this.getProps();i?this.pauseAnimation():this.stopAnimation(),t&&this.snapToCursor(hB(e).point)},onStart:(e,t)=>{let{drag:i,dragPropagation:n,onDragStart:r}=this.getProps();if(i&&!n&&(this.openDragLock&&this.openDragLock(),this.openDragLock="x"===i||"y"===i?cZ[i]?null:(cZ[i]=!0,()=>{cZ[i]=!1}):cZ.x||cZ.y?null:(cZ.x=cZ.y=!0,()=>{cZ.x=cZ.y=!1}),!this.openDragLock))return;this.isDragging=!0,this.currentDirection=null,this.resolveConstraints(),this.visualElement.projection&&(this.visualElement.projection.isAnimationBlocked=!0,this.visualElement.projection.target=void 0),pt(e=>{let t=this.getAxisMotionValue(e).get()||0;if(d3.test(t)){let{projection:i}=this.visualElement;if(i&&i.layout){let n=i.layout.layoutBox[e];if(n){let e=hY(n);t=parseFloat(t)/100*e}}}this.originPoint[e]=t}),r&&dh.postRender(()=>r(e,t)),dP(this.visualElement,"transform");let{animationState:s}=this.visualElement;s&&s.setActive("whileDrag",!0)},onMove:(e,t)=>{let{dragPropagation:i,dragDirectionLock:n,onDirectionLock:r,onDrag:s}=this.getProps();if(!i&&!this.openDragLock)return;let{offset:o}=t;if(n&&null===this.currentDirection){this.currentDirection=function(e,t=10){let i=null;return Math.abs(e.y)>t?i="y":Math.abs(e.x)>t&&(i="x"),i}(o),null!==this.currentDirection&&r&&r(this.currentDirection);return}this.updateAxis("x",t.point,o),this.updateAxis("y",t.point,o),this.visualElement.render(),s&&s(e,t)},onSessionEnd:(e,t)=>this.stop(e,t),resumeAnimation:()=>pt(e=>{var t;return"paused"===this.getAnimationState(e)&&(null===(t=this.getAxisMotionValue(e).animation)||void 0===t?void 0:t.play())})},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:n,contextWindow:pm(this.visualElement)})}stop(e,t){let i=this.isDragging;if(this.cancel(),!i)return;let{velocity:n}=t;this.startAnimation(n);let{onDragEnd:r}=this.getProps();r&&dh.postRender(()=>r(e,t))}cancel(){this.isDragging=!1;let{projection:e,animationState:t}=this.visualElement;e&&(e.isAnimationBlocked=!1),this.panSession&&this.panSession.end(),this.panSession=void 0;let{dragPropagation:i}=this.getProps();!i&&this.openDragLock&&(this.openDragLock(),this.openDragLock=null),t&&t.setActive("whileDrag",!1)}updateAxis(e,t,i){let{drag:n}=this.getProps();if(!i||!pv(e,n,this.currentDirection))return;let r=this.getAxisMotionValue(e),s=this.originPoint[e]+i[e];this.constraints&&this.constraints[e]&&(s=function(e,{min:t,max:i},n){return void 0!==t&&e<t?e=n?uG(t,e,n.min):Math.max(e,t):void 0!==i&&e>i&&(e=n?uG(i,e,n.max):Math.min(e,i)),e}(s,this.constraints[e],this.elastic[e])),r.set(s)}resolveConstraints(){var e;let{dragConstraints:t,dragElastic:i}=this.getProps(),n=this.visualElement.projection&&!this.visualElement.projection.layout?this.visualElement.projection.measure(!1):null===(e=this.visualElement.projection)||void 0===e?void 0:e.layout,r=this.constraints;t&&hX(t)?this.constraints||(this.constraints=this.resolveRefConstraints()):t&&n?this.constraints=function(e,{top:t,left:i,bottom:n,right:r}){return{x:h3(e.x,i,r),y:h3(e.y,t,n)}}(n.layoutBox,t):this.constraints=!1,this.elastic=function(e=.35){return!1===e?e=0:!0===e&&(e=.35),{x:h4(e,"left","right"),y:h4(e,"top","bottom")}}(i),r!==this.constraints&&n&&this.constraints&&!this.hasMutatedConstraints&&pt(e=>{!1!==this.constraints&&this.getAxisMotionValue(e)&&(this.constraints[e]=function(e,t){let i={};return void 0!==t.min&&(i.min=t.min-e.min),void 0!==t.max&&(i.max=t.max-e.min),i}(n.layoutBox[e],this.constraints[e]))})}resolveRefConstraints(){var e;let{dragConstraints:t,onMeasureDragConstraints:i}=this.getProps();if(!t||!hX(t))return!1;let n=t.current;di(null!==n,"If `dragConstraints` is set as a React ref, that ref must be passed to another component's `ref` prop.");let{projection:r}=this.visualElement;if(!r||!r.layout)return!1;let s=function(e,t,i){let n=pp(e,i),{scroll:r}=t;return r&&(pd(n.x,r.offset.x),pd(n.y,r.offset.y)),n}(n,r.root,this.visualElement.getTransformPagePoint()),o={x:h5((e=r.layout.layoutBox).x,s.x),y:h5(e.y,s.y)};if(i){let e=i(function({x:e,y:t}){return{top:t.min,right:e.max,bottom:t.max,left:e.min}}(o));this.hasMutatedConstraints=!!e,e&&(o=pi(e))}return o}startAnimation(e){let{drag:t,dragMomentum:i,dragElastic:n,dragTransition:r,dragSnapToOrigin:s,onDragTransitionEnd:o}=this.getProps(),a=this.constraints||{};return Promise.all(pt(o=>{if(!pv(o,t,this.currentDirection))return;let l=a&&a[o]||{};s&&(l={min:0,max:0});let c={type:"inertia",velocity:i?e[o]:0,bounceStiffness:n?200:1e6,bounceDamping:n?40:1e7,timeConstant:750,restDelta:1,restSpeed:10,...r,...l};return this.startAxisValueAnimation(o,c)})).then(o)}startAxisValueAnimation(e,t){let i=this.getAxisMotionValue(e);return dP(this.visualElement,e),i.start(hx(e,i,0,t,this.visualElement,!1))}stopAnimation(){pt(e=>this.getAxisMotionValue(e).stop())}pauseAnimation(){pt(e=>{var t;return null===(t=this.getAxisMotionValue(e).animation)||void 0===t?void 0:t.pause()})}getAnimationState(e){var t;return null===(t=this.getAxisMotionValue(e).animation)||void 0===t?void 0:t.state}getAxisMotionValue(e){let t=`_drag${e.toUpperCase()}`,i=this.visualElement.getProps();return i[t]||this.visualElement.getValue(e,(i.initial?i.initial[e]:void 0)||0)}snapToCursor(e){pt(t=>{let{drag:i}=this.getProps();if(!pv(t,i,this.currentDirection))return;let{projection:n}=this.visualElement,r=this.getAxisMotionValue(t);if(n&&n.layout){let{min:i,max:s}=n.layout.layoutBox[t];r.set(e[t]-uG(i,s,.5))}})}scalePositionWithinConstraints(){if(!this.visualElement.current)return;let{drag:e,dragConstraints:t}=this.getProps(),{projection:i}=this.visualElement;if(!hX(t)||!i||!this.constraints)return;this.stopAnimation();let n={x:0,y:0};pt(e=>{let t=this.getAxisMotionValue(e);if(t&&!1!==this.constraints){let i=t.get();n[e]=function(e,t){let i=.5,n=hY(e),r=hY(t);return r>n?i=cJ(t.min,t.max-n,e.min):n>r&&(i=cJ(e.min,e.max-r,t.min)),dq(0,1,i)}({min:i,max:i},this.constraints[e])}});let{transformTemplate:r}=this.visualElement.getProps();this.visualElement.current.style.transform=r?r({},""):"none",i.root&&i.root.updateScroll(),i.updateLayout(),this.resolveConstraints(),pt(t=>{if(!pv(t,e,null))return;let i=this.getAxisMotionValue(t),{min:r,max:s}=this.constraints[t];i.set(uG(r,s,n[t]))})}addListeners(){if(!this.visualElement.current)return;pf.set(this.visualElement,this);let e=hz(this.visualElement.current,"pointerdown",e=>{let{drag:t,dragListener:i=!0}=this.getProps();t&&i&&this.start(e)}),t=()=>{let{dragConstraints:e}=this.getProps();hX(e)&&e.current&&(this.constraints=this.resolveRefConstraints())},{projection:i}=this.visualElement,n=i.addEventListener("measure",t);i&&!i.layout&&(i.root&&i.root.updateScroll(),i.updateLayout()),dh.read(t);let r=hV(window,"resize",()=>this.scalePositionWithinConstraints()),s=i.addEventListener("didUpdate",({delta:e,hasLayoutChanged:t})=>{this.isDragging&&t&&(pt(t=>{let i=this.getAxisMotionValue(t);i&&(this.originPoint[t]+=e[t].translate,i.set(i.get()+e[t].translate))}),this.visualElement.render())});return()=>{r(),e(),n(),s&&s()}}getProps(){let e=this.visualElement.getProps(),{drag:t=!1,dragDirectionLock:i=!1,dragPropagation:n=!1,dragConstraints:r=!1,dragElastic:s=.35,dragMomentum:o=!0}=e;return{...e,drag:t,dragDirectionLock:i,dragPropagation:n,dragConstraints:r,dragElastic:s,dragMomentum:o}}}function pv(e,t,i){return(!0===t||t===e)&&(null===i||i===e)}class py extends hL{constructor(e){super(e),this.removeGroupControls=di,this.removeListeners=di,this.controls=new pg(e)}mount(){let{dragControls:e}=this.node.getProps();e&&(this.removeGroupControls=e.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||di}unmount(){this.removeGroupControls(),this.removeListeners()}}let pb=e=>(t,i)=>{e&&dh.postRender(()=>e(t,i))};class pk extends hL{constructor(){super(...arguments),this.removePointerDownListener=di}onPointerDown(e){this.session=new hH(e,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:pm(this.node)})}createPanHandlers(){let{onPanSessionStart:e,onPanStart:t,onPan:i,onPanEnd:n}=this.node.getProps();return{onSessionStart:pb(e),onStart:pb(t),onMove:i,onEnd:(e,t)=>{delete this.session,n&&dh.postRender(()=>n(e,t))}}}mount(){this.removePointerDownListener=hz(this.node.current,"pointerdown",e=>this.onPointerDown(e))}update(){this.session&&this.session.updateHandlers(this.createPanHandlers())}unmount(){this.removePointerDownListener(),this.session&&this.session.end()}}let pT=(0,p.createContext)({}),pS={hasAnimatedSinceResize:!0,hasEverUpdated:!1};function pC(e,t){return t.max===t.min?0:e/(t.max-t.min)*100}let pw={correct:(e,t)=>{if(!t.target)return e;if("string"==typeof e){if(!d5.test(e))return e;e=parseFloat(e)}let i=pC(e,t.target.x),n=pC(e,t.target.y);return`${i}% ${n}%`}},pE={},{schedule:pP,cancel:px}=du(queueMicrotask,!1);class pR extends p.Component{componentDidMount(){let{visualElement:e,layoutGroup:t,switchLayoutGroup:i,layoutId:n}=this.props,{projection:r}=e;Object.assign(pE,pA),r&&(t.group&&t.group.add(r),i&&i.register&&n&&i.register(r),r.root.didUpdate(),r.addEventListener("animationComplete",()=>{this.safeToRemove()}),r.setOptions({...r.options,onExitComplete:()=>this.safeToRemove()})),pS.hasEverUpdated=!0}getSnapshotBeforeUpdate(e){let{layoutDependency:t,visualElement:i,drag:n,isPresent:r}=this.props,s=i.projection;return s&&(s.isPresent=r,n||e.layoutDependency!==t||void 0===t?s.willUpdate():this.safeToRemove(),e.isPresent===r||(r?s.promote():s.relegate()||dh.postRender(()=>{let e=s.getStack();e&&e.members.length||this.safeToRemove()}))),null}componentDidUpdate(){let{projection:e}=this.props.visualElement;e&&(e.root.didUpdate(),pP.postRender(()=>{!e.currentAnimation&&e.isLead()&&this.safeToRemove()}))}componentWillUnmount(){let{visualElement:e,layoutGroup:t,switchLayoutGroup:i}=this.props,{projection:n}=e;n&&(n.scheduleCheckAfterUnmount(),t&&t.group&&t.group.remove(n),i&&i.deregister&&i.deregister(n))}safeToRemove(){let{safeToRemove:e}=this.props;e&&e()}render(){return null}}function pO(e){let[t,i]=cC(),n=(0,p.useContext)(cf);return(0,u.jsx)(pR,{...e,layoutGroup:n,switchLayoutGroup:(0,p.useContext)(pT),isPresent:t,safeToRemove:i})}let pA={borderRadius:{...pw,applyTo:["borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"]},borderTopLeftRadius:pw,borderTopRightRadius:pw,borderBottomLeftRadius:pw,borderBottomRightRadius:pw,boxShadow:{correct:(e,{treeScale:t,projectionDelta:i})=>{let n=ul.parse(e);if(n.length>5)return e;let r=ul.createTransformer(e),s="number"!=typeof n[0]?1:0,o=i.x.scale*t.x,a=i.y.scale*t.y;n[0+s]/=o,n[1+s]/=a;let l=uG(o,a,.5);return"number"==typeof n[2+s]&&(n[2+s]/=l),"number"==typeof n[3+s]&&(n[3+s]/=l),r(n)}}},pI=(e,t)=>e.depth-t.depth;class pM{constructor(){this.children=[],this.isDirty=!1}add(e){dy(this.children,e),this.isDirty=!0}remove(e){db(this.children,e),this.isDirty=!0}forEach(e){this.isDirty&&this.children.sort(pI),this.isDirty=!1,this.children.forEach(e)}}function pD(e){let t=dE(e)?e.get():e;return da(t)?t.toValue():t}let p_=["TopLeft","TopRight","BottomLeft","BottomRight"],pN=p_.length,pL=e=>"string"==typeof e?parseFloat(e):e,pj=e=>"number"==typeof e||d5.test(e);function pU(e,t){return void 0!==e[t]?e[t]:e.borderRadius}let pF=pB(0,.5,dF),pV=pB(.5,.95,di);function pB(e,t,i){return n=>n<e?0:n>t?1:i(cJ(e,t,n))}function pq(e,t){e.min=t.min,e.max=t.max}function pz(e,t){pq(e.x,t.x),pq(e.y,t.y)}function pW(e,t){e.translate=t.translate,e.scale=t.scale,e.originPoint=t.originPoint,e.origin=t.origin}function pH(e,t,i,n,r){return e-=t,e=n+1/i*(e-n),void 0!==r&&(e=n+1/r*(e-n)),e}function pG(e,t,[i,n,r],s,o){!function(e,t=0,i=1,n=.5,r,s=e,o=e){if(d3.test(t)&&(t=parseFloat(t),t=uG(o.min,o.max,t/100)-o.min),"number"!=typeof t)return;let a=uG(s.min,s.max,n);e===s&&(a-=t),e.min=pH(e.min,t,i,a,r),e.max=pH(e.max,t,i,a,r)}(e,t[i],t[n],t[r],t.scale,s,o)}let p$=["x","scaleX","originX"],pK=["y","scaleY","originY"];function pJ(e,t,i,n){pG(e.x,t,p$,i?i.x:void 0,n?n.x:void 0),pG(e.y,t,pK,i?i.y:void 0,n?n.y:void 0)}function pX(e){return 0===e.translate&&1===e.scale}function pY(e){return pX(e.x)&&pX(e.y)}function pQ(e,t){return e.min===t.min&&e.max===t.max}function pZ(e,t){return Math.round(e.min)===Math.round(t.min)&&Math.round(e.max)===Math.round(t.max)}function p0(e,t){return pZ(e.x,t.x)&&pZ(e.y,t.y)}function p1(e){return hY(e.x)/hY(e.y)}function p2(e,t){return e.translate===t.translate&&e.scale===t.scale&&e.originPoint===t.originPoint}class p3{constructor(){this.members=[]}add(e){dy(this.members,e),e.scheduleRender()}remove(e){if(db(this.members,e),e===this.prevLead&&(this.prevLead=void 0),e===this.lead){let e=this.members[this.members.length-1];e&&this.promote(e)}}relegate(e){let t;let i=this.members.findIndex(t=>e===t);if(0===i)return!1;for(let e=i;e>=0;e--){let i=this.members[e];if(!1!==i.isPresent){t=i;break}}return!!t&&(this.promote(t),!0)}promote(e,t){let i=this.lead;if(e!==i&&(this.prevLead=i,this.lead=e,e.show(),i)){i.instance&&i.scheduleRender(),e.scheduleRender(),e.resumeFrom=i,t&&(e.resumeFrom.preserveOpacity=!0),i.snapshot&&(e.snapshot=i.snapshot,e.snapshot.latestValues=i.animationValues||i.latestValues),e.root&&e.root.isUpdating&&(e.isLayoutDirty=!0);let{crossfade:n}=e.options;!1===n&&i.hide()}}exitAnimationComplete(){this.members.forEach(e=>{let{options:t,resumingFrom:i}=e;t.onExitComplete&&t.onExitComplete(),i&&i.options.onExitComplete&&i.options.onExitComplete()})}scheduleRender(){this.members.forEach(e=>{e.instance&&e.scheduleRender(!1)})}removeLeadSnapshot(){this.lead&&this.lead.snapshot&&(this.lead.snapshot=void 0)}}let p5={type:"projectionFrame",totalNodes:0,resolvedTargetDeltas:0,recalculatedProjection:0},p4="undefined"!=typeof window&&void 0!==window.MotionDebug,p6=["","X","Y","Z"],p9={visibility:"hidden"},p8=0;function p7(e,t,i,n){let{latestValues:r}=t;r[e]&&(i[e]=r[e],t.setStaticValue(e,0),n&&(n[e]=0))}function me({attachResizeListener:e,defaultParent:t,measureScroll:i,checkIsScrollRoot:n,resetTransform:r}){return class{constructor(e={},i=null==t?void 0:t()){this.id=p8++,this.animationId=0,this.children=new Set,this.options={},this.isTreeAnimating=!1,this.isAnimationBlocked=!1,this.isLayoutDirty=!1,this.isProjectionDirty=!1,this.isSharedProjectionDirty=!1,this.isTransformDirty=!1,this.updateManuallyBlocked=!1,this.updateBlockedByResize=!1,this.isUpdating=!1,this.isSVG=!1,this.needsReset=!1,this.shouldResetTransform=!1,this.hasCheckedOptimisedAppear=!1,this.treeScale={x:1,y:1},this.eventHandlers=new Map,this.hasTreeAnimated=!1,this.updateScheduled=!1,this.scheduleUpdate=()=>this.update(),this.projectionUpdateScheduled=!1,this.checkUpdateFailed=()=>{this.isUpdating&&(this.isUpdating=!1,this.clearAllSnapshots())},this.updateProjection=()=>{this.projectionUpdateScheduled=!1,p4&&(p5.totalNodes=p5.resolvedTargetDeltas=p5.recalculatedProjection=0),this.nodes.forEach(mn),this.nodes.forEach(md),this.nodes.forEach(mu),this.nodes.forEach(mr),p4&&window.MotionDebug.record(p5)},this.resolvedRelativeTargetAt=0,this.hasProjected=!1,this.isVisible=!0,this.animationProgress=0,this.sharedNodes=new Map,this.latestValues=e,this.root=i?i.root||i:this,this.path=i?[...i.path,i]:[],this.parent=i,this.depth=i?i.depth+1:0;for(let e=0;e<this.path.length;e++)this.path[e].shouldResetTransform=!0;this.root===this&&(this.nodes=new pM)}addEventListener(e,t){return this.eventHandlers.has(e)||this.eventHandlers.set(e,new dk),this.eventHandlers.get(e).add(t)}notifyListeners(e,...t){let i=this.eventHandlers.get(e);i&&i.notify(...t)}hasListeners(e){return this.eventHandlers.has(e)}mount(t,i=this.root.hasTreeAnimated){if(this.instance)return;this.isSVG=t instanceof SVGElement&&"svg"!==t.tagName,this.instance=t;let{layoutId:n,layout:r,visualElement:s}=this.options;if(s&&!s.current&&s.mount(t),this.root.nodes.add(this),this.parent&&this.parent.children.add(this),i&&(r||n)&&(this.isLayoutDirty=!0),e){let i;let n=()=>this.root.updateBlockedByResize=!1;e(t,()=>{this.root.updateBlockedByResize=!0,i&&i(),i=function(e,t){let i=dv.now(),n=({timestamp:t})=>{let r=t-i;r>=250&&(dp(n),e(r-250))};return dh.read(n,!0),()=>dp(n)}(n,250),pS.hasAnimatedSinceResize&&(pS.hasAnimatedSinceResize=!1,this.nodes.forEach(mc))})}n&&this.root.registerSharedNode(n,this),!1!==this.options.animate&&s&&(n||r)&&this.addEventListener("didUpdate",({delta:e,hasLayoutChanged:t,hasRelativeTargetChanged:i,layout:n})=>{if(this.isTreeAnimationBlocked()){this.target=void 0,this.relativeTarget=void 0;return}let r=this.options.transition||s.getDefaultTransition()||mv,{onLayoutAnimationStart:o,onLayoutAnimationComplete:a}=s.getProps(),l=!this.targetLayout||!p0(this.targetLayout,n)||i,c=!t&&i;if(this.options.layoutRoot||this.resumeFrom&&this.resumeFrom.instance||c||t&&(l||!this.currentAnimation)){this.resumeFrom&&(this.resumingFrom=this.resumeFrom,this.resumingFrom.resumingFrom=void 0),this.setAnimationOrigin(e,c);let t={...cq(r,"layout"),onPlay:o,onComplete:a};(s.shouldReduceMotion||this.options.layoutRoot)&&(t.delay=0,t.type=!1),this.startAnimation(t)}else t||mc(this),this.isLead()&&this.options.onExitComplete&&this.options.onExitComplete();this.targetLayout=n})}unmount(){this.options.layoutId&&this.willUpdate(),this.root.nodes.remove(this);let e=this.getStack();e&&e.remove(this),this.parent&&this.parent.children.delete(this),this.instance=void 0,dp(this.updateProjection)}blockUpdate(){this.updateManuallyBlocked=!0}unblockUpdate(){this.updateManuallyBlocked=!1}isUpdateBlocked(){return this.updateManuallyBlocked||this.updateBlockedByResize}isTreeAnimationBlocked(){return this.isAnimationBlocked||this.parent&&this.parent.isTreeAnimationBlocked()||!1}startUpdate(){!this.isUpdateBlocked()&&(this.isUpdating=!0,this.nodes&&this.nodes.forEach(mh),this.animationId++)}getTransformTemplate(){let{visualElement:e}=this.options;return e&&e.getProps().transformTemplate}willUpdate(e=!0){if(this.root.hasTreeAnimated=!0,this.root.isUpdateBlocked()){this.options.onExitComplete&&this.options.onExitComplete();return}if(window.MotionCancelOptimisedAnimation&&!this.hasCheckedOptimisedAppear&&function e(t){if(t.hasCheckedOptimisedAppear=!0,t.root===t)return;let{visualElement:i}=t.options;if(!i)return;let n=i.props[dR];if(window.MotionHasOptimisedAnimation(n,"transform")){let{layout:e,layoutId:i}=t.options;window.MotionCancelOptimisedAnimation(n,"transform",dh,!(e||i))}let{parent:r}=t;r&&!r.hasCheckedOptimisedAppear&&e(r)}(this),this.root.isUpdating||this.root.startUpdate(),this.isLayoutDirty)return;this.isLayoutDirty=!0;for(let e=0;e<this.path.length;e++){let t=this.path[e];t.shouldResetTransform=!0,t.updateScroll("snapshot"),t.options.layoutRoot&&t.willUpdate(!1)}let{layoutId:t,layout:i}=this.options;if(void 0===t&&!i)return;let n=this.getTransformTemplate();this.prevTransformTemplateValue=n?n(this.latestValues,""):void 0,this.updateSnapshot(),e&&this.notifyListeners("willUpdate")}update(){if(this.updateScheduled=!1,this.isUpdateBlocked()){this.unblockUpdate(),this.clearAllSnapshots(),this.nodes.forEach(mo);return}this.isUpdating||this.nodes.forEach(ma),this.isUpdating=!1,this.nodes.forEach(ml),this.nodes.forEach(mt),this.nodes.forEach(mi),this.clearAllSnapshots();let e=dv.now();dm.delta=dq(0,1e3/60,e-dm.timestamp),dm.timestamp=e,dm.isProcessing=!0,df.update.process(dm),df.preRender.process(dm),df.render.process(dm),dm.isProcessing=!1}didUpdate(){this.updateScheduled||(this.updateScheduled=!0,pP.read(this.scheduleUpdate))}clearAllSnapshots(){this.nodes.forEach(ms),this.sharedNodes.forEach(mp)}scheduleUpdateProjection(){this.projectionUpdateScheduled||(this.projectionUpdateScheduled=!0,dh.preRender(this.updateProjection,!1,!0))}scheduleCheckAfterUnmount(){dh.postRender(()=>{this.isLayoutDirty?this.root.didUpdate():this.root.checkUpdateFailed()})}updateSnapshot(){!this.snapshot&&this.instance&&(this.snapshot=this.measure())}updateLayout(){if(!this.instance||(this.updateScroll(),!(this.options.alwaysMeasureLayout&&this.isLead())&&!this.isLayoutDirty))return;if(this.resumeFrom&&!this.resumeFrom.instance)for(let e=0;e<this.path.length;e++)this.path[e].updateScroll();let e=this.layout;this.layout=this.measure(!1),this.layoutCorrected=pe(),this.isLayoutDirty=!1,this.projectionDelta=void 0,this.notifyListeners("measure",this.layout.layoutBox);let{visualElement:t}=this.options;t&&t.notify("LayoutMeasure",this.layout.layoutBox,e?e.layoutBox:void 0)}updateScroll(e="measure"){let t=!!(this.options.layoutScroll&&this.instance);if(this.scroll&&this.scroll.animationId===this.root.animationId&&this.scroll.phase===e&&(t=!1),t){let t=n(this.instance);this.scroll={animationId:this.root.animationId,phase:e,isRoot:t,offset:i(this.instance),wasRoot:this.scroll?this.scroll.isRoot:t}}}resetTransform(){if(!r)return;let e=this.isLayoutDirty||this.shouldResetTransform||this.options.alwaysMeasureLayout,t=this.projectionDelta&&!pY(this.projectionDelta),i=this.getTransformTemplate(),n=i?i(this.latestValues,""):void 0,s=n!==this.prevTransformTemplateValue;e&&(t||ps(this.latestValues)||s)&&(r(this.instance,n),this.shouldResetTransform=!1,this.scheduleRender())}measure(e=!0){var t;let i=this.measurePageBox(),n=this.removeElementScroll(i);return e&&(n=this.removeTransform(n)),mk((t=n).x),mk(t.y),{animationId:this.root.animationId,measuredBox:i,layoutBox:n,latestValues:{},source:this.id}}measurePageBox(){var e;let{visualElement:t}=this.options;if(!t)return pe();let i=t.measureViewportBox();if(!((null===(e=this.scroll)||void 0===e?void 0:e.wasRoot)||this.path.some(mS))){let{scroll:e}=this.root;e&&(pd(i.x,e.offset.x),pd(i.y,e.offset.y))}return i}removeElementScroll(e){var t;let i=pe();if(pz(i,e),null===(t=this.scroll)||void 0===t?void 0:t.wasRoot)return i;for(let t=0;t<this.path.length;t++){let n=this.path[t],{scroll:r,options:s}=n;n!==this.root&&r&&s.layoutScroll&&(r.wasRoot&&pz(i,e),pd(i.x,r.offset.x),pd(i.y,r.offset.y))}return i}applyTransform(e,t=!1){let i=pe();pz(i,e);for(let e=0;e<this.path.length;e++){let n=this.path[e];!t&&n.options.layoutScroll&&n.scroll&&n!==n.root&&ph(i,{x:-n.scroll.offset.x,y:-n.scroll.offset.y}),ps(n.latestValues)&&ph(i,n.latestValues)}return ps(this.latestValues)&&ph(i,this.latestValues),i}removeTransform(e){let t=pe();pz(t,e);for(let e=0;e<this.path.length;e++){let i=this.path[e];if(!i.instance||!ps(i.latestValues))continue;pr(i.latestValues)&&i.updateSnapshot();let n=pe();pz(n,i.measurePageBox()),pJ(t,i.latestValues,i.snapshot?i.snapshot.layoutBox:void 0,n)}return ps(this.latestValues)&&pJ(t,this.latestValues),t}setTargetDelta(e){this.targetDelta=e,this.root.scheduleUpdateProjection(),this.isProjectionDirty=!0}setOptions(e){this.options={...this.options,...e,crossfade:void 0===e.crossfade||e.crossfade}}clearMeasurements(){this.scroll=void 0,this.layout=void 0,this.snapshot=void 0,this.prevTransformTemplateValue=void 0,this.targetDelta=void 0,this.target=void 0,this.isLayoutDirty=!1}forceRelativeParentToResolveTarget(){this.relativeParent&&this.relativeParent.resolvedRelativeTargetAt!==dm.timestamp&&this.relativeParent.resolveTargetDelta(!0)}resolveTargetDelta(e=!1){var t,i,n,r;let s=this.getLead();this.isProjectionDirty||(this.isProjectionDirty=s.isProjectionDirty),this.isTransformDirty||(this.isTransformDirty=s.isTransformDirty),this.isSharedProjectionDirty||(this.isSharedProjectionDirty=s.isSharedProjectionDirty);let o=!!this.resumingFrom||this!==s;if(!(e||o&&this.isSharedProjectionDirty||this.isProjectionDirty||(null===(t=this.parent)||void 0===t?void 0:t.isProjectionDirty)||this.attemptToResolveRelativeTarget||this.root.updateBlockedByResize))return;let{layout:a,layoutId:l}=this.options;if(this.layout&&(a||l)){if(this.resolvedRelativeTargetAt=dm.timestamp,!this.targetDelta&&!this.relativeTarget){let e=this.getClosestProjectingParent();e&&e.layout&&1!==this.animationProgress?(this.relativeParent=e,this.forceRelativeParentToResolveTarget(),this.relativeTarget=pe(),this.relativeTargetOrigin=pe(),h2(this.relativeTargetOrigin,this.layout.layoutBox,e.layout.layoutBox),pz(this.relativeTarget,this.relativeTargetOrigin)):this.relativeParent=this.relativeTarget=void 0}if(this.relativeTarget||this.targetDelta){if((this.target||(this.target=pe(),this.targetWithTransforms=pe()),this.relativeTarget&&this.relativeTargetOrigin&&this.relativeParent&&this.relativeParent.target)?(this.forceRelativeParentToResolveTarget(),i=this.target,n=this.relativeTarget,r=this.relativeParent.target,h0(i.x,n.x,r.x),h0(i.y,n.y,r.y)):this.targetDelta?(this.resumingFrom?this.target=this.applyTransform(this.layout.layoutBox):pz(this.target,this.layout.layoutBox),pc(this.target,this.targetDelta)):pz(this.target,this.layout.layoutBox),this.attemptToResolveRelativeTarget){this.attemptToResolveRelativeTarget=!1;let e=this.getClosestProjectingParent();e&&!!e.resumingFrom==!!this.resumingFrom&&!e.options.layoutScroll&&e.target&&1!==this.animationProgress?(this.relativeParent=e,this.forceRelativeParentToResolveTarget(),this.relativeTarget=pe(),this.relativeTargetOrigin=pe(),h2(this.relativeTargetOrigin,this.target,e.target),pz(this.relativeTarget,this.relativeTargetOrigin)):this.relativeParent=this.relativeTarget=void 0}p4&&p5.resolvedTargetDeltas++}}}getClosestProjectingParent(){return!this.parent||pr(this.parent.latestValues)||po(this.parent.latestValues)?void 0:this.parent.isProjecting()?this.parent:this.parent.getClosestProjectingParent()}isProjecting(){return!!((this.relativeTarget||this.targetDelta||this.options.layoutRoot)&&this.layout)}calcProjection(){var e;let t=this.getLead(),i=!!this.resumingFrom||this!==t,n=!0;if((this.isProjectionDirty||(null===(e=this.parent)||void 0===e?void 0:e.isProjectionDirty))&&(n=!1),i&&(this.isSharedProjectionDirty||this.isTransformDirty)&&(n=!1),this.resolvedRelativeTargetAt===dm.timestamp&&(n=!1),n)return;let{layout:r,layoutId:s}=this.options;if(this.isTreeAnimating=!!(this.parent&&this.parent.isTreeAnimating||this.currentAnimation||this.pendingAnimation),this.isTreeAnimating||(this.targetDelta=this.relativeTarget=void 0),!this.layout||!(r||s))return;pz(this.layoutCorrected,this.layout.layoutBox);let o=this.treeScale.x,a=this.treeScale.y;(function(e,t,i,n=!1){let r,s;let o=i.length;if(o){t.x=t.y=1;for(let a=0;a<o;a++){s=(r=i[a]).projectionDelta;let{visualElement:o}=r.options;(!o||!o.props.style||"contents"!==o.props.style.display)&&(n&&r.options.layoutScroll&&r.scroll&&r!==r.root&&ph(e,{x:-r.scroll.offset.x,y:-r.scroll.offset.y}),s&&(t.x*=s.x.scale,t.y*=s.y.scale,pc(e,s)),n&&ps(r.latestValues)&&ph(e,r.latestValues))}t.x<1.0000000000001&&t.x>.999999999999&&(t.x=1),t.y<1.0000000000001&&t.y>.999999999999&&(t.y=1)}})(this.layoutCorrected,this.treeScale,this.path,i),t.layout&&!t.target&&(1!==this.treeScale.x||1!==this.treeScale.y)&&(t.target=t.layout.layoutBox,t.targetWithTransforms=pe());let{target:l}=t;if(!l){this.prevProjectionDelta&&(this.createProjectionDeltas(),this.scheduleRender());return}this.projectionDelta&&this.prevProjectionDelta?(pW(this.prevProjectionDelta.x,this.projectionDelta.x),pW(this.prevProjectionDelta.y,this.projectionDelta.y)):this.createProjectionDeltas(),hZ(this.projectionDelta,this.layoutCorrected,l,this.latestValues),this.treeScale.x===o&&this.treeScale.y===a&&p2(this.projectionDelta.x,this.prevProjectionDelta.x)&&p2(this.projectionDelta.y,this.prevProjectionDelta.y)||(this.hasProjected=!0,this.scheduleRender(),this.notifyListeners("projectionUpdate",l)),p4&&p5.recalculatedProjection++}hide(){this.isVisible=!1}show(){this.isVisible=!0}scheduleRender(e=!0){var t;if(null===(t=this.options.visualElement)||void 0===t||t.scheduleRender(),e){let e=this.getStack();e&&e.scheduleRender()}this.resumingFrom&&!this.resumingFrom.instance&&(this.resumingFrom=void 0)}createProjectionDeltas(){this.prevProjectionDelta=h8(),this.projectionDelta=h8(),this.projectionDeltaWithTransform=h8()}setAnimationOrigin(e,t=!1){let i;let n=this.snapshot,r=n?n.latestValues:{},s={...this.latestValues},o=h8();this.relativeParent&&this.relativeParent.options.layoutRoot||(this.relativeTarget=this.relativeTargetOrigin=void 0),this.attemptToResolveRelativeTarget=!t;let a=pe(),l=(n?n.source:void 0)!==(this.layout?this.layout.source:void 0),c=this.getStack(),d=!c||c.members.length<=1,u=!!(l&&!d&&!0===this.options.crossfade&&!this.path.some(mg));this.animationProgress=0,this.mixTargetDelta=t=>{let n=t/1e3;if(mm(o.x,e.x,n),mm(o.y,e.y,n),this.setTargetDelta(o),this.relativeTarget&&this.relativeTargetOrigin&&this.layout&&this.relativeParent&&this.relativeParent.layout){var c,h,p,m;h2(a,this.layout.layoutBox,this.relativeParent.layout.layoutBox),p=this.relativeTarget,m=this.relativeTargetOrigin,mf(p.x,m.x,a.x,n),mf(p.y,m.y,a.y,n),i&&(c=this.relativeTarget,h=i,pQ(c.x,h.x)&&pQ(c.y,h.y))&&(this.isProjectionDirty=!1),i||(i=pe()),pz(i,this.relativeTarget)}l&&(this.animationValues=s,function(e,t,i,n,r,s){r?(e.opacity=uG(0,void 0!==i.opacity?i.opacity:1,pF(n)),e.opacityExit=uG(void 0!==t.opacity?t.opacity:1,0,pV(n))):s&&(e.opacity=uG(void 0!==t.opacity?t.opacity:1,void 0!==i.opacity?i.opacity:1,n));for(let r=0;r<pN;r++){let s=`border${p_[r]}Radius`,o=pU(t,s),a=pU(i,s);(void 0!==o||void 0!==a)&&(o||(o=0),a||(a=0),0===o||0===a||pj(o)===pj(a)?(e[s]=Math.max(uG(pL(o),pL(a),n),0),(d3.test(a)||d3.test(o))&&(e[s]+="%")):e[s]=a)}(t.rotate||i.rotate)&&(e.rotate=uG(t.rotate||0,i.rotate||0,n))}(s,r,this.latestValues,n,u,d)),this.root.scheduleUpdateProjection(),this.scheduleRender(),this.animationProgress=n},this.mixTargetDelta(this.options.layoutRoot?1e3:0)}startAnimation(e){this.notifyListeners("animationStart"),this.currentAnimation&&this.currentAnimation.stop(),this.resumingFrom&&this.resumingFrom.currentAnimation&&this.resumingFrom.currentAnimation.stop(),this.pendingAnimation&&(dp(this.pendingAnimation),this.pendingAnimation=void 0),this.pendingAnimation=dh.update(()=>{pS.hasAnimatedSinceResize=!0,this.currentAnimation=function(e,t,i){let n=dE(0)?0:dw(0);return n.start(hx("",n,1e3,i)),n.animation}(0,0,{...e,onUpdate:t=>{this.mixTargetDelta(t),e.onUpdate&&e.onUpdate(t)},onComplete:()=>{e.onComplete&&e.onComplete(),this.completeAnimation()}}),this.resumingFrom&&(this.resumingFrom.currentAnimation=this.currentAnimation),this.pendingAnimation=void 0})}completeAnimation(){this.resumingFrom&&(this.resumingFrom.currentAnimation=void 0,this.resumingFrom.preserveOpacity=void 0);let e=this.getStack();e&&e.exitAnimationComplete(),this.resumingFrom=this.currentAnimation=this.animationValues=void 0,this.notifyListeners("animationComplete")}finishAnimation(){this.currentAnimation&&(this.mixTargetDelta&&this.mixTargetDelta(1e3),this.currentAnimation.stop()),this.completeAnimation()}applyTransformsToTarget(){let e=this.getLead(),{targetWithTransforms:t,target:i,layout:n,latestValues:r}=e;if(t&&i&&n){if(this!==e&&this.layout&&n&&mT(this.options.animationType,this.layout.layoutBox,n.layoutBox)){i=this.target||pe();let t=hY(this.layout.layoutBox.x);i.x.min=e.target.x.min,i.x.max=i.x.min+t;let n=hY(this.layout.layoutBox.y);i.y.min=e.target.y.min,i.y.max=i.y.min+n}pz(t,i),ph(t,r),hZ(this.projectionDeltaWithTransform,this.layoutCorrected,t,r)}}registerSharedNode(e,t){this.sharedNodes.has(e)||this.sharedNodes.set(e,new p3),this.sharedNodes.get(e).add(t);let i=t.options.initialPromotionConfig;t.promote({transition:i?i.transition:void 0,preserveFollowOpacity:i&&i.shouldPreserveFollowOpacity?i.shouldPreserveFollowOpacity(t):void 0})}isLead(){let e=this.getStack();return!e||e.lead===this}getLead(){var e;let{layoutId:t}=this.options;return t&&(null===(e=this.getStack())||void 0===e?void 0:e.lead)||this}getPrevLead(){var e;let{layoutId:t}=this.options;return t?null===(e=this.getStack())||void 0===e?void 0:e.prevLead:void 0}getStack(){let{layoutId:e}=this.options;if(e)return this.root.sharedNodes.get(e)}promote({needsReset:e,transition:t,preserveFollowOpacity:i}={}){let n=this.getStack();n&&n.promote(this,i),e&&(this.projectionDelta=void 0,this.needsReset=!0),t&&this.setOptions({transition:t})}relegate(){let e=this.getStack();return!!e&&e.relegate(this)}resetSkewAndRotation(){let{visualElement:e}=this.options;if(!e)return;let t=!1,{latestValues:i}=e;if((i.z||i.rotate||i.rotateX||i.rotateY||i.rotateZ||i.skewX||i.skewY)&&(t=!0),!t)return;let n={};i.z&&p7("z",e,n,this.animationValues);for(let t=0;t<p6.length;t++)p7(`rotate${p6[t]}`,e,n,this.animationValues),p7(`skew${p6[t]}`,e,n,this.animationValues);for(let t in e.render(),n)e.setStaticValue(t,n[t]),this.animationValues&&(this.animationValues[t]=n[t]);e.scheduleRender()}getProjectionStyles(e){var t,i;if(!this.instance||this.isSVG)return;if(!this.isVisible)return p9;let n={visibility:""},r=this.getTransformTemplate();if(this.needsReset)return this.needsReset=!1,n.opacity="",n.pointerEvents=pD(null==e?void 0:e.pointerEvents)||"",n.transform=r?r(this.latestValues,""):"none",n;let s=this.getLead();if(!this.projectionDelta||!this.layout||!s.target){let t={};return this.options.layoutId&&(t.opacity=void 0!==this.latestValues.opacity?this.latestValues.opacity:1,t.pointerEvents=pD(null==e?void 0:e.pointerEvents)||""),this.hasProjected&&!ps(this.latestValues)&&(t.transform=r?r({},""):"none",this.hasProjected=!1),t}let o=s.animationValues||s.latestValues;this.applyTransformsToTarget(),n.transform=function(e,t,i){let n="",r=e.x.translate/t.x,s=e.y.translate/t.y,o=(null==i?void 0:i.z)||0;if((r||s||o)&&(n=`translate3d(${r}px, ${s}px, ${o}px) `),(1!==t.x||1!==t.y)&&(n+=`scale(${1/t.x}, ${1/t.y}) `),i){let{transformPerspective:e,rotate:t,rotateX:r,rotateY:s,skewX:o,skewY:a}=i;e&&(n=`perspective(${e}px) ${n}`),t&&(n+=`rotate(${t}deg) `),r&&(n+=`rotateX(${r}deg) `),s&&(n+=`rotateY(${s}deg) `),o&&(n+=`skewX(${o}deg) `),a&&(n+=`skewY(${a}deg) `)}let a=e.x.scale*t.x,l=e.y.scale*t.y;return(1!==a||1!==l)&&(n+=`scale(${a}, ${l})`),n||"none"}(this.projectionDeltaWithTransform,this.treeScale,o),r&&(n.transform=r(o,n.transform));let{x:a,y:l}=this.projectionDelta;for(let e in n.transformOrigin=`${100*a.origin}% ${100*l.origin}% 0`,s.animationValues?n.opacity=s===this?null!==(i=null!==(t=o.opacity)&&void 0!==t?t:this.latestValues.opacity)&&void 0!==i?i:1:this.preserveOpacity?this.latestValues.opacity:o.opacityExit:n.opacity=s===this?void 0!==o.opacity?o.opacity:"":void 0!==o.opacityExit?o.opacityExit:0,pE){if(void 0===o[e])continue;let{correct:t,applyTo:i}=pE[e],r="none"===n.transform?o[e]:t(o[e],s);if(i){let e=i.length;for(let t=0;t<e;t++)n[i[t]]=r}else n[e]=r}return this.options.layoutId&&(n.pointerEvents=s===this?pD(null==e?void 0:e.pointerEvents)||"":"none"),n}clearSnapshot(){this.resumeFrom=this.snapshot=void 0}resetTree(){this.root.nodes.forEach(e=>{var t;return null===(t=e.currentAnimation)||void 0===t?void 0:t.stop()}),this.root.nodes.forEach(mo),this.root.sharedNodes.clear()}}}function mt(e){e.updateLayout()}function mi(e){var t;let i=(null===(t=e.resumeFrom)||void 0===t?void 0:t.snapshot)||e.snapshot;if(e.isLead()&&e.layout&&i&&e.hasListeners("didUpdate")){let{layoutBox:t,measuredBox:n}=e.layout,{animationType:r}=e.options,s=i.source!==e.layout.source;"size"===r?pt(e=>{let n=s?i.measuredBox[e]:i.layoutBox[e],r=hY(n);n.min=t[e].min,n.max=n.min+r}):mT(r,i.layoutBox,t)&&pt(n=>{let r=s?i.measuredBox[n]:i.layoutBox[n],o=hY(t[n]);r.max=r.min+o,e.relativeTarget&&!e.currentAnimation&&(e.isProjectionDirty=!0,e.relativeTarget[n].max=e.relativeTarget[n].min+o)});let o=h8();hZ(o,t,i.layoutBox);let a=h8();s?hZ(a,e.applyTransform(n,!0),i.measuredBox):hZ(a,t,i.layoutBox);let l=!pY(o),c=!1;if(!e.resumeFrom){let n=e.getClosestProjectingParent();if(n&&!n.resumeFrom){let{snapshot:r,layout:s}=n;if(r&&s){let o=pe();h2(o,i.layoutBox,r.layoutBox);let a=pe();h2(a,t,s.layoutBox),p0(o,a)||(c=!0),n.options.layoutRoot&&(e.relativeTarget=a,e.relativeTargetOrigin=o,e.relativeParent=n)}}}e.notifyListeners("didUpdate",{layout:t,snapshot:i,delta:a,layoutDelta:o,hasLayoutChanged:l,hasRelativeTargetChanged:c})}else if(e.isLead()){let{onExitComplete:t}=e.options;t&&t()}e.options.transition=void 0}function mn(e){p4&&p5.totalNodes++,e.parent&&(e.isProjecting()||(e.isProjectionDirty=e.parent.isProjectionDirty),e.isSharedProjectionDirty||(e.isSharedProjectionDirty=!!(e.isProjectionDirty||e.parent.isProjectionDirty||e.parent.isSharedProjectionDirty)),e.isTransformDirty||(e.isTransformDirty=e.parent.isTransformDirty))}function mr(e){e.isProjectionDirty=e.isSharedProjectionDirty=e.isTransformDirty=!1}function ms(e){e.clearSnapshot()}function mo(e){e.clearMeasurements()}function ma(e){e.isLayoutDirty=!1}function ml(e){let{visualElement:t}=e.options;t&&t.getProps().onBeforeLayoutMeasure&&t.notify("BeforeLayoutMeasure"),e.resetTransform()}function mc(e){e.finishAnimation(),e.targetDelta=e.relativeTarget=e.target=void 0,e.isProjectionDirty=!0}function md(e){e.resolveTargetDelta()}function mu(e){e.calcProjection()}function mh(e){e.resetSkewAndRotation()}function mp(e){e.removeLeadSnapshot()}function mm(e,t,i){e.translate=uG(t.translate,0,i),e.scale=uG(t.scale,1,i),e.origin=t.origin,e.originPoint=t.originPoint}function mf(e,t,i,n){e.min=uG(t.min,i.min,n),e.max=uG(t.max,i.max,n)}function mg(e){return e.animationValues&&void 0!==e.animationValues.opacityExit}let mv={duration:.45,ease:[.4,0,.1,1]},my=e=>"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().includes(e),mb=my("applewebkit/")&&!my("chrome/")?Math.round:di;function mk(e){e.min=mb(e.min),e.max=mb(e.max)}function mT(e,t,i){return"position"===e||"preserve-aspect"===e&&!(.2>=Math.abs(p1(t)-p1(i)))}function mS(e){var t;return e!==e.root&&(null===(t=e.scroll)||void 0===t?void 0:t.wasRoot)}let mC=me({attachResizeListener:(e,t)=>hV(e,"resize",t),measureScroll:()=>({x:document.documentElement.scrollLeft||document.body.scrollLeft,y:document.documentElement.scrollTop||document.body.scrollTop}),checkIsScrollRoot:()=>!0}),mw={current:void 0},mE=me({measureScroll:e=>({x:e.scrollLeft,y:e.scrollTop}),defaultParent:()=>{if(!mw.current){let e=new mC({});e.mount(window),e.setOptions({layoutScroll:!0}),mw.current=e}return mw.current},resetTransform:(e,t)=>{e.style.transform=void 0!==t?t:"none"},checkIsScrollRoot:e=>"fixed"===window.getComputedStyle(e).position});function mP(e,t,i){let{props:n}=e;e.animationState&&n.whileHover&&e.animationState.setActive("whileHover","Start"===i);let r=n["onHover"+i];r&&dh.postRender(()=>r(t,hB(t)))}class mx extends hL{mount(){let{current:e}=this.node;e&&(this.unmount=function(e,t,i={}){let[n,r,s]=c0(e,i),o=c1(e=>{let{target:i}=e,n=t(e);if("function"!=typeof n||!i)return;let s=c1(e=>{n(e),i.removeEventListener("pointerleave",s)});i.addEventListener("pointerleave",s,r)});return n.forEach(e=>{e.addEventListener("pointerenter",o,r)}),s}(e,e=>(mP(this.node,e,"Start"),e=>mP(this.node,e,"End"))))}unmount(){}}class mR extends hL{constructor(){super(...arguments),this.isActive=!1}onFocus(){let e=!1;try{e=this.node.current.matches(":focus-visible")}catch(t){e=!0}e&&this.node.animationState&&(this.node.animationState.setActive("whileFocus",!0),this.isActive=!0)}onBlur(){this.isActive&&this.node.animationState&&(this.node.animationState.setActive("whileFocus",!1),this.isActive=!1)}mount(){this.unmount=u1(hV(this.node.current,"focus",()=>this.onFocus()),hV(this.node.current,"blur",()=>this.onBlur()))}unmount(){}}function mO(e,t,i){let{props:n}=e;e.animationState&&n.whileTap&&e.animationState.setActive("whileTap","Start"===i);let r=n["onTap"+("End"===i?"":i)];r&&dh.postRender(()=>r(t,hB(t)))}class mA extends hL{mount(){let{current:e}=this.node;e&&(this.unmount=function(e,t,i={}){let[n,r,s]=c0(e,i),o=e=>{let n=e.currentTarget;if(!c7(e)||c4.has(n))return;c4.add(n);let s=t(e),o=(e,t)=>{window.removeEventListener("pointerup",a),window.removeEventListener("pointercancel",l),c7(e)&&c4.has(n)&&(c4.delete(n),"function"==typeof s&&s(e,{success:t}))},a=e=>{o(e,i.useGlobalTarget||c2(n,e.target))},l=e=>{o(e,!1)};window.addEventListener("pointerup",a,r),window.addEventListener("pointercancel",l,r)};return n.forEach(e=>{c5.has(e.tagName)||-1!==e.tabIndex||null!==e.getAttribute("tabindex")||(e.tabIndex=0),(i.useGlobalTarget?window:e).addEventListener("pointerdown",o,r),e.addEventListener("focus",e=>c8(e,r),r)}),s}(e,e=>(mO(this.node,e,"Start"),(e,{success:t})=>mO(this.node,e,t?"End":"Cancel")),{useGlobalTarget:this.node.props.globalTapTarget}))}unmount(){}}let mI=new WeakMap,mM=new WeakMap,mD=e=>{let t=mI.get(e.target);t&&t(e)},m_=e=>{e.forEach(mD)},mN={some:0,all:1};class mL extends hL{constructor(){super(...arguments),this.hasEnteredView=!1,this.isInView=!1}startObserver(){this.unmount();let{viewport:e={}}=this.node.getProps(),{root:t,margin:i,amount:n="some",once:r}=e,s={root:t?t.current:void 0,rootMargin:i,threshold:"number"==typeof n?n:mN[n]};return function(e,t,i){let n=function({root:e,...t}){let i=e||document;mM.has(i)||mM.set(i,{});let n=mM.get(i),r=JSON.stringify(t);return n[r]||(n[r]=new IntersectionObserver(m_,{root:e,...t})),n[r]}(t);return mI.set(e,i),n.observe(e),()=>{mI.delete(e),n.unobserve(e)}}(this.node.current,s,e=>{let{isIntersecting:t}=e;if(this.isInView===t||(this.isInView=t,r&&!t&&this.hasEnteredView))return;t&&(this.hasEnteredView=!0),this.node.animationState&&this.node.animationState.setActive("whileInView",t);let{onViewportEnter:i,onViewportLeave:n}=this.node.getProps(),s=t?i:n;s&&s(e)})}mount(){this.startObserver()}update(){if("undefined"==typeof IntersectionObserver)return;let{props:e,prevProps:t}=this.node;["amount","margin","root"].some(function({viewport:e={}},{viewport:t={}}={}){return i=>e[i]!==t[i]}(e,t))&&this.startObserver()}unmount(){}}let mj=(0,p.createContext)({strict:!1}),mU=(0,p.createContext)({});function mF(e){return cO(e.animate)||cj.some(t=>cM(e[t]))}function mV(e){return!!(mF(e)||e.variants)}function mB(e){return Array.isArray(e)?e.join(" "):e}let mq={animation:["animate","variants","whileHover","whileTap","exit","whileInView","whileFocus","whileDrag"],exit:["exit"],drag:["drag","dragControls"],focus:["whileFocus"],hover:["whileHover","onHoverStart","onHoverEnd"],tap:["whileTap","onTap","onTapStart","onTapCancel"],pan:["onPan","onPanStart","onPanSessionStart","onPanEnd"],inView:["whileInView","onViewportEnter","onViewportLeave"],layout:["layout","layoutId"]},mz={};for(let e in mq)mz[e]={isEnabled:t=>mq[e].some(e=>!!t[e])};let mW=Symbol.for("motionComponentSymbol"),mH=["animate","circle","defs","desc","ellipse","g","image","line","filter","marker","mask","metadata","path","pattern","polygon","polyline","rect","stop","switch","symbol","svg","text","tspan","use","view"];function mG(e){if("string"!=typeof e||e.includes("-"));else if(mH.indexOf(e)>-1||/[A-Z]/u.test(e))return!0;return!1}let m$=e=>(t,i)=>{let n=(0,p.useContext)(mU),r=(0,p.useContext)(cv),s=()=>(function({scrapeMotionValuesFromProps:e,createRenderState:t,onUpdate:i},n,r,s){let o={latestValues:function(e,t,i,n){let r={},s=n(e,{});for(let e in s)r[e]=pD(s[e]);let{initial:o,animate:a}=e,l=mF(e),c=mV(e);t&&c&&!l&&!1!==e.inherit&&(void 0===o&&(o=t.initial),void 0===a&&(a=t.animate));let d=!!i&&!1===i.initial,u=(d=d||!1===o)?a:o;if(u&&"boolean"!=typeof u&&!cO(u)){let t=Array.isArray(u)?u:[u];for(let i=0;i<t.length;i++){let n=c_(e,t[i]);if(n){let{transitionEnd:e,transition:t,...i}=n;for(let e in i){let t=i[e];if(Array.isArray(t)){let e=d?t.length-1:0;t=t[e]}null!==t&&(r[e]=t)}for(let t in e)r[t]=e[t]}}}return r}(n,r,s,e),renderState:t()};return i&&(o.onMount=e=>i({props:n,current:e,...o}),o.onUpdate=e=>i(e)),o})(e,t,n,r);return i?s():cg(s)},mK=(e,t)=>t&&"number"==typeof e?t.transform(e):e,mJ={x:"translateX",y:"translateY",z:"translateZ",transformPerspective:"perspective"},mX=dn.length;function mY(e,t,i){let{style:n,vars:r,transformOrigin:s}=e,o=!1,a=!1;for(let e in t){let i=t[e];if(dr.has(e)){o=!0;continue}if(uD(e)){r[e]=i;continue}{let t=mK(i,um[e]);e.startsWith("origin")?(a=!0,s[e]=t):n[e]=t}}if(!t.transform&&(o||i?n.transform=function(e,t,i){let n="",r=!0;for(let s=0;s<mX;s++){let o=dn[s],a=e[o];if(void 0===a)continue;let l=!0;if(!(l="number"==typeof a?a===(o.startsWith("scale")?1:0):0===parseFloat(a))||i){let e=mK(a,um[o]);if(!l){r=!1;let t=mJ[o]||o;n+=`${t}(${e}) `}i&&(t[o]=e)}}return n=n.trim(),i?n=i(t,r?"":n):r&&(n="none"),n}(t,e.transform,i):n.transform&&(n.transform="none")),a){let{originX:e="50%",originY:t="50%",originZ:i=0}=s;n.transformOrigin=`${e} ${t} ${i}`}}let mQ={offset:"stroke-dashoffset",array:"stroke-dasharray"},mZ={offset:"strokeDashoffset",array:"strokeDasharray"};function m0(e,t,i){return"string"==typeof e?e:d5.transform(t+i*e)}function m1(e,{attrX:t,attrY:i,attrScale:n,originX:r,originY:s,pathLength:o,pathSpacing:a=1,pathOffset:l=0,...c},d,u){if(mY(e,c,u),d){e.style.viewBox&&(e.attrs.viewBox=e.style.viewBox);return}e.attrs=e.style,e.style={};let{attrs:h,style:p,dimensions:m}=e;h.transform&&(m&&(p.transform=h.transform),delete h.transform),m&&(void 0!==r||void 0!==s||p.transform)&&(p.transformOrigin=function(e,t,i){let n=m0(t,e.x,e.width),r=m0(i,e.y,e.height);return`${n} ${r}`}(m,void 0!==r?r:.5,void 0!==s?s:.5)),void 0!==t&&(h.x=t),void 0!==i&&(h.y=i),void 0!==n&&(h.scale=n),void 0!==o&&function(e,t,i=1,n=0,r=!0){e.pathLength=1;let s=r?mQ:mZ;e[s.offset]=d5.transform(-n);let o=d5.transform(t),a=d5.transform(i);e[s.array]=`${o} ${a}`}(h,o,a,l,!1)}let m2=()=>({style:{},transform:{},transformOrigin:{},vars:{}}),m3=()=>({...m2(),attrs:{}}),m5=e=>"string"==typeof e&&"svg"===e.toLowerCase();function m4(e,{style:t,vars:i},n,r){for(let s in Object.assign(e.style,t,r&&r.getProjectionStyles(n)),i)e.style.setProperty(s,i[s])}let m6=new Set(["baseFrequency","diffuseConstant","kernelMatrix","kernelUnitLength","keySplines","keyTimes","limitingConeAngle","markerHeight","markerWidth","numOctaves","targetX","targetY","surfaceScale","specularConstant","specularExponent","stdDeviation","tableValues","viewBox","gradientTransform","pathLength","startOffset","textLength","lengthAdjust"]);function m9(e,t,i,n){for(let i in m4(e,t,void 0,n),t.attrs)e.setAttribute(m6.has(i)?i:dx(i),t.attrs[i])}function m8(e,{layout:t,layoutId:i}){return dr.has(e)||e.startsWith("origin")||(t||void 0!==i)&&(!!pE[e]||"opacity"===e)}function m7(e,t,i){var n;let{style:r}=e,s={};for(let o in r)(dE(r[o])||t.style&&dE(t.style[o])||m8(o,e)||(null===(n=null==i?void 0:i.getValue(o))||void 0===n?void 0:n.liveStyle)!==void 0)&&(s[o]=r[o]);return s}function fe(e,t,i){let n=m7(e,t,i);for(let i in e)(dE(e[i])||dE(t[i]))&&(n[-1!==dn.indexOf(i)?"attr"+i.charAt(0).toUpperCase()+i.substring(1):i]=e[i]);return n}let ft=["x","y","width","height","cx","cy","r"],fi={useVisualState:m$({scrapeMotionValuesFromProps:fe,createRenderState:m3,onUpdate:({props:e,prevProps:t,current:i,renderState:n,latestValues:r})=>{if(!i)return;let s=!!e.drag;if(!s){for(let e in r)if(dr.has(e)){s=!0;break}}if(!s)return;let o=!t;if(t)for(let i=0;i<ft.length;i++){let n=ft[i];e[n]!==t[n]&&(o=!0)}o&&dh.read(()=>{(function(e,t){try{t.dimensions="function"==typeof e.getBBox?e.getBBox():e.getBoundingClientRect()}catch(e){t.dimensions={x:0,y:0,width:0,height:0}}})(i,n),dh.render(()=>{m1(n,r,m5(i.tagName),e.transformTemplate),m9(i,n)})})}})},fn={useVisualState:m$({scrapeMotionValuesFromProps:m7,createRenderState:m2})};function fr(e,t,i){for(let n in t)dE(t[n])||m8(n,i)||(e[n]=t[n])}let fs=new Set(["animate","exit","variants","initial","style","values","variants","transition","transformTemplate","custom","inherit","onBeforeLayoutMeasure","onAnimationStart","onAnimationComplete","onUpdate","onDragStart","onDrag","onDragEnd","onMeasureDragConstraints","onDirectionLock","onDragTransitionEnd","_dragX","_dragY","onHoverStart","onHoverEnd","onViewportEnter","onViewportLeave","globalTapTarget","ignoreStrict","viewport"]);function fo(e){return e.startsWith("while")||e.startsWith("drag")&&"draggable"!==e||e.startsWith("layout")||e.startsWith("onTap")||e.startsWith("onPan")||e.startsWith("onLayout")||fs.has(e)}let fa=e=>!fo(e);try{!function(e){e&&(fa=t=>t.startsWith("on")?!fo(t):e(t))}(require("@emotion/is-prop-valid").default)}catch(e){}let fl={current:null},fc={current:!1},fd=[...uF,d7,ul],fu=e=>fd.find(uU(e)),fh=new WeakMap,fp=["AnimationStart","AnimationComplete","Update","BeforeLayoutMeasure","LayoutMeasure","LayoutAnimationStart","LayoutAnimationComplete"];class fm{scrapeMotionValuesFromProps(e,t,i){return{}}constructor({parent:e,props:t,presenceContext:i,reducedMotionConfig:n,blockInitialAnimation:r,visualState:s},o={}){this.current=null,this.children=new Set,this.isVariantNode=!1,this.isControllingVariants=!1,this.shouldReduceMotion=null,this.values=new Map,this.KeyframeResolver=uA,this.features={},this.valueSubscriptions=new Map,this.prevMotionValues={},this.events={},this.propEventSubscriptions={},this.notifyUpdate=()=>this.notify("Update",this.latestValues),this.render=()=>{this.current&&(this.triggerBuild(),this.renderInstance(this.current,this.renderState,this.props.style,this.projection))},this.renderScheduledAt=0,this.scheduleRender=()=>{let e=dv.now();this.renderScheduledAt<e&&(this.renderScheduledAt=e,dh.render(this.render,!1,!0))};let{latestValues:a,renderState:l,onUpdate:c}=s;this.onUpdate=c,this.latestValues=a,this.baseTarget={...a},this.initialValues=t.initial?{...a}:{},this.renderState=l,this.parent=e,this.props=t,this.presenceContext=i,this.depth=e?e.depth+1:0,this.reducedMotionConfig=n,this.options=o,this.blockInitialAnimation=!!r,this.isControllingVariants=mF(t),this.isVariantNode=mV(t),this.isVariantNode&&(this.variantChildren=new Set),this.manuallyAnimateOnMount=!!(e&&e.current);let{willChange:d,...u}=this.scrapeMotionValuesFromProps(t,{},this);for(let e in u){let t=u[e];void 0!==a[e]&&dE(t)&&t.set(a[e],!1)}}mount(e){this.current=e,fh.set(e,this),this.projection&&!this.projection.instance&&this.projection.mount(e),this.parent&&this.isVariantNode&&!this.isControllingVariants&&(this.removeFromVariantTree=this.parent.addVariantChild(this)),this.values.forEach((e,t)=>this.bindToMotionValue(t,e)),fc.current||function(){if(fc.current=!0,cP){if(window.matchMedia){let e=window.matchMedia("(prefers-reduced-motion)"),t=()=>fl.current=e.matches;e.addListener(t),t()}else fl.current=!1}}(),this.shouldReduceMotion="never"!==this.reducedMotionConfig&&("always"===this.reducedMotionConfig||fl.current),this.parent&&this.parent.children.add(this),this.update(this.props,this.presenceContext)}unmount(){for(let e in fh.delete(this.current),this.projection&&this.projection.unmount(),dp(this.notifyUpdate),dp(this.render),this.valueSubscriptions.forEach(e=>e()),this.valueSubscriptions.clear(),this.removeFromVariantTree&&this.removeFromVariantTree(),this.parent&&this.parent.children.delete(this),this.events)this.events[e].clear();for(let e in this.features){let t=this.features[e];t&&(t.unmount(),t.isMounted=!1)}this.current=null}bindToMotionValue(e,t){let i;this.valueSubscriptions.has(e)&&this.valueSubscriptions.get(e)();let n=dr.has(e),r=t.on("change",t=>{this.latestValues[e]=t,this.props.onUpdate&&dh.preRender(this.notifyUpdate),n&&this.projection&&(this.projection.isTransformDirty=!0)}),s=t.on("renderRequest",this.scheduleRender);window.MotionCheckAppearSync&&(i=window.MotionCheckAppearSync(this,e,t)),this.valueSubscriptions.set(e,()=>{r(),s(),i&&i(),t.owner&&t.stop()})}sortNodePosition(e){return this.current&&this.sortInstanceNodePosition&&this.type===e.type?this.sortInstanceNodePosition(this.current,e.current):0}updateFeatures(){let e="animation";for(e in mz){let t=mz[e];if(!t)continue;let{isEnabled:i,Feature:n}=t;if(!this.features[e]&&n&&i(this.props)&&(this.features[e]=new n(this)),this.features[e]){let t=this.features[e];t.isMounted?t.update():(t.mount(),t.isMounted=!0)}}}triggerBuild(){this.build(this.renderState,this.latestValues,this.props)}measureViewportBox(){return this.current?this.measureInstanceViewportBox(this.current,this.props):pe()}getStaticValue(e){return this.latestValues[e]}setStaticValue(e,t){this.latestValues[e]=t}update(e,t){(e.transformTemplate||this.props.transformTemplate)&&this.scheduleRender(),this.prevProps=this.props,this.props=e,this.prevPresenceContext=this.presenceContext,this.presenceContext=t;for(let t=0;t<fp.length;t++){let i=fp[t];this.propEventSubscriptions[i]&&(this.propEventSubscriptions[i](),delete this.propEventSubscriptions[i]);let n=e["on"+i];n&&(this.propEventSubscriptions[i]=this.on(i,n))}this.prevMotionValues=function(e,t,i){for(let n in t){let r=t[n],s=i[n];if(dE(r))e.addValue(n,r);else if(dE(s))e.addValue(n,dw(r,{owner:e}));else if(s!==r){if(e.hasValue(n)){let t=e.getValue(n);!0===t.liveStyle?t.jump(r):t.hasAnimated||t.set(r)}else{let t=e.getStaticValue(n);e.addValue(n,dw(void 0!==t?t:r,{owner:e}))}}}for(let n in i)void 0===t[n]&&e.removeValue(n);return t}(this,this.scrapeMotionValuesFromProps(e,this.prevProps,this),this.prevMotionValues),this.handleChildMotionValue&&this.handleChildMotionValue(),this.onUpdate&&this.onUpdate(this)}getProps(){return this.props}getVariant(e){return this.props.variants?this.props.variants[e]:void 0}getDefaultTransition(){return this.props.transition}getTransformPagePoint(){return this.props.transformPagePoint}getClosestVariantNode(){return this.isVariantNode?this:this.parent?this.parent.getClosestVariantNode():void 0}addVariantChild(e){let t=this.getClosestVariantNode();if(t)return t.variantChildren&&t.variantChildren.add(e),()=>t.variantChildren.delete(e)}addValue(e,t){let i=this.values.get(e);t!==i&&(i&&this.removeValue(e),this.bindToMotionValue(e,t),this.values.set(e,t),this.latestValues[e]=t.get())}removeValue(e){this.values.delete(e);let t=this.valueSubscriptions.get(e);t&&(t(),this.valueSubscriptions.delete(e)),delete this.latestValues[e],this.removeValueFromRenderState(e,this.renderState)}hasValue(e){return this.values.has(e)}getValue(e,t){if(this.props.values&&this.props.values[e])return this.props.values[e];let i=this.values.get(e);return void 0===i&&void 0!==t&&(i=dw(null===t?void 0:t,{owner:this}),this.addValue(e,i)),i}readValue(e,t){var i;let n=void 0===this.latestValues[e]&&this.current?null!==(i=this.getBaseTargetFromProps(this.props,e))&&void 0!==i?i:this.readValueFromInstance(this.current,e,this.options):this.latestValues[e];return null!=n&&("string"==typeof n&&(uI(n)||dB(n))?n=parseFloat(n):!fu(n)&&ul.test(t)&&(n=uv(e,t)),this.setBaseTarget(e,dE(n)?n.get():n)),dE(n)?n.get():n}setBaseTarget(e,t){this.baseTarget[e]=t}getBaseTarget(e){var t;let i;let{initial:n}=this.props;if("string"==typeof n||"object"==typeof n){let r=c_(this.props,n,null===(t=this.presenceContext)||void 0===t?void 0:t.custom);r&&(i=r[e])}if(n&&void 0!==i)return i;let r=this.getBaseTargetFromProps(this.props,e);return void 0===r||dE(r)?void 0!==this.initialValues[e]&&void 0===i?void 0:this.baseTarget[e]:r}on(e,t){return this.events[e]||(this.events[e]=new dk),this.events[e].add(t)}notify(e,...t){this.events[e]&&this.events[e].notify(...t)}}class ff extends fm{constructor(){super(...arguments),this.KeyframeResolver=uB}sortInstanceNodePosition(e,t){return 2&e.compareDocumentPosition(t)?1:-1}getBaseTargetFromProps(e,t){return e.style?e.style[t]:void 0}removeValueFromRenderState(e,{vars:t,style:i}){delete t[e],delete i[e]}handleChildMotionValue(){this.childSubscription&&(this.childSubscription(),delete this.childSubscription);let{children:e}=this.props;dE(e)&&(this.childSubscription=e.on("change",e=>{this.current&&(this.current.textContent=`${e}`)}))}}class fg extends ff{constructor(){super(...arguments),this.type="html",this.renderInstance=m4}readValueFromInstance(e,t){if(dr.has(t)){let e=ug(t);return e&&e.default||0}{let i=window.getComputedStyle(e),n=(uD(t)?i.getPropertyValue(t):i[t])||0;return"string"==typeof n?n.trim():n}}measureInstanceViewportBox(e,{transformPagePoint:t}){return pp(e,t)}build(e,t,i){mY(e,t,i.transformTemplate)}scrapeMotionValuesFromProps(e,t,i){return m7(e,t,i)}}class fv extends ff{constructor(){super(...arguments),this.type="svg",this.isSVGTag=!1,this.measureInstanceViewportBox=pe}getBaseTargetFromProps(e,t){return e[t]}readValueFromInstance(e,t){if(dr.has(t)){let e=ug(t);return e&&e.default||0}return t=m6.has(t)?t:dx(t),e.getAttribute(t)}scrapeMotionValuesFromProps(e,t,i){return fe(e,t,i)}build(e,t,i){m1(e,t,this.isSVGTag,i.transformTemplate)}renderInstance(e,t,i,n){m9(e,t,i,n)}mount(e){this.isSVGTag=m5(e.tagName),super.mount(e)}}let fy=function(e){if("undefined"==typeof Proxy)return e;let t=new Map;return new Proxy((...t)=>e(...t),{get:(i,n)=>"create"===n?e:(t.has(n)||t.set(n,e(n)),t.get(n))})}((a={animation:{Feature:hj},exit:{Feature:hF},inView:{Feature:mL},tap:{Feature:mA},focus:{Feature:mR},hover:{Feature:mx},pan:{Feature:pk},drag:{Feature:py,ProjectionNode:mE,MeasureLayout:pO},layout:{ProjectionNode:mE,MeasureLayout:pO}},l=(e,t)=>mG(e)?new fv(t):new fg(t,{allowProjection:e!==p.Fragment}),function(e,{forwardMotionProps:t}={forwardMotionProps:!1}){return function({preloadedFeatures:e,createVisualElement:t,useRender:i,useVisualState:n,Component:r}){var s,o;function a(e,s){var o;let a;let l={...(0,p.useContext)(cy),...e,layoutId:function({layoutId:e}){let t=(0,p.useContext)(cf).id;return t&&void 0!==e?t+"-"+e:e}(e)},{isStatic:c}=l,d=function(e){let{initial:t,animate:i}=function(e,t){if(mF(e)){let{initial:t,animate:i}=e;return{initial:!1===t||cM(t)?t:void 0,animate:cM(i)?i:void 0}}return!1!==e.inherit?t:{}}(e,(0,p.useContext)(mU));return(0,p.useMemo)(()=>({initial:t,animate:i}),[mB(t),mB(i)])}(e),h=n(e,c);if(!c&&cP){(0,p.useContext)(mj).strict;let e=function(e){let{drag:t,layout:i}=mz;if(!t&&!i)return{};let n={...t,...i};return{MeasureLayout:(null==t?void 0:t.isEnabled(e))||(null==i?void 0:i.isEnabled(e))?n.MeasureLayout:void 0,ProjectionNode:n.ProjectionNode}}(l);a=e.MeasureLayout,d.visualElement=function(e,t,i,n,r){var s,o;let{visualElement:a}=(0,p.useContext)(mU),l=(0,p.useContext)(mj),c=(0,p.useContext)(cv),d=(0,p.useContext)(cy).reducedMotion,u=(0,p.useRef)(null);n=n||l.renderer,!u.current&&n&&(u.current=n(e,{visualState:t,parent:a,props:i,presenceContext:c,blockInitialAnimation:!!c&&!1===c.initial,reducedMotionConfig:d}));let h=u.current,m=(0,p.useContext)(pT);h&&!h.projection&&r&&("html"===h.type||"svg"===h.type)&&function(e,t,i,n){let{layoutId:r,layout:s,drag:o,dragConstraints:a,layoutScroll:l,layoutRoot:c}=t;e.projection=new i(e.latestValues,t["data-framer-portal-id"]?void 0:function e(t){if(t)return!1!==t.options.allowProjection?t.projection:e(t.parent)}(e.parent)),e.projection.setOptions({layoutId:r,layout:s,alwaysMeasureLayout:!!o||a&&hX(a),visualElement:e,animationType:"string"==typeof s?s:"both",initialPromotionConfig:n,layoutScroll:l,layoutRoot:c})}(u.current,i,r,m);let f=(0,p.useRef)(!1);(0,p.useInsertionEffect)(()=>{h&&f.current&&h.update(i,c)});let g=i[dR],v=(0,p.useRef)(!!g&&!(null===(s=window.MotionHandoffIsComplete)||void 0===s?void 0:s.call(window,g))&&(null===(o=window.MotionHasOptimisedAnimation)||void 0===o?void 0:o.call(window,g)));return cx(()=>{h&&(f.current=!0,window.MotionIsMounted=!0,h.updateFeatures(),pP.render(h.render),v.current&&h.animationState&&h.animationState.animateChanges())}),(0,p.useEffect)(()=>{h&&(!v.current&&h.animationState&&h.animationState.animateChanges(),v.current&&(queueMicrotask(()=>{var e;null===(e=window.MotionHandoffMarkAsComplete)||void 0===e||e.call(window,g)}),v.current=!1))}),h}(r,h,l,t,e.ProjectionNode)}return(0,u.jsxs)(mU.Provider,{value:d,children:[a&&d.visualElement?(0,u.jsx)(a,{visualElement:d.visualElement,...l}):null,i(r,e,(o=d.visualElement,(0,p.useCallback)(e=>{e&&h.onMount&&h.onMount(e),o&&(e?o.mount(e):o.unmount()),s&&("function"==typeof s?s(e):hX(s)&&(s.current=e))},[o])),h,c,d.visualElement)]})}e&&function(e){for(let t in e)mz[t]={...mz[t],...e[t]}}(e),a.displayName=`motion.${"string"==typeof r?r:`create(${null!==(o=null!==(s=r.displayName)&&void 0!==s?s:r.name)&&void 0!==o?o:""})`}`;let l=(0,p.forwardRef)(a);return l[mW]=r,l}({...mG(e)?fi:fn,preloadedFeatures:a,useRender:function(e=!1){return(t,i,n,{latestValues:r},s)=>{let o=(mG(t)?function(e,t,i,n){let r=(0,p.useMemo)(()=>{let i=m3();return m1(i,t,m5(n),e.transformTemplate),{...i.attrs,style:{...i.style}}},[t]);if(e.style){let t={};fr(t,e.style,e),r.style={...t,...r.style}}return r}:function(e,t){let i={},n=function(e,t){let i=e.style||{},n={};return fr(n,i,e),Object.assign(n,function({transformTemplate:e},t){return(0,p.useMemo)(()=>{let i=m2();return mY(i,t,e),Object.assign({},i.vars,i.style)},[t])}(e,t)),n}(e,t);return e.drag&&!1!==e.dragListener&&(i.draggable=!1,n.userSelect=n.WebkitUserSelect=n.WebkitTouchCallout="none",n.touchAction=!0===e.drag?"none":`pan-${"x"===e.drag?"y":"x"}`),void 0===e.tabIndex&&(e.onTap||e.onTapStart||e.whileTap)&&(i.tabIndex=0),i.style=n,i})(i,r,s,t),a=function(e,t,i){let n={};for(let r in e)("values"!==r||"object"!=typeof e.values)&&(fa(r)||!0===i&&fo(r)||!t&&!fo(r)||e.draggable&&r.startsWith("onDrag"))&&(n[r]=e[r]);return n}(i,"string"==typeof t,e),l=t!==p.Fragment?{...a,...o,ref:n}:{},{children:c}=i,d=(0,p.useMemo)(()=>dE(c)?c.get():c,[c]);return(0,p.createElement)(t,{...l,children:d})}}(t),createVisualElement:l,Component:e})}));function fb(){let[e]=(0,p.useState)(new sj),[t,i]=(0,p.useState)(""),[n,r]=(0,p.useState)(""),s=(0,p.useCallback)(async()=>{r("");let i=new URL(process.env.NEXT_PUBLIC_CONN_DETAILS_ENDPOINT??"/api/connection-details",window.location.origin);i.searchParams.set("password",t);let n=await fetch(i.toString());if(!n.ok){401===n.status?r("Invalid password"):r("Connection failed");return}let s=await n.json();await e.connect(s.serverUrl,s.participantToken),await e.localParticipant.setMicrophoneEnabled(!0)},[e,t]);return u.jsx("main",{"data-lk-theme":"default",className:"h-full grid content-center bg-[var(--lk-bg)]",children:u.jsx(lL.Provider,{value:e,children:u.jsx("div",{className:"lk-room-container max-w-[1024px] w-[90vw] mx-auto max-h-[90vh]",children:u.jsx(fk,{onConnectButtonClicked:s,password:t,setPassword:i,error:n})})})})}function fk(e){let{state:t}=l0();return u.jsx(u.Fragment,{children:u.jsx(cR,{mode:"wait",children:"disconnected"===t?u.jsx(fy.div,{initial:{opacity:0,scale:.95},animate:{opacity:1,scale:1},exit:{opacity:0,scale:.95},transition:{duration:.3,ease:[.09,1.04,.245,1.055]},className:"grid items-center justify-center h-full",children:(0,u.jsxs)("div",{className:"flex flex-col items-center gap-4",children:[u.jsx("input",{type:"password",placeholder:"Enter password",value:e.password,onChange:t=>e.setPassword(t.target.value),onKeyPress:t=>{"Enter"===t.key&&e.onConnectButtonClicked()},className:"px-4 py-2 bg-gray-800 text-white rounded-md focus:outline-none focus:ring-2 focus:ring-white"}),e.error&&u.jsx("p",{className:"text-red-500 text-sm",children:e.error}),u.jsx(fy.button,{initial:{opacity:0},animate:{opacity:1},transition:{duration:.3,delay:.1},className:"uppercase px-4 py-2 bg-white text-black rounded-md",onClick:()=>e.onConnectButtonClicked(),children:"Start a conversation"})]})},"disconnected"):(0,u.jsxs)(fy.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},exit:{opacity:0,y:-20},transition:{duration:.3,ease:[.09,1.04,.245,1.055]},className:"flex flex-col items-center gap-4 h-full",children:[u.jsx(fT,{}),u.jsx("div",{className:"flex-1 w-full",children:u.jsx(l1,{})}),u.jsx("div",{className:"w-full",children:u.jsx(fS,{onConnectButtonClicked:e.onConnectButtonClicked})}),u.jsx(co,{}),u.jsx(m,{state:t})]},"connected")})})}function fT(){let{state:e,videoTrack:t,audioTrack:i}=l0();return t?u.jsx("div",{className:"h-[512px] w-[512px] rounded-lg overflow-hidden",children:u.jsx(cr,{trackRef:t})}):u.jsx("div",{className:"h-[300px] w-full",children:u.jsx(ch,{state:e,barCount:5,trackRef:i,className:"agent-visualizer",options:{minHeight:24}})})}function fS(e){let{state:t}=l0();return(0,u.jsxs)("div",{className:"relative h-[60px]",children:[u.jsx(cR,{children:"disconnected"===t&&u.jsx(fy.button,{initial:{opacity:0,top:0},animate:{opacity:1},exit:{opacity:0,top:"-10px"},transition:{duration:1,ease:[.09,1.04,.245,1.055]},className:"uppercase absolute left-1/2 -translate-x-1/2 px-4 py-2 bg-white text-black rounded-md",onClick:()=>e.onConnectButtonClicked(),children:"Start a conversation"})}),u.jsx(cR,{children:"disconnected"!==t&&"connecting"!==t&&(0,u.jsxs)(fy.div,{initial:{opacity:0,top:"10px"},animate:{opacity:1,top:0},exit:{opacity:0,top:"-10px"},transition:{duration:.4,ease:[.09,1.04,.245,1.055]},className:"flex h-8 absolute left-1/2 -translate-x-1/2 justify-center",children:[u.jsx(cm,{controls:{leave:!1}}),u.jsx(l2,{children:u.jsx(h,{})})]})})]})}},1506:(e,t,i)=>{"use strict";i.r(t),i.d(t,{default:()=>a,metadata:()=>o});var n=i(9510),r=i(2219),s=i.n(r);i(6078),i(7272);let o={title:"Voice Assistant"};function a({children:e}){return n.jsx("html",{lang:"en",className:`h-full ${s().className}`,children:n.jsx("body",{className:"h-full",children:e})})}},908:(e,t,i)=>{"use strict";i.r(t),i.d(t,{default:()=>n});let n=(0,i(8570).createProxy)(String.raw`/tmp/build-via-sdist-z_iazuah/voice_mode-4.4.0/voice_mode/frontend/app/page.tsx#default`)},338:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var i in t)Object.defineProperty(e,i,{enumerable:!0,get:t[i]})}(t,{ACTION:function(){return n},FLIGHT_PARAMETERS:function(){return l},NEXT_DID_POSTPONE_HEADER:function(){return d},NEXT_ROUTER_PREFETCH_HEADER:function(){return s},NEXT_ROUTER_STATE_TREE:function(){return r},NEXT_RSC_UNION_QUERY:function(){return c},NEXT_URL:function(){return o},RSC_CONTENT_TYPE_HEADER:function(){return a},RSC_HEADER:function(){return i}});let i="RSC",n="Next-Action",r="Next-Router-State-Tree",s="Next-Router-Prefetch",o="Next-Url",a="text/x-component",l=[[i],[r],[s]],c="_rsc",d="x-nextjs-postponed";("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},7255:e=>{(()=>{"use strict";"undefined"!=typeof __nccwpck_require__&&(__nccwpck_require__.ab=__dirname+"/");var t={};(()=>{t.parse=function(t,i){if("string"!=typeof t)throw TypeError("argument str must be a string");for(var r={},s=t.split(n),o=(i||{}).decode||e,a=0;a<s.length;a++){var l=s[a],c=l.indexOf("=");if(!(c<0)){var d=l.substr(0,c).trim(),u=l.substr(++c,l.length).trim();'"'==u[0]&&(u=u.slice(1,-1)),void 0==r[d]&&(r[d]=function(e,t){try{return t(e)}catch(t){return e}}(u,o))}}return r},t.serialize=function(e,t,n){var s=n||{},o=s.encode||i;if("function"!=typeof o)throw TypeError("option encode is invalid");if(!r.test(e))throw TypeError("argument name is invalid");var a=o(t);if(a&&!r.test(a))throw TypeError("argument val is invalid");var l=e+"="+a;if(null!=s.maxAge){var c=s.maxAge-0;if(isNaN(c)||!isFinite(c))throw TypeError("option maxAge is invalid");l+="; Max-Age="+Math.floor(c)}if(s.domain){if(!r.test(s.domain))throw TypeError("option domain is invalid");l+="; Domain="+s.domain}if(s.path){if(!r.test(s.path))throw TypeError("option path is invalid");l+="; Path="+s.path}if(s.expires){if("function"!=typeof s.expires.toUTCString)throw TypeError("option expires is invalid");l+="; Expires="+s.expires.toUTCString()}if(s.httpOnly&&(l+="; HttpOnly"),s.secure&&(l+="; Secure"),s.sameSite)switch("string"==typeof s.sameSite?s.sameSite.toLowerCase():s.sameSite){case!0:case"strict":l+="; SameSite=Strict";break;case"lax":l+="; SameSite=Lax";break;case"none":l+="; SameSite=None";break;default:throw TypeError("option sameSite is invalid")}return l};var e=decodeURIComponent,i=encodeURIComponent,n=/; */,r=/^[\u0009\u0020-\u007e\u0080-\u00ff]+$/})(),e.exports=t})()},1792:(e,t)=>{"use strict";function i(e,t){void 0===t&&(t={});for(var i=function(e){for(var t=[],i=0;i<e.length;){var n=e[i];if("*"===n||"+"===n||"?"===n){t.push({type:"MODIFIER",index:i,value:e[i++]});continue}if("\\"===n){t.push({type:"ESCAPED_CHAR",index:i++,value:e[i++]});continue}if("{"===n){t.push({type:"OPEN",index:i,value:e[i++]});continue}if("}"===n){t.push({type:"CLOSE",index:i,value:e[i++]});continue}if(":"===n){for(var r="",s=i+1;s<e.length;){var o=e.charCodeAt(s);if(o>=48&&o<=57||o>=65&&o<=90||o>=97&&o<=122||95===o){r+=e[s++];continue}break}if(!r)throw TypeError("Missing parameter name at "+i);t.push({type:"NAME",index:i,value:r}),i=s;continue}if("("===n){var a=1,l="",s=i+1;if("?"===e[s])throw TypeError('Pattern cannot start with "?" at '+s);for(;s<e.length;){if("\\"===e[s]){l+=e[s++]+e[s++];continue}if(")"===e[s]){if(0==--a){s++;break}}else if("("===e[s]&&(a++,"?"!==e[s+1]))throw TypeError("Capturing groups are not allowed at "+s);l+=e[s++]}if(a)throw TypeError("Unbalanced pattern at "+i);if(!l)throw TypeError("Missing pattern at "+i);t.push({type:"PATTERN",index:i,value:l}),i=s;continue}t.push({type:"CHAR",index:i,value:e[i++]})}return t.push({type:"END",index:i,value:""}),t}(e),n=t.prefixes,r=void 0===n?"./":n,o="[^"+s(t.delimiter||"/#?")+"]+?",a=[],l=0,c=0,d="",u=function(e){if(c<i.length&&i[c].type===e)return i[c++].value},h=function(e){var t=u(e);if(void 0!==t)return t;var n=i[c];throw TypeError("Unexpected "+n.type+" at "+n.index+", expected "+e)},p=function(){for(var e,t="";e=u("CHAR")||u("ESCAPED_CHAR");)t+=e;return t};c<i.length;){var m=u("CHAR"),f=u("NAME"),g=u("PATTERN");if(f||g){var v=m||"";-1===r.indexOf(v)&&(d+=v,v=""),d&&(a.push(d),d=""),a.push({name:f||l++,prefix:v,suffix:"",pattern:g||o,modifier:u("MODIFIER")||""});continue}var y=m||u("ESCAPED_CHAR");if(y){d+=y;continue}if(d&&(a.push(d),d=""),u("OPEN")){var v=p(),b=u("NAME")||"",k=u("PATTERN")||"",T=p();h("CLOSE"),a.push({name:b||(k?l++:""),pattern:b&&!k?o:k,prefix:v,suffix:T,modifier:u("MODIFIER")||""});continue}h("END")}return a}function n(e,t){void 0===t&&(t={});var i=o(t),n=t.encode,r=void 0===n?function(e){return e}:n,s=t.validate,a=void 0===s||s,l=e.map(function(e){if("object"==typeof e)return RegExp("^(?:"+e.pattern+")$",i)});return function(t){for(var i="",n=0;n<e.length;n++){var s=e[n];if("string"==typeof s){i+=s;continue}var o=t?t[s.name]:void 0,c="?"===s.modifier||"*"===s.modifier,d="*"===s.modifier||"+"===s.modifier;if(Array.isArray(o)){if(!d)throw TypeError('Expected "'+s.name+'" to not repeat, but got an array');if(0===o.length){if(c)continue;throw TypeError('Expected "'+s.name+'" to not be empty')}for(var u=0;u<o.length;u++){var h=r(o[u],s);if(a&&!l[n].test(h))throw TypeError('Expected all "'+s.name+'" to match "'+s.pattern+'", but got "'+h+'"');i+=s.prefix+h+s.suffix}continue}if("string"==typeof o||"number"==typeof o){var h=r(String(o),s);if(a&&!l[n].test(h))throw TypeError('Expected "'+s.name+'" to match "'+s.pattern+'", but got "'+h+'"');i+=s.prefix+h+s.suffix;continue}if(!c){var p=d?"an array":"a string";throw TypeError('Expected "'+s.name+'" to be '+p)}}return i}}function r(e,t,i){void 0===i&&(i={});var n=i.decode,r=void 0===n?function(e){return e}:n;return function(i){var n=e.exec(i);if(!n)return!1;for(var s=n[0],o=n.index,a=Object.create(null),l=1;l<n.length;l++)!function(e){if(void 0!==n[e]){var i=t[e-1];"*"===i.modifier||"+"===i.modifier?a[i.name]=n[e].split(i.prefix+i.suffix).map(function(e){return r(e,i)}):a[i.name]=r(n[e],i)}}(l);return{path:s,index:o,params:a}}}function s(e){return e.replace(/([.+*?=^!:${}()[\]|/\\])/g,"\\$1")}function o(e){return e&&e.sensitive?"":"i"}function a(e,t,i){void 0===i&&(i={});for(var n=i.strict,r=void 0!==n&&n,a=i.start,l=i.end,c=i.encode,d=void 0===c?function(e){return e}:c,u="["+s(i.endsWith||"")+"]|$",h="["+s(i.delimiter||"/#?")+"]",p=void 0===a||a?"^":"",m=0;m<e.length;m++){var f=e[m];if("string"==typeof f)p+=s(d(f));else{var g=s(d(f.prefix)),v=s(d(f.suffix));if(f.pattern){if(t&&t.push(f),g||v){if("+"===f.modifier||"*"===f.modifier){var y="*"===f.modifier?"?":"";p+="(?:"+g+"((?:"+f.pattern+")(?:"+v+g+"(?:"+f.pattern+"))*)"+v+")"+y}else p+="(?:"+g+"("+f.pattern+")"+v+")"+f.modifier}else p+="("+f.pattern+")"+f.modifier}else p+="(?:"+g+v+")"+f.modifier}}if(void 0===l||l)r||(p+=h+"?"),p+=i.endsWith?"(?="+u+")":"$";else{var b=e[e.length-1],k="string"==typeof b?h.indexOf(b[b.length-1])>-1:void 0===b;r||(p+="(?:"+h+"(?="+u+"))?"),k||(p+="(?="+h+"|"+u+")")}return new RegExp(p,o(i))}function l(e,t,n){return e instanceof RegExp?function(e,t){if(!t)return e;var i=e.source.match(/\((?!\?)/g);if(i)for(var n=0;n<i.length;n++)t.push({name:n,prefix:"",suffix:"",modifier:"",pattern:""});return e}(e,t):Array.isArray(e)?RegExp("(?:"+e.map(function(e){return l(e,t,n).source}).join("|")+")",o(n)):a(i(e,n),t,n)}Object.defineProperty(t,"__esModule",{value:!0}),t.parse=i,t.compile=function(e,t){return n(i(e,t),t)},t.tokensToFunction=n,t.match=function(e,t){var i=[];return r(l(e,i,t),i,t)},t.regexpToFunction=r,t.tokensToRegexp=a,t.pathToRegexp=l},6621:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var i in t)Object.defineProperty(e,i,{enumerable:!0,get:t[i]})}(t,{fillMetadataSegment:function(){return u},normalizeMetadataRoute:function(){return h}});let n=i(616),r=function(e){return e&&e.__esModule?e:{default:e}}(i(1293)),s=i(7262),o=i(5679),a=i(8785),l=i(8168),c=i(1040);function d(e){let t="";return(e.includes("(")&&e.includes(")")||e.includes("@"))&&(t=(0,a.djb2Hash)(e).toString(36).slice(0,6)),t}function u(e,t,i){let n=(0,l.normalizeAppPath)(e),a=(0,o.getNamedRouteRegex)(n,!1),u=(0,s.interpolateDynamicPath)(n,t,a),h=d(e),p=h?`-${h}`:"",{name:m,ext:f}=r.default.parse(i);return(0,c.normalizePathSep)(r.default.join(u,`${m}${p}${f}`))}function h(e){if(!(0,n.isMetadataRoute)(e))return e;let t=e,i="";if("/robots"===e?t+=".txt":"/manifest"===e?t+=".webmanifest":e.endsWith("/sitemap")?t+=".xml":i=d(e.slice(0,-(r.default.basename(e).length+1))),!t.endsWith("/route")){let{dir:s,name:o,ext:a}=r.default.parse(t),l=(0,n.isStaticMetadataRoute)(e);t=r.default.posix.join(s,`${o}${i?`-${i}`:""}${a}`,l?"":"[[...__metadata_id__]]","route")}return t}},616:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var i in t)Object.defineProperty(e,i,{enumerable:!0,get:t[i]})}(t,{STATIC_METADATA_IMAGES:function(){return r},isMetadataRoute:function(){return d},isMetadataRouteFile:function(){return a},isStaticMetadataRoute:function(){return c},isStaticMetadataRouteFile:function(){return l}});let n=i(1040),r={icon:{filename:"icon",extensions:["ico","jpg","jpeg","png","svg"]},apple:{filename:"apple-icon",extensions:["jpg","jpeg","png"]},favicon:{filename:"favicon",extensions:["ico"]},openGraph:{filename:"opengraph-image",extensions:["jpg","jpeg","png","gif"]},twitter:{filename:"twitter-image",extensions:["jpg","jpeg","png","gif"]}},s=["js","jsx","ts","tsx"],o=e=>`(?:${e.join("|")})`;function a(e,t,i){let s=[RegExp(`^[\\\\/]robots${i?`\\.${o(t.concat("txt"))}$`:""}`),RegExp(`^[\\\\/]manifest${i?`\\.${o(t.concat("webmanifest","json"))}$`:""}`),RegExp("^[\\\\/]favicon\\.ico$"),RegExp(`[\\\\/]sitemap${i?`\\.${o(t.concat("xml"))}$`:""}`),RegExp(`[\\\\/]${r.icon.filename}\\d?${i?`\\.${o(t.concat(r.icon.extensions))}$`:""}`),RegExp(`[\\\\/]${r.apple.filename}\\d?${i?`\\.${o(t.concat(r.apple.extensions))}$`:""}`),RegExp(`[\\\\/]${r.openGraph.filename}\\d?${i?`\\.${o(t.concat(r.openGraph.extensions))}$`:""}`),RegExp(`[\\\\/]${r.twitter.filename}\\d?${i?`\\.${o(t.concat(r.twitter.extensions))}$`:""}`)],a=(0,n.normalizePathSep)(e);return s.some(e=>e.test(a))}function l(e){return a(e,[],!0)}function c(e){return"/robots"===e||"/manifest"===e||l(e)}function d(e){let t=e.replace(/^\/?app\//,"").replace(/\/route$/,"");return"/"!==t[0]&&(t="/"+t),!t.endsWith("/page")&&a(t,s,!1)}},6975:(e,t,i)=>{"use strict";function n(e){return function(){let{cookie:t}=e;if(!t)return{};let{parse:n}=i(7255);return n(Array.isArray(t)?t.join("; "):t)}}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"getCookieParser",{enumerable:!0,get:function(){return n}})},1586:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var i in t)Object.defineProperty(e,i,{enumerable:!0,get:t[i]})}(t,{INTERCEPTION_ROUTE_MARKERS:function(){return r},extractInterceptionRouteInformation:function(){return o},isInterceptionRouteAppPath:function(){return s}});let n=i(8168),r=["(..)(..)","(.)","(..)","(...)"];function s(e){return void 0!==e.split("/").find(e=>r.find(t=>e.startsWith(t)))}function o(e){let t,i,s;for(let n of e.split("/"))if(i=r.find(e=>n.startsWith(e))){[t,s]=e.split(i,2);break}if(!t||!i||!s)throw Error(`Invalid interception route: ${e}. Must be in the format /<intercepting route>/(..|...|..)(..)/<intercepted route>`);switch(t=(0,n.normalizeAppPath)(t),i){case"(.)":s="/"===t?`/${s}`:t+"/"+s;break;case"(..)":if("/"===t)throw Error(`Invalid interception route: ${e}. Cannot use (..) marker at the root level, use (.) instead.`);s=t.split("/").slice(0,-1).concat(s).join("/");break;case"(...)":s="/"+s;break;case"(..)(..)":let o=t.split("/");if(o.length<=2)throw Error(`Invalid interception route: ${e}. Cannot use (..)(..) marker at the root level or one level up.`);s=o.slice(0,-2).concat(s).join("/");break;default:throw Error("Invariant: unexpected marker")}return{interceptingRoute:t,interceptedRoute:s}}},7262:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var i in t)Object.defineProperty(e,i,{enumerable:!0,get:t[i]})}(t,{getUtils:function(){return f},interpolateDynamicPath:function(){return p},normalizeDynamicRouteParams:function(){return m},normalizeVercelUrl:function(){return h}});let n=i(7360),r=i(5014),s=i(3707),o=i(5679),a=i(3525),l=i(5257),c=i(7847),d=i(8168),u=i(1943);function h(e,t,i,r,s){if(r&&t&&s){let t=(0,n.parse)(e.url,!0);for(let e of(delete t.search,Object.keys(t.query))){let n=e!==u.NEXT_QUERY_PARAM_PREFIX&&e.startsWith(u.NEXT_QUERY_PARAM_PREFIX),r=e!==u.NEXT_INTERCEPTION_MARKER_PREFIX&&e.startsWith(u.NEXT_INTERCEPTION_MARKER_PREFIX);(n||r||(i||Object.keys(s.groups)).includes(e))&&delete t.query[e]}e.url=(0,n.format)(t)}}function p(e,t,i){if(!i)return e;for(let n of Object.keys(i.groups)){let{optional:r,repeat:s}=i.groups[n],o=`[${s?"...":""}${n}]`;r&&(o=`[${o}]`);let a=e.indexOf(o);if(a>-1){let i;let r=t[n];i=Array.isArray(r)?r.map(e=>e&&encodeURIComponent(e)).join("/"):r?encodeURIComponent(r):"",e=e.slice(0,a)+i+e.slice(a+o.length)}}return e}function m(e,t,i,n){let r=!0;return i?{params:e=Object.keys(i.groups).reduce((s,o)=>{let a=e[o];"string"==typeof a&&(a=(0,d.normalizeRscURL)(a)),Array.isArray(a)&&(a=a.map(e=>("string"==typeof e&&(e=(0,d.normalizeRscURL)(e)),e)));let l=n[o],c=i.groups[o].optional;return((Array.isArray(l)?l.some(e=>Array.isArray(a)?a.some(t=>t.includes(e)):null==a?void 0:a.includes(e)):null==a?void 0:a.includes(l))||void 0===a&&!(c&&t))&&(r=!1),c&&(!a||Array.isArray(a)&&1===a.length&&("index"===a[0]||a[0]===`[[...${o}]]`))&&(a=void 0,delete e[o]),a&&"string"==typeof a&&i.groups[o].repeat&&(a=a.split("/")),a&&(s[o]=a),s},{}),hasValidParams:r}:{params:e,hasValidParams:!1}}function f({page:e,i18n:t,basePath:i,rewrites:n,pageIsDynamic:d,trailingSlash:f,caseSensitive:g}){let v,y,b;return d&&(v=(0,o.getNamedRouteRegex)(e,!1),b=(y=(0,a.getRouteMatcher)(v))(e)),{handleRewrites:function(o,a){let u={},h=a.pathname,p=n=>{let c=(0,s.getPathMatch)(n.source+(f?"(/)?":""),{removeUnnamedParams:!0,strict:!0,sensitive:!!g})(a.pathname);if((n.has||n.missing)&&c){let e=(0,l.matchHas)(o,a.query,n.has,n.missing);e?Object.assign(c,e):c=!1}if(c){let{parsedDestination:s,destQuery:o}=(0,l.prepareDestination)({appendParamsToQuery:!0,destination:n.destination,params:c,query:a.query});if(s.protocol)return!0;if(Object.assign(u,o,c),Object.assign(a.query,s.query),delete s.query,Object.assign(a,s),h=a.pathname,i&&(h=h.replace(RegExp(`^${i}`),"")||"/"),t){let e=(0,r.normalizeLocalePath)(h,t.locales);h=e.pathname,a.query.nextInternalLocale=e.detectedLocale||c.nextInternalLocale}if(h===e)return!0;if(d&&y){let e=y(h);if(e)return a.query={...a.query,...e},!0}}return!1};for(let e of n.beforeFiles||[])p(e);if(h!==e){let t=!1;for(let e of n.afterFiles||[])if(t=p(e))break;if(!t&&!(()=>{let t=(0,c.removeTrailingSlash)(h||"");return t===(0,c.removeTrailingSlash)(e)||(null==y?void 0:y(t))})()){for(let e of n.fallback||[])if(t=p(e))break}}return u},defaultRouteRegex:v,dynamicRouteMatcher:y,defaultRouteMatches:b,getParamsFromRouteMatches:function(e,i,n){return(0,a.getRouteMatcher)(function(){let{groups:e,routeKeys:r}=v;return{re:{exec:s=>{let o=Object.fromEntries(new URLSearchParams(s)),a=t&&n&&o["1"]===n;for(let e of Object.keys(o)){let t=o[e];e!==u.NEXT_QUERY_PARAM_PREFIX&&e.startsWith(u.NEXT_QUERY_PARAM_PREFIX)&&(o[e.substring(u.NEXT_QUERY_PARAM_PREFIX.length)]=t,delete o[e])}let l=Object.keys(r||{}),c=e=>{if(t){let r=Array.isArray(e),s=r?e[0]:e;if("string"==typeof s&&t.locales.some(e=>e.toLowerCase()===s.toLowerCase()&&(n=e,i.locale=n,!0)))return r&&e.splice(0,1),!r||0===e.length}return!1};return l.every(e=>o[e])?l.reduce((t,i)=>{let n=null==r?void 0:r[i];return n&&!c(o[i])&&(t[e[n].pos]=o[i]),t},{}):Object.keys(o).reduce((e,t)=>{if(!c(o[t])){let i=t;return a&&(i=parseInt(t,10)-1+""),Object.assign(e,{[i]:o[t]})}return e},{})}},groups:e}}())(e.headers["x-now-route-matches"])},normalizeDynamicRouteParams:(e,t)=>m(e,t,v,b),normalizeVercelUrl:(e,t,i)=>h(e,t,i,d,v),interpolateDynamicPath:(e,t)=>p(e,t,v)}}},4080:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"escapeStringRegexp",{enumerable:!0,get:function(){return r}});let i=/[|\\{}()[\]^$+*?.-]/,n=/[|\\{}()[\]^$+*?.-]/g;function r(e){return i.test(e)?e.replace(n,"\\$&"):e}},8785:(e,t)=>{"use strict";function i(e){let t=5381;for(let i=0;i<e.length;i++)t=(t<<5)+t+e.charCodeAt(i)&4294967295;return t>>>0}function n(e){return i(e).toString(36).slice(0,5)}Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var i in t)Object.defineProperty(e,i,{enumerable:!0,get:t[i]})}(t,{djb2Hash:function(){return i},hexHash:function(){return n}})},5014:(e,t)=>{"use strict";function i(e,t){let i;let n=e.split("/");return(t||[]).some(t=>!!n[1]&&n[1].toLowerCase()===t.toLowerCase()&&(i=t,n.splice(1,1),e=n.join("/")||"/",!0)),{pathname:e,detectedLocale:i}}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"normalizeLocalePath",{enumerable:!0,get:function(){return i}})},1293:(e,t,i)=>{"use strict";let n;n=i(5315),e.exports=n},1555:(e,t)=>{"use strict";function i(e){return e.startsWith("/")?e:"/"+e}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"ensureLeadingSlash",{enumerable:!0,get:function(){return i}})},1040:(e,t)=>{"use strict";function i(e){return e.replace(/\\/g,"/")}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"normalizePathSep",{enumerable:!0,get:function(){return i}})},8168:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var i in t)Object.defineProperty(e,i,{enumerable:!0,get:t[i]})}(t,{normalizeAppPath:function(){return s},normalizeRscURL:function(){return o}});let n=i(1555),r=i(5406);function s(e){return(0,n.ensureLeadingSlash)(e.split("/").reduce((e,t,i,n)=>!t||(0,r.isGroupSegment)(t)||"@"===t[0]||("page"===t||"route"===t)&&i===n.length-1?e:e+"/"+t,""))}function o(e){return e.replace(/\.rsc($|\?)/,"$1")}},1942:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"parseRelativeUrl",{enumerable:!0,get:function(){return r}}),i(2569);let n=i(4869);function r(e,t){let i=new URL("http://n"),r=t?new URL(t,i):e.startsWith(".")?new URL("http://n"):i,{pathname:s,searchParams:o,search:a,hash:l,href:c,origin:d}=new URL(e,r);if(d!==i.origin)throw Error("invariant: invalid relative URL, router received "+e);return{pathname:s,query:(0,n.searchParamsToUrlQuery)(o),search:a,hash:l,href:c.slice(i.origin.length)}}},3226:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"parseUrl",{enumerable:!0,get:function(){return s}});let n=i(4869),r=i(1942);function s(e){if(e.startsWith("/"))return(0,r.parseRelativeUrl)(e);let t=new URL(e);return{hash:t.hash,hostname:t.hostname,href:t.href,pathname:t.pathname,port:t.port,protocol:t.protocol,query:(0,n.searchParamsToUrlQuery)(t.searchParams),search:t.search}}},3707:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"getPathMatch",{enumerable:!0,get:function(){return r}});let n=i(1792);function r(e,t){let i=[],r=(0,n.pathToRegexp)(e,i,{delimiter:"/",sensitive:"boolean"==typeof(null==t?void 0:t.sensitive)&&t.sensitive,strict:null==t?void 0:t.strict}),s=(0,n.regexpToFunction)((null==t?void 0:t.regexModifier)?new RegExp(t.regexModifier(r.source),r.flags):r,i);return(e,n)=>{if("string"!=typeof e)return!1;let r=s(e);if(!r)return!1;if(null==t?void 0:t.removeUnnamedParams)for(let e of i)"number"==typeof e.name&&delete r.params[e.name];return{...n,...r.params}}}},5257:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var i in t)Object.defineProperty(e,i,{enumerable:!0,get:t[i]})}(t,{compileNonPath:function(){return u},matchHas:function(){return d},prepareDestination:function(){return h}});let n=i(1792),r=i(4080),s=i(3226),o=i(1586),a=i(338),l=i(6975);function c(e){return e.replace(/__ESC_COLON_/gi,":")}function d(e,t,i,n){void 0===i&&(i=[]),void 0===n&&(n=[]);let r={},s=i=>{let n;let s=i.key;switch(i.type){case"header":s=s.toLowerCase(),n=e.headers[s];break;case"cookie":n="cookies"in e?e.cookies[i.key]:(0,l.getCookieParser)(e.headers)()[i.key];break;case"query":n=t[s];break;case"host":{let{host:t}=(null==e?void 0:e.headers)||{};n=null==t?void 0:t.split(":",1)[0].toLowerCase()}}if(!i.value&&n)return r[function(e){let t="";for(let i=0;i<e.length;i++){let n=e.charCodeAt(i);(n>64&&n<91||n>96&&n<123)&&(t+=e[i])}return t}(s)]=n,!0;if(n){let e=RegExp("^"+i.value+"$"),t=Array.isArray(n)?n.slice(-1)[0].match(e):n.match(e);if(t)return Array.isArray(t)&&(t.groups?Object.keys(t.groups).forEach(e=>{r[e]=t.groups[e]}):"host"===i.type&&t[0]&&(r.host=t[0])),!0}return!1};return!!i.every(e=>s(e))&&!n.some(e=>s(e))&&r}function u(e,t){if(!e.includes(":"))return e;for(let i of Object.keys(t))e.includes(":"+i)&&(e=e.replace(RegExp(":"+i+"\\*","g"),":"+i+"--ESCAPED_PARAM_ASTERISKS").replace(RegExp(":"+i+"\\?","g"),":"+i+"--ESCAPED_PARAM_QUESTION").replace(RegExp(":"+i+"\\+","g"),":"+i+"--ESCAPED_PARAM_PLUS").replace(RegExp(":"+i+"(?!\\w)","g"),"--ESCAPED_PARAM_COLON"+i));return e=e.replace(/(:|\*|\?|\+|\(|\)|\{|\})/g,"\\$1").replace(/--ESCAPED_PARAM_PLUS/g,"+").replace(/--ESCAPED_PARAM_COLON/g,":").replace(/--ESCAPED_PARAM_QUESTION/g,"?").replace(/--ESCAPED_PARAM_ASTERISKS/g,"*"),(0,n.compile)("/"+e,{validate:!1})(t).slice(1)}function h(e){let t;let i=Object.assign({},e.query);delete i.__nextLocale,delete i.__nextDefaultLocale,delete i.__nextDataReq,delete i.__nextInferredLocaleFromDefault,delete i[a.NEXT_RSC_UNION_QUERY];let l=e.destination;for(let t of Object.keys({...e.params,...i}))l=l.replace(RegExp(":"+(0,r.escapeStringRegexp)(t),"g"),"__ESC_COLON_"+t);let d=(0,s.parseUrl)(l),h=d.query,p=c(""+d.pathname+(d.hash||"")),m=c(d.hostname||""),f=[],g=[];(0,n.pathToRegexp)(p,f),(0,n.pathToRegexp)(m,g);let v=[];f.forEach(e=>v.push(e.name)),g.forEach(e=>v.push(e.name));let y=(0,n.compile)(p,{validate:!1}),b=(0,n.compile)(m,{validate:!1});for(let[t,i]of Object.entries(h))Array.isArray(i)?h[t]=i.map(t=>u(c(t),e.params)):"string"==typeof i&&(h[t]=u(c(i),e.params));let k=Object.keys(e.params).filter(e=>"nextInternalLocale"!==e);if(e.appendParamsToQuery&&!k.some(e=>v.includes(e)))for(let t of k)t in h||(h[t]=e.params[t]);if((0,o.isInterceptionRouteAppPath)(p))for(let t of p.split("/")){let i=o.INTERCEPTION_ROUTE_MARKERS.find(e=>t.startsWith(e));if(i){e.params["0"]=i;break}}try{let[i,n]=(t=y(e.params)).split("#",2);d.hostname=b(e.params),d.pathname=i,d.hash=(n?"#":"")+(n||""),delete d.search}catch(e){if(e.message.match(/Expected .*? to not repeat, but got an array/))throw Error("To use a multi-match in the destination you must add `*` at the end of the param name to signify it should repeat. https://nextjs.org/docs/messages/invalid-multi-match");throw e}return d.query={...i,...d.query},{newUrl:t,destQuery:h,parsedDestination:d}}},4869:(e,t)=>{"use strict";function i(e){let t={};return e.forEach((e,i)=>{void 0===t[i]?t[i]=e:Array.isArray(t[i])?t[i].push(e):t[i]=[t[i],e]}),t}function n(e){return"string"!=typeof e&&("number"!=typeof e||isNaN(e))&&"boolean"!=typeof e?"":String(e)}function r(e){let t=new URLSearchParams;return Object.entries(e).forEach(e=>{let[i,r]=e;Array.isArray(r)?r.forEach(e=>t.append(i,n(e))):t.set(i,n(r))}),t}function s(e){for(var t=arguments.length,i=Array(t>1?t-1:0),n=1;n<t;n++)i[n-1]=arguments[n];return i.forEach(t=>{Array.from(t.keys()).forEach(t=>e.delete(t)),t.forEach((t,i)=>e.append(i,t))}),e}Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var i in t)Object.defineProperty(e,i,{enumerable:!0,get:t[i]})}(t,{assign:function(){return s},searchParamsToUrlQuery:function(){return i},urlQueryToSearchParams:function(){return r}})},7847:(e,t)=>{"use strict";function i(e){return e.replace(/\/$/,"")||"/"}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"removeTrailingSlash",{enumerable:!0,get:function(){return i}})},3525:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"getRouteMatcher",{enumerable:!0,get:function(){return r}});let n=i(2569);function r(e){let{re:t,groups:i}=e;return e=>{let r=t.exec(e);if(!r)return!1;let s=e=>{try{return decodeURIComponent(e)}catch(e){throw new n.DecodeError("failed to decode param")}},o={};return Object.keys(i).forEach(e=>{let t=i[e],n=r[t.pos];void 0!==n&&(o[e]=~n.indexOf("/")?n.split("/").map(e=>s(e)):t.repeat?[s(n)]:s(n))}),o}}},5679:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var i in t)Object.defineProperty(e,i,{enumerable:!0,get:t[i]})}(t,{getNamedMiddlewareRegex:function(){return p},getNamedRouteRegex:function(){return h},getRouteRegex:function(){return c},parseParameter:function(){return a}});let n=i(1943),r=i(1586),s=i(4080),o=i(7847);function a(e){let t=e.startsWith("[")&&e.endsWith("]");t&&(e=e.slice(1,-1));let i=e.startsWith("...");return i&&(e=e.slice(3)),{key:e,repeat:i,optional:t}}function l(e){let t=(0,o.removeTrailingSlash)(e).slice(1).split("/"),i={},n=1;return{parameterizedRoute:t.map(e=>{let t=r.INTERCEPTION_ROUTE_MARKERS.find(t=>e.startsWith(t)),o=e.match(/\[((?:\[.*\])|.+)\]/);if(t&&o){let{key:e,optional:r,repeat:l}=a(o[1]);return i[e]={pos:n++,repeat:l,optional:r},"/"+(0,s.escapeStringRegexp)(t)+"([^/]+?)"}if(!o)return"/"+(0,s.escapeStringRegexp)(e);{let{key:e,repeat:t,optional:r}=a(o[1]);return i[e]={pos:n++,repeat:t,optional:r},t?r?"(?:/(.+?))?":"/(.+?)":"/([^/]+?)"}}).join(""),groups:i}}function c(e){let{parameterizedRoute:t,groups:i}=l(e);return{re:RegExp("^"+t+"(?:/)?$"),groups:i}}function d(e){let{interceptionMarker:t,getSafeRouteKey:i,segment:n,routeKeys:r,keyPrefix:o}=e,{key:l,optional:c,repeat:d}=a(n),u=l.replace(/\W/g,"");o&&(u=""+o+u);let h=!1;(0===u.length||u.length>30)&&(h=!0),isNaN(parseInt(u.slice(0,1)))||(h=!0),h&&(u=i()),o?r[u]=""+o+l:r[u]=l;let p=t?(0,s.escapeStringRegexp)(t):"";return d?c?"(?:/"+p+"(?<"+u+">.+?))?":"/"+p+"(?<"+u+">.+?)":"/"+p+"(?<"+u+">[^/]+?)"}function u(e,t){let i;let a=(0,o.removeTrailingSlash)(e).slice(1).split("/"),l=(i=0,()=>{let e="",t=++i;for(;t>0;)e+=String.fromCharCode(97+(t-1)%26),t=Math.floor((t-1)/26);return e}),c={};return{namedParameterizedRoute:a.map(e=>{let i=r.INTERCEPTION_ROUTE_MARKERS.some(t=>e.startsWith(t)),o=e.match(/\[((?:\[.*\])|.+)\]/);if(i&&o){let[i]=e.split(o[0]);return d({getSafeRouteKey:l,interceptionMarker:i,segment:o[1],routeKeys:c,keyPrefix:t?n.NEXT_INTERCEPTION_MARKER_PREFIX:void 0})}return o?d({getSafeRouteKey:l,segment:o[1],routeKeys:c,keyPrefix:t?n.NEXT_QUERY_PARAM_PREFIX:void 0}):"/"+(0,s.escapeStringRegexp)(e)}).join(""),routeKeys:c}}function h(e,t){let i=u(e,t);return{...c(e),namedRegex:"^"+i.namedParameterizedRoute+"(?:/)?$",routeKeys:i.routeKeys}}function p(e,t){let{parameterizedRoute:i}=l(e),{catchAll:n=!0}=t;if("/"===i)return{namedRegex:"^/"+(n?".*":"")+"$"};let{namedParameterizedRoute:r}=u(e,!1);return{namedRegex:"^"+r+(n?"(?:(/.*)?)":"")+"$"}}},5406:(e,t)=>{"use strict";function i(e){return"("===e[0]&&e.endsWith(")")}Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var i in t)Object.defineProperty(e,i,{enumerable:!0,get:t[i]})}(t,{DEFAULT_SEGMENT_KEY:function(){return r},PAGE_SEGMENT_KEY:function(){return n},isGroupSegment:function(){return i}});let n="__PAGE__",r="__DEFAULT__"},2569:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var i in t)Object.defineProperty(e,i,{enumerable:!0,get:t[i]})}(t,{DecodeError:function(){return m},MiddlewareNotFoundError:function(){return y},MissingStaticPage:function(){return v},NormalizeError:function(){return f},PageNotFoundError:function(){return g},SP:function(){return h},ST:function(){return p},WEB_VITALS:function(){return i},execOnce:function(){return n},getDisplayName:function(){return l},getLocationOrigin:function(){return o},getURL:function(){return a},isAbsoluteUrl:function(){return s},isResSent:function(){return c},loadGetInitialProps:function(){return u},normalizeRepeatedSlashes:function(){return d},stringifyError:function(){return b}});let i=["CLS","FCP","FID","INP","LCP","TTFB"];function n(e){let t,i=!1;return function(){for(var n=arguments.length,r=Array(n),s=0;s<n;s++)r[s]=arguments[s];return i||(i=!0,t=e(...r)),t}}let r=/^[a-zA-Z][a-zA-Z\d+\-.]*?:/,s=e=>r.test(e);function o(){let{protocol:e,hostname:t,port:i}=window.location;return e+"//"+t+(i?":"+i:"")}function a(){let{href:e}=window.location,t=o();return e.substring(t.length)}function l(e){return"string"==typeof e?e:e.displayName||e.name||"Unknown"}function c(e){return e.finished||e.headersSent}function d(e){let t=e.split("?");return t[0].replace(/\\/g,"/").replace(/\/\/+/g,"/")+(t[1]?"?"+t.slice(1).join("?"):"")}async function u(e,t){let i=t.res||t.ctx&&t.ctx.res;if(!e.getInitialProps)return t.ctx&&t.Component?{pageProps:await u(t.Component,t.ctx)}:{};let n=await e.getInitialProps(t);if(i&&c(i))return n;if(!n)throw Error('"'+l(e)+'.getInitialProps()" should resolve to an object. But found "'+n+'" instead.');return n}let h="undefined"!=typeof performance,p=h&&["mark","measure","getEntriesByName"].every(e=>"function"==typeof performance[e]);class m extends Error{}class f extends Error{}class g extends Error{constructor(e){super(),this.code="ENOENT",this.name="PageNotFoundError",this.message="Cannot find module for page: "+e}}class v extends Error{constructor(e,t){super(),this.message="Failed to load static file for page: "+e+" "+t}}class y extends Error{constructor(){super(),this.code="ENOENT",this.message="Cannot find the middleware module"}}function b(e){return JSON.stringify({message:e.message,stack:e.stack})}},7481:(e,t,i)=>{"use strict";i.r(t),i.d(t,{default:()=>r});var n=i(6621);let r=e=>[{type:"image/x-icon",sizes:"16x16",url:(0,n.fillMetadataSegment)(".",e.params,"favicon.ico")+""}]},7272:()=>{}};var t=require("../webpack-runtime.js");t.C(e);var i=e=>t(t.s=e),n=t.X(0,[948,994],()=>i(2806));module.exports=n})();
11
+ `),()=>{document.head.removeChild(c)}},[t]),(0,u.jsx)(cb,{isPresent:t,childRef:n,sizeRef:r,children:p.cloneElement(e,{ref:n})})}let cT=({children:e,initial:t,isPresent:i,onExitComplete:n,custom:r,presenceAffectsLayout:s,mode:o})=>{let a=cg(cS),l=(0,p.useId)(),c=(0,p.useCallback)(e=>{for(let t of(a.set(e,!0),a.values()))if(!t)return;n&&n()},[a,n]),d=(0,p.useMemo)(()=>({id:l,initial:t,isPresent:i,custom:r,onExitComplete:c,register:e=>(a.set(e,!1),()=>a.delete(e))}),s?[Math.random(),c]:[i,c]);return(0,p.useMemo)(()=>{a.forEach((e,t)=>a.set(t,!1))},[i]),p.useEffect(()=>{i||a.size||!n||n()},[i]),"popLayout"===o&&(e=(0,u.jsx)(ck,{isPresent:i,children:e})),(0,u.jsx)(cv.Provider,{value:d,children:e})};function cS(){return new Map}function cC(e=!0){let t=(0,p.useContext)(cv);if(null===t)return[!0,null];let{isPresent:i,onExitComplete:n,register:r}=t,s=(0,p.useId)();(0,p.useEffect)(()=>{e&&r(s)},[e]);let o=(0,p.useCallback)(()=>e&&n&&n(s),[s,n,e]);return!i&&n?[!1,o]:[!0]}let cw=e=>e.key||"";function cE(e){let t=[];return p.Children.forEach(e,e=>{(0,p.isValidElement)(e)&&t.push(e)}),t}let cP="undefined"!=typeof window,cx=cP?p.useLayoutEffect:p.useEffect,cR=({children:e,custom:t,initial:i=!0,onExitComplete:n,presenceAffectsLayout:r=!0,mode:s="sync",propagate:o=!1})=>{let[a,l]=cC(o),c=(0,p.useMemo)(()=>cE(e),[e]),d=o&&!a?[]:c.map(cw),h=(0,p.useRef)(!0),m=(0,p.useRef)(c),f=cg(()=>new Map),[g,v]=(0,p.useState)(c),[y,b]=(0,p.useState)(c);cx(()=>{h.current=!1,m.current=c;for(let e=0;e<y.length;e++){let t=cw(y[e]);d.includes(t)?f.delete(t):!0!==f.get(t)&&f.set(t,!1)}},[y,d.length,d.join("-")]);let k=[];if(c!==g){let e=[...c];for(let t=0;t<y.length;t++){let i=y[t],n=cw(i);d.includes(n)||(e.splice(t,0,i),k.push(i))}"wait"===s&&k.length&&(e=k),b(cE(e)),v(c);return}let{forceRender:T}=(0,p.useContext)(cf);return(0,u.jsx)(u.Fragment,{children:y.map(e=>{let p=cw(e),g=(!o||!!a)&&(c===y||d.includes(p));return(0,u.jsx)(cT,{isPresent:g,initial:(!h.current||!!i)&&void 0,custom:g?void 0:t,presenceAffectsLayout:r,mode:s,onExitComplete:g?void 0:()=>{if(!f.has(p))return;f.set(p,!0);let e=!0;f.forEach(t=>{t||(e=!1)}),e&&(null==T||T(),b(m.current),o&&(null==l||l()),n&&n())},children:e},p)})})};function cO(e){return null!==e&&"object"==typeof e&&"function"==typeof e.start}let cA=e=>Array.isArray(e);function cI(e,t){if(!Array.isArray(t))return!1;let i=t.length;if(i!==e.length)return!1;for(let n=0;n<i;n++)if(t[n]!==e[n])return!1;return!0}function cM(e){return"string"==typeof e||Array.isArray(e)}function cD(e){let t=[{},{}];return null==e||e.values.forEach((e,i)=>{t[0][i]=e.get(),t[1][i]=e.getVelocity()}),t}function c_(e,t,i,n){if("function"==typeof t){let[r,s]=cD(n);t=t(void 0!==i?i:e.custom,r,s)}if("string"==typeof t&&(t=e.variants&&e.variants[t]),"function"==typeof t){let[r,s]=cD(n);t=t(void 0!==i?i:e.custom,r,s)}return t}function cN(e,t,i){let n=e.getProps();return c_(n,t,void 0!==i?i:n.custom,e)}let cL=["animate","whileInView","whileFocus","whileHover","whileTap","whileDrag","exit"],cj=["initial",...cL];function cU(e){let t;return()=>(void 0===t&&(t=e()),t)}let cF=cU(()=>void 0!==window.ScrollTimeline);class cV{constructor(e){this.stop=()=>this.runAll("stop"),this.animations=e.filter(Boolean)}get finished(){return Promise.all(this.animations.map(e=>"finished"in e?e.finished:e))}getAll(e){return this.animations[0][e]}setAll(e,t){for(let i=0;i<this.animations.length;i++)this.animations[i][e]=t}attachTimeline(e,t){let i=this.animations.map(i=>cF()&&i.attachTimeline?i.attachTimeline(e):"function"==typeof t?t(i):void 0);return()=>{i.forEach((e,t)=>{e&&e(),this.animations[t].stop()})}}get time(){return this.getAll("time")}set time(e){this.setAll("time",e)}get speed(){return this.getAll("speed")}set speed(e){this.setAll("speed",e)}get startTime(){return this.getAll("startTime")}get duration(){let e=0;for(let t=0;t<this.animations.length;t++)e=Math.max(e,this.animations[t].duration);return e}runAll(e){this.animations.forEach(t=>t[e]())}flatten(){this.runAll("flatten")}play(){this.runAll("play")}pause(){this.runAll("pause")}cancel(){this.runAll("cancel")}complete(){this.runAll("complete")}}class cB extends cV{then(e,t){return Promise.all(this.animations).then(e).catch(t)}}function cq(e,t){return e?e[t]||e.default||e:void 0}function cW(e){let t=0,i=e.next(t);for(;!i.done&&t<2e4;)t+=50,i=e.next(t);return t>=2e4?1/0:t}function cz(e){return"function"==typeof e}function cH(e,t){e.timeline=t,e.onfinish=null}let cG=e=>Array.isArray(e)&&"number"==typeof e[0],c$={linearEasing:void 0},cK=function(e,t){let i=cU(e);return()=>{var e;return null!==(e=c$[t])&&void 0!==e?e:i()}}(()=>{try{document.createElement("div").animate({opacity:0},{easing:"linear(0, 1)"})}catch(e){return!1}return!0},"linearEasing"),cJ=(e,t,i)=>{let n=t-e;return 0===n?1:(i-e)/n},cX=(e,t,i=10)=>{let n="",r=Math.max(Math.round(t/i),2);for(let t=0;t<r;t++)n+=e(cJ(0,r-1,t))+", ";return`linear(${n.substring(0,n.length-2)})`},cY=([e,t,i,n])=>`cubic-bezier(${e}, ${t}, ${i}, ${n})`,cQ={linear:"linear",ease:"ease",easeIn:"ease-in",easeOut:"ease-out",easeInOut:"ease-in-out",circIn:cY([0,.65,.55,1]),circOut:cY([.55,0,1,.45]),backIn:cY([.31,.01,.66,-.59]),backOut:cY([.33,1.53,.69,.99])},cZ={x:!1,y:!1};function c0(e,t){let i=function(e,t,i){if(e instanceof Element)return[e];if("string"==typeof e){let t=document.querySelectorAll(e);return t?Array.from(t):[]}return Array.from(e)}(e),n=new AbortController;return[i,{passive:!0,...t,signal:n.signal},()=>n.abort()]}function c1(e){return t=>{"touch"===t.pointerType||cZ.x||cZ.y||e(t)}}let c2=(e,t)=>!!t&&(e===t||c2(e,t.parentElement)),c3=e=>"mouse"===e.pointerType?"number"!=typeof e.button||e.button<=0:!1!==e.isPrimary,c5=new Set(["BUTTON","INPUT","SELECT","TEXTAREA","A"]),c4=new WeakSet;function c6(e){return t=>{"Enter"===t.key&&e(t)}}function c9(e,t){e.dispatchEvent(new PointerEvent("pointer"+t,{isPrimary:!0,bubbles:!0}))}let c8=(e,t)=>{let i=e.currentTarget;if(!i)return;let n=c6(()=>{if(c4.has(i))return;c9(i,"down");let e=c6(()=>{c9(i,"up")});i.addEventListener("keyup",e,t),i.addEventListener("blur",()=>c9(i,"cancel"),t)});i.addEventListener("keydown",n,t),i.addEventListener("blur",()=>i.removeEventListener("keydown",n),t)};function c7(e){return c3(e)&&!(cZ.x||cZ.y)}let de=e=>1e3*e,dt=e=>e/1e3,di=e=>e,dn=["transformPerspective","x","y","z","translateX","translateY","translateZ","scale","scaleX","scaleY","rotate","rotateX","rotateY","rotateZ","skew","skewX","skewY"],dr=new Set(dn),ds=new Set(["width","height","top","left","right","bottom",...dn]),da=e=>!!(e&&"object"==typeof e&&e.mix&&e.toValue),dl=e=>cA(e)?e[e.length-1]||0:e,dc={skipAnimations:!1,useManualTiming:!1},dd=["read","resolveKeyframes","update","preRender","render","postRender"];function du(e,t){let i=!1,n=!0,r={delta:0,timestamp:0,isProcessing:!1},s=()=>i=!0,o=dd.reduce((e,t)=>(e[t]=function(e){let t=new Set,i=new Set,n=!1,r=!1,s=new WeakSet,o={delta:0,timestamp:0,isProcessing:!1};function a(t){s.has(t)&&(l.schedule(t),e()),t(o)}let l={schedule:(e,r=!1,o=!1)=>{let a=o&&n?t:i;return r&&s.add(e),a.has(e)||a.add(e),e},cancel:e=>{i.delete(e),s.delete(e)},process:e=>{if(o=e,n){r=!0;return}n=!0,[t,i]=[i,t],t.forEach(a),t.clear(),n=!1,r&&(r=!1,l.process(e))}};return l}(s),e),{}),{read:a,resolveKeyframes:l,update:c,preRender:d,render:u,postRender:h}=o,p=()=>{let s=dc.useManualTiming?r.timestamp:performance.now();i=!1,r.delta=n?1e3/60:Math.max(Math.min(s-r.timestamp,40),1),r.timestamp=s,r.isProcessing=!0,a.process(r),l.process(r),c.process(r),d.process(r),u.process(r),h.process(r),r.isProcessing=!1,i&&t&&(n=!1,e(p))},m=()=>{i=!0,n=!0,r.isProcessing||e(p)};return{schedule:dd.reduce((e,t)=>{let n=o[t];return e[t]=(e,t=!1,r=!1)=>(i||m(),n.schedule(e,t,r)),e},{}),cancel:e=>{for(let t=0;t<dd.length;t++)o[dd[t]].cancel(e)},state:r,steps:o}}let{schedule:dh,cancel:dp,state:dm,steps:df}=du("undefined"!=typeof requestAnimationFrame?requestAnimationFrame:di,!0);function dg(){o=void 0}let dv={now:()=>(void 0===o&&dv.set(dm.isProcessing||dc.useManualTiming?dm.timestamp:performance.now()),o),set:e=>{o=e,queueMicrotask(dg)}};function dy(e,t){-1===e.indexOf(t)&&e.push(t)}function db(e,t){let i=e.indexOf(t);i>-1&&e.splice(i,1)}class dk{constructor(){this.subscriptions=[]}add(e){return dy(this.subscriptions,e),()=>db(this.subscriptions,e)}notify(e,t,i){let n=this.subscriptions.length;if(n){if(1===n)this.subscriptions[0](e,t,i);else for(let r=0;r<n;r++){let n=this.subscriptions[r];n&&n(e,t,i)}}}getSize(){return this.subscriptions.length}clear(){this.subscriptions.length=0}}let dT=e=>!isNaN(parseFloat(e)),dS={current:void 0};class dC{constructor(e,t={}){this.version="11.18.2",this.canTrackVelocity=null,this.events={},this.updateAndNotify=(e,t=!0)=>{let i=dv.now();this.updatedAt!==i&&this.setPrevFrameValue(),this.prev=this.current,this.setCurrent(e),this.current!==this.prev&&this.events.change&&this.events.change.notify(this.current),t&&this.events.renderRequest&&this.events.renderRequest.notify(this.current)},this.hasAnimated=!1,this.setCurrent(e),this.owner=t.owner}setCurrent(e){this.current=e,this.updatedAt=dv.now(),null===this.canTrackVelocity&&void 0!==e&&(this.canTrackVelocity=dT(this.current))}setPrevFrameValue(e=this.current){this.prevFrameValue=e,this.prevUpdatedAt=this.updatedAt}onChange(e){return this.on("change",e)}on(e,t){this.events[e]||(this.events[e]=new dk);let i=this.events[e].add(t);return"change"===e?()=>{i(),dh.read(()=>{this.events.change.getSize()||this.stop()})}:i}clearListeners(){for(let e in this.events)this.events[e].clear()}attach(e,t){this.passiveEffect=e,this.stopPassiveEffect=t}set(e,t=!0){t&&this.passiveEffect?this.passiveEffect(e,this.updateAndNotify):this.updateAndNotify(e,t)}setWithVelocity(e,t,i){this.set(t),this.prev=void 0,this.prevFrameValue=e,this.prevUpdatedAt=this.updatedAt-i}jump(e,t=!0){this.updateAndNotify(e),this.prev=e,this.prevUpdatedAt=this.prevFrameValue=void 0,t&&this.stop(),this.stopPassiveEffect&&this.stopPassiveEffect()}get(){return dS.current&&dS.current.push(this),this.current}getPrevious(){return this.prev}getVelocity(){var e;let t=dv.now();if(!this.canTrackVelocity||void 0===this.prevFrameValue||t-this.updatedAt>30)return 0;let i=Math.min(this.updatedAt-this.prevUpdatedAt,30);return e=parseFloat(this.current)-parseFloat(this.prevFrameValue),i?1e3/i*e:0}start(e){return this.stop(),new Promise(t=>{this.hasAnimated=!0,this.animation=e(t),this.events.animationStart&&this.events.animationStart.notify()}).then(()=>{this.events.animationComplete&&this.events.animationComplete.notify(),this.clearAnimation()})}stop(){this.animation&&(this.animation.stop(),this.events.animationCancel&&this.events.animationCancel.notify()),this.clearAnimation()}isAnimating(){return!!this.animation}clearAnimation(){delete this.animation}destroy(){this.clearListeners(),this.stop(),this.stopPassiveEffect&&this.stopPassiveEffect()}}function dw(e,t){return new dC(e,t)}let dE=e=>!!(e&&e.getVelocity);function dP(e,t){let i=e.getValue("willChange");if(dE(i)&&i.add)return i.add(t)}let dx=e=>e.replace(/([a-z])([A-Z])/gu,"$1-$2").toLowerCase(),dR="data-"+dx("framerAppearId"),dO={current:!1},dA=(e,t,i)=>(((1-3*i+3*t)*e+(3*i-6*t))*e+3*t)*e;function dI(e,t,i,n){if(e===t&&i===n)return di;let r=t=>(function(e,t,i,n,r){let s,o;let a=0;do(s=dA(o=t+(i-t)/2,n,r)-e)>0?i=o:t=o;while(Math.abs(s)>1e-7&&++a<12);return o})(t,0,1,e,i);return e=>0===e||1===e?e:dA(r(e),t,n)}let dM=e=>t=>t<=.5?e(2*t)/2:(2-e(2*(1-t)))/2,dD=e=>t=>1-e(1-t),d_=dI(.33,1.53,.69,.99),dN=dD(d_),dL=dM(dN),dj=e=>(e*=2)<1?.5*dN(e):.5*(2-Math.pow(2,-10*(e-1))),dU=e=>1-Math.sin(Math.acos(e)),dF=dD(dU),dV=dM(dU),dB=e=>/^0[^.\s]+$/u.test(e),dq=(e,t,i)=>i>t?t:i<e?e:i,dW={test:e=>"number"==typeof e,parse:parseFloat,transform:e=>e},dz={...dW,transform:e=>dq(0,1,e)},dH={...dW,default:1},dG=e=>Math.round(1e5*e)/1e5,d$=/-?(?:\d+(?:\.\d+)?|\.\d+)/gu,dK=/^(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))$/iu,dJ=(e,t)=>i=>!!("string"==typeof i&&dK.test(i)&&i.startsWith(e)||t&&null!=i&&Object.prototype.hasOwnProperty.call(i,t)),dX=(e,t,i)=>n=>{if("string"!=typeof n)return n;let[r,s,o,a]=n.match(d$);return{[e]:parseFloat(r),[t]:parseFloat(s),[i]:parseFloat(o),alpha:void 0!==a?parseFloat(a):1}},dY=e=>dq(0,255,e),dQ={...dW,transform:e=>Math.round(dY(e))},dZ={test:dJ("rgb","red"),parse:dX("red","green","blue"),transform:({red:e,green:t,blue:i,alpha:n=1})=>"rgba("+dQ.transform(e)+", "+dQ.transform(t)+", "+dQ.transform(i)+", "+dG(dz.transform(n))+")"},d0={test:dJ("#"),parse:function(e){let t="",i="",n="",r="";return e.length>5?(t=e.substring(1,3),i=e.substring(3,5),n=e.substring(5,7),r=e.substring(7,9)):(t=e.substring(1,2),i=e.substring(2,3),n=e.substring(3,4),r=e.substring(4,5),t+=t,i+=i,n+=n,r+=r),{red:parseInt(t,16),green:parseInt(i,16),blue:parseInt(n,16),alpha:r?parseInt(r,16)/255:1}},transform:dZ.transform},d1=e=>({test:t=>"string"==typeof t&&t.endsWith(e)&&1===t.split(" ").length,parse:parseFloat,transform:t=>`${t}${e}`}),d2=d1("deg"),d3=d1("%"),d5=d1("px"),d4=d1("vh"),d6=d1("vw"),d9={...d3,parse:e=>d3.parse(e)/100,transform:e=>d3.transform(100*e)},d8={test:dJ("hsl","hue"),parse:dX("hue","saturation","lightness"),transform:({hue:e,saturation:t,lightness:i,alpha:n=1})=>"hsla("+Math.round(e)+", "+d3.transform(dG(t))+", "+d3.transform(dG(i))+", "+dG(dz.transform(n))+")"},d7={test:e=>dZ.test(e)||d0.test(e)||d8.test(e),parse:e=>dZ.test(e)?dZ.parse(e):d8.test(e)?d8.parse(e):d0.parse(e),transform:e=>"string"==typeof e?e:e.hasOwnProperty("red")?dZ.transform(e):d8.transform(e)},ue=/(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))/giu,ut="number",ui="color",un=/var\s*\(\s*--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)|#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\)|-?(?:\d+(?:\.\d+)?|\.\d+)/giu;function ur(e){let t=e.toString(),i=[],n={color:[],number:[],var:[]},r=[],s=0,o=t.replace(un,e=>(d7.test(e)?(n.color.push(s),r.push(ui),i.push(d7.parse(e))):e.startsWith("var(")?(n.var.push(s),r.push("var"),i.push(e)):(n.number.push(s),r.push(ut),i.push(parseFloat(e))),++s,"${}")).split("${}");return{values:i,split:o,indexes:n,types:r}}function us(e){return ur(e).values}function uo(e){let{split:t,types:i}=ur(e),n=t.length;return e=>{let r="";for(let s=0;s<n;s++)if(r+=t[s],void 0!==e[s]){let t=i[s];t===ut?r+=dG(e[s]):t===ui?r+=d7.transform(e[s]):r+=e[s]}return r}}let ua=e=>"number"==typeof e?0:e,ul={test:function(e){var t,i;return isNaN(e)&&"string"==typeof e&&((null===(t=e.match(d$))||void 0===t?void 0:t.length)||0)+((null===(i=e.match(ue))||void 0===i?void 0:i.length)||0)>0},parse:us,createTransformer:uo,getAnimatableNone:function(e){let t=us(e);return uo(e)(t.map(ua))}},uc=new Set(["brightness","contrast","saturate","opacity"]);function ud(e){let[t,i]=e.slice(0,-1).split("(");if("drop-shadow"===t)return e;let[n]=i.match(d$)||[];if(!n)return e;let r=i.replace(n,""),s=uc.has(t)?1:0;return n!==i&&(s*=100),t+"("+s+r+")"}let uu=/\b([a-z-]*)\(.*?\)/gu,uh={...ul,getAnimatableNone:e=>{let t=e.match(uu);return t?t.map(ud).join(" "):e}},up={...dW,transform:Math.round},um={borderWidth:d5,borderTopWidth:d5,borderRightWidth:d5,borderBottomWidth:d5,borderLeftWidth:d5,borderRadius:d5,radius:d5,borderTopLeftRadius:d5,borderTopRightRadius:d5,borderBottomRightRadius:d5,borderBottomLeftRadius:d5,width:d5,maxWidth:d5,height:d5,maxHeight:d5,top:d5,right:d5,bottom:d5,left:d5,padding:d5,paddingTop:d5,paddingRight:d5,paddingBottom:d5,paddingLeft:d5,margin:d5,marginTop:d5,marginRight:d5,marginBottom:d5,marginLeft:d5,backgroundPositionX:d5,backgroundPositionY:d5,rotate:d2,rotateX:d2,rotateY:d2,rotateZ:d2,scale:dH,scaleX:dH,scaleY:dH,scaleZ:dH,skew:d2,skewX:d2,skewY:d2,distance:d5,translateX:d5,translateY:d5,translateZ:d5,x:d5,y:d5,z:d5,perspective:d5,transformPerspective:d5,opacity:dz,originX:d9,originY:d9,originZ:d5,zIndex:up,size:d5,fillOpacity:dz,strokeOpacity:dz,numOctaves:up},uf={...um,color:d7,backgroundColor:d7,outlineColor:d7,fill:d7,stroke:d7,borderColor:d7,borderTopColor:d7,borderRightColor:d7,borderBottomColor:d7,borderLeftColor:d7,filter:uh,WebkitFilter:uh},ug=e=>uf[e];function uv(e,t){let i=ug(e);return i!==uh&&(i=ul),i.getAnimatableNone?i.getAnimatableNone(t):void 0}let uy=new Set(["auto","none","0"]),ub=e=>e===dW||e===d5,uk=(e,t)=>parseFloat(e.split(", ")[t]),uT=(e,t)=>(i,{transform:n})=>{if("none"===n||!n)return 0;let r=n.match(/^matrix3d\((.+)\)$/u);if(r)return uk(r[1],t);{let t=n.match(/^matrix\((.+)\)$/u);return t?uk(t[1],e):0}},uS=new Set(["x","y","z"]),uC=dn.filter(e=>!uS.has(e)),uw={width:({x:e},{paddingLeft:t="0",paddingRight:i="0"})=>e.max-e.min-parseFloat(t)-parseFloat(i),height:({y:e},{paddingTop:t="0",paddingBottom:i="0"})=>e.max-e.min-parseFloat(t)-parseFloat(i),top:(e,{top:t})=>parseFloat(t),left:(e,{left:t})=>parseFloat(t),bottom:({y:e},{top:t})=>parseFloat(t)+(e.max-e.min),right:({x:e},{left:t})=>parseFloat(t)+(e.max-e.min),x:uT(4,13),y:uT(5,14)};uw.translateX=uw.x,uw.translateY=uw.y;let uE=new Set,uP=!1,ux=!1;function uR(){if(ux){let e=Array.from(uE).filter(e=>e.needsMeasurement),t=new Set(e.map(e=>e.element)),i=new Map;t.forEach(e=>{let t=function(e){let t=[];return uC.forEach(i=>{let n=e.getValue(i);void 0!==n&&(t.push([i,n.get()]),n.set(i.startsWith("scale")?1:0))}),t}(e);t.length&&(i.set(e,t),e.render())}),e.forEach(e=>e.measureInitialState()),t.forEach(e=>{e.render();let t=i.get(e);t&&t.forEach(([t,i])=>{var n;null===(n=e.getValue(t))||void 0===n||n.set(i)})}),e.forEach(e=>e.measureEndState()),e.forEach(e=>{void 0!==e.suspendedScrollY&&window.scrollTo(0,e.suspendedScrollY)})}ux=!1,uP=!1,uE.forEach(e=>e.complete()),uE.clear()}function uO(){uE.forEach(e=>{e.readKeyframes(),e.needsMeasurement&&(ux=!0)})}class uA{constructor(e,t,i,n,r,s=!1){this.isComplete=!1,this.isAsync=!1,this.needsMeasurement=!1,this.isScheduled=!1,this.unresolvedKeyframes=[...e],this.onComplete=t,this.name=i,this.motionValue=n,this.element=r,this.isAsync=s}scheduleResolve(){this.isScheduled=!0,this.isAsync?(uE.add(this),uP||(uP=!0,dh.read(uO),dh.resolveKeyframes(uR))):(this.readKeyframes(),this.complete())}readKeyframes(){let{unresolvedKeyframes:e,name:t,element:i,motionValue:n}=this;for(let r=0;r<e.length;r++)if(null===e[r]){if(0===r){let r=null==n?void 0:n.get(),s=e[e.length-1];if(void 0!==r)e[0]=r;else if(i&&t){let n=i.readValue(t,s);null!=n&&(e[0]=n)}void 0===e[0]&&(e[0]=s),n&&void 0===r&&n.set(e[0])}else e[r]=e[r-1]}}setFinalKeyframe(){}measureInitialState(){}renderEndStyles(){}measureEndState(){}complete(){this.isComplete=!0,this.onComplete(this.unresolvedKeyframes,this.finalKeyframe),uE.delete(this)}cancel(){this.isComplete||(this.isScheduled=!1,uE.delete(this))}resume(){this.isComplete||this.scheduleResolve()}}let uI=e=>/^-?(?:\d+(?:\.\d+)?|\.\d+)$/u.test(e),uM=e=>t=>"string"==typeof t&&t.startsWith(e),uD=uM("--"),u_=uM("var(--"),uN=e=>!!u_(e)&&uL.test(e.split("/*")[0].trim()),uL=/var\(--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)$/iu,uj=/^var\(--(?:([\w-]+)|([\w-]+), ?([a-zA-Z\d ()%#.,-]+))\)/u,uU=e=>t=>t.test(e),uF=[dW,d5,d3,d2,d6,d4,{test:e=>"auto"===e,parse:e=>e}],uV=e=>uF.find(uU(e));class uB extends uA{constructor(e,t,i,n,r){super(e,t,i,n,r,!0)}readKeyframes(){let{unresolvedKeyframes:e,element:t,name:i}=this;if(!t||!t.current)return;super.readKeyframes();for(let i=0;i<e.length;i++){let n=e[i];if("string"==typeof n&&uN(n=n.trim())){let r=function e(t,i,n=1){di(n<=4,`Max CSS variable fallback depth detected in property "${t}". This may indicate a circular fallback dependency.`);let[r,s]=function(e){let t=uj.exec(e);if(!t)return[,];let[,i,n,r]=t;return[`--${null!=i?i:n}`,r]}(t);if(!r)return;let o=window.getComputedStyle(i).getPropertyValue(r);if(o){let e=o.trim();return uI(e)?parseFloat(e):e}return uN(s)?e(s,i,n+1):s}(n,t.current);void 0!==r&&(e[i]=r),i===e.length-1&&(this.finalKeyframe=n)}}if(this.resolveNoneKeyframes(),!ds.has(i)||2!==e.length)return;let[n,r]=e,s=uV(n),o=uV(r);if(s!==o){if(ub(s)&&ub(o))for(let t=0;t<e.length;t++){let i=e[t];"string"==typeof i&&(e[t]=parseFloat(i))}else this.needsMeasurement=!0}}resolveNoneKeyframes(){let{unresolvedKeyframes:e,name:t}=this,i=[];for(let t=0;t<e.length;t++){var n;("number"==typeof(n=e[t])?0===n:null===n||"none"===n||"0"===n||dB(n))&&i.push(t)}i.length&&function(e,t,i){let n,r=0;for(;r<e.length&&!n;){let t=e[r];"string"==typeof t&&!uy.has(t)&&ur(t).values.length&&(n=e[r]),r++}if(n&&i)for(let r of t)e[r]=uv(i,n)}(e,i,t)}measureInitialState(){let{element:e,unresolvedKeyframes:t,name:i}=this;if(!e||!e.current)return;"height"===i&&(this.suspendedScrollY=window.pageYOffset),this.measuredOrigin=uw[i](e.measureViewportBox(),window.getComputedStyle(e.current)),t[0]=this.measuredOrigin;let n=t[t.length-1];void 0!==n&&e.getValue(i,n).jump(n,!1)}measureEndState(){var e;let{element:t,name:i,unresolvedKeyframes:n}=this;if(!t||!t.current)return;let r=t.getValue(i);r&&r.jump(this.measuredOrigin,!1);let s=n.length-1,o=n[s];n[s]=uw[i](t.measureViewportBox(),window.getComputedStyle(t.current)),null!==o&&void 0===this.finalKeyframe&&(this.finalKeyframe=o),(null===(e=this.removedTransforms)||void 0===e?void 0:e.length)&&this.removedTransforms.forEach(([e,i])=>{t.getValue(e).set(i)}),this.resolveNoneKeyframes()}}let uq=(e,t)=>"zIndex"!==t&&!!("number"==typeof e||Array.isArray(e)||"string"==typeof e&&(ul.test(e)||"0"===e)&&!e.startsWith("url(")),uW=e=>null!==e;function uz(e,{repeat:t,repeatType:i="loop"},n){let r=e.filter(uW),s=t&&"loop"!==i&&t%2==1?0:r.length-1;return s&&void 0!==n?n:r[s]}class uH{constructor({autoplay:e=!0,delay:t=0,type:i="keyframes",repeat:n=0,repeatDelay:r=0,repeatType:s="loop",...o}){this.isStopped=!1,this.hasAttemptedResolve=!1,this.createdAt=dv.now(),this.options={autoplay:e,delay:t,type:i,repeat:n,repeatDelay:r,repeatType:s,...o},this.updateFinishedPromise()}calcStartTime(){return this.resolvedAt&&this.resolvedAt-this.createdAt>40?this.resolvedAt:this.createdAt}get resolved(){return this._resolved||this.hasAttemptedResolve||(uO(),uR()),this._resolved}onKeyframesResolved(e,t){this.resolvedAt=dv.now(),this.hasAttemptedResolve=!0;let{name:i,type:n,velocity:r,delay:s,onComplete:o,onUpdate:a,isGenerator:l}=this.options;if(!l&&!function(e,t,i,n){let r=e[0];if(null===r)return!1;if("display"===t||"visibility"===t)return!0;let s=e[e.length-1],o=uq(r,t),a=uq(s,t);return di(o===a,`You are trying to animate ${t} from "${r}" to "${s}". ${r} is not an animatable value - to enable this animation set ${r} to a value animatable to ${s} via the \`style\` property.`),!!o&&!!a&&(function(e){let t=e[0];if(1===e.length)return!0;for(let i=0;i<e.length;i++)if(e[i]!==t)return!0}(e)||("spring"===i||cz(i))&&n)}(e,i,n,r)){if(dO.current||!s){a&&a(uz(e,this.options,t)),o&&o(),this.resolveFinishedPromise();return}this.options.duration=0}let c=this.initPlayback(e,t);!1!==c&&(this._resolved={keyframes:e,finalKeyframe:t,...c},this.onPostResolved())}onPostResolved(){}then(e,t){return this.currentFinishedPromise.then(e,t)}flatten(){this.options.type="keyframes",this.options.ease="linear"}updateFinishedPromise(){this.currentFinishedPromise=new Promise(e=>{this.resolveFinishedPromise=e})}}let uG=(e,t,i)=>e+(t-e)*i;function u$(e,t,i){return(i<0&&(i+=1),i>1&&(i-=1),i<1/6)?e+(t-e)*6*i:i<.5?t:i<2/3?e+(t-e)*(2/3-i)*6:e}function uK(e,t){return i=>i>0?t:e}let uJ=(e,t,i)=>{let n=e*e,r=i*(t*t-n)+n;return r<0?0:Math.sqrt(r)},uX=[d0,dZ,d8],uY=e=>uX.find(t=>t.test(e));function uQ(e){let t=uY(e);if(di(!!t,`'${e}' is not an animatable color. Use the equivalent color code instead.`),!t)return!1;let i=t.parse(e);return t===d8&&(i=function({hue:e,saturation:t,lightness:i,alpha:n}){e/=360,i/=100;let r=0,s=0,o=0;if(t/=100){let n=i<.5?i*(1+t):i+t-i*t,a=2*i-n;r=u$(a,n,e+1/3),s=u$(a,n,e),o=u$(a,n,e-1/3)}else r=s=o=i;return{red:Math.round(255*r),green:Math.round(255*s),blue:Math.round(255*o),alpha:n}}(i)),i}let uZ=(e,t)=>{let i=uQ(e),n=uQ(t);if(!i||!n)return uK(e,t);let r={...i};return e=>(r.red=uJ(i.red,n.red,e),r.green=uJ(i.green,n.green,e),r.blue=uJ(i.blue,n.blue,e),r.alpha=uG(i.alpha,n.alpha,e),dZ.transform(r))},u0=(e,t)=>i=>t(e(i)),u1=(...e)=>e.reduce(u0),u2=new Set(["none","hidden"]);function u3(e,t){return i=>uG(e,t,i)}function u5(e){return"number"==typeof e?u3:"string"==typeof e?uN(e)?uK:d7.test(e)?uZ:u9:Array.isArray(e)?u4:"object"==typeof e?d7.test(e)?uZ:u6:uK}function u4(e,t){let i=[...e],n=i.length,r=e.map((e,i)=>u5(e)(e,t[i]));return e=>{for(let t=0;t<n;t++)i[t]=r[t](e);return i}}function u6(e,t){let i={...e,...t},n={};for(let r in i)void 0!==e[r]&&void 0!==t[r]&&(n[r]=u5(e[r])(e[r],t[r]));return e=>{for(let t in n)i[t]=n[t](e);return i}}let u9=(e,t)=>{let i=ul.createTransformer(t),n=ur(e),r=ur(t);return n.indexes.var.length===r.indexes.var.length&&n.indexes.color.length===r.indexes.color.length&&n.indexes.number.length>=r.indexes.number.length?u2.has(e)&&!r.values.length||u2.has(t)&&!n.values.length?function(e,t){return u2.has(e)?i=>i<=0?e:t:i=>i>=1?t:e}(e,t):u1(u4(function(e,t){var i;let n=[],r={color:0,var:0,number:0};for(let s=0;s<t.values.length;s++){let o=t.types[s],a=e.indexes[o][r[o]],l=null!==(i=e.values[a])&&void 0!==i?i:0;n[s]=l,r[o]++}return n}(n,r),r.values),i):(di(!0,`Complex values '${e}' and '${t}' too different to mix. Ensure all colors are of the same type, and that each contains the same quantity of number and color values. Falling back to instant transition.`),uK(e,t))};function u8(e,t,i){return"number"==typeof e&&"number"==typeof t&&"number"==typeof i?uG(e,t,i):u5(e)(e,t)}function u7(e,t,i){var n,r;let s=Math.max(t-5,0);return n=i-e(s),(r=t-s)?1e3/r*n:0}let he={stiffness:100,damping:10,mass:1,velocity:0,duration:800,bounce:.3,visualDuration:.3,restSpeed:{granular:.01,default:2},restDelta:{granular:.005,default:.5},minDuration:.01,maxDuration:10,minDamping:.05,maxDamping:1};function ht(e,t){return e*Math.sqrt(1-t*t)}let hi=["duration","bounce"],hn=["stiffness","damping","mass"];function hr(e,t){return t.some(t=>void 0!==e[t])}function hs(e=he.visualDuration,t=he.bounce){let i;let n="object"!=typeof e?{visualDuration:e,keyframes:[0,1],bounce:t}:e,{restSpeed:r,restDelta:s}=n,o=n.keyframes[0],a=n.keyframes[n.keyframes.length-1],l={done:!1,value:o},{stiffness:c,damping:d,mass:u,duration:h,velocity:p,isResolvedFromDuration:m}=function(e){let t={velocity:he.velocity,stiffness:he.stiffness,damping:he.damping,mass:he.mass,isResolvedFromDuration:!1,...e};if(!hr(e,hn)&&hr(e,hi)){if(e.visualDuration){let i=2*Math.PI/(1.2*e.visualDuration),n=i*i,r=2*dq(.05,1,1-(e.bounce||0))*Math.sqrt(n);t={...t,mass:he.mass,stiffness:n,damping:r}}else{let i=function({duration:e=he.duration,bounce:t=he.bounce,velocity:i=he.velocity,mass:n=he.mass}){let r,s;di(e<=de(he.maxDuration),"Spring duration must be 10 seconds or less");let o=1-t;o=dq(he.minDamping,he.maxDamping,o),e=dq(he.minDuration,he.maxDuration,dt(e)),o<1?(r=t=>{let n=t*o,r=n*e;return .001-(n-i)/ht(t,o)*Math.exp(-r)},s=t=>{let n=t*o*e,s=Math.pow(o,2)*Math.pow(t,2)*e,a=ht(Math.pow(t,2),o);return(n*i+i-s)*Math.exp(-n)*(-r(t)+.001>0?-1:1)/a}):(r=t=>-.001+Math.exp(-t*e)*((t-i)*e+1),s=t=>e*e*(i-t)*Math.exp(-t*e));let a=function(e,t,i){let n=i;for(let i=1;i<12;i++)n-=e(n)/t(n);return n}(r,s,5/e);if(e=de(e),isNaN(a))return{stiffness:he.stiffness,damping:he.damping,duration:e};{let t=Math.pow(a,2)*n;return{stiffness:t,damping:2*o*Math.sqrt(n*t),duration:e}}}(e);(t={...t,...i,mass:he.mass}).isResolvedFromDuration=!0}}return t}({...n,velocity:-dt(n.velocity||0)}),f=p||0,g=d/(2*Math.sqrt(c*u)),v=a-o,y=dt(Math.sqrt(c/u)),b=5>Math.abs(v);if(r||(r=b?he.restSpeed.granular:he.restSpeed.default),s||(s=b?he.restDelta.granular:he.restDelta.default),g<1){let e=ht(y,g);i=t=>a-Math.exp(-g*y*t)*((f+g*y*v)/e*Math.sin(e*t)+v*Math.cos(e*t))}else if(1===g)i=e=>a-Math.exp(-y*e)*(v+(f+y*v)*e);else{let e=y*Math.sqrt(g*g-1);i=t=>{let i=Math.exp(-g*y*t),n=Math.min(e*t,300);return a-i*((f+g*y*v)*Math.sinh(n)+e*v*Math.cosh(n))/e}}let k={calculatedDuration:m&&h||null,next:e=>{let t=i(e);if(m)l.done=e>=h;else{let n=0;g<1&&(n=0===e?de(f):u7(i,e,t));let o=Math.abs(n)<=r,c=Math.abs(a-t)<=s;l.done=o&&c}return l.value=l.done?a:t,l},toString:()=>{let e=Math.min(cW(k),2e4),t=cX(t=>k.next(e*t).value,e,30);return e+"ms "+t}};return k}function ho({keyframes:e,velocity:t=0,power:i=.8,timeConstant:n=325,bounceDamping:r=10,bounceStiffness:s=500,modifyTarget:o,min:a,max:l,restDelta:c=.5,restSpeed:d}){let u,h;let p=e[0],m={done:!1,value:p},f=e=>void 0!==a&&e<a||void 0!==l&&e>l,g=e=>void 0===a?l:void 0===l?a:Math.abs(a-e)<Math.abs(l-e)?a:l,v=i*t,y=p+v,b=void 0===o?y:o(y);b!==y&&(v=b-p);let k=e=>-v*Math.exp(-e/n),T=e=>b+k(e),S=e=>{let t=k(e),i=T(e);m.done=Math.abs(t)<=c,m.value=m.done?b:i},C=e=>{f(m.value)&&(u=e,h=hs({keyframes:[m.value,g(m.value)],velocity:u7(T,e,m.value),damping:r,stiffness:s,restDelta:c,restSpeed:d}))};return C(0),{calculatedDuration:null,next:e=>{let t=!1;return(h||void 0!==u||(t=!0,S(e),C(e)),void 0!==u&&e>=u)?h.next(e-u):(t||S(e),m)}}}let ha=dI(.42,0,1,1),hl=dI(0,0,.58,1),hc=dI(.42,0,.58,1),hd=e=>Array.isArray(e)&&"number"!=typeof e[0],hu={linear:di,easeIn:ha,easeInOut:hc,easeOut:hl,circIn:dU,circInOut:dV,circOut:dF,backIn:dN,backInOut:dL,backOut:d_,anticipate:dj},hh=e=>{if(cG(e)){di(4===e.length,"Cubic bezier arrays must contain four numerical values.");let[t,i,n,r]=e;return dI(t,i,n,r)}return"string"==typeof e?(di(void 0!==hu[e],`Invalid easing type '${e}'`),hu[e]):e};function hp({duration:e=300,keyframes:t,times:i,ease:n="easeInOut"}){let r=hd(n)?n.map(hh):hh(n),s={done:!1,value:t[0]},o=function(e,t,{clamp:i=!0,ease:n,mixer:r}={}){let s=e.length;if(di(s===t.length,"Both input and output ranges must be the same length"),1===s)return()=>t[0];if(2===s&&t[0]===t[1])return()=>t[1];let o=e[0]===e[1];e[0]>e[s-1]&&(e=[...e].reverse(),t=[...t].reverse());let a=function(e,t,i){let n=[],r=i||u8,s=e.length-1;for(let i=0;i<s;i++){let s=r(e[i],e[i+1]);t&&(s=u1(Array.isArray(t)?t[i]||di:t,s)),n.push(s)}return n}(t,n,r),l=a.length,c=i=>{if(o&&i<e[0])return t[0];let n=0;if(l>1)for(;n<e.length-2&&!(i<e[n+1]);n++);let r=cJ(e[n],e[n+1],i);return a[n](r)};return i?t=>c(dq(e[0],e[s-1],t)):c}((i&&i.length===t.length?i:function(e){let t=[0];return function(e,t){let i=e[e.length-1];for(let n=1;n<=t;n++){let r=cJ(0,t,n);e.push(uG(i,1,r))}}(t,e.length-1),t}(t)).map(t=>t*e),t,{ease:Array.isArray(r)?r:t.map(()=>r||hc).splice(0,t.length-1)});return{calculatedDuration:e,next:t=>(s.value=o(t),s.done=t>=e,s)}}let hm=e=>{let t=({timestamp:t})=>e(t);return{start:()=>dh.update(t,!0),stop:()=>dp(t),now:()=>dm.isProcessing?dm.timestamp:dv.now()}},hf={decay:ho,inertia:ho,tween:hp,keyframes:hp,spring:hs},hg=e=>e/100;class hv extends uH{constructor(e){super(e),this.holdTime=null,this.cancelTime=null,this.currentTime=0,this.playbackSpeed=1,this.pendingPlayState="running",this.startTime=null,this.state="idle",this.stop=()=>{if(this.resolver.cancel(),this.isStopped=!0,"idle"===this.state)return;this.teardown();let{onStop:e}=this.options;e&&e()};let{name:t,motionValue:i,element:n,keyframes:r}=this.options,s=(null==n?void 0:n.KeyframeResolver)||uA;this.resolver=new s(r,(e,t)=>this.onKeyframesResolved(e,t),t,i,n),this.resolver.scheduleResolve()}flatten(){super.flatten(),this._resolved&&Object.assign(this._resolved,this.initPlayback(this._resolved.keyframes))}initPlayback(e){let t,i;let{type:n="keyframes",repeat:r=0,repeatDelay:s=0,repeatType:o,velocity:a=0}=this.options,l=cz(n)?n:hf[n]||hp;l!==hp&&"number"!=typeof e[0]&&(t=u1(hg,u8(e[0],e[1])),e=[0,100]);let c=l({...this.options,keyframes:e});"mirror"===o&&(i=l({...this.options,keyframes:[...e].reverse(),velocity:-a})),null===c.calculatedDuration&&(c.calculatedDuration=cW(c));let{calculatedDuration:d}=c,u=d+s;return{generator:c,mirroredGenerator:i,mapPercentToKeyframes:t,calculatedDuration:d,resolvedDuration:u,totalDuration:u*(r+1)-s}}onPostResolved(){let{autoplay:e=!0}=this.options;this.play(),"paused"!==this.pendingPlayState&&e?this.state=this.pendingPlayState:this.pause()}tick(e,t=!1){let{resolved:i}=this;if(!i){let{keyframes:e}=this.options;return{done:!0,value:e[e.length-1]}}let{finalKeyframe:n,generator:r,mirroredGenerator:s,mapPercentToKeyframes:o,keyframes:a,calculatedDuration:l,totalDuration:c,resolvedDuration:d}=i;if(null===this.startTime)return r.next(0);let{delay:u,repeat:h,repeatType:p,repeatDelay:m,onUpdate:f}=this.options;this.speed>0?this.startTime=Math.min(this.startTime,e):this.speed<0&&(this.startTime=Math.min(e-c/this.speed,this.startTime)),t?this.currentTime=e:null!==this.holdTime?this.currentTime=this.holdTime:this.currentTime=Math.round(e-this.startTime)*this.speed;let g=this.currentTime-u*(this.speed>=0?1:-1),v=this.speed>=0?g<0:g>c;this.currentTime=Math.max(g,0),"finished"===this.state&&null===this.holdTime&&(this.currentTime=c);let y=this.currentTime,b=r;if(h){let e=Math.min(this.currentTime,c)/d,t=Math.floor(e),i=e%1;!i&&e>=1&&(i=1),1===i&&t--,(t=Math.min(t,h+1))%2&&("reverse"===p?(i=1-i,m&&(i-=m/d)):"mirror"===p&&(b=s)),y=dq(0,1,i)*d}let k=v?{done:!1,value:a[0]}:b.next(y);o&&(k.value=o(k.value));let{done:T}=k;v||null===l||(T=this.speed>=0?this.currentTime>=c:this.currentTime<=0);let S=null===this.holdTime&&("finished"===this.state||"running"===this.state&&T);return S&&void 0!==n&&(k.value=uz(a,this.options,n)),f&&f(k.value),S&&this.finish(),k}get duration(){let{resolved:e}=this;return e?dt(e.calculatedDuration):0}get time(){return dt(this.currentTime)}set time(e){e=de(e),this.currentTime=e,null!==this.holdTime||0===this.speed?this.holdTime=e:this.driver&&(this.startTime=this.driver.now()-e/this.speed)}get speed(){return this.playbackSpeed}set speed(e){let t=this.playbackSpeed!==e;this.playbackSpeed=e,t&&(this.time=dt(this.currentTime))}play(){if(this.resolver.isScheduled||this.resolver.resume(),!this._resolved){this.pendingPlayState="running";return}if(this.isStopped)return;let{driver:e=hm,onPlay:t,startTime:i}=this.options;this.driver||(this.driver=e(e=>this.tick(e))),t&&t();let n=this.driver.now();null!==this.holdTime?this.startTime=n-this.holdTime:this.startTime?"finished"===this.state&&(this.startTime=n):this.startTime=null!=i?i:this.calcStartTime(),"finished"===this.state&&this.updateFinishedPromise(),this.cancelTime=this.startTime,this.holdTime=null,this.state="running",this.driver.start()}pause(){var e;if(!this._resolved){this.pendingPlayState="paused";return}this.state="paused",this.holdTime=null!==(e=this.currentTime)&&void 0!==e?e:0}complete(){"running"!==this.state&&this.play(),this.pendingPlayState=this.state="finished",this.holdTime=null}finish(){this.teardown(),this.state="finished";let{onComplete:e}=this.options;e&&e()}cancel(){null!==this.cancelTime&&this.tick(this.cancelTime),this.teardown(),this.updateFinishedPromise()}teardown(){this.state="idle",this.stopDriver(),this.resolveFinishedPromise(),this.updateFinishedPromise(),this.startTime=this.cancelTime=null,this.resolver.cancel()}stopDriver(){this.driver&&(this.driver.stop(),this.driver=void 0)}sample(e){return this.startTime=0,this.tick(e,!0)}}let hy=new Set(["opacity","clipPath","filter","transform"]),hb=cU(()=>Object.hasOwnProperty.call(Element.prototype,"animate")),hk={anticipate:dj,backInOut:dL,circInOut:dV};class hT extends uH{constructor(e){super(e);let{name:t,motionValue:i,element:n,keyframes:r}=this.options;this.resolver=new uB(r,(e,t)=>this.onKeyframesResolved(e,t),t,i,n),this.resolver.scheduleResolve()}initPlayback(e,t){var i;let{duration:n=300,times:r,ease:s,type:o,motionValue:a,name:l,startTime:c}=this.options;if(!a.owner||!a.owner.current)return!1;if("string"==typeof s&&cK()&&s in hk&&(s=hk[s]),cz((i=this.options).type)||"spring"===i.type||!function e(t){return!!("function"==typeof t&&cK()||!t||"string"==typeof t&&(t in cQ||cK())||cG(t)||Array.isArray(t)&&t.every(e))}(i.ease)){let{onComplete:t,onUpdate:i,motionValue:a,element:l,...c}=this.options,d=function(e,t){let i=new hv({...t,keyframes:e,repeat:0,delay:0,isGenerator:!0}),n={done:!1,value:e[0]},r=[],s=0;for(;!n.done&&s<2e4;)r.push((n=i.sample(s)).value),s+=10;return{times:void 0,keyframes:r,duration:s-10,ease:"linear"}}(e,c);1===(e=d.keyframes).length&&(e[1]=e[0]),n=d.duration,r=d.times,s=d.ease,o="keyframes"}let d=function(e,t,i,{delay:n=0,duration:r=300,repeat:s=0,repeatType:o="loop",ease:a="easeInOut",times:l}={}){let c={[t]:i};l&&(c.offset=l);let d=function e(t,i){if(t)return"function"==typeof t&&cK()?cX(t,i):cG(t)?cY(t):Array.isArray(t)?t.map(t=>e(t,i)||cQ.easeOut):cQ[t]}(a,r);return Array.isArray(d)&&(c.easing=d),e.animate(c,{delay:n,duration:r,easing:Array.isArray(d)?"linear":d,fill:"both",iterations:s+1,direction:"reverse"===o?"alternate":"normal"})}(a.owner.current,l,e,{...this.options,duration:n,times:r,ease:s});return d.startTime=null!=c?c:this.calcStartTime(),this.pendingTimeline?(cH(d,this.pendingTimeline),this.pendingTimeline=void 0):d.onfinish=()=>{let{onComplete:i}=this.options;a.set(uz(e,this.options,t)),i&&i(),this.cancel(),this.resolveFinishedPromise()},{animation:d,duration:n,times:r,type:o,ease:s,keyframes:e}}get duration(){let{resolved:e}=this;if(!e)return 0;let{duration:t}=e;return dt(t)}get time(){let{resolved:e}=this;if(!e)return 0;let{animation:t}=e;return dt(t.currentTime||0)}set time(e){let{resolved:t}=this;if(!t)return;let{animation:i}=t;i.currentTime=de(e)}get speed(){let{resolved:e}=this;if(!e)return 1;let{animation:t}=e;return t.playbackRate}set speed(e){let{resolved:t}=this;if(!t)return;let{animation:i}=t;i.playbackRate=e}get state(){let{resolved:e}=this;if(!e)return"idle";let{animation:t}=e;return t.playState}get startTime(){let{resolved:e}=this;if(!e)return null;let{animation:t}=e;return t.startTime}attachTimeline(e){if(this._resolved){let{resolved:t}=this;if(!t)return di;let{animation:i}=t;cH(i,e)}else this.pendingTimeline=e;return di}play(){if(this.isStopped)return;let{resolved:e}=this;if(!e)return;let{animation:t}=e;"finished"===t.playState&&this.updateFinishedPromise(),t.play()}pause(){let{resolved:e}=this;if(!e)return;let{animation:t}=e;t.pause()}stop(){if(this.resolver.cancel(),this.isStopped=!0,"idle"===this.state)return;this.resolveFinishedPromise(),this.updateFinishedPromise();let{resolved:e}=this;if(!e)return;let{animation:t,keyframes:i,duration:n,type:r,ease:s,times:o}=e;if("idle"===t.playState||"finished"===t.playState)return;if(this.time){let{motionValue:e,onUpdate:t,onComplete:a,element:l,...c}=this.options,d=new hv({...c,keyframes:i,duration:n,type:r,ease:s,times:o,isGenerator:!0}),u=de(this.time);e.setWithVelocity(d.sample(u-10).value,d.sample(u).value,10)}let{onStop:a}=this.options;a&&a(),this.cancel()}complete(){let{resolved:e}=this;e&&e.animation.finish()}cancel(){let{resolved:e}=this;e&&e.animation.cancel()}static supports(e){let{motionValue:t,name:i,repeatDelay:n,repeatType:r,damping:s,type:o}=e;if(!t||!t.owner||!(t.owner.current instanceof HTMLElement))return!1;let{onUpdate:a,transformTemplate:l}=t.owner.getProps();return hb()&&i&&hy.has(i)&&!a&&!l&&!n&&"mirror"!==r&&0!==s&&"inertia"!==o}}let hS={type:"spring",stiffness:500,damping:25,restSpeed:10},hC=e=>({type:"spring",stiffness:550,damping:0===e?2*Math.sqrt(550):30,restSpeed:10}),hw={type:"keyframes",duration:.8},hE={type:"keyframes",ease:[.25,.1,.35,1],duration:.3},hP=(e,{keyframes:t})=>t.length>2?hw:dr.has(e)?e.startsWith("scale")?hC(t[1]):hS:hE,hx=(e,t,i,n={},r,s)=>o=>{let a=cq(n,e)||{},l=a.delay||n.delay||0,{elapsed:c=0}=n;c-=de(l);let d={keyframes:Array.isArray(i)?i:[null,i],ease:"easeOut",velocity:t.getVelocity(),...a,delay:-c,onUpdate:e=>{t.set(e),a.onUpdate&&a.onUpdate(e)},onComplete:()=>{o(),a.onComplete&&a.onComplete()},name:e,motionValue:t,element:s?void 0:r};!function({when:e,delay:t,delayChildren:i,staggerChildren:n,staggerDirection:r,repeat:s,repeatType:o,repeatDelay:a,from:l,elapsed:c,...d}){return!!Object.keys(d).length}(a)&&(d={...d,...hP(e,d)}),d.duration&&(d.duration=de(d.duration)),d.repeatDelay&&(d.repeatDelay=de(d.repeatDelay)),void 0!==d.from&&(d.keyframes[0]=d.from);let u=!1;if(!1!==d.type&&(0!==d.duration||d.repeatDelay)||(d.duration=0,0!==d.delay||(u=!0)),(dO.current||dc.skipAnimations)&&(u=!0,d.duration=0,d.delay=0),u&&!s&&void 0!==t.get()){let e=uz(d.keyframes,a);if(void 0!==e)return dh.update(()=>{d.onUpdate(e),d.onComplete()}),new cB([])}return!s&&hT.supports(d)?new hT(d):new hv(d)};function hR(e,t,{delay:i=0,transitionOverride:n,type:r}={}){var s;let{transition:o=e.getDefaultTransition(),transitionEnd:a,...l}=t;n&&(o=n);let c=[],d=r&&e.animationState&&e.animationState.getState()[r];for(let t in l){let n=e.getValue(t,null!==(s=e.latestValues[t])&&void 0!==s?s:null),r=l[t];if(void 0===r||d&&function({protectedKeys:e,needsAnimating:t},i){let n=e.hasOwnProperty(i)&&!0!==t[i];return t[i]=!1,n}(d,t))continue;let a={delay:i,...cq(o||{},t)},u=!1;if(window.MotionHandoffAnimation){let i=e.props[dR];if(i){let e=window.MotionHandoffAnimation(i,t,dh);null!==e&&(a.startTime=e,u=!0)}}dP(e,t),n.start(hx(t,n,r,e.shouldReduceMotion&&ds.has(t)?{type:!1}:a,e,u));let h=n.animation;h&&c.push(h)}return a&&Promise.all(c).then(()=>{dh.update(()=>{a&&function(e,t){let{transitionEnd:i={},transition:n={},...r}=cN(e,t)||{};for(let t in r={...r,...i}){let i=dl(r[t]);e.hasValue(t)?e.getValue(t).set(i):e.addValue(t,dw(i))}}(e,a)})}),c}function hO(e,t,i={}){var n;let r=cN(e,t,"exit"===i.type?null===(n=e.presenceContext)||void 0===n?void 0:n.custom:void 0),{transition:s=e.getDefaultTransition()||{}}=r||{};i.transitionOverride&&(s=i.transitionOverride);let o=r?()=>Promise.all(hR(e,r,i)):()=>Promise.resolve(),a=e.variantChildren&&e.variantChildren.size?(n=0)=>{let{delayChildren:r=0,staggerChildren:o,staggerDirection:a}=s;return function(e,t,i=0,n=0,r=1,s){let o=[],a=(e.variantChildren.size-1)*n,l=1===r?(e=0)=>e*n:(e=0)=>a-e*n;return Array.from(e.variantChildren).sort(hA).forEach((e,n)=>{e.notify("AnimationStart",t),o.push(hO(e,t,{...s,delay:i+l(n)}).then(()=>e.notify("AnimationComplete",t)))}),Promise.all(o)}(e,t,r+n,o,a,i)}:()=>Promise.resolve(),{when:l}=s;if(!l)return Promise.all([o(),a(i.delay)]);{let[e,t]="beforeChildren"===l?[o,a]:[a,o];return e().then(()=>t())}}function hA(e,t){return e.sortNodePosition(t)}let hI=cj.length,hM=[...cL].reverse(),hD=cL.length;function h_(e=!1){return{isActive:e,protectedKeys:{},needsAnimating:{},prevResolvedValues:{}}}function hN(){return{animate:h_(!0),whileInView:h_(),whileHover:h_(),whileTap:h_(),whileDrag:h_(),whileFocus:h_(),exit:h_()}}class hL{constructor(e){this.isMounted=!1,this.node=e}update(){}}class hj extends hL{constructor(e){super(e),e.animationState||(e.animationState=function(e){let t=t=>Promise.all(t.map(({animation:t,options:i})=>(function(e,t,i={}){let n;if(e.notify("AnimationStart",t),Array.isArray(t))n=Promise.all(t.map(t=>hO(e,t,i)));else if("string"==typeof t)n=hO(e,t,i);else{let r="function"==typeof t?cN(e,t,i.custom):t;n=Promise.all(hR(e,r,i))}return n.then(()=>{e.notify("AnimationComplete",t)})})(e,t,i))),i=hN(),n=!0,r=t=>(i,n)=>{var r;let s=cN(e,n,"exit"===t?null===(r=e.presenceContext)||void 0===r?void 0:r.custom:void 0);if(s){let{transition:e,transitionEnd:t,...n}=s;i={...i,...n,...t}}return i};function s(s){let{props:o}=e,a=function e(t){if(!t)return;if(!t.isControllingVariants){let i=t.parent&&e(t.parent)||{};return void 0!==t.props.initial&&(i.initial=t.props.initial),i}let i={};for(let e=0;e<hI;e++){let n=cj[e],r=t.props[n];(cM(r)||!1===r)&&(i[n]=r)}return i}(e.parent)||{},l=[],c=new Set,d={},u=1/0;for(let t=0;t<hD;t++){var h;let p=hM[t],m=i[p],f=void 0!==o[p]?o[p]:a[p],g=cM(f),v=p===s?m.isActive:null;!1===v&&(u=t);let y=f===a[p]&&f!==o[p]&&g;if(y&&n&&e.manuallyAnimateOnMount&&(y=!1),m.protectedKeys={...d},!m.isActive&&null===v||!f&&!m.prevProp||cO(f)||"boolean"==typeof f)continue;let b=(h=m.prevProp,"string"==typeof f?f!==h:!!Array.isArray(f)&&!cI(f,h)),k=b||p===s&&m.isActive&&!y&&g||t>u&&g,T=!1,S=Array.isArray(f)?f:[f],C=S.reduce(r(p),{});!1===v&&(C={});let{prevResolvedValues:w={}}=m,E={...w,...C},P=t=>{k=!0,c.has(t)&&(T=!0,c.delete(t)),m.needsAnimating[t]=!0;let i=e.getValue(t);i&&(i.liveStyle=!1)};for(let e in E){let t=C[e],i=w[e];if(!d.hasOwnProperty(e))(cA(t)&&cA(i)?cI(t,i):t===i)?void 0!==t&&c.has(e)?P(e):m.protectedKeys[e]=!0:null!=t?P(e):c.add(e)}m.prevProp=f,m.prevResolvedValues=C,m.isActive&&(d={...d,...C}),n&&e.blockInitialAnimation&&(k=!1);let x=!(y&&b)||T;k&&x&&l.push(...S.map(e=>({animation:e,options:{type:p}})))}if(c.size){let t={};c.forEach(i=>{let n=e.getBaseTarget(i),r=e.getValue(i);r&&(r.liveStyle=!0),t[i]=null!=n?n:null}),l.push({animation:t})}let p=!!l.length;return n&&(!1===o.initial||o.initial===o.animate)&&!e.manuallyAnimateOnMount&&(p=!1),n=!1,p?t(l):Promise.resolve()}return{animateChanges:s,setActive:function(t,n){var r;if(i[t].isActive===n)return Promise.resolve();null===(r=e.variantChildren)||void 0===r||r.forEach(e=>{var i;return null===(i=e.animationState)||void 0===i?void 0:i.setActive(t,n)}),i[t].isActive=n;let o=s(t);for(let e in i)i[e].protectedKeys={};return o},setAnimateFunction:function(i){t=i(e)},getState:()=>i,reset:()=>{i=hN(),n=!0}}}(e))}updateAnimationControlsSubscription(){let{animate:e}=this.node.getProps();cO(e)&&(this.unmountControls=e.subscribe(this.node))}mount(){this.updateAnimationControlsSubscription()}update(){let{animate:e}=this.node.getProps(),{animate:t}=this.node.prevProps||{};e!==t&&this.updateAnimationControlsSubscription()}unmount(){var e;this.node.animationState.reset(),null===(e=this.unmountControls)||void 0===e||e.call(this)}}let hU=0;class hF extends hL{constructor(){super(...arguments),this.id=hU++}update(){if(!this.node.presenceContext)return;let{isPresent:e,onExitComplete:t}=this.node.presenceContext,{isPresent:i}=this.node.prevPresenceContext||{};if(!this.node.animationState||e===i)return;let n=this.node.animationState.setActive("exit",!e);t&&!e&&n.then(()=>t(this.id))}mount(){let{register:e}=this.node.presenceContext||{};e&&(this.unmount=e(this.id))}unmount(){}}function hV(e,t,i,n={passive:!0}){return e.addEventListener(t,i,n),()=>e.removeEventListener(t,i)}function hB(e){return{point:{x:e.pageX,y:e.pageY}}}let hq=e=>t=>c3(t)&&e(t,hB(t));function hW(e,t,i,n){return hV(e,t,hq(i),n)}let hz=(e,t)=>Math.abs(e-t);class hH{constructor(e,t,{transformPagePoint:i,contextWindow:n,dragSnapToOrigin:r=!1}={}){if(this.startEvent=null,this.lastMoveEvent=null,this.lastMoveEventInfo=null,this.handlers={},this.contextWindow=window,this.updatePoint=()=>{if(!(this.lastMoveEvent&&this.lastMoveEventInfo))return;let e=hK(this.lastMoveEventInfo,this.history),t=null!==this.startEvent,i=function(e,t){return Math.sqrt(hz(e.x,t.x)**2+hz(e.y,t.y)**2)}(e.offset,{x:0,y:0})>=3;if(!t&&!i)return;let{point:n}=e,{timestamp:r}=dm;this.history.push({...n,timestamp:r});let{onStart:s,onMove:o}=this.handlers;t||(s&&s(this.lastMoveEvent,e),this.startEvent=this.lastMoveEvent),o&&o(this.lastMoveEvent,e)},this.handlePointerMove=(e,t)=>{this.lastMoveEvent=e,this.lastMoveEventInfo=hG(t,this.transformPagePoint),dh.update(this.updatePoint,!0)},this.handlePointerUp=(e,t)=>{this.end();let{onEnd:i,onSessionEnd:n,resumeAnimation:r}=this.handlers;if(this.dragSnapToOrigin&&r&&r(),!(this.lastMoveEvent&&this.lastMoveEventInfo))return;let s=hK("pointercancel"===e.type?this.lastMoveEventInfo:hG(t,this.transformPagePoint),this.history);this.startEvent&&i&&i(e,s),n&&n(e,s)},!c3(e))return;this.dragSnapToOrigin=r,this.handlers=t,this.transformPagePoint=i,this.contextWindow=n||window;let s=hG(hB(e),this.transformPagePoint),{point:o}=s,{timestamp:a}=dm;this.history=[{...o,timestamp:a}];let{onSessionStart:l}=t;l&&l(e,hK(s,this.history)),this.removeListeners=u1(hW(this.contextWindow,"pointermove",this.handlePointerMove),hW(this.contextWindow,"pointerup",this.handlePointerUp),hW(this.contextWindow,"pointercancel",this.handlePointerUp))}updateHandlers(e){this.handlers=e}end(){this.removeListeners&&this.removeListeners(),dp(this.updatePoint)}}function hG(e,t){return t?{point:t(e.point)}:e}function h$(e,t){return{x:e.x-t.x,y:e.y-t.y}}function hK({point:e},t){return{point:e,delta:h$(e,hJ(t)),offset:h$(e,t[0]),velocity:function(e,t){if(e.length<2)return{x:0,y:0};let i=e.length-1,n=null,r=hJ(e);for(;i>=0&&(n=e[i],!(r.timestamp-n.timestamp>de(.1)));)i--;if(!n)return{x:0,y:0};let s=dt(r.timestamp-n.timestamp);if(0===s)return{x:0,y:0};let o={x:(r.x-n.x)/s,y:(r.y-n.y)/s};return o.x===1/0&&(o.x=0),o.y===1/0&&(o.y=0),o}(t,0)}}function hJ(e){return e[e.length-1]}function hX(e){return e&&"object"==typeof e&&Object.prototype.hasOwnProperty.call(e,"current")}function hY(e){return e.max-e.min}function hQ(e,t,i,n=.5){e.origin=n,e.originPoint=uG(t.min,t.max,e.origin),e.scale=hY(i)/hY(t),e.translate=uG(i.min,i.max,e.origin)-e.originPoint,(e.scale>=.9999&&e.scale<=1.0001||isNaN(e.scale))&&(e.scale=1),(e.translate>=-.01&&e.translate<=.01||isNaN(e.translate))&&(e.translate=0)}function hZ(e,t,i,n){hQ(e.x,t.x,i.x,n?n.originX:void 0),hQ(e.y,t.y,i.y,n?n.originY:void 0)}function h0(e,t,i){e.min=i.min+t.min,e.max=e.min+hY(t)}function h1(e,t,i){e.min=t.min-i.min,e.max=e.min+hY(t)}function h2(e,t,i){h1(e.x,t.x,i.x),h1(e.y,t.y,i.y)}function h3(e,t,i){return{min:void 0!==t?e.min+t:void 0,max:void 0!==i?e.max+i-(e.max-e.min):void 0}}function h5(e,t){let i=t.min-e.min,n=t.max-e.max;return t.max-t.min<e.max-e.min&&([i,n]=[n,i]),{min:i,max:n}}function h4(e,t,i){return{min:h6(e,t),max:h6(e,i)}}function h6(e,t){return"number"==typeof e?e:e[t]||0}let h9=()=>({translate:0,scale:1,origin:0,originPoint:0}),h8=()=>({x:h9(),y:h9()}),h7=()=>({min:0,max:0}),pe=()=>({x:h7(),y:h7()});function pt(e){return[e("x"),e("y")]}function pi({top:e,left:t,right:i,bottom:n}){return{x:{min:t,max:i},y:{min:e,max:n}}}function pn(e){return void 0===e||1===e}function pr({scale:e,scaleX:t,scaleY:i}){return!pn(e)||!pn(t)||!pn(i)}function ps(e){return pr(e)||po(e)||e.z||e.rotate||e.rotateX||e.rotateY||e.skewX||e.skewY}function po(e){var t,i;return(t=e.x)&&"0%"!==t||(i=e.y)&&"0%"!==i}function pa(e,t,i,n,r){return void 0!==r&&(e=n+r*(e-n)),n+i*(e-n)+t}function pl(e,t=0,i=1,n,r){e.min=pa(e.min,t,i,n,r),e.max=pa(e.max,t,i,n,r)}function pc(e,{x:t,y:i}){pl(e.x,t.translate,t.scale,t.originPoint),pl(e.y,i.translate,i.scale,i.originPoint)}function pd(e,t){e.min=e.min+t,e.max=e.max+t}function pu(e,t,i,n,r=.5){let s=uG(e.min,e.max,r);pl(e,t,i,s,n)}function ph(e,t){pu(e.x,t.x,t.scaleX,t.scale,t.originX),pu(e.y,t.y,t.scaleY,t.scale,t.originY)}function pp(e,t){return pi(function(e,t){if(!t)return e;let i=t({x:e.left,y:e.top}),n=t({x:e.right,y:e.bottom});return{top:i.y,left:i.x,bottom:n.y,right:n.x}}(e.getBoundingClientRect(),t))}let pm=({current:e})=>e?e.ownerDocument.defaultView:null,pf=new WeakMap;class pg{constructor(e){this.openDragLock=null,this.isDragging=!1,this.currentDirection=null,this.originPoint={x:0,y:0},this.constraints=!1,this.hasMutatedConstraints=!1,this.elastic=pe(),this.visualElement=e}start(e,{snapToCursor:t=!1}={}){let{presenceContext:i}=this.visualElement;if(i&&!1===i.isPresent)return;let{dragSnapToOrigin:n}=this.getProps();this.panSession=new hH(e,{onSessionStart:e=>{let{dragSnapToOrigin:i}=this.getProps();i?this.pauseAnimation():this.stopAnimation(),t&&this.snapToCursor(hB(e).point)},onStart:(e,t)=>{let{drag:i,dragPropagation:n,onDragStart:r}=this.getProps();if(i&&!n&&(this.openDragLock&&this.openDragLock(),this.openDragLock="x"===i||"y"===i?cZ[i]?null:(cZ[i]=!0,()=>{cZ[i]=!1}):cZ.x||cZ.y?null:(cZ.x=cZ.y=!0,()=>{cZ.x=cZ.y=!1}),!this.openDragLock))return;this.isDragging=!0,this.currentDirection=null,this.resolveConstraints(),this.visualElement.projection&&(this.visualElement.projection.isAnimationBlocked=!0,this.visualElement.projection.target=void 0),pt(e=>{let t=this.getAxisMotionValue(e).get()||0;if(d3.test(t)){let{projection:i}=this.visualElement;if(i&&i.layout){let n=i.layout.layoutBox[e];if(n){let e=hY(n);t=parseFloat(t)/100*e}}}this.originPoint[e]=t}),r&&dh.postRender(()=>r(e,t)),dP(this.visualElement,"transform");let{animationState:s}=this.visualElement;s&&s.setActive("whileDrag",!0)},onMove:(e,t)=>{let{dragPropagation:i,dragDirectionLock:n,onDirectionLock:r,onDrag:s}=this.getProps();if(!i&&!this.openDragLock)return;let{offset:o}=t;if(n&&null===this.currentDirection){this.currentDirection=function(e,t=10){let i=null;return Math.abs(e.y)>t?i="y":Math.abs(e.x)>t&&(i="x"),i}(o),null!==this.currentDirection&&r&&r(this.currentDirection);return}this.updateAxis("x",t.point,o),this.updateAxis("y",t.point,o),this.visualElement.render(),s&&s(e,t)},onSessionEnd:(e,t)=>this.stop(e,t),resumeAnimation:()=>pt(e=>{var t;return"paused"===this.getAnimationState(e)&&(null===(t=this.getAxisMotionValue(e).animation)||void 0===t?void 0:t.play())})},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:n,contextWindow:pm(this.visualElement)})}stop(e,t){let i=this.isDragging;if(this.cancel(),!i)return;let{velocity:n}=t;this.startAnimation(n);let{onDragEnd:r}=this.getProps();r&&dh.postRender(()=>r(e,t))}cancel(){this.isDragging=!1;let{projection:e,animationState:t}=this.visualElement;e&&(e.isAnimationBlocked=!1),this.panSession&&this.panSession.end(),this.panSession=void 0;let{dragPropagation:i}=this.getProps();!i&&this.openDragLock&&(this.openDragLock(),this.openDragLock=null),t&&t.setActive("whileDrag",!1)}updateAxis(e,t,i){let{drag:n}=this.getProps();if(!i||!pv(e,n,this.currentDirection))return;let r=this.getAxisMotionValue(e),s=this.originPoint[e]+i[e];this.constraints&&this.constraints[e]&&(s=function(e,{min:t,max:i},n){return void 0!==t&&e<t?e=n?uG(t,e,n.min):Math.max(e,t):void 0!==i&&e>i&&(e=n?uG(i,e,n.max):Math.min(e,i)),e}(s,this.constraints[e],this.elastic[e])),r.set(s)}resolveConstraints(){var e;let{dragConstraints:t,dragElastic:i}=this.getProps(),n=this.visualElement.projection&&!this.visualElement.projection.layout?this.visualElement.projection.measure(!1):null===(e=this.visualElement.projection)||void 0===e?void 0:e.layout,r=this.constraints;t&&hX(t)?this.constraints||(this.constraints=this.resolveRefConstraints()):t&&n?this.constraints=function(e,{top:t,left:i,bottom:n,right:r}){return{x:h3(e.x,i,r),y:h3(e.y,t,n)}}(n.layoutBox,t):this.constraints=!1,this.elastic=function(e=.35){return!1===e?e=0:!0===e&&(e=.35),{x:h4(e,"left","right"),y:h4(e,"top","bottom")}}(i),r!==this.constraints&&n&&this.constraints&&!this.hasMutatedConstraints&&pt(e=>{!1!==this.constraints&&this.getAxisMotionValue(e)&&(this.constraints[e]=function(e,t){let i={};return void 0!==t.min&&(i.min=t.min-e.min),void 0!==t.max&&(i.max=t.max-e.min),i}(n.layoutBox[e],this.constraints[e]))})}resolveRefConstraints(){var e;let{dragConstraints:t,onMeasureDragConstraints:i}=this.getProps();if(!t||!hX(t))return!1;let n=t.current;di(null!==n,"If `dragConstraints` is set as a React ref, that ref must be passed to another component's `ref` prop.");let{projection:r}=this.visualElement;if(!r||!r.layout)return!1;let s=function(e,t,i){let n=pp(e,i),{scroll:r}=t;return r&&(pd(n.x,r.offset.x),pd(n.y,r.offset.y)),n}(n,r.root,this.visualElement.getTransformPagePoint()),o={x:h5((e=r.layout.layoutBox).x,s.x),y:h5(e.y,s.y)};if(i){let e=i(function({x:e,y:t}){return{top:t.min,right:e.max,bottom:t.max,left:e.min}}(o));this.hasMutatedConstraints=!!e,e&&(o=pi(e))}return o}startAnimation(e){let{drag:t,dragMomentum:i,dragElastic:n,dragTransition:r,dragSnapToOrigin:s,onDragTransitionEnd:o}=this.getProps(),a=this.constraints||{};return Promise.all(pt(o=>{if(!pv(o,t,this.currentDirection))return;let l=a&&a[o]||{};s&&(l={min:0,max:0});let c={type:"inertia",velocity:i?e[o]:0,bounceStiffness:n?200:1e6,bounceDamping:n?40:1e7,timeConstant:750,restDelta:1,restSpeed:10,...r,...l};return this.startAxisValueAnimation(o,c)})).then(o)}startAxisValueAnimation(e,t){let i=this.getAxisMotionValue(e);return dP(this.visualElement,e),i.start(hx(e,i,0,t,this.visualElement,!1))}stopAnimation(){pt(e=>this.getAxisMotionValue(e).stop())}pauseAnimation(){pt(e=>{var t;return null===(t=this.getAxisMotionValue(e).animation)||void 0===t?void 0:t.pause()})}getAnimationState(e){var t;return null===(t=this.getAxisMotionValue(e).animation)||void 0===t?void 0:t.state}getAxisMotionValue(e){let t=`_drag${e.toUpperCase()}`,i=this.visualElement.getProps();return i[t]||this.visualElement.getValue(e,(i.initial?i.initial[e]:void 0)||0)}snapToCursor(e){pt(t=>{let{drag:i}=this.getProps();if(!pv(t,i,this.currentDirection))return;let{projection:n}=this.visualElement,r=this.getAxisMotionValue(t);if(n&&n.layout){let{min:i,max:s}=n.layout.layoutBox[t];r.set(e[t]-uG(i,s,.5))}})}scalePositionWithinConstraints(){if(!this.visualElement.current)return;let{drag:e,dragConstraints:t}=this.getProps(),{projection:i}=this.visualElement;if(!hX(t)||!i||!this.constraints)return;this.stopAnimation();let n={x:0,y:0};pt(e=>{let t=this.getAxisMotionValue(e);if(t&&!1!==this.constraints){let i=t.get();n[e]=function(e,t){let i=.5,n=hY(e),r=hY(t);return r>n?i=cJ(t.min,t.max-n,e.min):n>r&&(i=cJ(e.min,e.max-r,t.min)),dq(0,1,i)}({min:i,max:i},this.constraints[e])}});let{transformTemplate:r}=this.visualElement.getProps();this.visualElement.current.style.transform=r?r({},""):"none",i.root&&i.root.updateScroll(),i.updateLayout(),this.resolveConstraints(),pt(t=>{if(!pv(t,e,null))return;let i=this.getAxisMotionValue(t),{min:r,max:s}=this.constraints[t];i.set(uG(r,s,n[t]))})}addListeners(){if(!this.visualElement.current)return;pf.set(this.visualElement,this);let e=hW(this.visualElement.current,"pointerdown",e=>{let{drag:t,dragListener:i=!0}=this.getProps();t&&i&&this.start(e)}),t=()=>{let{dragConstraints:e}=this.getProps();hX(e)&&e.current&&(this.constraints=this.resolveRefConstraints())},{projection:i}=this.visualElement,n=i.addEventListener("measure",t);i&&!i.layout&&(i.root&&i.root.updateScroll(),i.updateLayout()),dh.read(t);let r=hV(window,"resize",()=>this.scalePositionWithinConstraints()),s=i.addEventListener("didUpdate",({delta:e,hasLayoutChanged:t})=>{this.isDragging&&t&&(pt(t=>{let i=this.getAxisMotionValue(t);i&&(this.originPoint[t]+=e[t].translate,i.set(i.get()+e[t].translate))}),this.visualElement.render())});return()=>{r(),e(),n(),s&&s()}}getProps(){let e=this.visualElement.getProps(),{drag:t=!1,dragDirectionLock:i=!1,dragPropagation:n=!1,dragConstraints:r=!1,dragElastic:s=.35,dragMomentum:o=!0}=e;return{...e,drag:t,dragDirectionLock:i,dragPropagation:n,dragConstraints:r,dragElastic:s,dragMomentum:o}}}function pv(e,t,i){return(!0===t||t===e)&&(null===i||i===e)}class py extends hL{constructor(e){super(e),this.removeGroupControls=di,this.removeListeners=di,this.controls=new pg(e)}mount(){let{dragControls:e}=this.node.getProps();e&&(this.removeGroupControls=e.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||di}unmount(){this.removeGroupControls(),this.removeListeners()}}let pb=e=>(t,i)=>{e&&dh.postRender(()=>e(t,i))};class pk extends hL{constructor(){super(...arguments),this.removePointerDownListener=di}onPointerDown(e){this.session=new hH(e,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:pm(this.node)})}createPanHandlers(){let{onPanSessionStart:e,onPanStart:t,onPan:i,onPanEnd:n}=this.node.getProps();return{onSessionStart:pb(e),onStart:pb(t),onMove:i,onEnd:(e,t)=>{delete this.session,n&&dh.postRender(()=>n(e,t))}}}mount(){this.removePointerDownListener=hW(this.node.current,"pointerdown",e=>this.onPointerDown(e))}update(){this.session&&this.session.updateHandlers(this.createPanHandlers())}unmount(){this.removePointerDownListener(),this.session&&this.session.end()}}let pT=(0,p.createContext)({}),pS={hasAnimatedSinceResize:!0,hasEverUpdated:!1};function pC(e,t){return t.max===t.min?0:e/(t.max-t.min)*100}let pw={correct:(e,t)=>{if(!t.target)return e;if("string"==typeof e){if(!d5.test(e))return e;e=parseFloat(e)}let i=pC(e,t.target.x),n=pC(e,t.target.y);return`${i}% ${n}%`}},pE={},{schedule:pP,cancel:px}=du(queueMicrotask,!1);class pR extends p.Component{componentDidMount(){let{visualElement:e,layoutGroup:t,switchLayoutGroup:i,layoutId:n}=this.props,{projection:r}=e;Object.assign(pE,pA),r&&(t.group&&t.group.add(r),i&&i.register&&n&&i.register(r),r.root.didUpdate(),r.addEventListener("animationComplete",()=>{this.safeToRemove()}),r.setOptions({...r.options,onExitComplete:()=>this.safeToRemove()})),pS.hasEverUpdated=!0}getSnapshotBeforeUpdate(e){let{layoutDependency:t,visualElement:i,drag:n,isPresent:r}=this.props,s=i.projection;return s&&(s.isPresent=r,n||e.layoutDependency!==t||void 0===t?s.willUpdate():this.safeToRemove(),e.isPresent===r||(r?s.promote():s.relegate()||dh.postRender(()=>{let e=s.getStack();e&&e.members.length||this.safeToRemove()}))),null}componentDidUpdate(){let{projection:e}=this.props.visualElement;e&&(e.root.didUpdate(),pP.postRender(()=>{!e.currentAnimation&&e.isLead()&&this.safeToRemove()}))}componentWillUnmount(){let{visualElement:e,layoutGroup:t,switchLayoutGroup:i}=this.props,{projection:n}=e;n&&(n.scheduleCheckAfterUnmount(),t&&t.group&&t.group.remove(n),i&&i.deregister&&i.deregister(n))}safeToRemove(){let{safeToRemove:e}=this.props;e&&e()}render(){return null}}function pO(e){let[t,i]=cC(),n=(0,p.useContext)(cf);return(0,u.jsx)(pR,{...e,layoutGroup:n,switchLayoutGroup:(0,p.useContext)(pT),isPresent:t,safeToRemove:i})}let pA={borderRadius:{...pw,applyTo:["borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"]},borderTopLeftRadius:pw,borderTopRightRadius:pw,borderBottomLeftRadius:pw,borderBottomRightRadius:pw,boxShadow:{correct:(e,{treeScale:t,projectionDelta:i})=>{let n=ul.parse(e);if(n.length>5)return e;let r=ul.createTransformer(e),s="number"!=typeof n[0]?1:0,o=i.x.scale*t.x,a=i.y.scale*t.y;n[0+s]/=o,n[1+s]/=a;let l=uG(o,a,.5);return"number"==typeof n[2+s]&&(n[2+s]/=l),"number"==typeof n[3+s]&&(n[3+s]/=l),r(n)}}},pI=(e,t)=>e.depth-t.depth;class pM{constructor(){this.children=[],this.isDirty=!1}add(e){dy(this.children,e),this.isDirty=!0}remove(e){db(this.children,e),this.isDirty=!0}forEach(e){this.isDirty&&this.children.sort(pI),this.isDirty=!1,this.children.forEach(e)}}function pD(e){let t=dE(e)?e.get():e;return da(t)?t.toValue():t}let p_=["TopLeft","TopRight","BottomLeft","BottomRight"],pN=p_.length,pL=e=>"string"==typeof e?parseFloat(e):e,pj=e=>"number"==typeof e||d5.test(e);function pU(e,t){return void 0!==e[t]?e[t]:e.borderRadius}let pF=pB(0,.5,dF),pV=pB(.5,.95,di);function pB(e,t,i){return n=>n<e?0:n>t?1:i(cJ(e,t,n))}function pq(e,t){e.min=t.min,e.max=t.max}function pW(e,t){pq(e.x,t.x),pq(e.y,t.y)}function pz(e,t){e.translate=t.translate,e.scale=t.scale,e.originPoint=t.originPoint,e.origin=t.origin}function pH(e,t,i,n,r){return e-=t,e=n+1/i*(e-n),void 0!==r&&(e=n+1/r*(e-n)),e}function pG(e,t,[i,n,r],s,o){!function(e,t=0,i=1,n=.5,r,s=e,o=e){if(d3.test(t)&&(t=parseFloat(t),t=uG(o.min,o.max,t/100)-o.min),"number"!=typeof t)return;let a=uG(s.min,s.max,n);e===s&&(a-=t),e.min=pH(e.min,t,i,a,r),e.max=pH(e.max,t,i,a,r)}(e,t[i],t[n],t[r],t.scale,s,o)}let p$=["x","scaleX","originX"],pK=["y","scaleY","originY"];function pJ(e,t,i,n){pG(e.x,t,p$,i?i.x:void 0,n?n.x:void 0),pG(e.y,t,pK,i?i.y:void 0,n?n.y:void 0)}function pX(e){return 0===e.translate&&1===e.scale}function pY(e){return pX(e.x)&&pX(e.y)}function pQ(e,t){return e.min===t.min&&e.max===t.max}function pZ(e,t){return Math.round(e.min)===Math.round(t.min)&&Math.round(e.max)===Math.round(t.max)}function p0(e,t){return pZ(e.x,t.x)&&pZ(e.y,t.y)}function p1(e){return hY(e.x)/hY(e.y)}function p2(e,t){return e.translate===t.translate&&e.scale===t.scale&&e.originPoint===t.originPoint}class p3{constructor(){this.members=[]}add(e){dy(this.members,e),e.scheduleRender()}remove(e){if(db(this.members,e),e===this.prevLead&&(this.prevLead=void 0),e===this.lead){let e=this.members[this.members.length-1];e&&this.promote(e)}}relegate(e){let t;let i=this.members.findIndex(t=>e===t);if(0===i)return!1;for(let e=i;e>=0;e--){let i=this.members[e];if(!1!==i.isPresent){t=i;break}}return!!t&&(this.promote(t),!0)}promote(e,t){let i=this.lead;if(e!==i&&(this.prevLead=i,this.lead=e,e.show(),i)){i.instance&&i.scheduleRender(),e.scheduleRender(),e.resumeFrom=i,t&&(e.resumeFrom.preserveOpacity=!0),i.snapshot&&(e.snapshot=i.snapshot,e.snapshot.latestValues=i.animationValues||i.latestValues),e.root&&e.root.isUpdating&&(e.isLayoutDirty=!0);let{crossfade:n}=e.options;!1===n&&i.hide()}}exitAnimationComplete(){this.members.forEach(e=>{let{options:t,resumingFrom:i}=e;t.onExitComplete&&t.onExitComplete(),i&&i.options.onExitComplete&&i.options.onExitComplete()})}scheduleRender(){this.members.forEach(e=>{e.instance&&e.scheduleRender(!1)})}removeLeadSnapshot(){this.lead&&this.lead.snapshot&&(this.lead.snapshot=void 0)}}let p5={type:"projectionFrame",totalNodes:0,resolvedTargetDeltas:0,recalculatedProjection:0},p4="undefined"!=typeof window&&void 0!==window.MotionDebug,p6=["","X","Y","Z"],p9={visibility:"hidden"},p8=0;function p7(e,t,i,n){let{latestValues:r}=t;r[e]&&(i[e]=r[e],t.setStaticValue(e,0),n&&(n[e]=0))}function me({attachResizeListener:e,defaultParent:t,measureScroll:i,checkIsScrollRoot:n,resetTransform:r}){return class{constructor(e={},i=null==t?void 0:t()){this.id=p8++,this.animationId=0,this.children=new Set,this.options={},this.isTreeAnimating=!1,this.isAnimationBlocked=!1,this.isLayoutDirty=!1,this.isProjectionDirty=!1,this.isSharedProjectionDirty=!1,this.isTransformDirty=!1,this.updateManuallyBlocked=!1,this.updateBlockedByResize=!1,this.isUpdating=!1,this.isSVG=!1,this.needsReset=!1,this.shouldResetTransform=!1,this.hasCheckedOptimisedAppear=!1,this.treeScale={x:1,y:1},this.eventHandlers=new Map,this.hasTreeAnimated=!1,this.updateScheduled=!1,this.scheduleUpdate=()=>this.update(),this.projectionUpdateScheduled=!1,this.checkUpdateFailed=()=>{this.isUpdating&&(this.isUpdating=!1,this.clearAllSnapshots())},this.updateProjection=()=>{this.projectionUpdateScheduled=!1,p4&&(p5.totalNodes=p5.resolvedTargetDeltas=p5.recalculatedProjection=0),this.nodes.forEach(mn),this.nodes.forEach(md),this.nodes.forEach(mu),this.nodes.forEach(mr),p4&&window.MotionDebug.record(p5)},this.resolvedRelativeTargetAt=0,this.hasProjected=!1,this.isVisible=!0,this.animationProgress=0,this.sharedNodes=new Map,this.latestValues=e,this.root=i?i.root||i:this,this.path=i?[...i.path,i]:[],this.parent=i,this.depth=i?i.depth+1:0;for(let e=0;e<this.path.length;e++)this.path[e].shouldResetTransform=!0;this.root===this&&(this.nodes=new pM)}addEventListener(e,t){return this.eventHandlers.has(e)||this.eventHandlers.set(e,new dk),this.eventHandlers.get(e).add(t)}notifyListeners(e,...t){let i=this.eventHandlers.get(e);i&&i.notify(...t)}hasListeners(e){return this.eventHandlers.has(e)}mount(t,i=this.root.hasTreeAnimated){if(this.instance)return;this.isSVG=t instanceof SVGElement&&"svg"!==t.tagName,this.instance=t;let{layoutId:n,layout:r,visualElement:s}=this.options;if(s&&!s.current&&s.mount(t),this.root.nodes.add(this),this.parent&&this.parent.children.add(this),i&&(r||n)&&(this.isLayoutDirty=!0),e){let i;let n=()=>this.root.updateBlockedByResize=!1;e(t,()=>{this.root.updateBlockedByResize=!0,i&&i(),i=function(e,t){let i=dv.now(),n=({timestamp:t})=>{let r=t-i;r>=250&&(dp(n),e(r-250))};return dh.read(n,!0),()=>dp(n)}(n,250),pS.hasAnimatedSinceResize&&(pS.hasAnimatedSinceResize=!1,this.nodes.forEach(mc))})}n&&this.root.registerSharedNode(n,this),!1!==this.options.animate&&s&&(n||r)&&this.addEventListener("didUpdate",({delta:e,hasLayoutChanged:t,hasRelativeTargetChanged:i,layout:n})=>{if(this.isTreeAnimationBlocked()){this.target=void 0,this.relativeTarget=void 0;return}let r=this.options.transition||s.getDefaultTransition()||mv,{onLayoutAnimationStart:o,onLayoutAnimationComplete:a}=s.getProps(),l=!this.targetLayout||!p0(this.targetLayout,n)||i,c=!t&&i;if(this.options.layoutRoot||this.resumeFrom&&this.resumeFrom.instance||c||t&&(l||!this.currentAnimation)){this.resumeFrom&&(this.resumingFrom=this.resumeFrom,this.resumingFrom.resumingFrom=void 0),this.setAnimationOrigin(e,c);let t={...cq(r,"layout"),onPlay:o,onComplete:a};(s.shouldReduceMotion||this.options.layoutRoot)&&(t.delay=0,t.type=!1),this.startAnimation(t)}else t||mc(this),this.isLead()&&this.options.onExitComplete&&this.options.onExitComplete();this.targetLayout=n})}unmount(){this.options.layoutId&&this.willUpdate(),this.root.nodes.remove(this);let e=this.getStack();e&&e.remove(this),this.parent&&this.parent.children.delete(this),this.instance=void 0,dp(this.updateProjection)}blockUpdate(){this.updateManuallyBlocked=!0}unblockUpdate(){this.updateManuallyBlocked=!1}isUpdateBlocked(){return this.updateManuallyBlocked||this.updateBlockedByResize}isTreeAnimationBlocked(){return this.isAnimationBlocked||this.parent&&this.parent.isTreeAnimationBlocked()||!1}startUpdate(){!this.isUpdateBlocked()&&(this.isUpdating=!0,this.nodes&&this.nodes.forEach(mh),this.animationId++)}getTransformTemplate(){let{visualElement:e}=this.options;return e&&e.getProps().transformTemplate}willUpdate(e=!0){if(this.root.hasTreeAnimated=!0,this.root.isUpdateBlocked()){this.options.onExitComplete&&this.options.onExitComplete();return}if(window.MotionCancelOptimisedAnimation&&!this.hasCheckedOptimisedAppear&&function e(t){if(t.hasCheckedOptimisedAppear=!0,t.root===t)return;let{visualElement:i}=t.options;if(!i)return;let n=i.props[dR];if(window.MotionHasOptimisedAnimation(n,"transform")){let{layout:e,layoutId:i}=t.options;window.MotionCancelOptimisedAnimation(n,"transform",dh,!(e||i))}let{parent:r}=t;r&&!r.hasCheckedOptimisedAppear&&e(r)}(this),this.root.isUpdating||this.root.startUpdate(),this.isLayoutDirty)return;this.isLayoutDirty=!0;for(let e=0;e<this.path.length;e++){let t=this.path[e];t.shouldResetTransform=!0,t.updateScroll("snapshot"),t.options.layoutRoot&&t.willUpdate(!1)}let{layoutId:t,layout:i}=this.options;if(void 0===t&&!i)return;let n=this.getTransformTemplate();this.prevTransformTemplateValue=n?n(this.latestValues,""):void 0,this.updateSnapshot(),e&&this.notifyListeners("willUpdate")}update(){if(this.updateScheduled=!1,this.isUpdateBlocked()){this.unblockUpdate(),this.clearAllSnapshots(),this.nodes.forEach(mo);return}this.isUpdating||this.nodes.forEach(ma),this.isUpdating=!1,this.nodes.forEach(ml),this.nodes.forEach(mt),this.nodes.forEach(mi),this.clearAllSnapshots();let e=dv.now();dm.delta=dq(0,1e3/60,e-dm.timestamp),dm.timestamp=e,dm.isProcessing=!0,df.update.process(dm),df.preRender.process(dm),df.render.process(dm),dm.isProcessing=!1}didUpdate(){this.updateScheduled||(this.updateScheduled=!0,pP.read(this.scheduleUpdate))}clearAllSnapshots(){this.nodes.forEach(ms),this.sharedNodes.forEach(mp)}scheduleUpdateProjection(){this.projectionUpdateScheduled||(this.projectionUpdateScheduled=!0,dh.preRender(this.updateProjection,!1,!0))}scheduleCheckAfterUnmount(){dh.postRender(()=>{this.isLayoutDirty?this.root.didUpdate():this.root.checkUpdateFailed()})}updateSnapshot(){!this.snapshot&&this.instance&&(this.snapshot=this.measure())}updateLayout(){if(!this.instance||(this.updateScroll(),!(this.options.alwaysMeasureLayout&&this.isLead())&&!this.isLayoutDirty))return;if(this.resumeFrom&&!this.resumeFrom.instance)for(let e=0;e<this.path.length;e++)this.path[e].updateScroll();let e=this.layout;this.layout=this.measure(!1),this.layoutCorrected=pe(),this.isLayoutDirty=!1,this.projectionDelta=void 0,this.notifyListeners("measure",this.layout.layoutBox);let{visualElement:t}=this.options;t&&t.notify("LayoutMeasure",this.layout.layoutBox,e?e.layoutBox:void 0)}updateScroll(e="measure"){let t=!!(this.options.layoutScroll&&this.instance);if(this.scroll&&this.scroll.animationId===this.root.animationId&&this.scroll.phase===e&&(t=!1),t){let t=n(this.instance);this.scroll={animationId:this.root.animationId,phase:e,isRoot:t,offset:i(this.instance),wasRoot:this.scroll?this.scroll.isRoot:t}}}resetTransform(){if(!r)return;let e=this.isLayoutDirty||this.shouldResetTransform||this.options.alwaysMeasureLayout,t=this.projectionDelta&&!pY(this.projectionDelta),i=this.getTransformTemplate(),n=i?i(this.latestValues,""):void 0,s=n!==this.prevTransformTemplateValue;e&&(t||ps(this.latestValues)||s)&&(r(this.instance,n),this.shouldResetTransform=!1,this.scheduleRender())}measure(e=!0){var t;let i=this.measurePageBox(),n=this.removeElementScroll(i);return e&&(n=this.removeTransform(n)),mk((t=n).x),mk(t.y),{animationId:this.root.animationId,measuredBox:i,layoutBox:n,latestValues:{},source:this.id}}measurePageBox(){var e;let{visualElement:t}=this.options;if(!t)return pe();let i=t.measureViewportBox();if(!((null===(e=this.scroll)||void 0===e?void 0:e.wasRoot)||this.path.some(mS))){let{scroll:e}=this.root;e&&(pd(i.x,e.offset.x),pd(i.y,e.offset.y))}return i}removeElementScroll(e){var t;let i=pe();if(pW(i,e),null===(t=this.scroll)||void 0===t?void 0:t.wasRoot)return i;for(let t=0;t<this.path.length;t++){let n=this.path[t],{scroll:r,options:s}=n;n!==this.root&&r&&s.layoutScroll&&(r.wasRoot&&pW(i,e),pd(i.x,r.offset.x),pd(i.y,r.offset.y))}return i}applyTransform(e,t=!1){let i=pe();pW(i,e);for(let e=0;e<this.path.length;e++){let n=this.path[e];!t&&n.options.layoutScroll&&n.scroll&&n!==n.root&&ph(i,{x:-n.scroll.offset.x,y:-n.scroll.offset.y}),ps(n.latestValues)&&ph(i,n.latestValues)}return ps(this.latestValues)&&ph(i,this.latestValues),i}removeTransform(e){let t=pe();pW(t,e);for(let e=0;e<this.path.length;e++){let i=this.path[e];if(!i.instance||!ps(i.latestValues))continue;pr(i.latestValues)&&i.updateSnapshot();let n=pe();pW(n,i.measurePageBox()),pJ(t,i.latestValues,i.snapshot?i.snapshot.layoutBox:void 0,n)}return ps(this.latestValues)&&pJ(t,this.latestValues),t}setTargetDelta(e){this.targetDelta=e,this.root.scheduleUpdateProjection(),this.isProjectionDirty=!0}setOptions(e){this.options={...this.options,...e,crossfade:void 0===e.crossfade||e.crossfade}}clearMeasurements(){this.scroll=void 0,this.layout=void 0,this.snapshot=void 0,this.prevTransformTemplateValue=void 0,this.targetDelta=void 0,this.target=void 0,this.isLayoutDirty=!1}forceRelativeParentToResolveTarget(){this.relativeParent&&this.relativeParent.resolvedRelativeTargetAt!==dm.timestamp&&this.relativeParent.resolveTargetDelta(!0)}resolveTargetDelta(e=!1){var t,i,n,r;let s=this.getLead();this.isProjectionDirty||(this.isProjectionDirty=s.isProjectionDirty),this.isTransformDirty||(this.isTransformDirty=s.isTransformDirty),this.isSharedProjectionDirty||(this.isSharedProjectionDirty=s.isSharedProjectionDirty);let o=!!this.resumingFrom||this!==s;if(!(e||o&&this.isSharedProjectionDirty||this.isProjectionDirty||(null===(t=this.parent)||void 0===t?void 0:t.isProjectionDirty)||this.attemptToResolveRelativeTarget||this.root.updateBlockedByResize))return;let{layout:a,layoutId:l}=this.options;if(this.layout&&(a||l)){if(this.resolvedRelativeTargetAt=dm.timestamp,!this.targetDelta&&!this.relativeTarget){let e=this.getClosestProjectingParent();e&&e.layout&&1!==this.animationProgress?(this.relativeParent=e,this.forceRelativeParentToResolveTarget(),this.relativeTarget=pe(),this.relativeTargetOrigin=pe(),h2(this.relativeTargetOrigin,this.layout.layoutBox,e.layout.layoutBox),pW(this.relativeTarget,this.relativeTargetOrigin)):this.relativeParent=this.relativeTarget=void 0}if(this.relativeTarget||this.targetDelta){if((this.target||(this.target=pe(),this.targetWithTransforms=pe()),this.relativeTarget&&this.relativeTargetOrigin&&this.relativeParent&&this.relativeParent.target)?(this.forceRelativeParentToResolveTarget(),i=this.target,n=this.relativeTarget,r=this.relativeParent.target,h0(i.x,n.x,r.x),h0(i.y,n.y,r.y)):this.targetDelta?(this.resumingFrom?this.target=this.applyTransform(this.layout.layoutBox):pW(this.target,this.layout.layoutBox),pc(this.target,this.targetDelta)):pW(this.target,this.layout.layoutBox),this.attemptToResolveRelativeTarget){this.attemptToResolveRelativeTarget=!1;let e=this.getClosestProjectingParent();e&&!!e.resumingFrom==!!this.resumingFrom&&!e.options.layoutScroll&&e.target&&1!==this.animationProgress?(this.relativeParent=e,this.forceRelativeParentToResolveTarget(),this.relativeTarget=pe(),this.relativeTargetOrigin=pe(),h2(this.relativeTargetOrigin,this.target,e.target),pW(this.relativeTarget,this.relativeTargetOrigin)):this.relativeParent=this.relativeTarget=void 0}p4&&p5.resolvedTargetDeltas++}}}getClosestProjectingParent(){return!this.parent||pr(this.parent.latestValues)||po(this.parent.latestValues)?void 0:this.parent.isProjecting()?this.parent:this.parent.getClosestProjectingParent()}isProjecting(){return!!((this.relativeTarget||this.targetDelta||this.options.layoutRoot)&&this.layout)}calcProjection(){var e;let t=this.getLead(),i=!!this.resumingFrom||this!==t,n=!0;if((this.isProjectionDirty||(null===(e=this.parent)||void 0===e?void 0:e.isProjectionDirty))&&(n=!1),i&&(this.isSharedProjectionDirty||this.isTransformDirty)&&(n=!1),this.resolvedRelativeTargetAt===dm.timestamp&&(n=!1),n)return;let{layout:r,layoutId:s}=this.options;if(this.isTreeAnimating=!!(this.parent&&this.parent.isTreeAnimating||this.currentAnimation||this.pendingAnimation),this.isTreeAnimating||(this.targetDelta=this.relativeTarget=void 0),!this.layout||!(r||s))return;pW(this.layoutCorrected,this.layout.layoutBox);let o=this.treeScale.x,a=this.treeScale.y;(function(e,t,i,n=!1){let r,s;let o=i.length;if(o){t.x=t.y=1;for(let a=0;a<o;a++){s=(r=i[a]).projectionDelta;let{visualElement:o}=r.options;(!o||!o.props.style||"contents"!==o.props.style.display)&&(n&&r.options.layoutScroll&&r.scroll&&r!==r.root&&ph(e,{x:-r.scroll.offset.x,y:-r.scroll.offset.y}),s&&(t.x*=s.x.scale,t.y*=s.y.scale,pc(e,s)),n&&ps(r.latestValues)&&ph(e,r.latestValues))}t.x<1.0000000000001&&t.x>.999999999999&&(t.x=1),t.y<1.0000000000001&&t.y>.999999999999&&(t.y=1)}})(this.layoutCorrected,this.treeScale,this.path,i),t.layout&&!t.target&&(1!==this.treeScale.x||1!==this.treeScale.y)&&(t.target=t.layout.layoutBox,t.targetWithTransforms=pe());let{target:l}=t;if(!l){this.prevProjectionDelta&&(this.createProjectionDeltas(),this.scheduleRender());return}this.projectionDelta&&this.prevProjectionDelta?(pz(this.prevProjectionDelta.x,this.projectionDelta.x),pz(this.prevProjectionDelta.y,this.projectionDelta.y)):this.createProjectionDeltas(),hZ(this.projectionDelta,this.layoutCorrected,l,this.latestValues),this.treeScale.x===o&&this.treeScale.y===a&&p2(this.projectionDelta.x,this.prevProjectionDelta.x)&&p2(this.projectionDelta.y,this.prevProjectionDelta.y)||(this.hasProjected=!0,this.scheduleRender(),this.notifyListeners("projectionUpdate",l)),p4&&p5.recalculatedProjection++}hide(){this.isVisible=!1}show(){this.isVisible=!0}scheduleRender(e=!0){var t;if(null===(t=this.options.visualElement)||void 0===t||t.scheduleRender(),e){let e=this.getStack();e&&e.scheduleRender()}this.resumingFrom&&!this.resumingFrom.instance&&(this.resumingFrom=void 0)}createProjectionDeltas(){this.prevProjectionDelta=h8(),this.projectionDelta=h8(),this.projectionDeltaWithTransform=h8()}setAnimationOrigin(e,t=!1){let i;let n=this.snapshot,r=n?n.latestValues:{},s={...this.latestValues},o=h8();this.relativeParent&&this.relativeParent.options.layoutRoot||(this.relativeTarget=this.relativeTargetOrigin=void 0),this.attemptToResolveRelativeTarget=!t;let a=pe(),l=(n?n.source:void 0)!==(this.layout?this.layout.source:void 0),c=this.getStack(),d=!c||c.members.length<=1,u=!!(l&&!d&&!0===this.options.crossfade&&!this.path.some(mg));this.animationProgress=0,this.mixTargetDelta=t=>{let n=t/1e3;if(mm(o.x,e.x,n),mm(o.y,e.y,n),this.setTargetDelta(o),this.relativeTarget&&this.relativeTargetOrigin&&this.layout&&this.relativeParent&&this.relativeParent.layout){var c,h,p,m;h2(a,this.layout.layoutBox,this.relativeParent.layout.layoutBox),p=this.relativeTarget,m=this.relativeTargetOrigin,mf(p.x,m.x,a.x,n),mf(p.y,m.y,a.y,n),i&&(c=this.relativeTarget,h=i,pQ(c.x,h.x)&&pQ(c.y,h.y))&&(this.isProjectionDirty=!1),i||(i=pe()),pW(i,this.relativeTarget)}l&&(this.animationValues=s,function(e,t,i,n,r,s){r?(e.opacity=uG(0,void 0!==i.opacity?i.opacity:1,pF(n)),e.opacityExit=uG(void 0!==t.opacity?t.opacity:1,0,pV(n))):s&&(e.opacity=uG(void 0!==t.opacity?t.opacity:1,void 0!==i.opacity?i.opacity:1,n));for(let r=0;r<pN;r++){let s=`border${p_[r]}Radius`,o=pU(t,s),a=pU(i,s);(void 0!==o||void 0!==a)&&(o||(o=0),a||(a=0),0===o||0===a||pj(o)===pj(a)?(e[s]=Math.max(uG(pL(o),pL(a),n),0),(d3.test(a)||d3.test(o))&&(e[s]+="%")):e[s]=a)}(t.rotate||i.rotate)&&(e.rotate=uG(t.rotate||0,i.rotate||0,n))}(s,r,this.latestValues,n,u,d)),this.root.scheduleUpdateProjection(),this.scheduleRender(),this.animationProgress=n},this.mixTargetDelta(this.options.layoutRoot?1e3:0)}startAnimation(e){this.notifyListeners("animationStart"),this.currentAnimation&&this.currentAnimation.stop(),this.resumingFrom&&this.resumingFrom.currentAnimation&&this.resumingFrom.currentAnimation.stop(),this.pendingAnimation&&(dp(this.pendingAnimation),this.pendingAnimation=void 0),this.pendingAnimation=dh.update(()=>{pS.hasAnimatedSinceResize=!0,this.currentAnimation=function(e,t,i){let n=dE(0)?0:dw(0);return n.start(hx("",n,1e3,i)),n.animation}(0,0,{...e,onUpdate:t=>{this.mixTargetDelta(t),e.onUpdate&&e.onUpdate(t)},onComplete:()=>{e.onComplete&&e.onComplete(),this.completeAnimation()}}),this.resumingFrom&&(this.resumingFrom.currentAnimation=this.currentAnimation),this.pendingAnimation=void 0})}completeAnimation(){this.resumingFrom&&(this.resumingFrom.currentAnimation=void 0,this.resumingFrom.preserveOpacity=void 0);let e=this.getStack();e&&e.exitAnimationComplete(),this.resumingFrom=this.currentAnimation=this.animationValues=void 0,this.notifyListeners("animationComplete")}finishAnimation(){this.currentAnimation&&(this.mixTargetDelta&&this.mixTargetDelta(1e3),this.currentAnimation.stop()),this.completeAnimation()}applyTransformsToTarget(){let e=this.getLead(),{targetWithTransforms:t,target:i,layout:n,latestValues:r}=e;if(t&&i&&n){if(this!==e&&this.layout&&n&&mT(this.options.animationType,this.layout.layoutBox,n.layoutBox)){i=this.target||pe();let t=hY(this.layout.layoutBox.x);i.x.min=e.target.x.min,i.x.max=i.x.min+t;let n=hY(this.layout.layoutBox.y);i.y.min=e.target.y.min,i.y.max=i.y.min+n}pW(t,i),ph(t,r),hZ(this.projectionDeltaWithTransform,this.layoutCorrected,t,r)}}registerSharedNode(e,t){this.sharedNodes.has(e)||this.sharedNodes.set(e,new p3),this.sharedNodes.get(e).add(t);let i=t.options.initialPromotionConfig;t.promote({transition:i?i.transition:void 0,preserveFollowOpacity:i&&i.shouldPreserveFollowOpacity?i.shouldPreserveFollowOpacity(t):void 0})}isLead(){let e=this.getStack();return!e||e.lead===this}getLead(){var e;let{layoutId:t}=this.options;return t&&(null===(e=this.getStack())||void 0===e?void 0:e.lead)||this}getPrevLead(){var e;let{layoutId:t}=this.options;return t?null===(e=this.getStack())||void 0===e?void 0:e.prevLead:void 0}getStack(){let{layoutId:e}=this.options;if(e)return this.root.sharedNodes.get(e)}promote({needsReset:e,transition:t,preserveFollowOpacity:i}={}){let n=this.getStack();n&&n.promote(this,i),e&&(this.projectionDelta=void 0,this.needsReset=!0),t&&this.setOptions({transition:t})}relegate(){let e=this.getStack();return!!e&&e.relegate(this)}resetSkewAndRotation(){let{visualElement:e}=this.options;if(!e)return;let t=!1,{latestValues:i}=e;if((i.z||i.rotate||i.rotateX||i.rotateY||i.rotateZ||i.skewX||i.skewY)&&(t=!0),!t)return;let n={};i.z&&p7("z",e,n,this.animationValues);for(let t=0;t<p6.length;t++)p7(`rotate${p6[t]}`,e,n,this.animationValues),p7(`skew${p6[t]}`,e,n,this.animationValues);for(let t in e.render(),n)e.setStaticValue(t,n[t]),this.animationValues&&(this.animationValues[t]=n[t]);e.scheduleRender()}getProjectionStyles(e){var t,i;if(!this.instance||this.isSVG)return;if(!this.isVisible)return p9;let n={visibility:""},r=this.getTransformTemplate();if(this.needsReset)return this.needsReset=!1,n.opacity="",n.pointerEvents=pD(null==e?void 0:e.pointerEvents)||"",n.transform=r?r(this.latestValues,""):"none",n;let s=this.getLead();if(!this.projectionDelta||!this.layout||!s.target){let t={};return this.options.layoutId&&(t.opacity=void 0!==this.latestValues.opacity?this.latestValues.opacity:1,t.pointerEvents=pD(null==e?void 0:e.pointerEvents)||""),this.hasProjected&&!ps(this.latestValues)&&(t.transform=r?r({},""):"none",this.hasProjected=!1),t}let o=s.animationValues||s.latestValues;this.applyTransformsToTarget(),n.transform=function(e,t,i){let n="",r=e.x.translate/t.x,s=e.y.translate/t.y,o=(null==i?void 0:i.z)||0;if((r||s||o)&&(n=`translate3d(${r}px, ${s}px, ${o}px) `),(1!==t.x||1!==t.y)&&(n+=`scale(${1/t.x}, ${1/t.y}) `),i){let{transformPerspective:e,rotate:t,rotateX:r,rotateY:s,skewX:o,skewY:a}=i;e&&(n=`perspective(${e}px) ${n}`),t&&(n+=`rotate(${t}deg) `),r&&(n+=`rotateX(${r}deg) `),s&&(n+=`rotateY(${s}deg) `),o&&(n+=`skewX(${o}deg) `),a&&(n+=`skewY(${a}deg) `)}let a=e.x.scale*t.x,l=e.y.scale*t.y;return(1!==a||1!==l)&&(n+=`scale(${a}, ${l})`),n||"none"}(this.projectionDeltaWithTransform,this.treeScale,o),r&&(n.transform=r(o,n.transform));let{x:a,y:l}=this.projectionDelta;for(let e in n.transformOrigin=`${100*a.origin}% ${100*l.origin}% 0`,s.animationValues?n.opacity=s===this?null!==(i=null!==(t=o.opacity)&&void 0!==t?t:this.latestValues.opacity)&&void 0!==i?i:1:this.preserveOpacity?this.latestValues.opacity:o.opacityExit:n.opacity=s===this?void 0!==o.opacity?o.opacity:"":void 0!==o.opacityExit?o.opacityExit:0,pE){if(void 0===o[e])continue;let{correct:t,applyTo:i}=pE[e],r="none"===n.transform?o[e]:t(o[e],s);if(i){let e=i.length;for(let t=0;t<e;t++)n[i[t]]=r}else n[e]=r}return this.options.layoutId&&(n.pointerEvents=s===this?pD(null==e?void 0:e.pointerEvents)||"":"none"),n}clearSnapshot(){this.resumeFrom=this.snapshot=void 0}resetTree(){this.root.nodes.forEach(e=>{var t;return null===(t=e.currentAnimation)||void 0===t?void 0:t.stop()}),this.root.nodes.forEach(mo),this.root.sharedNodes.clear()}}}function mt(e){e.updateLayout()}function mi(e){var t;let i=(null===(t=e.resumeFrom)||void 0===t?void 0:t.snapshot)||e.snapshot;if(e.isLead()&&e.layout&&i&&e.hasListeners("didUpdate")){let{layoutBox:t,measuredBox:n}=e.layout,{animationType:r}=e.options,s=i.source!==e.layout.source;"size"===r?pt(e=>{let n=s?i.measuredBox[e]:i.layoutBox[e],r=hY(n);n.min=t[e].min,n.max=n.min+r}):mT(r,i.layoutBox,t)&&pt(n=>{let r=s?i.measuredBox[n]:i.layoutBox[n],o=hY(t[n]);r.max=r.min+o,e.relativeTarget&&!e.currentAnimation&&(e.isProjectionDirty=!0,e.relativeTarget[n].max=e.relativeTarget[n].min+o)});let o=h8();hZ(o,t,i.layoutBox);let a=h8();s?hZ(a,e.applyTransform(n,!0),i.measuredBox):hZ(a,t,i.layoutBox);let l=!pY(o),c=!1;if(!e.resumeFrom){let n=e.getClosestProjectingParent();if(n&&!n.resumeFrom){let{snapshot:r,layout:s}=n;if(r&&s){let o=pe();h2(o,i.layoutBox,r.layoutBox);let a=pe();h2(a,t,s.layoutBox),p0(o,a)||(c=!0),n.options.layoutRoot&&(e.relativeTarget=a,e.relativeTargetOrigin=o,e.relativeParent=n)}}}e.notifyListeners("didUpdate",{layout:t,snapshot:i,delta:a,layoutDelta:o,hasLayoutChanged:l,hasRelativeTargetChanged:c})}else if(e.isLead()){let{onExitComplete:t}=e.options;t&&t()}e.options.transition=void 0}function mn(e){p4&&p5.totalNodes++,e.parent&&(e.isProjecting()||(e.isProjectionDirty=e.parent.isProjectionDirty),e.isSharedProjectionDirty||(e.isSharedProjectionDirty=!!(e.isProjectionDirty||e.parent.isProjectionDirty||e.parent.isSharedProjectionDirty)),e.isTransformDirty||(e.isTransformDirty=e.parent.isTransformDirty))}function mr(e){e.isProjectionDirty=e.isSharedProjectionDirty=e.isTransformDirty=!1}function ms(e){e.clearSnapshot()}function mo(e){e.clearMeasurements()}function ma(e){e.isLayoutDirty=!1}function ml(e){let{visualElement:t}=e.options;t&&t.getProps().onBeforeLayoutMeasure&&t.notify("BeforeLayoutMeasure"),e.resetTransform()}function mc(e){e.finishAnimation(),e.targetDelta=e.relativeTarget=e.target=void 0,e.isProjectionDirty=!0}function md(e){e.resolveTargetDelta()}function mu(e){e.calcProjection()}function mh(e){e.resetSkewAndRotation()}function mp(e){e.removeLeadSnapshot()}function mm(e,t,i){e.translate=uG(t.translate,0,i),e.scale=uG(t.scale,1,i),e.origin=t.origin,e.originPoint=t.originPoint}function mf(e,t,i,n){e.min=uG(t.min,i.min,n),e.max=uG(t.max,i.max,n)}function mg(e){return e.animationValues&&void 0!==e.animationValues.opacityExit}let mv={duration:.45,ease:[.4,0,.1,1]},my=e=>"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().includes(e),mb=my("applewebkit/")&&!my("chrome/")?Math.round:di;function mk(e){e.min=mb(e.min),e.max=mb(e.max)}function mT(e,t,i){return"position"===e||"preserve-aspect"===e&&!(.2>=Math.abs(p1(t)-p1(i)))}function mS(e){var t;return e!==e.root&&(null===(t=e.scroll)||void 0===t?void 0:t.wasRoot)}let mC=me({attachResizeListener:(e,t)=>hV(e,"resize",t),measureScroll:()=>({x:document.documentElement.scrollLeft||document.body.scrollLeft,y:document.documentElement.scrollTop||document.body.scrollTop}),checkIsScrollRoot:()=>!0}),mw={current:void 0},mE=me({measureScroll:e=>({x:e.scrollLeft,y:e.scrollTop}),defaultParent:()=>{if(!mw.current){let e=new mC({});e.mount(window),e.setOptions({layoutScroll:!0}),mw.current=e}return mw.current},resetTransform:(e,t)=>{e.style.transform=void 0!==t?t:"none"},checkIsScrollRoot:e=>"fixed"===window.getComputedStyle(e).position});function mP(e,t,i){let{props:n}=e;e.animationState&&n.whileHover&&e.animationState.setActive("whileHover","Start"===i);let r=n["onHover"+i];r&&dh.postRender(()=>r(t,hB(t)))}class mx extends hL{mount(){let{current:e}=this.node;e&&(this.unmount=function(e,t,i={}){let[n,r,s]=c0(e,i),o=c1(e=>{let{target:i}=e,n=t(e);if("function"!=typeof n||!i)return;let s=c1(e=>{n(e),i.removeEventListener("pointerleave",s)});i.addEventListener("pointerleave",s,r)});return n.forEach(e=>{e.addEventListener("pointerenter",o,r)}),s}(e,e=>(mP(this.node,e,"Start"),e=>mP(this.node,e,"End"))))}unmount(){}}class mR extends hL{constructor(){super(...arguments),this.isActive=!1}onFocus(){let e=!1;try{e=this.node.current.matches(":focus-visible")}catch(t){e=!0}e&&this.node.animationState&&(this.node.animationState.setActive("whileFocus",!0),this.isActive=!0)}onBlur(){this.isActive&&this.node.animationState&&(this.node.animationState.setActive("whileFocus",!1),this.isActive=!1)}mount(){this.unmount=u1(hV(this.node.current,"focus",()=>this.onFocus()),hV(this.node.current,"blur",()=>this.onBlur()))}unmount(){}}function mO(e,t,i){let{props:n}=e;e.animationState&&n.whileTap&&e.animationState.setActive("whileTap","Start"===i);let r=n["onTap"+("End"===i?"":i)];r&&dh.postRender(()=>r(t,hB(t)))}class mA extends hL{mount(){let{current:e}=this.node;e&&(this.unmount=function(e,t,i={}){let[n,r,s]=c0(e,i),o=e=>{let n=e.currentTarget;if(!c7(e)||c4.has(n))return;c4.add(n);let s=t(e),o=(e,t)=>{window.removeEventListener("pointerup",a),window.removeEventListener("pointercancel",l),c7(e)&&c4.has(n)&&(c4.delete(n),"function"==typeof s&&s(e,{success:t}))},a=e=>{o(e,i.useGlobalTarget||c2(n,e.target))},l=e=>{o(e,!1)};window.addEventListener("pointerup",a,r),window.addEventListener("pointercancel",l,r)};return n.forEach(e=>{c5.has(e.tagName)||-1!==e.tabIndex||null!==e.getAttribute("tabindex")||(e.tabIndex=0),(i.useGlobalTarget?window:e).addEventListener("pointerdown",o,r),e.addEventListener("focus",e=>c8(e,r),r)}),s}(e,e=>(mO(this.node,e,"Start"),(e,{success:t})=>mO(this.node,e,t?"End":"Cancel")),{useGlobalTarget:this.node.props.globalTapTarget}))}unmount(){}}let mI=new WeakMap,mM=new WeakMap,mD=e=>{let t=mI.get(e.target);t&&t(e)},m_=e=>{e.forEach(mD)},mN={some:0,all:1};class mL extends hL{constructor(){super(...arguments),this.hasEnteredView=!1,this.isInView=!1}startObserver(){this.unmount();let{viewport:e={}}=this.node.getProps(),{root:t,margin:i,amount:n="some",once:r}=e,s={root:t?t.current:void 0,rootMargin:i,threshold:"number"==typeof n?n:mN[n]};return function(e,t,i){let n=function({root:e,...t}){let i=e||document;mM.has(i)||mM.set(i,{});let n=mM.get(i),r=JSON.stringify(t);return n[r]||(n[r]=new IntersectionObserver(m_,{root:e,...t})),n[r]}(t);return mI.set(e,i),n.observe(e),()=>{mI.delete(e),n.unobserve(e)}}(this.node.current,s,e=>{let{isIntersecting:t}=e;if(this.isInView===t||(this.isInView=t,r&&!t&&this.hasEnteredView))return;t&&(this.hasEnteredView=!0),this.node.animationState&&this.node.animationState.setActive("whileInView",t);let{onViewportEnter:i,onViewportLeave:n}=this.node.getProps(),s=t?i:n;s&&s(e)})}mount(){this.startObserver()}update(){if("undefined"==typeof IntersectionObserver)return;let{props:e,prevProps:t}=this.node;["amount","margin","root"].some(function({viewport:e={}},{viewport:t={}}={}){return i=>e[i]!==t[i]}(e,t))&&this.startObserver()}unmount(){}}let mj=(0,p.createContext)({strict:!1}),mU=(0,p.createContext)({});function mF(e){return cO(e.animate)||cj.some(t=>cM(e[t]))}function mV(e){return!!(mF(e)||e.variants)}function mB(e){return Array.isArray(e)?e.join(" "):e}let mq={animation:["animate","variants","whileHover","whileTap","exit","whileInView","whileFocus","whileDrag"],exit:["exit"],drag:["drag","dragControls"],focus:["whileFocus"],hover:["whileHover","onHoverStart","onHoverEnd"],tap:["whileTap","onTap","onTapStart","onTapCancel"],pan:["onPan","onPanStart","onPanSessionStart","onPanEnd"],inView:["whileInView","onViewportEnter","onViewportLeave"],layout:["layout","layoutId"]},mW={};for(let e in mq)mW[e]={isEnabled:t=>mq[e].some(e=>!!t[e])};let mz=Symbol.for("motionComponentSymbol"),mH=["animate","circle","defs","desc","ellipse","g","image","line","filter","marker","mask","metadata","path","pattern","polygon","polyline","rect","stop","switch","symbol","svg","text","tspan","use","view"];function mG(e){if("string"!=typeof e||e.includes("-"));else if(mH.indexOf(e)>-1||/[A-Z]/u.test(e))return!0;return!1}let m$=e=>(t,i)=>{let n=(0,p.useContext)(mU),r=(0,p.useContext)(cv),s=()=>(function({scrapeMotionValuesFromProps:e,createRenderState:t,onUpdate:i},n,r,s){let o={latestValues:function(e,t,i,n){let r={},s=n(e,{});for(let e in s)r[e]=pD(s[e]);let{initial:o,animate:a}=e,l=mF(e),c=mV(e);t&&c&&!l&&!1!==e.inherit&&(void 0===o&&(o=t.initial),void 0===a&&(a=t.animate));let d=!!i&&!1===i.initial,u=(d=d||!1===o)?a:o;if(u&&"boolean"!=typeof u&&!cO(u)){let t=Array.isArray(u)?u:[u];for(let i=0;i<t.length;i++){let n=c_(e,t[i]);if(n){let{transitionEnd:e,transition:t,...i}=n;for(let e in i){let t=i[e];if(Array.isArray(t)){let e=d?t.length-1:0;t=t[e]}null!==t&&(r[e]=t)}for(let t in e)r[t]=e[t]}}}return r}(n,r,s,e),renderState:t()};return i&&(o.onMount=e=>i({props:n,current:e,...o}),o.onUpdate=e=>i(e)),o})(e,t,n,r);return i?s():cg(s)},mK=(e,t)=>t&&"number"==typeof e?t.transform(e):e,mJ={x:"translateX",y:"translateY",z:"translateZ",transformPerspective:"perspective"},mX=dn.length;function mY(e,t,i){let{style:n,vars:r,transformOrigin:s}=e,o=!1,a=!1;for(let e in t){let i=t[e];if(dr.has(e)){o=!0;continue}if(uD(e)){r[e]=i;continue}{let t=mK(i,um[e]);e.startsWith("origin")?(a=!0,s[e]=t):n[e]=t}}if(!t.transform&&(o||i?n.transform=function(e,t,i){let n="",r=!0;for(let s=0;s<mX;s++){let o=dn[s],a=e[o];if(void 0===a)continue;let l=!0;if(!(l="number"==typeof a?a===(o.startsWith("scale")?1:0):0===parseFloat(a))||i){let e=mK(a,um[o]);if(!l){r=!1;let t=mJ[o]||o;n+=`${t}(${e}) `}i&&(t[o]=e)}}return n=n.trim(),i?n=i(t,r?"":n):r&&(n="none"),n}(t,e.transform,i):n.transform&&(n.transform="none")),a){let{originX:e="50%",originY:t="50%",originZ:i=0}=s;n.transformOrigin=`${e} ${t} ${i}`}}let mQ={offset:"stroke-dashoffset",array:"stroke-dasharray"},mZ={offset:"strokeDashoffset",array:"strokeDasharray"};function m0(e,t,i){return"string"==typeof e?e:d5.transform(t+i*e)}function m1(e,{attrX:t,attrY:i,attrScale:n,originX:r,originY:s,pathLength:o,pathSpacing:a=1,pathOffset:l=0,...c},d,u){if(mY(e,c,u),d){e.style.viewBox&&(e.attrs.viewBox=e.style.viewBox);return}e.attrs=e.style,e.style={};let{attrs:h,style:p,dimensions:m}=e;h.transform&&(m&&(p.transform=h.transform),delete h.transform),m&&(void 0!==r||void 0!==s||p.transform)&&(p.transformOrigin=function(e,t,i){let n=m0(t,e.x,e.width),r=m0(i,e.y,e.height);return`${n} ${r}`}(m,void 0!==r?r:.5,void 0!==s?s:.5)),void 0!==t&&(h.x=t),void 0!==i&&(h.y=i),void 0!==n&&(h.scale=n),void 0!==o&&function(e,t,i=1,n=0,r=!0){e.pathLength=1;let s=r?mQ:mZ;e[s.offset]=d5.transform(-n);let o=d5.transform(t),a=d5.transform(i);e[s.array]=`${o} ${a}`}(h,o,a,l,!1)}let m2=()=>({style:{},transform:{},transformOrigin:{},vars:{}}),m3=()=>({...m2(),attrs:{}}),m5=e=>"string"==typeof e&&"svg"===e.toLowerCase();function m4(e,{style:t,vars:i},n,r){for(let s in Object.assign(e.style,t,r&&r.getProjectionStyles(n)),i)e.style.setProperty(s,i[s])}let m6=new Set(["baseFrequency","diffuseConstant","kernelMatrix","kernelUnitLength","keySplines","keyTimes","limitingConeAngle","markerHeight","markerWidth","numOctaves","targetX","targetY","surfaceScale","specularConstant","specularExponent","stdDeviation","tableValues","viewBox","gradientTransform","pathLength","startOffset","textLength","lengthAdjust"]);function m9(e,t,i,n){for(let i in m4(e,t,void 0,n),t.attrs)e.setAttribute(m6.has(i)?i:dx(i),t.attrs[i])}function m8(e,{layout:t,layoutId:i}){return dr.has(e)||e.startsWith("origin")||(t||void 0!==i)&&(!!pE[e]||"opacity"===e)}function m7(e,t,i){var n;let{style:r}=e,s={};for(let o in r)(dE(r[o])||t.style&&dE(t.style[o])||m8(o,e)||(null===(n=null==i?void 0:i.getValue(o))||void 0===n?void 0:n.liveStyle)!==void 0)&&(s[o]=r[o]);return s}function fe(e,t,i){let n=m7(e,t,i);for(let i in e)(dE(e[i])||dE(t[i]))&&(n[-1!==dn.indexOf(i)?"attr"+i.charAt(0).toUpperCase()+i.substring(1):i]=e[i]);return n}let ft=["x","y","width","height","cx","cy","r"],fi={useVisualState:m$({scrapeMotionValuesFromProps:fe,createRenderState:m3,onUpdate:({props:e,prevProps:t,current:i,renderState:n,latestValues:r})=>{if(!i)return;let s=!!e.drag;if(!s){for(let e in r)if(dr.has(e)){s=!0;break}}if(!s)return;let o=!t;if(t)for(let i=0;i<ft.length;i++){let n=ft[i];e[n]!==t[n]&&(o=!0)}o&&dh.read(()=>{(function(e,t){try{t.dimensions="function"==typeof e.getBBox?e.getBBox():e.getBoundingClientRect()}catch(e){t.dimensions={x:0,y:0,width:0,height:0}}})(i,n),dh.render(()=>{m1(n,r,m5(i.tagName),e.transformTemplate),m9(i,n)})})}})},fn={useVisualState:m$({scrapeMotionValuesFromProps:m7,createRenderState:m2})};function fr(e,t,i){for(let n in t)dE(t[n])||m8(n,i)||(e[n]=t[n])}let fs=new Set(["animate","exit","variants","initial","style","values","variants","transition","transformTemplate","custom","inherit","onBeforeLayoutMeasure","onAnimationStart","onAnimationComplete","onUpdate","onDragStart","onDrag","onDragEnd","onMeasureDragConstraints","onDirectionLock","onDragTransitionEnd","_dragX","_dragY","onHoverStart","onHoverEnd","onViewportEnter","onViewportLeave","globalTapTarget","ignoreStrict","viewport"]);function fo(e){return e.startsWith("while")||e.startsWith("drag")&&"draggable"!==e||e.startsWith("layout")||e.startsWith("onTap")||e.startsWith("onPan")||e.startsWith("onLayout")||fs.has(e)}let fa=e=>!fo(e);try{!function(e){e&&(fa=t=>t.startsWith("on")?!fo(t):e(t))}(require("@emotion/is-prop-valid").default)}catch(e){}let fl={current:null},fc={current:!1},fd=[...uF,d7,ul],fu=e=>fd.find(uU(e)),fh=new WeakMap,fp=["AnimationStart","AnimationComplete","Update","BeforeLayoutMeasure","LayoutMeasure","LayoutAnimationStart","LayoutAnimationComplete"];class fm{scrapeMotionValuesFromProps(e,t,i){return{}}constructor({parent:e,props:t,presenceContext:i,reducedMotionConfig:n,blockInitialAnimation:r,visualState:s},o={}){this.current=null,this.children=new Set,this.isVariantNode=!1,this.isControllingVariants=!1,this.shouldReduceMotion=null,this.values=new Map,this.KeyframeResolver=uA,this.features={},this.valueSubscriptions=new Map,this.prevMotionValues={},this.events={},this.propEventSubscriptions={},this.notifyUpdate=()=>this.notify("Update",this.latestValues),this.render=()=>{this.current&&(this.triggerBuild(),this.renderInstance(this.current,this.renderState,this.props.style,this.projection))},this.renderScheduledAt=0,this.scheduleRender=()=>{let e=dv.now();this.renderScheduledAt<e&&(this.renderScheduledAt=e,dh.render(this.render,!1,!0))};let{latestValues:a,renderState:l,onUpdate:c}=s;this.onUpdate=c,this.latestValues=a,this.baseTarget={...a},this.initialValues=t.initial?{...a}:{},this.renderState=l,this.parent=e,this.props=t,this.presenceContext=i,this.depth=e?e.depth+1:0,this.reducedMotionConfig=n,this.options=o,this.blockInitialAnimation=!!r,this.isControllingVariants=mF(t),this.isVariantNode=mV(t),this.isVariantNode&&(this.variantChildren=new Set),this.manuallyAnimateOnMount=!!(e&&e.current);let{willChange:d,...u}=this.scrapeMotionValuesFromProps(t,{},this);for(let e in u){let t=u[e];void 0!==a[e]&&dE(t)&&t.set(a[e],!1)}}mount(e){this.current=e,fh.set(e,this),this.projection&&!this.projection.instance&&this.projection.mount(e),this.parent&&this.isVariantNode&&!this.isControllingVariants&&(this.removeFromVariantTree=this.parent.addVariantChild(this)),this.values.forEach((e,t)=>this.bindToMotionValue(t,e)),fc.current||function(){if(fc.current=!0,cP){if(window.matchMedia){let e=window.matchMedia("(prefers-reduced-motion)"),t=()=>fl.current=e.matches;e.addListener(t),t()}else fl.current=!1}}(),this.shouldReduceMotion="never"!==this.reducedMotionConfig&&("always"===this.reducedMotionConfig||fl.current),this.parent&&this.parent.children.add(this),this.update(this.props,this.presenceContext)}unmount(){for(let e in fh.delete(this.current),this.projection&&this.projection.unmount(),dp(this.notifyUpdate),dp(this.render),this.valueSubscriptions.forEach(e=>e()),this.valueSubscriptions.clear(),this.removeFromVariantTree&&this.removeFromVariantTree(),this.parent&&this.parent.children.delete(this),this.events)this.events[e].clear();for(let e in this.features){let t=this.features[e];t&&(t.unmount(),t.isMounted=!1)}this.current=null}bindToMotionValue(e,t){let i;this.valueSubscriptions.has(e)&&this.valueSubscriptions.get(e)();let n=dr.has(e),r=t.on("change",t=>{this.latestValues[e]=t,this.props.onUpdate&&dh.preRender(this.notifyUpdate),n&&this.projection&&(this.projection.isTransformDirty=!0)}),s=t.on("renderRequest",this.scheduleRender);window.MotionCheckAppearSync&&(i=window.MotionCheckAppearSync(this,e,t)),this.valueSubscriptions.set(e,()=>{r(),s(),i&&i(),t.owner&&t.stop()})}sortNodePosition(e){return this.current&&this.sortInstanceNodePosition&&this.type===e.type?this.sortInstanceNodePosition(this.current,e.current):0}updateFeatures(){let e="animation";for(e in mW){let t=mW[e];if(!t)continue;let{isEnabled:i,Feature:n}=t;if(!this.features[e]&&n&&i(this.props)&&(this.features[e]=new n(this)),this.features[e]){let t=this.features[e];t.isMounted?t.update():(t.mount(),t.isMounted=!0)}}}triggerBuild(){this.build(this.renderState,this.latestValues,this.props)}measureViewportBox(){return this.current?this.measureInstanceViewportBox(this.current,this.props):pe()}getStaticValue(e){return this.latestValues[e]}setStaticValue(e,t){this.latestValues[e]=t}update(e,t){(e.transformTemplate||this.props.transformTemplate)&&this.scheduleRender(),this.prevProps=this.props,this.props=e,this.prevPresenceContext=this.presenceContext,this.presenceContext=t;for(let t=0;t<fp.length;t++){let i=fp[t];this.propEventSubscriptions[i]&&(this.propEventSubscriptions[i](),delete this.propEventSubscriptions[i]);let n=e["on"+i];n&&(this.propEventSubscriptions[i]=this.on(i,n))}this.prevMotionValues=function(e,t,i){for(let n in t){let r=t[n],s=i[n];if(dE(r))e.addValue(n,r);else if(dE(s))e.addValue(n,dw(r,{owner:e}));else if(s!==r){if(e.hasValue(n)){let t=e.getValue(n);!0===t.liveStyle?t.jump(r):t.hasAnimated||t.set(r)}else{let t=e.getStaticValue(n);e.addValue(n,dw(void 0!==t?t:r,{owner:e}))}}}for(let n in i)void 0===t[n]&&e.removeValue(n);return t}(this,this.scrapeMotionValuesFromProps(e,this.prevProps,this),this.prevMotionValues),this.handleChildMotionValue&&this.handleChildMotionValue(),this.onUpdate&&this.onUpdate(this)}getProps(){return this.props}getVariant(e){return this.props.variants?this.props.variants[e]:void 0}getDefaultTransition(){return this.props.transition}getTransformPagePoint(){return this.props.transformPagePoint}getClosestVariantNode(){return this.isVariantNode?this:this.parent?this.parent.getClosestVariantNode():void 0}addVariantChild(e){let t=this.getClosestVariantNode();if(t)return t.variantChildren&&t.variantChildren.add(e),()=>t.variantChildren.delete(e)}addValue(e,t){let i=this.values.get(e);t!==i&&(i&&this.removeValue(e),this.bindToMotionValue(e,t),this.values.set(e,t),this.latestValues[e]=t.get())}removeValue(e){this.values.delete(e);let t=this.valueSubscriptions.get(e);t&&(t(),this.valueSubscriptions.delete(e)),delete this.latestValues[e],this.removeValueFromRenderState(e,this.renderState)}hasValue(e){return this.values.has(e)}getValue(e,t){if(this.props.values&&this.props.values[e])return this.props.values[e];let i=this.values.get(e);return void 0===i&&void 0!==t&&(i=dw(null===t?void 0:t,{owner:this}),this.addValue(e,i)),i}readValue(e,t){var i;let n=void 0===this.latestValues[e]&&this.current?null!==(i=this.getBaseTargetFromProps(this.props,e))&&void 0!==i?i:this.readValueFromInstance(this.current,e,this.options):this.latestValues[e];return null!=n&&("string"==typeof n&&(uI(n)||dB(n))?n=parseFloat(n):!fu(n)&&ul.test(t)&&(n=uv(e,t)),this.setBaseTarget(e,dE(n)?n.get():n)),dE(n)?n.get():n}setBaseTarget(e,t){this.baseTarget[e]=t}getBaseTarget(e){var t;let i;let{initial:n}=this.props;if("string"==typeof n||"object"==typeof n){let r=c_(this.props,n,null===(t=this.presenceContext)||void 0===t?void 0:t.custom);r&&(i=r[e])}if(n&&void 0!==i)return i;let r=this.getBaseTargetFromProps(this.props,e);return void 0===r||dE(r)?void 0!==this.initialValues[e]&&void 0===i?void 0:this.baseTarget[e]:r}on(e,t){return this.events[e]||(this.events[e]=new dk),this.events[e].add(t)}notify(e,...t){this.events[e]&&this.events[e].notify(...t)}}class ff extends fm{constructor(){super(...arguments),this.KeyframeResolver=uB}sortInstanceNodePosition(e,t){return 2&e.compareDocumentPosition(t)?1:-1}getBaseTargetFromProps(e,t){return e.style?e.style[t]:void 0}removeValueFromRenderState(e,{vars:t,style:i}){delete t[e],delete i[e]}handleChildMotionValue(){this.childSubscription&&(this.childSubscription(),delete this.childSubscription);let{children:e}=this.props;dE(e)&&(this.childSubscription=e.on("change",e=>{this.current&&(this.current.textContent=`${e}`)}))}}class fg extends ff{constructor(){super(...arguments),this.type="html",this.renderInstance=m4}readValueFromInstance(e,t){if(dr.has(t)){let e=ug(t);return e&&e.default||0}{let i=window.getComputedStyle(e),n=(uD(t)?i.getPropertyValue(t):i[t])||0;return"string"==typeof n?n.trim():n}}measureInstanceViewportBox(e,{transformPagePoint:t}){return pp(e,t)}build(e,t,i){mY(e,t,i.transformTemplate)}scrapeMotionValuesFromProps(e,t,i){return m7(e,t,i)}}class fv extends ff{constructor(){super(...arguments),this.type="svg",this.isSVGTag=!1,this.measureInstanceViewportBox=pe}getBaseTargetFromProps(e,t){return e[t]}readValueFromInstance(e,t){if(dr.has(t)){let e=ug(t);return e&&e.default||0}return t=m6.has(t)?t:dx(t),e.getAttribute(t)}scrapeMotionValuesFromProps(e,t,i){return fe(e,t,i)}build(e,t,i){m1(e,t,this.isSVGTag,i.transformTemplate)}renderInstance(e,t,i,n){m9(e,t,i,n)}mount(e){this.isSVGTag=m5(e.tagName),super.mount(e)}}let fy=function(e){if("undefined"==typeof Proxy)return e;let t=new Map;return new Proxy((...t)=>e(...t),{get:(i,n)=>"create"===n?e:(t.has(n)||t.set(n,e(n)),t.get(n))})}((a={animation:{Feature:hj},exit:{Feature:hF},inView:{Feature:mL},tap:{Feature:mA},focus:{Feature:mR},hover:{Feature:mx},pan:{Feature:pk},drag:{Feature:py,ProjectionNode:mE,MeasureLayout:pO},layout:{ProjectionNode:mE,MeasureLayout:pO}},l=(e,t)=>mG(e)?new fv(t):new fg(t,{allowProjection:e!==p.Fragment}),function(e,{forwardMotionProps:t}={forwardMotionProps:!1}){return function({preloadedFeatures:e,createVisualElement:t,useRender:i,useVisualState:n,Component:r}){var s,o;function a(e,s){var o;let a;let l={...(0,p.useContext)(cy),...e,layoutId:function({layoutId:e}){let t=(0,p.useContext)(cf).id;return t&&void 0!==e?t+"-"+e:e}(e)},{isStatic:c}=l,d=function(e){let{initial:t,animate:i}=function(e,t){if(mF(e)){let{initial:t,animate:i}=e;return{initial:!1===t||cM(t)?t:void 0,animate:cM(i)?i:void 0}}return!1!==e.inherit?t:{}}(e,(0,p.useContext)(mU));return(0,p.useMemo)(()=>({initial:t,animate:i}),[mB(t),mB(i)])}(e),h=n(e,c);if(!c&&cP){(0,p.useContext)(mj).strict;let e=function(e){let{drag:t,layout:i}=mW;if(!t&&!i)return{};let n={...t,...i};return{MeasureLayout:(null==t?void 0:t.isEnabled(e))||(null==i?void 0:i.isEnabled(e))?n.MeasureLayout:void 0,ProjectionNode:n.ProjectionNode}}(l);a=e.MeasureLayout,d.visualElement=function(e,t,i,n,r){var s,o;let{visualElement:a}=(0,p.useContext)(mU),l=(0,p.useContext)(mj),c=(0,p.useContext)(cv),d=(0,p.useContext)(cy).reducedMotion,u=(0,p.useRef)(null);n=n||l.renderer,!u.current&&n&&(u.current=n(e,{visualState:t,parent:a,props:i,presenceContext:c,blockInitialAnimation:!!c&&!1===c.initial,reducedMotionConfig:d}));let h=u.current,m=(0,p.useContext)(pT);h&&!h.projection&&r&&("html"===h.type||"svg"===h.type)&&function(e,t,i,n){let{layoutId:r,layout:s,drag:o,dragConstraints:a,layoutScroll:l,layoutRoot:c}=t;e.projection=new i(e.latestValues,t["data-framer-portal-id"]?void 0:function e(t){if(t)return!1!==t.options.allowProjection?t.projection:e(t.parent)}(e.parent)),e.projection.setOptions({layoutId:r,layout:s,alwaysMeasureLayout:!!o||a&&hX(a),visualElement:e,animationType:"string"==typeof s?s:"both",initialPromotionConfig:n,layoutScroll:l,layoutRoot:c})}(u.current,i,r,m);let f=(0,p.useRef)(!1);(0,p.useInsertionEffect)(()=>{h&&f.current&&h.update(i,c)});let g=i[dR],v=(0,p.useRef)(!!g&&!(null===(s=window.MotionHandoffIsComplete)||void 0===s?void 0:s.call(window,g))&&(null===(o=window.MotionHasOptimisedAnimation)||void 0===o?void 0:o.call(window,g)));return cx(()=>{h&&(f.current=!0,window.MotionIsMounted=!0,h.updateFeatures(),pP.render(h.render),v.current&&h.animationState&&h.animationState.animateChanges())}),(0,p.useEffect)(()=>{h&&(!v.current&&h.animationState&&h.animationState.animateChanges(),v.current&&(queueMicrotask(()=>{var e;null===(e=window.MotionHandoffMarkAsComplete)||void 0===e||e.call(window,g)}),v.current=!1))}),h}(r,h,l,t,e.ProjectionNode)}return(0,u.jsxs)(mU.Provider,{value:d,children:[a&&d.visualElement?(0,u.jsx)(a,{visualElement:d.visualElement,...l}):null,i(r,e,(o=d.visualElement,(0,p.useCallback)(e=>{e&&h.onMount&&h.onMount(e),o&&(e?o.mount(e):o.unmount()),s&&("function"==typeof s?s(e):hX(s)&&(s.current=e))},[o])),h,c,d.visualElement)]})}e&&function(e){for(let t in e)mW[t]={...mW[t],...e[t]}}(e),a.displayName=`motion.${"string"==typeof r?r:`create(${null!==(o=null!==(s=r.displayName)&&void 0!==s?s:r.name)&&void 0!==o?o:""})`}`;let l=(0,p.forwardRef)(a);return l[mz]=r,l}({...mG(e)?fi:fn,preloadedFeatures:a,useRender:function(e=!1){return(t,i,n,{latestValues:r},s)=>{let o=(mG(t)?function(e,t,i,n){let r=(0,p.useMemo)(()=>{let i=m3();return m1(i,t,m5(n),e.transformTemplate),{...i.attrs,style:{...i.style}}},[t]);if(e.style){let t={};fr(t,e.style,e),r.style={...t,...r.style}}return r}:function(e,t){let i={},n=function(e,t){let i=e.style||{},n={};return fr(n,i,e),Object.assign(n,function({transformTemplate:e},t){return(0,p.useMemo)(()=>{let i=m2();return mY(i,t,e),Object.assign({},i.vars,i.style)},[t])}(e,t)),n}(e,t);return e.drag&&!1!==e.dragListener&&(i.draggable=!1,n.userSelect=n.WebkitUserSelect=n.WebkitTouchCallout="none",n.touchAction=!0===e.drag?"none":`pan-${"x"===e.drag?"y":"x"}`),void 0===e.tabIndex&&(e.onTap||e.onTapStart||e.whileTap)&&(i.tabIndex=0),i.style=n,i})(i,r,s,t),a=function(e,t,i){let n={};for(let r in e)("values"!==r||"object"!=typeof e.values)&&(fa(r)||!0===i&&fo(r)||!t&&!fo(r)||e.draggable&&r.startsWith("onDrag"))&&(n[r]=e[r]);return n}(i,"string"==typeof t,e),l=t!==p.Fragment?{...a,...o,ref:n}:{},{children:c}=i,d=(0,p.useMemo)(()=>dE(c)?c.get():c,[c]);return(0,p.createElement)(t,{...l,children:d})}}(t),createVisualElement:l,Component:e})}));function fb(){let[e]=(0,p.useState)(new sj),[t,i]=(0,p.useState)(""),[n,r]=(0,p.useState)(""),s=(0,p.useCallback)(async()=>{r("");let i=new URL(process.env.NEXT_PUBLIC_CONN_DETAILS_ENDPOINT??"/api/connection-details",window.location.origin);i.searchParams.set("password",t);let n=await fetch(i.toString());if(!n.ok){401===n.status?r("Invalid password"):r("Connection failed");return}let s=await n.json();await e.connect(s.serverUrl,s.participantToken),await e.localParticipant.setMicrophoneEnabled(!0)},[e,t]);return u.jsx("main",{"data-lk-theme":"default",className:"h-full grid content-center bg-[var(--lk-bg)]",children:u.jsx(lL.Provider,{value:e,children:u.jsx("div",{className:"lk-room-container max-w-[1024px] w-[90vw] mx-auto max-h-[90vh]",children:u.jsx(fk,{onConnectButtonClicked:s,password:t,setPassword:i,error:n})})})})}function fk(e){let{state:t}=l0();return u.jsx(u.Fragment,{children:u.jsx(cR,{mode:"wait",children:"disconnected"===t?u.jsx(fy.div,{initial:{opacity:0,scale:.95},animate:{opacity:1,scale:1},exit:{opacity:0,scale:.95},transition:{duration:.3,ease:[.09,1.04,.245,1.055]},className:"grid items-center justify-center h-full",children:(0,u.jsxs)("div",{className:"flex flex-col items-center gap-4",children:[u.jsx("input",{type:"password",placeholder:"Enter password",value:e.password,onChange:t=>e.setPassword(t.target.value),onKeyPress:t=>{"Enter"===t.key&&e.onConnectButtonClicked()},className:"px-4 py-2 bg-gray-800 text-white rounded-md focus:outline-none focus:ring-2 focus:ring-white"}),e.error&&u.jsx("p",{className:"text-red-500 text-sm",children:e.error}),u.jsx(fy.button,{initial:{opacity:0},animate:{opacity:1},transition:{duration:.3,delay:.1},className:"uppercase px-4 py-2 bg-white text-black rounded-md",onClick:()=>e.onConnectButtonClicked(),children:"Start a conversation"})]})},"disconnected"):(0,u.jsxs)(fy.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},exit:{opacity:0,y:-20},transition:{duration:.3,ease:[.09,1.04,.245,1.055]},className:"flex flex-col items-center gap-4 h-full",children:[u.jsx(fT,{}),u.jsx("div",{className:"flex-1 w-full",children:u.jsx(l1,{})}),u.jsx("div",{className:"w-full",children:u.jsx(fS,{onConnectButtonClicked:e.onConnectButtonClicked})}),u.jsx(co,{}),u.jsx(m,{state:t})]},"connected")})})}function fT(){let{state:e,videoTrack:t,audioTrack:i}=l0();return t?u.jsx("div",{className:"h-[512px] w-[512px] rounded-lg overflow-hidden",children:u.jsx(cr,{trackRef:t})}):u.jsx("div",{className:"h-[300px] w-full",children:u.jsx(ch,{state:e,barCount:5,trackRef:i,className:"agent-visualizer",options:{minHeight:24}})})}function fS(e){let{state:t}=l0();return(0,u.jsxs)("div",{className:"relative h-[60px]",children:[u.jsx(cR,{children:"disconnected"===t&&u.jsx(fy.button,{initial:{opacity:0,top:0},animate:{opacity:1},exit:{opacity:0,top:"-10px"},transition:{duration:1,ease:[.09,1.04,.245,1.055]},className:"uppercase absolute left-1/2 -translate-x-1/2 px-4 py-2 bg-white text-black rounded-md",onClick:()=>e.onConnectButtonClicked(),children:"Start a conversation"})}),u.jsx(cR,{children:"disconnected"!==t&&"connecting"!==t&&(0,u.jsxs)(fy.div,{initial:{opacity:0,top:"10px"},animate:{opacity:1,top:0},exit:{opacity:0,top:"-10px"},transition:{duration:.4,ease:[.09,1.04,.245,1.055]},className:"flex h-8 absolute left-1/2 -translate-x-1/2 justify-center",children:[u.jsx(cm,{controls:{leave:!1}}),u.jsx(l2,{children:u.jsx(h,{})})]})})]})}},1506:(e,t,i)=>{"use strict";i.r(t),i.d(t,{default:()=>a,metadata:()=>o});var n=i(9510),r=i(2219),s=i.n(r);i(6078),i(7272);let o={title:"Voice Assistant"};function a({children:e}){return n.jsx("html",{lang:"en",className:`h-full ${s().className}`,children:n.jsx("body",{className:"h-full",children:e})})}},908:(e,t,i)=>{"use strict";i.r(t),i.d(t,{default:()=>n});let n=(0,i(8570).createProxy)(String.raw`/tmp/build-via-sdist-yrh8rni2/voice_mode-4.5.0/voice_mode/frontend/app/page.tsx#default`)},338:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var i in t)Object.defineProperty(e,i,{enumerable:!0,get:t[i]})}(t,{ACTION:function(){return n},FLIGHT_PARAMETERS:function(){return l},NEXT_DID_POSTPONE_HEADER:function(){return d},NEXT_ROUTER_PREFETCH_HEADER:function(){return s},NEXT_ROUTER_STATE_TREE:function(){return r},NEXT_RSC_UNION_QUERY:function(){return c},NEXT_URL:function(){return o},RSC_CONTENT_TYPE_HEADER:function(){return a},RSC_HEADER:function(){return i}});let i="RSC",n="Next-Action",r="Next-Router-State-Tree",s="Next-Router-Prefetch",o="Next-Url",a="text/x-component",l=[[i],[r],[s]],c="_rsc",d="x-nextjs-postponed";("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},7255:e=>{(()=>{"use strict";"undefined"!=typeof __nccwpck_require__&&(__nccwpck_require__.ab=__dirname+"/");var t={};(()=>{t.parse=function(t,i){if("string"!=typeof t)throw TypeError("argument str must be a string");for(var r={},s=t.split(n),o=(i||{}).decode||e,a=0;a<s.length;a++){var l=s[a],c=l.indexOf("=");if(!(c<0)){var d=l.substr(0,c).trim(),u=l.substr(++c,l.length).trim();'"'==u[0]&&(u=u.slice(1,-1)),void 0==r[d]&&(r[d]=function(e,t){try{return t(e)}catch(t){return e}}(u,o))}}return r},t.serialize=function(e,t,n){var s=n||{},o=s.encode||i;if("function"!=typeof o)throw TypeError("option encode is invalid");if(!r.test(e))throw TypeError("argument name is invalid");var a=o(t);if(a&&!r.test(a))throw TypeError("argument val is invalid");var l=e+"="+a;if(null!=s.maxAge){var c=s.maxAge-0;if(isNaN(c)||!isFinite(c))throw TypeError("option maxAge is invalid");l+="; Max-Age="+Math.floor(c)}if(s.domain){if(!r.test(s.domain))throw TypeError("option domain is invalid");l+="; Domain="+s.domain}if(s.path){if(!r.test(s.path))throw TypeError("option path is invalid");l+="; Path="+s.path}if(s.expires){if("function"!=typeof s.expires.toUTCString)throw TypeError("option expires is invalid");l+="; Expires="+s.expires.toUTCString()}if(s.httpOnly&&(l+="; HttpOnly"),s.secure&&(l+="; Secure"),s.sameSite)switch("string"==typeof s.sameSite?s.sameSite.toLowerCase():s.sameSite){case!0:case"strict":l+="; SameSite=Strict";break;case"lax":l+="; SameSite=Lax";break;case"none":l+="; SameSite=None";break;default:throw TypeError("option sameSite is invalid")}return l};var e=decodeURIComponent,i=encodeURIComponent,n=/; */,r=/^[\u0009\u0020-\u007e\u0080-\u00ff]+$/})(),e.exports=t})()},1792:(e,t)=>{"use strict";function i(e,t){void 0===t&&(t={});for(var i=function(e){for(var t=[],i=0;i<e.length;){var n=e[i];if("*"===n||"+"===n||"?"===n){t.push({type:"MODIFIER",index:i,value:e[i++]});continue}if("\\"===n){t.push({type:"ESCAPED_CHAR",index:i++,value:e[i++]});continue}if("{"===n){t.push({type:"OPEN",index:i,value:e[i++]});continue}if("}"===n){t.push({type:"CLOSE",index:i,value:e[i++]});continue}if(":"===n){for(var r="",s=i+1;s<e.length;){var o=e.charCodeAt(s);if(o>=48&&o<=57||o>=65&&o<=90||o>=97&&o<=122||95===o){r+=e[s++];continue}break}if(!r)throw TypeError("Missing parameter name at "+i);t.push({type:"NAME",index:i,value:r}),i=s;continue}if("("===n){var a=1,l="",s=i+1;if("?"===e[s])throw TypeError('Pattern cannot start with "?" at '+s);for(;s<e.length;){if("\\"===e[s]){l+=e[s++]+e[s++];continue}if(")"===e[s]){if(0==--a){s++;break}}else if("("===e[s]&&(a++,"?"!==e[s+1]))throw TypeError("Capturing groups are not allowed at "+s);l+=e[s++]}if(a)throw TypeError("Unbalanced pattern at "+i);if(!l)throw TypeError("Missing pattern at "+i);t.push({type:"PATTERN",index:i,value:l}),i=s;continue}t.push({type:"CHAR",index:i,value:e[i++]})}return t.push({type:"END",index:i,value:""}),t}(e),n=t.prefixes,r=void 0===n?"./":n,o="[^"+s(t.delimiter||"/#?")+"]+?",a=[],l=0,c=0,d="",u=function(e){if(c<i.length&&i[c].type===e)return i[c++].value},h=function(e){var t=u(e);if(void 0!==t)return t;var n=i[c];throw TypeError("Unexpected "+n.type+" at "+n.index+", expected "+e)},p=function(){for(var e,t="";e=u("CHAR")||u("ESCAPED_CHAR");)t+=e;return t};c<i.length;){var m=u("CHAR"),f=u("NAME"),g=u("PATTERN");if(f||g){var v=m||"";-1===r.indexOf(v)&&(d+=v,v=""),d&&(a.push(d),d=""),a.push({name:f||l++,prefix:v,suffix:"",pattern:g||o,modifier:u("MODIFIER")||""});continue}var y=m||u("ESCAPED_CHAR");if(y){d+=y;continue}if(d&&(a.push(d),d=""),u("OPEN")){var v=p(),b=u("NAME")||"",k=u("PATTERN")||"",T=p();h("CLOSE"),a.push({name:b||(k?l++:""),pattern:b&&!k?o:k,prefix:v,suffix:T,modifier:u("MODIFIER")||""});continue}h("END")}return a}function n(e,t){void 0===t&&(t={});var i=o(t),n=t.encode,r=void 0===n?function(e){return e}:n,s=t.validate,a=void 0===s||s,l=e.map(function(e){if("object"==typeof e)return RegExp("^(?:"+e.pattern+")$",i)});return function(t){for(var i="",n=0;n<e.length;n++){var s=e[n];if("string"==typeof s){i+=s;continue}var o=t?t[s.name]:void 0,c="?"===s.modifier||"*"===s.modifier,d="*"===s.modifier||"+"===s.modifier;if(Array.isArray(o)){if(!d)throw TypeError('Expected "'+s.name+'" to not repeat, but got an array');if(0===o.length){if(c)continue;throw TypeError('Expected "'+s.name+'" to not be empty')}for(var u=0;u<o.length;u++){var h=r(o[u],s);if(a&&!l[n].test(h))throw TypeError('Expected all "'+s.name+'" to match "'+s.pattern+'", but got "'+h+'"');i+=s.prefix+h+s.suffix}continue}if("string"==typeof o||"number"==typeof o){var h=r(String(o),s);if(a&&!l[n].test(h))throw TypeError('Expected "'+s.name+'" to match "'+s.pattern+'", but got "'+h+'"');i+=s.prefix+h+s.suffix;continue}if(!c){var p=d?"an array":"a string";throw TypeError('Expected "'+s.name+'" to be '+p)}}return i}}function r(e,t,i){void 0===i&&(i={});var n=i.decode,r=void 0===n?function(e){return e}:n;return function(i){var n=e.exec(i);if(!n)return!1;for(var s=n[0],o=n.index,a=Object.create(null),l=1;l<n.length;l++)!function(e){if(void 0!==n[e]){var i=t[e-1];"*"===i.modifier||"+"===i.modifier?a[i.name]=n[e].split(i.prefix+i.suffix).map(function(e){return r(e,i)}):a[i.name]=r(n[e],i)}}(l);return{path:s,index:o,params:a}}}function s(e){return e.replace(/([.+*?=^!:${}()[\]|/\\])/g,"\\$1")}function o(e){return e&&e.sensitive?"":"i"}function a(e,t,i){void 0===i&&(i={});for(var n=i.strict,r=void 0!==n&&n,a=i.start,l=i.end,c=i.encode,d=void 0===c?function(e){return e}:c,u="["+s(i.endsWith||"")+"]|$",h="["+s(i.delimiter||"/#?")+"]",p=void 0===a||a?"^":"",m=0;m<e.length;m++){var f=e[m];if("string"==typeof f)p+=s(d(f));else{var g=s(d(f.prefix)),v=s(d(f.suffix));if(f.pattern){if(t&&t.push(f),g||v){if("+"===f.modifier||"*"===f.modifier){var y="*"===f.modifier?"?":"";p+="(?:"+g+"((?:"+f.pattern+")(?:"+v+g+"(?:"+f.pattern+"))*)"+v+")"+y}else p+="(?:"+g+"("+f.pattern+")"+v+")"+f.modifier}else p+="("+f.pattern+")"+f.modifier}else p+="(?:"+g+v+")"+f.modifier}}if(void 0===l||l)r||(p+=h+"?"),p+=i.endsWith?"(?="+u+")":"$";else{var b=e[e.length-1],k="string"==typeof b?h.indexOf(b[b.length-1])>-1:void 0===b;r||(p+="(?:"+h+"(?="+u+"))?"),k||(p+="(?="+h+"|"+u+")")}return new RegExp(p,o(i))}function l(e,t,n){return e instanceof RegExp?function(e,t){if(!t)return e;var i=e.source.match(/\((?!\?)/g);if(i)for(var n=0;n<i.length;n++)t.push({name:n,prefix:"",suffix:"",modifier:"",pattern:""});return e}(e,t):Array.isArray(e)?RegExp("(?:"+e.map(function(e){return l(e,t,n).source}).join("|")+")",o(n)):a(i(e,n),t,n)}Object.defineProperty(t,"__esModule",{value:!0}),t.parse=i,t.compile=function(e,t){return n(i(e,t),t)},t.tokensToFunction=n,t.match=function(e,t){var i=[];return r(l(e,i,t),i,t)},t.regexpToFunction=r,t.tokensToRegexp=a,t.pathToRegexp=l},6621:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var i in t)Object.defineProperty(e,i,{enumerable:!0,get:t[i]})}(t,{fillMetadataSegment:function(){return u},normalizeMetadataRoute:function(){return h}});let n=i(616),r=function(e){return e&&e.__esModule?e:{default:e}}(i(1293)),s=i(7262),o=i(5679),a=i(8785),l=i(8168),c=i(1040);function d(e){let t="";return(e.includes("(")&&e.includes(")")||e.includes("@"))&&(t=(0,a.djb2Hash)(e).toString(36).slice(0,6)),t}function u(e,t,i){let n=(0,l.normalizeAppPath)(e),a=(0,o.getNamedRouteRegex)(n,!1),u=(0,s.interpolateDynamicPath)(n,t,a),h=d(e),p=h?`-${h}`:"",{name:m,ext:f}=r.default.parse(i);return(0,c.normalizePathSep)(r.default.join(u,`${m}${p}${f}`))}function h(e){if(!(0,n.isMetadataRoute)(e))return e;let t=e,i="";if("/robots"===e?t+=".txt":"/manifest"===e?t+=".webmanifest":e.endsWith("/sitemap")?t+=".xml":i=d(e.slice(0,-(r.default.basename(e).length+1))),!t.endsWith("/route")){let{dir:s,name:o,ext:a}=r.default.parse(t),l=(0,n.isStaticMetadataRoute)(e);t=r.default.posix.join(s,`${o}${i?`-${i}`:""}${a}`,l?"":"[[...__metadata_id__]]","route")}return t}},616:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var i in t)Object.defineProperty(e,i,{enumerable:!0,get:t[i]})}(t,{STATIC_METADATA_IMAGES:function(){return r},isMetadataRoute:function(){return d},isMetadataRouteFile:function(){return a},isStaticMetadataRoute:function(){return c},isStaticMetadataRouteFile:function(){return l}});let n=i(1040),r={icon:{filename:"icon",extensions:["ico","jpg","jpeg","png","svg"]},apple:{filename:"apple-icon",extensions:["jpg","jpeg","png"]},favicon:{filename:"favicon",extensions:["ico"]},openGraph:{filename:"opengraph-image",extensions:["jpg","jpeg","png","gif"]},twitter:{filename:"twitter-image",extensions:["jpg","jpeg","png","gif"]}},s=["js","jsx","ts","tsx"],o=e=>`(?:${e.join("|")})`;function a(e,t,i){let s=[RegExp(`^[\\\\/]robots${i?`\\.${o(t.concat("txt"))}$`:""}`),RegExp(`^[\\\\/]manifest${i?`\\.${o(t.concat("webmanifest","json"))}$`:""}`),RegExp("^[\\\\/]favicon\\.ico$"),RegExp(`[\\\\/]sitemap${i?`\\.${o(t.concat("xml"))}$`:""}`),RegExp(`[\\\\/]${r.icon.filename}\\d?${i?`\\.${o(t.concat(r.icon.extensions))}$`:""}`),RegExp(`[\\\\/]${r.apple.filename}\\d?${i?`\\.${o(t.concat(r.apple.extensions))}$`:""}`),RegExp(`[\\\\/]${r.openGraph.filename}\\d?${i?`\\.${o(t.concat(r.openGraph.extensions))}$`:""}`),RegExp(`[\\\\/]${r.twitter.filename}\\d?${i?`\\.${o(t.concat(r.twitter.extensions))}$`:""}`)],a=(0,n.normalizePathSep)(e);return s.some(e=>e.test(a))}function l(e){return a(e,[],!0)}function c(e){return"/robots"===e||"/manifest"===e||l(e)}function d(e){let t=e.replace(/^\/?app\//,"").replace(/\/route$/,"");return"/"!==t[0]&&(t="/"+t),!t.endsWith("/page")&&a(t,s,!1)}},6975:(e,t,i)=>{"use strict";function n(e){return function(){let{cookie:t}=e;if(!t)return{};let{parse:n}=i(7255);return n(Array.isArray(t)?t.join("; "):t)}}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"getCookieParser",{enumerable:!0,get:function(){return n}})},1586:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var i in t)Object.defineProperty(e,i,{enumerable:!0,get:t[i]})}(t,{INTERCEPTION_ROUTE_MARKERS:function(){return r},extractInterceptionRouteInformation:function(){return o},isInterceptionRouteAppPath:function(){return s}});let n=i(8168),r=["(..)(..)","(.)","(..)","(...)"];function s(e){return void 0!==e.split("/").find(e=>r.find(t=>e.startsWith(t)))}function o(e){let t,i,s;for(let n of e.split("/"))if(i=r.find(e=>n.startsWith(e))){[t,s]=e.split(i,2);break}if(!t||!i||!s)throw Error(`Invalid interception route: ${e}. Must be in the format /<intercepting route>/(..|...|..)(..)/<intercepted route>`);switch(t=(0,n.normalizeAppPath)(t),i){case"(.)":s="/"===t?`/${s}`:t+"/"+s;break;case"(..)":if("/"===t)throw Error(`Invalid interception route: ${e}. Cannot use (..) marker at the root level, use (.) instead.`);s=t.split("/").slice(0,-1).concat(s).join("/");break;case"(...)":s="/"+s;break;case"(..)(..)":let o=t.split("/");if(o.length<=2)throw Error(`Invalid interception route: ${e}. Cannot use (..)(..) marker at the root level or one level up.`);s=o.slice(0,-2).concat(s).join("/");break;default:throw Error("Invariant: unexpected marker")}return{interceptingRoute:t,interceptedRoute:s}}},7262:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var i in t)Object.defineProperty(e,i,{enumerable:!0,get:t[i]})}(t,{getUtils:function(){return f},interpolateDynamicPath:function(){return p},normalizeDynamicRouteParams:function(){return m},normalizeVercelUrl:function(){return h}});let n=i(7360),r=i(5014),s=i(3707),o=i(5679),a=i(3525),l=i(5257),c=i(7847),d=i(8168),u=i(1943);function h(e,t,i,r,s){if(r&&t&&s){let t=(0,n.parse)(e.url,!0);for(let e of(delete t.search,Object.keys(t.query))){let n=e!==u.NEXT_QUERY_PARAM_PREFIX&&e.startsWith(u.NEXT_QUERY_PARAM_PREFIX),r=e!==u.NEXT_INTERCEPTION_MARKER_PREFIX&&e.startsWith(u.NEXT_INTERCEPTION_MARKER_PREFIX);(n||r||(i||Object.keys(s.groups)).includes(e))&&delete t.query[e]}e.url=(0,n.format)(t)}}function p(e,t,i){if(!i)return e;for(let n of Object.keys(i.groups)){let{optional:r,repeat:s}=i.groups[n],o=`[${s?"...":""}${n}]`;r&&(o=`[${o}]`);let a=e.indexOf(o);if(a>-1){let i;let r=t[n];i=Array.isArray(r)?r.map(e=>e&&encodeURIComponent(e)).join("/"):r?encodeURIComponent(r):"",e=e.slice(0,a)+i+e.slice(a+o.length)}}return e}function m(e,t,i,n){let r=!0;return i?{params:e=Object.keys(i.groups).reduce((s,o)=>{let a=e[o];"string"==typeof a&&(a=(0,d.normalizeRscURL)(a)),Array.isArray(a)&&(a=a.map(e=>("string"==typeof e&&(e=(0,d.normalizeRscURL)(e)),e)));let l=n[o],c=i.groups[o].optional;return((Array.isArray(l)?l.some(e=>Array.isArray(a)?a.some(t=>t.includes(e)):null==a?void 0:a.includes(e)):null==a?void 0:a.includes(l))||void 0===a&&!(c&&t))&&(r=!1),c&&(!a||Array.isArray(a)&&1===a.length&&("index"===a[0]||a[0]===`[[...${o}]]`))&&(a=void 0,delete e[o]),a&&"string"==typeof a&&i.groups[o].repeat&&(a=a.split("/")),a&&(s[o]=a),s},{}),hasValidParams:r}:{params:e,hasValidParams:!1}}function f({page:e,i18n:t,basePath:i,rewrites:n,pageIsDynamic:d,trailingSlash:f,caseSensitive:g}){let v,y,b;return d&&(v=(0,o.getNamedRouteRegex)(e,!1),b=(y=(0,a.getRouteMatcher)(v))(e)),{handleRewrites:function(o,a){let u={},h=a.pathname,p=n=>{let c=(0,s.getPathMatch)(n.source+(f?"(/)?":""),{removeUnnamedParams:!0,strict:!0,sensitive:!!g})(a.pathname);if((n.has||n.missing)&&c){let e=(0,l.matchHas)(o,a.query,n.has,n.missing);e?Object.assign(c,e):c=!1}if(c){let{parsedDestination:s,destQuery:o}=(0,l.prepareDestination)({appendParamsToQuery:!0,destination:n.destination,params:c,query:a.query});if(s.protocol)return!0;if(Object.assign(u,o,c),Object.assign(a.query,s.query),delete s.query,Object.assign(a,s),h=a.pathname,i&&(h=h.replace(RegExp(`^${i}`),"")||"/"),t){let e=(0,r.normalizeLocalePath)(h,t.locales);h=e.pathname,a.query.nextInternalLocale=e.detectedLocale||c.nextInternalLocale}if(h===e)return!0;if(d&&y){let e=y(h);if(e)return a.query={...a.query,...e},!0}}return!1};for(let e of n.beforeFiles||[])p(e);if(h!==e){let t=!1;for(let e of n.afterFiles||[])if(t=p(e))break;if(!t&&!(()=>{let t=(0,c.removeTrailingSlash)(h||"");return t===(0,c.removeTrailingSlash)(e)||(null==y?void 0:y(t))})()){for(let e of n.fallback||[])if(t=p(e))break}}return u},defaultRouteRegex:v,dynamicRouteMatcher:y,defaultRouteMatches:b,getParamsFromRouteMatches:function(e,i,n){return(0,a.getRouteMatcher)(function(){let{groups:e,routeKeys:r}=v;return{re:{exec:s=>{let o=Object.fromEntries(new URLSearchParams(s)),a=t&&n&&o["1"]===n;for(let e of Object.keys(o)){let t=o[e];e!==u.NEXT_QUERY_PARAM_PREFIX&&e.startsWith(u.NEXT_QUERY_PARAM_PREFIX)&&(o[e.substring(u.NEXT_QUERY_PARAM_PREFIX.length)]=t,delete o[e])}let l=Object.keys(r||{}),c=e=>{if(t){let r=Array.isArray(e),s=r?e[0]:e;if("string"==typeof s&&t.locales.some(e=>e.toLowerCase()===s.toLowerCase()&&(n=e,i.locale=n,!0)))return r&&e.splice(0,1),!r||0===e.length}return!1};return l.every(e=>o[e])?l.reduce((t,i)=>{let n=null==r?void 0:r[i];return n&&!c(o[i])&&(t[e[n].pos]=o[i]),t},{}):Object.keys(o).reduce((e,t)=>{if(!c(o[t])){let i=t;return a&&(i=parseInt(t,10)-1+""),Object.assign(e,{[i]:o[t]})}return e},{})}},groups:e}}())(e.headers["x-now-route-matches"])},normalizeDynamicRouteParams:(e,t)=>m(e,t,v,b),normalizeVercelUrl:(e,t,i)=>h(e,t,i,d,v),interpolateDynamicPath:(e,t)=>p(e,t,v)}}},4080:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"escapeStringRegexp",{enumerable:!0,get:function(){return r}});let i=/[|\\{}()[\]^$+*?.-]/,n=/[|\\{}()[\]^$+*?.-]/g;function r(e){return i.test(e)?e.replace(n,"\\$&"):e}},8785:(e,t)=>{"use strict";function i(e){let t=5381;for(let i=0;i<e.length;i++)t=(t<<5)+t+e.charCodeAt(i)&4294967295;return t>>>0}function n(e){return i(e).toString(36).slice(0,5)}Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var i in t)Object.defineProperty(e,i,{enumerable:!0,get:t[i]})}(t,{djb2Hash:function(){return i},hexHash:function(){return n}})},5014:(e,t)=>{"use strict";function i(e,t){let i;let n=e.split("/");return(t||[]).some(t=>!!n[1]&&n[1].toLowerCase()===t.toLowerCase()&&(i=t,n.splice(1,1),e=n.join("/")||"/",!0)),{pathname:e,detectedLocale:i}}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"normalizeLocalePath",{enumerable:!0,get:function(){return i}})},1293:(e,t,i)=>{"use strict";let n;n=i(5315),e.exports=n},1555:(e,t)=>{"use strict";function i(e){return e.startsWith("/")?e:"/"+e}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"ensureLeadingSlash",{enumerable:!0,get:function(){return i}})},1040:(e,t)=>{"use strict";function i(e){return e.replace(/\\/g,"/")}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"normalizePathSep",{enumerable:!0,get:function(){return i}})},8168:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var i in t)Object.defineProperty(e,i,{enumerable:!0,get:t[i]})}(t,{normalizeAppPath:function(){return s},normalizeRscURL:function(){return o}});let n=i(1555),r=i(5406);function s(e){return(0,n.ensureLeadingSlash)(e.split("/").reduce((e,t,i,n)=>!t||(0,r.isGroupSegment)(t)||"@"===t[0]||("page"===t||"route"===t)&&i===n.length-1?e:e+"/"+t,""))}function o(e){return e.replace(/\.rsc($|\?)/,"$1")}},1942:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"parseRelativeUrl",{enumerable:!0,get:function(){return r}}),i(2569);let n=i(4869);function r(e,t){let i=new URL("http://n"),r=t?new URL(t,i):e.startsWith(".")?new URL("http://n"):i,{pathname:s,searchParams:o,search:a,hash:l,href:c,origin:d}=new URL(e,r);if(d!==i.origin)throw Error("invariant: invalid relative URL, router received "+e);return{pathname:s,query:(0,n.searchParamsToUrlQuery)(o),search:a,hash:l,href:c.slice(i.origin.length)}}},3226:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"parseUrl",{enumerable:!0,get:function(){return s}});let n=i(4869),r=i(1942);function s(e){if(e.startsWith("/"))return(0,r.parseRelativeUrl)(e);let t=new URL(e);return{hash:t.hash,hostname:t.hostname,href:t.href,pathname:t.pathname,port:t.port,protocol:t.protocol,query:(0,n.searchParamsToUrlQuery)(t.searchParams),search:t.search}}},3707:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"getPathMatch",{enumerable:!0,get:function(){return r}});let n=i(1792);function r(e,t){let i=[],r=(0,n.pathToRegexp)(e,i,{delimiter:"/",sensitive:"boolean"==typeof(null==t?void 0:t.sensitive)&&t.sensitive,strict:null==t?void 0:t.strict}),s=(0,n.regexpToFunction)((null==t?void 0:t.regexModifier)?new RegExp(t.regexModifier(r.source),r.flags):r,i);return(e,n)=>{if("string"!=typeof e)return!1;let r=s(e);if(!r)return!1;if(null==t?void 0:t.removeUnnamedParams)for(let e of i)"number"==typeof e.name&&delete r.params[e.name];return{...n,...r.params}}}},5257:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var i in t)Object.defineProperty(e,i,{enumerable:!0,get:t[i]})}(t,{compileNonPath:function(){return u},matchHas:function(){return d},prepareDestination:function(){return h}});let n=i(1792),r=i(4080),s=i(3226),o=i(1586),a=i(338),l=i(6975);function c(e){return e.replace(/__ESC_COLON_/gi,":")}function d(e,t,i,n){void 0===i&&(i=[]),void 0===n&&(n=[]);let r={},s=i=>{let n;let s=i.key;switch(i.type){case"header":s=s.toLowerCase(),n=e.headers[s];break;case"cookie":n="cookies"in e?e.cookies[i.key]:(0,l.getCookieParser)(e.headers)()[i.key];break;case"query":n=t[s];break;case"host":{let{host:t}=(null==e?void 0:e.headers)||{};n=null==t?void 0:t.split(":",1)[0].toLowerCase()}}if(!i.value&&n)return r[function(e){let t="";for(let i=0;i<e.length;i++){let n=e.charCodeAt(i);(n>64&&n<91||n>96&&n<123)&&(t+=e[i])}return t}(s)]=n,!0;if(n){let e=RegExp("^"+i.value+"$"),t=Array.isArray(n)?n.slice(-1)[0].match(e):n.match(e);if(t)return Array.isArray(t)&&(t.groups?Object.keys(t.groups).forEach(e=>{r[e]=t.groups[e]}):"host"===i.type&&t[0]&&(r.host=t[0])),!0}return!1};return!!i.every(e=>s(e))&&!n.some(e=>s(e))&&r}function u(e,t){if(!e.includes(":"))return e;for(let i of Object.keys(t))e.includes(":"+i)&&(e=e.replace(RegExp(":"+i+"\\*","g"),":"+i+"--ESCAPED_PARAM_ASTERISKS").replace(RegExp(":"+i+"\\?","g"),":"+i+"--ESCAPED_PARAM_QUESTION").replace(RegExp(":"+i+"\\+","g"),":"+i+"--ESCAPED_PARAM_PLUS").replace(RegExp(":"+i+"(?!\\w)","g"),"--ESCAPED_PARAM_COLON"+i));return e=e.replace(/(:|\*|\?|\+|\(|\)|\{|\})/g,"\\$1").replace(/--ESCAPED_PARAM_PLUS/g,"+").replace(/--ESCAPED_PARAM_COLON/g,":").replace(/--ESCAPED_PARAM_QUESTION/g,"?").replace(/--ESCAPED_PARAM_ASTERISKS/g,"*"),(0,n.compile)("/"+e,{validate:!1})(t).slice(1)}function h(e){let t;let i=Object.assign({},e.query);delete i.__nextLocale,delete i.__nextDefaultLocale,delete i.__nextDataReq,delete i.__nextInferredLocaleFromDefault,delete i[a.NEXT_RSC_UNION_QUERY];let l=e.destination;for(let t of Object.keys({...e.params,...i}))l=l.replace(RegExp(":"+(0,r.escapeStringRegexp)(t),"g"),"__ESC_COLON_"+t);let d=(0,s.parseUrl)(l),h=d.query,p=c(""+d.pathname+(d.hash||"")),m=c(d.hostname||""),f=[],g=[];(0,n.pathToRegexp)(p,f),(0,n.pathToRegexp)(m,g);let v=[];f.forEach(e=>v.push(e.name)),g.forEach(e=>v.push(e.name));let y=(0,n.compile)(p,{validate:!1}),b=(0,n.compile)(m,{validate:!1});for(let[t,i]of Object.entries(h))Array.isArray(i)?h[t]=i.map(t=>u(c(t),e.params)):"string"==typeof i&&(h[t]=u(c(i),e.params));let k=Object.keys(e.params).filter(e=>"nextInternalLocale"!==e);if(e.appendParamsToQuery&&!k.some(e=>v.includes(e)))for(let t of k)t in h||(h[t]=e.params[t]);if((0,o.isInterceptionRouteAppPath)(p))for(let t of p.split("/")){let i=o.INTERCEPTION_ROUTE_MARKERS.find(e=>t.startsWith(e));if(i){e.params["0"]=i;break}}try{let[i,n]=(t=y(e.params)).split("#",2);d.hostname=b(e.params),d.pathname=i,d.hash=(n?"#":"")+(n||""),delete d.search}catch(e){if(e.message.match(/Expected .*? to not repeat, but got an array/))throw Error("To use a multi-match in the destination you must add `*` at the end of the param name to signify it should repeat. https://nextjs.org/docs/messages/invalid-multi-match");throw e}return d.query={...i,...d.query},{newUrl:t,destQuery:h,parsedDestination:d}}},4869:(e,t)=>{"use strict";function i(e){let t={};return e.forEach((e,i)=>{void 0===t[i]?t[i]=e:Array.isArray(t[i])?t[i].push(e):t[i]=[t[i],e]}),t}function n(e){return"string"!=typeof e&&("number"!=typeof e||isNaN(e))&&"boolean"!=typeof e?"":String(e)}function r(e){let t=new URLSearchParams;return Object.entries(e).forEach(e=>{let[i,r]=e;Array.isArray(r)?r.forEach(e=>t.append(i,n(e))):t.set(i,n(r))}),t}function s(e){for(var t=arguments.length,i=Array(t>1?t-1:0),n=1;n<t;n++)i[n-1]=arguments[n];return i.forEach(t=>{Array.from(t.keys()).forEach(t=>e.delete(t)),t.forEach((t,i)=>e.append(i,t))}),e}Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var i in t)Object.defineProperty(e,i,{enumerable:!0,get:t[i]})}(t,{assign:function(){return s},searchParamsToUrlQuery:function(){return i},urlQueryToSearchParams:function(){return r}})},7847:(e,t)=>{"use strict";function i(e){return e.replace(/\/$/,"")||"/"}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"removeTrailingSlash",{enumerable:!0,get:function(){return i}})},3525:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"getRouteMatcher",{enumerable:!0,get:function(){return r}});let n=i(2569);function r(e){let{re:t,groups:i}=e;return e=>{let r=t.exec(e);if(!r)return!1;let s=e=>{try{return decodeURIComponent(e)}catch(e){throw new n.DecodeError("failed to decode param")}},o={};return Object.keys(i).forEach(e=>{let t=i[e],n=r[t.pos];void 0!==n&&(o[e]=~n.indexOf("/")?n.split("/").map(e=>s(e)):t.repeat?[s(n)]:s(n))}),o}}},5679:(e,t,i)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var i in t)Object.defineProperty(e,i,{enumerable:!0,get:t[i]})}(t,{getNamedMiddlewareRegex:function(){return p},getNamedRouteRegex:function(){return h},getRouteRegex:function(){return c},parseParameter:function(){return a}});let n=i(1943),r=i(1586),s=i(4080),o=i(7847);function a(e){let t=e.startsWith("[")&&e.endsWith("]");t&&(e=e.slice(1,-1));let i=e.startsWith("...");return i&&(e=e.slice(3)),{key:e,repeat:i,optional:t}}function l(e){let t=(0,o.removeTrailingSlash)(e).slice(1).split("/"),i={},n=1;return{parameterizedRoute:t.map(e=>{let t=r.INTERCEPTION_ROUTE_MARKERS.find(t=>e.startsWith(t)),o=e.match(/\[((?:\[.*\])|.+)\]/);if(t&&o){let{key:e,optional:r,repeat:l}=a(o[1]);return i[e]={pos:n++,repeat:l,optional:r},"/"+(0,s.escapeStringRegexp)(t)+"([^/]+?)"}if(!o)return"/"+(0,s.escapeStringRegexp)(e);{let{key:e,repeat:t,optional:r}=a(o[1]);return i[e]={pos:n++,repeat:t,optional:r},t?r?"(?:/(.+?))?":"/(.+?)":"/([^/]+?)"}}).join(""),groups:i}}function c(e){let{parameterizedRoute:t,groups:i}=l(e);return{re:RegExp("^"+t+"(?:/)?$"),groups:i}}function d(e){let{interceptionMarker:t,getSafeRouteKey:i,segment:n,routeKeys:r,keyPrefix:o}=e,{key:l,optional:c,repeat:d}=a(n),u=l.replace(/\W/g,"");o&&(u=""+o+u);let h=!1;(0===u.length||u.length>30)&&(h=!0),isNaN(parseInt(u.slice(0,1)))||(h=!0),h&&(u=i()),o?r[u]=""+o+l:r[u]=l;let p=t?(0,s.escapeStringRegexp)(t):"";return d?c?"(?:/"+p+"(?<"+u+">.+?))?":"/"+p+"(?<"+u+">.+?)":"/"+p+"(?<"+u+">[^/]+?)"}function u(e,t){let i;let a=(0,o.removeTrailingSlash)(e).slice(1).split("/"),l=(i=0,()=>{let e="",t=++i;for(;t>0;)e+=String.fromCharCode(97+(t-1)%26),t=Math.floor((t-1)/26);return e}),c={};return{namedParameterizedRoute:a.map(e=>{let i=r.INTERCEPTION_ROUTE_MARKERS.some(t=>e.startsWith(t)),o=e.match(/\[((?:\[.*\])|.+)\]/);if(i&&o){let[i]=e.split(o[0]);return d({getSafeRouteKey:l,interceptionMarker:i,segment:o[1],routeKeys:c,keyPrefix:t?n.NEXT_INTERCEPTION_MARKER_PREFIX:void 0})}return o?d({getSafeRouteKey:l,segment:o[1],routeKeys:c,keyPrefix:t?n.NEXT_QUERY_PARAM_PREFIX:void 0}):"/"+(0,s.escapeStringRegexp)(e)}).join(""),routeKeys:c}}function h(e,t){let i=u(e,t);return{...c(e),namedRegex:"^"+i.namedParameterizedRoute+"(?:/)?$",routeKeys:i.routeKeys}}function p(e,t){let{parameterizedRoute:i}=l(e),{catchAll:n=!0}=t;if("/"===i)return{namedRegex:"^/"+(n?".*":"")+"$"};let{namedParameterizedRoute:r}=u(e,!1);return{namedRegex:"^"+r+(n?"(?:(/.*)?)":"")+"$"}}},5406:(e,t)=>{"use strict";function i(e){return"("===e[0]&&e.endsWith(")")}Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var i in t)Object.defineProperty(e,i,{enumerable:!0,get:t[i]})}(t,{DEFAULT_SEGMENT_KEY:function(){return r},PAGE_SEGMENT_KEY:function(){return n},isGroupSegment:function(){return i}});let n="__PAGE__",r="__DEFAULT__"},2569:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),function(e,t){for(var i in t)Object.defineProperty(e,i,{enumerable:!0,get:t[i]})}(t,{DecodeError:function(){return m},MiddlewareNotFoundError:function(){return y},MissingStaticPage:function(){return v},NormalizeError:function(){return f},PageNotFoundError:function(){return g},SP:function(){return h},ST:function(){return p},WEB_VITALS:function(){return i},execOnce:function(){return n},getDisplayName:function(){return l},getLocationOrigin:function(){return o},getURL:function(){return a},isAbsoluteUrl:function(){return s},isResSent:function(){return c},loadGetInitialProps:function(){return u},normalizeRepeatedSlashes:function(){return d},stringifyError:function(){return b}});let i=["CLS","FCP","FID","INP","LCP","TTFB"];function n(e){let t,i=!1;return function(){for(var n=arguments.length,r=Array(n),s=0;s<n;s++)r[s]=arguments[s];return i||(i=!0,t=e(...r)),t}}let r=/^[a-zA-Z][a-zA-Z\d+\-.]*?:/,s=e=>r.test(e);function o(){let{protocol:e,hostname:t,port:i}=window.location;return e+"//"+t+(i?":"+i:"")}function a(){let{href:e}=window.location,t=o();return e.substring(t.length)}function l(e){return"string"==typeof e?e:e.displayName||e.name||"Unknown"}function c(e){return e.finished||e.headersSent}function d(e){let t=e.split("?");return t[0].replace(/\\/g,"/").replace(/\/\/+/g,"/")+(t[1]?"?"+t.slice(1).join("?"):"")}async function u(e,t){let i=t.res||t.ctx&&t.ctx.res;if(!e.getInitialProps)return t.ctx&&t.Component?{pageProps:await u(t.Component,t.ctx)}:{};let n=await e.getInitialProps(t);if(i&&c(i))return n;if(!n)throw Error('"'+l(e)+'.getInitialProps()" should resolve to an object. But found "'+n+'" instead.');return n}let h="undefined"!=typeof performance,p=h&&["mark","measure","getEntriesByName"].every(e=>"function"==typeof performance[e]);class m extends Error{}class f extends Error{}class g extends Error{constructor(e){super(),this.code="ENOENT",this.name="PageNotFoundError",this.message="Cannot find module for page: "+e}}class v extends Error{constructor(e,t){super(),this.message="Failed to load static file for page: "+e+" "+t}}class y extends Error{constructor(){super(),this.code="ENOENT",this.message="Cannot find the middleware module"}}function b(e){return JSON.stringify({message:e.message,stack:e.stack})}},7481:(e,t,i)=>{"use strict";i.r(t),i.d(t,{default:()=>r});var n=i(6621);let r=e=>[{type:"image/x-icon",sizes:"16x16",url:(0,n.fillMetadataSegment)(".",e.params,"favicon.ico")+""}]},7272:()=>{}};var t=require("../webpack-runtime.js");t.C(e);var i=e=>t(t.s=e),n=t.X(0,[948,994],()=>i(8148));module.exports=n})();